I've not played around with all possibilities, but at least I had the impression that this could be a python version related issue. No idea why, I just trusted my gut.
Thus I just changed the pythonPath to python3 (default: python):
"python.pythonPath": "python3"
I reinstalled the dependencies (including pylint!!!) with
pip3 install <package> --user
... and after restarting vs code, everything looked fine.
HTH Kai
Try wexpect, which is the windows alternative of pexpect.
import wexpect
p = wexpect.spawn('myprogram.exe')
p.stdout.readline('.') // regex pattern of any character
output_str = p.after()
Just send xml bytes directly:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import requests
xml = """<?xml version='1.0' encoding='utf-8'?>
<a>?</a>"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
print requests.post('http://httpbin.org/post', data=xml, headers=headers).text
{
"origin": "x.x.x.x",
"files": {},
"form": {},
"url": "http://httpbin.org/post",
"args": {},
"headers": {
"Content-Length": "48",
"Accept-Encoding": "identity, deflate, compress, gzip",
"Connection": "keep-alive",
"Accept": "*/*",
"User-Agent": "python-requests/0.13.9 CPython/2.7.3 Linux/3.2.0-30-generic",
"Host": "httpbin.org",
"Content-Type": "application/xml"
},
"json": null,
"data": "<?xml version='1.0' encoding='utf-8'?>\n<a>\u0431</a>"
}
... and Trick #3 Multiline entries in an Xtable
Generate some more data
moredata<-data.frame(Nominal=c(1:5), n=rep(5,5),
MeanLinBias=signif(rnorm(5, mean=0, sd=10), digits=4),
LinCI=paste("(",signif(rnorm(5,mean=-2, sd=5), digits=4),
", ", signif(rnorm(5, mean=2, sd=5), digits=4),")",sep=""),
MeanQuadBias=signif(rnorm(5, mean=0, sd=10), digits=4),
QuadCI=paste("(",signif(rnorm(5,mean=-2, sd=5), digits=4),
", ", signif(rnorm(5, mean=2, sd=5), digits=4),")",sep=""))
names(moredata)<-c("Nominal", "n","Linear Model \nBias","Linear \nCI", "Quadratic Model \nBias", "Quadratic \nCI")
Now produce our xtable, using the sanitize function to replace column names with the correct Latex newline commands (including double backslashes so R is happy)
<<label=multilinetable, results=tex, echo=FALSE>>=
foo<-xtable(moredata)
align(foo) <- c( rep('c',3),'p{1.8in}','p{2in}','p{1.8in}','p{2in}' )
print(foo,
floating=FALSE,
include.rownames=FALSE,
sanitize.text.function = function(str) {
str<-gsub("\n","\\\\", str, fixed=TRUE)
return(str)
},
sanitize.colnames.function = function(str) {
str<-c("Nominal", "n","\\centering Linear Model\\\\ \\% Bias","\\centering Linear \\\\ 95\\%CI", "\\centering Quadratic Model\\\\ \\%Bias", "\\centering Quadratic \\\\ 95\\%CI \\tabularnewline")
return(str)
})
@
(although this isn't perfect, as we need \tabularnewline so the table is formatted correctly, and Xtable still puts in a final \, so we end up with a blank line below the table header.)
You probably had a typo when you first ran it.
evaluating 0.5 % 0.3
returns '0.2' (A double) as expected.
Mindprod has a good overview of how modulus works in Java.
For those who are able to access cpanel, there is a simpler way getting around it.
log in cpanel => "Remote MySQL" under DATABASES section:
Add the IPs / hostname which you are accessing from
done!!!
you can try the following code
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("PayScale", typeof(string));
dt.Columns.Add("IncrementAmt", typeof(string));
dt.Columns.Add("Period", typeof(string));
}
DataRow NewRow = dt.NewRow();
NewRow[0] = TextBox1.Text;
NewRow[1] = TextBox2.Text;
dt.Rows.Add(NewRow);
GridView1.DataSource = dt;
GridViewl.DataBind();
}
here payscale,incrementamt and period are database field name.
Looking at the answers and the question, it seems the question has been modified significantly. So to answer the current question:
Convert LocalDateTime to LocalDateTime in UTC.
LocalDateTime
does not store any information about the time-zone, it just basically holds the values of year, month, day, hour, minute, second, and smaller units. So an important question is: What is the timezone of the original LocalDateTime
? It might as well be UTC already, therefore no conversion has to be made.
Considering that you asked the question anyway, you probably meant that the original time is in your system-default timezone and you want to convert it to UTC. Because usually a LocalDateTime
object is created by using LocalDateTime.now()
which returns the current time in the system-default timezone. In this case, the conversion would be the following:
LocalDateTime convertToUtc(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}
An example of the conversion process:
2019-02-25 11:39 // [time] original LocalDateTime without a timezone
2019-02-25 11:39 GMT+1 // [atZone] converted to ZonedDateTime (system timezone is Madrid)
2019-02-25 10:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2019-02-25 10:39 // [toLocalDateTime] losing the timezone information
In any other case, when you explicitly specify the timezone of the time to convert, the conversion would be the following:
LocalDateTime convertToUtc(LocalDateTime time, ZoneId zone) {
return time.atZone(zone).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}
An example of the conversion process:
2019-02-25 11:39 // [time] original LocalDateTime without a timezone
2019-02-25 11:39 GMT+2 // [atZone] converted to ZonedDateTime (zone is Europe/Tallinn)
2019-02-25 09:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2019-02-25 09:39 // [toLocalDateTime] losing the timezone information
atZone()
MethodThe result of the atZone()
method depends on the time passed as its argument, because it considers all the rules of the timezone, including Daylight Saving Time (DST). In the examples, the time was 25th February, in Europe this means winter time (no DST).
If we were to use a different date, let's say 25th August from last year, the result would be different, considering DST:
2018-08-25 11:39 // [time] original LocalDateTime without a timezone
2018-08-25 11:39 GMT+3 // [atZone] converted to ZonedDateTime (zone is Europe/Tallinn)
2018-08-25 08:39 GMT // [withZoneSameInstant] converted to UTC, still as ZonedDateTime
2018-08-25 08:39 // [toLocalDateTime] losing the timezone information
The GMT time does not change. Therefore the offsets in the other timezones are adjusted. In this example, the summer time of Estonia is GMT+3, and winter time GMT+2.
Also, if you specify a time within the transition of changing clocks back one hour. E.g. October 28th, 2018 03:30 for Estonia, this can mean two different times:
2018-10-28 03:30 GMT+3 // summer time [UTC 2018-10-28 00:30]
2018-10-28 04:00 GMT+3 // clocks are turned back 1 hour [UTC 2018-10-28 01:00]
2018-10-28 03:00 GMT+2 // same as above [UTC 2018-10-28 01:00]
2018-10-28 03:30 GMT+2 // winter time [UTC 2018-10-28 01:30]
Without specifying the offset manually (GMT+2 or GMT+3), the time 03:30
for the timezone Europe/Tallinn
can mean two different UTC times, and two different offsets.
As you can see, the end result depends on the timezone of the time passed as an argument. Because the timezone cannot be extracted from the LocalDateTime
object, you have to know yourself which timezone it is coming from in order to convert it to UTC.
If you have installed php 7.1
then this line work on your system.
sudo apt install php7.1-bcmath
check your php version in your system on ubuntu 16.04
php -v
and then result show there..
PHP 7.1.x+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Aug 19 2018 07:16:12) ( NTS ) Copyright (c) 1997-2018 The PHP Group Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies with Zend OPcache v7.2.9-1+ubuntu16.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies
I had to map FAKE/REAL to 0/1 but couldn't find proper answer.
Please find below how to map column name 'type' which has values FAKE/REAL to 0/1
(Note: similar can be applied to any column name and values)
df.loc[df['type'] == 'FAKE', 'type'] = 0
df.loc[df['type'] == 'REAL', 'type'] = 1
This is how I fixed it:
IIF(ValueA != 0, Total / ValueA, 0)
It can be wrapped in an update:
SET Pct = IIF(ValueA != 0, Total / ValueA, 0)
Or in a select:
SELECT IIF(ValueA != 0, Total / ValueA, 0) AS Pct FROM Tablename;
Thoughts?
NPP+ v7.9.1 with the latest version of XMLTools can't format exported VBA code from Office 2016/2019 Word. It puts all the code on the same line since it strips the CRLF out. Moreover, when you enable "auto validation" it errors out on the first VBA line that is, Attribute VB_Name = "The VBA module name". So any of the xml tool validations apparently can't be used for VBA validation.
The specific Date
constructor is deprecated, and Calendar
should be used instead.
The JavaDoc
for Date describes which constructors are deprecated and how to replace them using a Calendar
.
Local Computer FQDN via dotNet class
[System.Net.Dns]::GetHostEntry([string]$env:computername).HostName
or
[System.Net.Dns]::GetHostEntry([string]"localhost").HostName
Reference:
note: GetHostByName method is obsolete
Local computer FQDN via WMI query
$myFQDN=(Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain
Write-Host $myFQDN
Reference:
You can either
fig, ax = plt.subplots() #create figure and axes
candlestick(ax, quotes, ...)
or
candlestick(plt.gca(), quotes) #get the axis when calling the function
The first gives you more flexibility. The second is much easier if candlestick is the only thing you want to plot
Yes, it's "not equal".
dplyr has the function nth, where the first argument is the vector and the second is which place you want. This goes for repeating elements as well. For example:
x = c(1,2, 8, 16, 17, 20, 1, 20)
Finding the second largest value:
nth(unique(x),length(unique(x))-1)
[1] 17
In order to send data from child component create property decorated with output() in child component and in the parent listen to the created event. Emit this event with new values in the payload when ever it needed.
@Output() public eventName:EventEmitter = new EventEmitter();
to emit this event:
this.eventName.emit(payloadDataObject);
You can also do:
start notepad "C:\Users\kemp\INSTALL\Text1.txt"
The C:\Users\kemp\Install\
is your PATH. The Text1.txt is the FILE.
jQuery's attr
method returns the value of the attribute:
The
.attr()
method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's.each()
or.map()
method.
All you need is:
$('html').attr('lang') == 'fr-FR'
However, you might want to do a case-insensitive match:
$('html').attr('lang').toLowerCase() === 'fr-fr'
jQuery's val
method returns the value of a form element.
The
.val()
method is primarily used to get the values of form elements such asinput
,select
andtextarea
. In the case of<select multiple="multiple">
elements, the.val()
method returns an array containing each selected option; if no option is selected, it returnsnull
.
Use a subquery:
SELECT * FROM (
SELECT * FROM users ORDER BY RAND() LIMIT 20
) u
ORDER BY name
or a join to itself:
SELECT * FROM users u1
INNER JOIN (
SELECT id FROM users ORDER BY RAND() LIMIT 20
) u2 USING(id)
ORDER BY u1.name
I have no touch
and chmod
command in my cmd.exe
and git update-index --chmod=+x foo.sh
doesn't work for me.
I finally resolve it by setting skip-worktree
bit:
git update-index --skip-worktree --chmod=+x foo.sh
you can do so by using the :before
or :after
pseudo. read more about it here http://astronautweb.co/snippet/font-awesome/
change your code to this
.lb-prev:hover {
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
opacity: 1;
text-decoration: none;
}
.lb-prev:before {
font-family: FontAwesome;
content: "\f053";
font-size: 30px;
}
do the same for the other icons. you might want to adjust the color and height of the icons too. anyway here is the fiddle hope this helps
I would use a regex:
import re
new_list = [re.sub(r"\.(?=[^.]*$)", r". - ", s) for s in old_list]
Stack memory is specifically the range of memory that is accessible via the Stack register of the CPU. The Stack was used as a way to implement the "Jump-Subroutine"-"Return" code pattern in assembly language, and also as a means to implement hardware-level interrupt handling. For instance, during an interrupt, the Stack was used to store various CPU registers, including Status (which indicates the results of an operation) and Program Counter (where was the CPU in the program when the interrupt occurred).
Stack memory is very much the consequence of usual CPU design. The speed of its allocation/deallocation is fast because it is strictly a last-in/first-out design. It is a simple matter of a move operation and a decrement/increment operation on the Stack register.
Heap memory was simply the memory that was left over after the program was loaded and the Stack memory was allocated. It may (or may not) include global variable space (it's a matter of convention).
Modern pre-emptive multitasking OS's with virtual memory and memory-mapped devices make the actual situation more complicated, but that's Stack vs Heap in a nutshell.
This happened to me because I put a variable in the regex and sometimes its string value included a slash. Solution: preg_quote.
The essential difference between /*
and /
is that a servlet with mapping /*
will be selected before any servlet with an extension mapping (like *.html
), while a servlet with mapping /
will be selected only after extension mappings are considered (and will be used for any request which doesn't match anything else---it is the "default servlet").
In particular, a /*
mapping will always be selected before a /
mapping. Having either prevents any requests from reaching the container's own default servlet.
Either will be selected only after servlet mappings which are exact matches (like /foo/bar
) and those which are path mappings longer than /*
(like /foo/*
). Note that the empty string mapping is an exact match for the context root (http://host:port/context/
).
See Chapter 12 of the Java Servlet Specification, available in version 3.1 at http://download.oracle.com/otndocs/jcp/servlet-3_1-fr-eval-spec/index.html.
Try System.getProperty( "line.separator" )
writer.write(System.getProperty( "line.separator" ));
var spl = item.Split('/')[1];
var format =spl.Split(';')[0];
stringconvert=item.Replace($"data:image/{format};base64,",String.Empty);
Easy and better than str_replace
:
<?php
$arr = array(
"http://" => "http://www.",
"w" => "W",
"d" => "D");
$word = "http://desiweb.ir";
echo strtr($word,$arr);
?>
strtr
PHP doc here
I don't know about JSON.NET, but it works fine with JavaScriptSerializer
from System.Web.Extensions.dll
(.NET 3.5 SP1):
using System.Collections.Generic;
using System.Web.Script.Serialization;
public class NameTypePair
{
public string OBJECT_NAME { get; set; }
public string OBJECT_TYPE { get; set; }
}
public enum PositionType { none, point }
public class Ref
{
public int id { get; set; }
}
public class SubObject
{
public NameTypePair attributes { get; set; }
public Position position { get; set; }
}
public class Position
{
public int x { get; set; }
public int y { get; set; }
}
public class Foo
{
public Foo() { objects = new List<SubObject>(); }
public string displayFieldName { get; set; }
public NameTypePair fieldAliases { get; set; }
public PositionType positionType { get; set; }
public Ref reference { get; set; }
public List<SubObject> objects { get; set; }
}
static class Program
{
const string json = @"{
""displayFieldName"" : ""OBJECT_NAME"",
""fieldAliases"" : {
""OBJECT_NAME"" : ""OBJECT_NAME"",
""OBJECT_TYPE"" : ""OBJECT_TYPE""
},
""positionType"" : ""point"",
""reference"" : {
""id"" : 1111
},
""objects"" : [
{
""attributes"" : {
""OBJECT_NAME"" : ""test name"",
""OBJECT_TYPE"" : ""test type""
},
""position"" :
{
""x"" : 5,
""y"" : 7
}
}
]
}";
static void Main()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
Foo foo = ser.Deserialize<Foo>(json);
}
}
Edit:
Json.NET works using the same JSON and classes.
Foo foo = JsonConvert.DeserializeObject<Foo>(json);
Use This And Call This In OnCreate Method In Which Activity You Want
public void popupMessage(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("No Internet Connection. Check Your Wifi Or enter code hereMobile Data.");
alertDialogBuilder.setIcon(R.drawable.ic_no_internet);
alertDialogBuilder.setTitle("Connection Failed");
alertDialogBuilder.setNegativeButton("ok", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.d("internet","Ok btn pressed");
finishAffinity();
System.exit(0);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
I wanted a vanilla, lightweight (jQuery UI Layout weighs in at 185 KB), no dependency option (all existing libraries require jQuery), so I wrote Split.js.
It weights less than 2 KB and does not require any special markup. It supports older browsers back to Internet Explorer 9 (or Internet Explorer 8 with polyfills). For modern browsers, you can use it with Flexbox and grid layouts.
This seems like a protocol version mismatch, this exception normally happens when there is a mismatch between SSL protocol version used by the client and the server. your clients should use a proctocol version supported by the server.
No, it is not about the data type of input. It specifies the type of control to create:
type = text|password|checkbox|radio|submit|reset|file|hidden|image|button [CI] This attribute specifies the type of control to create. The default value for this attribute is "text".
Step 1: Highlight the entire column (not including the header) of the column you wish to populate
Step 2: (Using Kutools) On the Insert dropdown, click "Fill Custom List"
Step 3: Click Edit
Step 4: Create your list (For Ex: 1, 2)
Step 5: Choose your new custom list and then click "Fill Range"
DONE!!!
You can also use "bold" and "italic" instead of "normal" here. "Verdana" can be used for fontname..
But another question is this: How do you set the color of the text You write?
Answer: You use the turtle.color() method or turtle.fillcolor(), like this:
turtle.fillcolor("blue")
or just:
turtle.color("orange")
These calls must come before the turtle.write() command..
If you're behind a proxy, you should use X-Forwarded-For
: http://en.wikipedia.org/wiki/X-Forwarded-For
It is an IETF draft standard with wide support:
The X-Forwarded-For field is supported by most proxy servers, including Squid, Apache mod_proxy, Pound, HAProxy, Varnish cache, IronPort Web Security Appliance, AVANU WebMux, ArrayNetworks, Radware's AppDirector and Alteon ADC, ADC-VX, and ADC-VA, F5 Big-IP, Blue Coat ProxySG, Cisco Cache Engine, McAfee Web Gateway, Phion Airlock, Finjan's Vital Security, NetApp NetCache, jetNEXUS, Crescendo Networks' Maestro, Web Adjuster and Websense Web Security Gateway.
If not, here are a couple other common headers I've seen:
i do it like this cover button and the middle image that
<button><img src="foldername/imagename" width="30px" height= "30px"></button>
The simplest fix is to make the comparator function be static:
static int comparator (const Bar & first, const Bar & second);
^^^^^^
When invoking it in Count
, its name will be Foo::comparator
.
The way you have it now, it does not make sense to be a non-static member function because it does not use any member variables of Foo
.
Another option is to make it a non-member function, especially if it makes sense that this comparator might be used by other code besides just Foo
.
I don't seem to have enough rep to close this as a duplicate, but it is one if someone else can do that. I posted the same thing over at A more pretty/informative Var_dump alternative in PHP? but for the sake of saving time, I'll copy/paste it here too:
I had to add another answer here because I didn't really want to go through the steps in the other solutions. It is extremely simple and requires no extensions, includes etc and is what I prefer. It's very easy and very fast.
First just json_encode the variable in question:
echo json_encode($theResult);
Copy the result you get into the JSON Editor at http://jsoneditoronline.org/ just copy it into the left side pane, click Copy > and it pretty prints the JSON in a really nice tree format.
To each their own, but hopefully this helps some others have one more nice option! :)
I'd say the default value is always new DateTime()
. So we can write
DateTime datetime;
if (datetime == new DateTime())
{
//unassigned
}
If you have downloaded these files locally then you can change following classes in bootstrap-social.css, just added border-radius: 50%;
.btn-social-icon.btn-lg{height:45px;width:45px;
padding-left:0;padding-right:0; border-radius: 50%; }
And here is teh HTML
<a class="btn btn-social-icon btn-lg btn-twitter" >
<i class="fa fa-twitter"></i>
</a>
<a class=" btn btn-social-icon btn-lg btn-facebook">
<i class="fa fa-facebook sbg-facebook"></i>
</a>
<a class="btn btn-social-icon btn-lg btn-google-plus">
<i class="fa fa-google-plus"></i>
</a>
It works smooth for me.
So the package will be downloaded in a temp folder C:\Users\U122337.BOSTONADVISORS\AppData\Local\Temp\Rtmp404t8Y\downloaded_packages from where it will be installed into your library folder, e.g. C:\R\library\zoo
What you have to do once install command is done: Open Packages menu -> Load package...
You will see your package on the list. You can automate this: How to load packages in R automatically?
Use FLOOR(), if you want to round your decimal to the lower integer. Examples:
FLOOR(1.9) => 1
FLOOR(1.1) => 1
Use ROUND(), if you want to round your decimal to the nearest integer. Examples:
ROUND(1.9) => 2
ROUND(1.1) => 1
Use CEIL(), if you want to round your decimal to the upper integer. Examples:
CEIL(1.9) => 2
CEIL(1.1) => 2
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
// action one
let editAction = UITableViewRowAction(style: .default, title: "Edit", handler: { (action, indexPath) in
print("Edit tapped")
self.myArray.add(indexPath.row)
})
editAction.backgroundColor = UIColor.blue
// action two
let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, indexPath) in
print("Delete tapped")
self.myArray.removeObject(at: indexPath.row)
self.myTableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
})
deleteAction.backgroundColor = UIColor.red
// action three
let shareAction = UITableViewRowAction(style: .default, title: "Share", handler: { (action , indexPath)in
print("Share Tapped")
})
shareAction.backgroundColor = UIColor .green
return [editAction, deleteAction, shareAction]
}
Quote (read [here][1])-
When you use CAST to convert a CLOB value into a character datatype or a BLOB value into the RAW datatype, the database implicitly converts the LOB value to character or raw data and then explicitly casts the resulting value into the target datatype.
So, something like this should work-
report := CAST(report_clob AS VARCHAR2(100));
Or better yet use it as CAST(report_clob AS VARCHAR2(100))
where ever you are trying to use the BLOB
as VARCHAR
[1]: http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions016.htm
I made the below function after reading this thread. Simple and fast:
go
create function numbers(@begin int, @len int)
returns table as return
with d as (
select 1 v from (values(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) d(v)
)
select top (@len) @begin -1 + row_number() over(order by (select null)) v
from d d0
cross join d d1
cross join d d2
cross join d d3
cross join d d4
cross join d d5
cross join d d6
cross join d d7
go
select * from numbers(987654321,500000)
It means that the method accepts a variable number of arguments ("varargs") of type JID
. Within the method, recipientJids
is presented.
This is handy for cases where you've a method that can optionally handle more than one argument in a natural way, and allows you to write calls which can pass one, two or three parameters to the same method, without having the ugliness of creating an array on the fly.
It also enables idioms such as sprintf
from C; see String.format()
, for example.
This may mean that you are installing the wrong pre-build binary
since my CPU on Ubuntu 18.04 my download url was: https://github.com/lakshayg/tensorflow-build/releases/download/tf1.12.0-ubuntu18.04-py2-py3/tensorflow-1.12.0-cp36-cp36m-linux_x86_64.whl
as it can be found on this github page: https://github.com/lakshayg/tensorflow-build
pip install --ignore-installed --upgrade <LOCAL PATH / BINARY-URL>
resolved the issue for me.
I'd suggest using grep -i version
to make sure you get the right line containing the version string. If you have the environment variable JAVA_OPTIONS set, openjdk will print the java options before printing the version information. This version returns 1.6, 1.7 etc.
java -version 2>&1 | grep -i version | cut -d'"' -f2 | cut -d'.' -f1-2
'Date' is your index so you want to do,
print (df.index.min())
print (df.index.max())
2014-03-13 00:00:00
2014-03-31 00:00:00
With the help of pseudo classes removed margins from first and last child, and used adaptive height true in the script. Try this fiddle
One more Demo
$('.single-item').slick({
initialSlide: 3,
infinite: false,
adaptiveHeight: true
});
The problem for me was as simple as just not knowing Javascript well. I was trying to pass the name of the id using double quotes, when I should have been using single. And it worked fine.
This worked:
validateSelectizeDropdown('#PartCondition')
This did not:
validateSelectizeDropdown("#PartCondition")
And the function:
function validateSelectizeDropdown(name) {
if ($(name).val() === "") {
//do something
}
}
npm test -- SomeTestFileToRun
In order to run a specific test, you'll need to use the jest
command. npm test
will not work. To access jest
directly on the command line, install it via npm i -g jest-cli
or yarn global add jest-cli
.
Then simply run your specific test with jest bar.spec.js
.
Note: You don't have to enter the full path to your test file. The argument is interpreted as a regular expression. Any part of the full path that uniquely identifies a file suffices.
Array.filter( document.getElementsByClassName('appBanner'), function(elem){ elem.style.visibility = 'hidden'; });
Forked @http://jsfiddle.net/QVJXD/
(Expanding upon ????'s answer)
Style the canvas to fill the body. When rendering to the canvas take its size into account.
http://jsfiddle.net/mqFdk/356/
<!DOCTYPE html>
<html>
<head>
<title>aj</title>
</head>
<body>
<canvas id="c"></canvas>
</body>
</html>
CSS:
body {
margin: 0;
padding: 0
}
#c {
position: absolute;
width: 100%;
height: 100%;
overflow: hidden
}
Javascript:
function redraw() {
var cc = c.getContext("2d");
c.width = c.clientWidth;
c.height = c.clientHeight;
cc.scale(c.width, c.height);
// Draw a circle filling the canvas.
cc.beginPath();
cc.arc(0.5, 0.5, .5, 0, 2*Math.PI);
cc.fill();
}
// update on any window size change.
window.addEventListener("resize", redraw);
// first draw
redraw();
Andy E is correct that there is no HTML-based way to do this*; but if you are willing to use Flash, you can do it. The following works reliably on systems that have Flash installed. If your app needs to work on iPhone, then of course you'll need a fallback HTML-based solution.
* (Update 4/22/2013: HTML does now support this, in HTML5. See the other answers.)
Flash uploading also has other advantages -- Flash gives you the ability to show a progress bar as the upload of a large file progresses. (I'm pretty sure that's how Gmail does it, by using Flash behind the scenes, although I may be wrong about that.)
Here is a sample Flex 4 app that allows the user to pick a file, and then displays it:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
creationComplete="init()">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:Button x="10" y="10" label="Choose file..." click="showFilePicker()" />
<mx:Image id="myImage" x="9" y="44"/>
<fx:Script>
<![CDATA[
private var fr:FileReference = new FileReference();
// Called when the app starts.
private function init():void
{
// Set up event handlers.
fr.addEventListener(Event.SELECT, onSelect);
fr.addEventListener(Event.COMPLETE, onComplete);
}
// Called when the user clicks "Choose file..."
private function showFilePicker():void
{
fr.browse();
}
// Called when fr.browse() dispatches Event.SELECT to indicate
// that the user has picked a file.
private function onSelect(e:Event):void
{
fr.load(); // start reading the file
}
// Called when fr.load() dispatches Event.COMPLETE to indicate
// that the file has finished loading.
private function onComplete(e:Event):void
{
myImage.data = fr.data; // load the file's data into the Image
}
]]>
</fx:Script>
</s:Application>
You simply want the File.GetLastWriteTime
static method.
Example:
var lastModified = System.IO.File.GetLastWriteTime("C:\foo.bar");
Console.WriteLine(lastModified.ToString("dd/MM/yy HH:mm:ss"));
Note however that in the rare case the last-modified time is not updated by the system when writing to the file (this can happen intentionally as an optimisation for high-frequency writing, e.g. logging, or as a bug), then this approach will fail, and you will instead need to subscribe to file write notifications from the system, constantly listening.
you could also use display: table
insted of tables. Divs are way more flexible than tables.
Example:
.table {_x000D_
display: table;_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.table .table-row {_x000D_
display: table-row;_x000D_
}_x000D_
_x000D_
.table .table-cell {_x000D_
display: table-cell;_x000D_
text-align: left;_x000D_
vertical-align: top;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
<div class="table">_x000D_
<div class="table-row">_x000D_
<div class="table-cell">test</div>_x000D_
<div class="table-cell">test1123</div>_x000D_
</div>_x000D_
<div class="table-row">_x000D_
<div class="table-cell">test</div>_x000D_
<div class="table-cell">test123</div>_x000D_
</div>_x000D_
</div>
_x000D_
@Josue Alexander Ibarra answer works on centos 7 and version 9.5 if --dbname is not passed.
pg_dump postgresql://username:[email protected]:5432/mydatabase
All this peace of code put into *.bat file and run all at once:
My code for creating user in oracle. crate_drop_user.sql file
drop user "USER" cascade;
DROP TABLESPACE "USER";
CREATE TABLESPACE USER DATAFILE 'D:\ORA_DATA\ORA10\USER.ORA' SIZE 10M REUSE
AUTOEXTEND
ON NEXT 5M EXTENT MANAGEMENT LOCAL
SEGMENT SPACE MANAGEMENT AUTO
/
CREATE TEMPORARY TABLESPACE "USER_TEMP" TEMPFILE
'D:\ORA_DATA\ORA10\USER_TEMP.ORA' SIZE 10M REUSE AUTOEXTEND
ON NEXT 5M EXTENT MANAGEMENT LOCAL
UNIFORM SIZE 1M
/
CREATE USER "USER" PROFILE "DEFAULT"
IDENTIFIED BY "user_password" DEFAULT TABLESPACE "USER"
TEMPORARY TABLESPACE "USER_TEMP"
/
alter user USER quota unlimited on "USER";
GRANT CREATE PROCEDURE TO "USER";
GRANT CREATE PUBLIC SYNONYM TO "USER";
GRANT CREATE SEQUENCE TO "USER";
GRANT CREATE SNAPSHOT TO "USER";
GRANT CREATE SYNONYM TO "USER";
GRANT CREATE TABLE TO "USER";
GRANT CREATE TRIGGER TO "USER";
GRANT CREATE VIEW TO "USER";
GRANT "CONNECT" TO "USER";
GRANT SELECT ANY DICTIONARY to "USER";
GRANT CREATE TYPE TO "USER";
create file import.bat and put this lines in it:
SQLPLUS SYSTEM/systempassword@ORA_alias @"crate_drop_user.SQL"
IMP SYSTEM/systempassword@ORA_alias FILE=user.DMP FROMUSER=user TOUSER=user GRANTS=Y log =user.log
Be carefull if you will import from one user to another. For example if you have user named user1 and you will import to user2 you may lost all grants , so you have to recreate it.
Good luck, Ivan
I use this combination of extension methods:
public static Stream Copy(this Stream source)
{
if (source == null)
return null;
long originalPosition = -1;
if (source.CanSeek)
originalPosition = source.Position;
MemoryStream ms = new MemoryStream();
try
{
Copy(source, ms);
if (originalPosition > -1)
ms.Seek(originalPosition, SeekOrigin.Begin);
else
ms.Seek(0, SeekOrigin.Begin);
return ms;
}
catch
{
ms.Dispose();
throw;
}
}
public static void Copy(this Stream source, Stream target)
{
if (source == null)
throw new ArgumentNullException("source");
if (target == null)
throw new ArgumentNullException("target");
long originalSourcePosition = -1;
int count = 0;
byte[] buffer = new byte[0x1000];
if (source.CanSeek)
{
originalSourcePosition = source.Position;
source.Seek(0, SeekOrigin.Begin);
}
while ((count = source.Read(buffer, 0, buffer.Length)) > 0)
target.Write(buffer, 0, count);
if (originalSourcePosition > -1)
{
source.Seek(originalSourcePosition, SeekOrigin.Begin);
}
}
The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).
Your text may be located in the networking response.There is also a search tool in the Network tab, and you may try it.
What you want to search for may stay either in DOM or in memory. If it is not in DOM, well, it may be in memory, because you have just see it in your computer screen anyway. The text you search for may be loaded either from scripts in the initial DOM or from response in the later request.
As far as I'm aware Ratchet is the best PHP WebSocket solution available at the moment. And since it's open source you can see how the author has built this WebSocket solution using PHP.
public void DeleteUserIMP(UserIMP useriamp) {
synchronized (ListUserIMP) {
if (ListUserIMP.isEmpty()) {
System.out.println("user is empty");
} else {
Iterator<UserIMP> it = ListUserIMP.iterator();
while (it.hasNext()) {
UserIMP user = it.next();
if (useriamp.getMoblieNumber().equals(user.getMoblieNumber())) {
it.remove();
System.out.println("remove it");
}
}
// ListUserIMP.remove(useriamp);
System.out.println(" this user removed");
}
Constants.RESULT_FOR_REGISTRATION = Constants.MESSAGE_OK;
// System.out.println("This user Deleted " + Constants.MESSAGE_OK);
}
}
I created this directive that easily does that, truncates the string to a specified limit and adds a "show more/less" toggle. You can find it on GitHub: https://github.com/doukasd/AngularJS-Components
it can be used like this:
<p data-dd-collapse-text="100">{{veryLongText}}</p>
Here's the directive:
// a directive to auto-collapse long text
app.directive('ddCollapseText', ['$compile', function($compile) {
return {
restrict: 'A',
replace: true,
link: function(scope, element, attrs) {
// start collapsed
scope.collapsed = false;
// create the function to toggle the collapse
scope.toggle = function() {
scope.collapsed = !scope.collapsed;
};
// get the value of the dd-collapse-text attribute
attrs.$observe('ddCollapseText', function(maxLength) {
// get the contents of the element
var text = element.text();
if (text.length > maxLength) {
// split the text in two parts, the first always showing
var firstPart = String(text).substring(0, maxLength);
var secondPart = String(text).substring(maxLength, text.length);
// create some new html elements to hold the separate info
var firstSpan = $compile('<span>' + firstPart + '</span>')(scope);
var secondSpan = $compile('<span ng-if="collapsed">' + secondPart + '</span>')(scope);
var moreIndicatorSpan = $compile('<span ng-if="!collapsed">...</span>')(scope);
var toggleButton = $compile('<span class="collapse-text-toggle" ng-click="toggle()">{{collapsed ? "less" : "more"}}</span>')(scope);
// remove the current contents of the element
// and add the new ones we created
element.empty();
element.append(firstSpan);
element.append(secondSpan);
element.append(moreIndicatorSpan);
element.append(toggleButton);
}
});
}
};
}]);
And some CSS to go with it:
.collapse-text-toggle {
font-size: 0.9em;
color: #666666;
cursor: pointer;
}
.collapse-text-toggle:hover {
color: #222222;
}
.collapse-text-toggle:before {
content: '\00a0(';
}
.collapse-text-toggle:after {
content: ')';
}
After 8 years the situation is changed a bit.
I'm unable to open a new session of Google Chrome without other parameters and allow 'file:' schema.
On macOS I do:
open -n -a "Google Chrome" --args \
--disable-web-security \ # This disable all CORS and other security checks
--user-data-dir=$HOME/fakeChromeDir # This let you to force open a new Google Chrome session
Without this arguments I'm unable to test the XSL stylesheet in local.
Two ways are there by which you can use to erase an item particularly. lets take a vector
std :: vector < int > v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
v.push_back(40);
v.push_back(50);
1) Non efficient way : Although it seems to be quite efficient but it's not because erase function delets the elements and shifts all the elements towards left by 1. so its complexity will be O(n^2)
std :: vector < int > :: iterator itr = v.begin();
int value = 40;
while ( itr != v.end() )
{
if(*itr == value)
{
v.erase(itr);
}
else
++itr;
}
2) Efficient way ( RECOMMENDED ) : It is also known as ERASE - REMOVE idioms .
output of the remove algorithm is :
10 20 30 50 40 50
as return type of remove is iterator to the new end of that range.
template <class ForwardIterator, class T>
ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val);
Now use vector’s erase function to delete elements from the new end to old end of the vector. It requires O(1) time.
v.erase ( std :: remove (v.begin() , v.end() , element ) , v.end () );
so this method work in O(n)
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
Long.valueOf(String s) - obviously due care must be taken to protect against non-numbers if that is possible in your code.
For those who look for a safe client-side solution that also works on server-side, there is genversion. It is a command-line tool that reads the version from the nearest package.json and generates an importable CommonJS module file that exports the version. Disclaimer: I'm a maintainer.
$ genversion lib/version.js
I acknowledge the client-side safety was not OP's primary intention, but as discussed in answers by Mark Wallace and aug, it is highly relevant and also the reason I found this Q&A.
theres krugle and koders but both are expensive. Both have ide plugins for eclipse.
Update: This will create a second context same as in applicationContext.xml
or you can add this code snippet to your web.xml
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
instead of
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
Another table that is useful is:
SELECT * FROM user_objects WHERE object_type='TRIGGER';
You can also use this to query views, indexes etc etc
You can't. Full stop.
switch
is only for integral types, if you want to branch depending on a string you need to use if/else
.
I have a file called NewsArticle.txt on my Desktop.
In Spark, I typed:
val textFile= sc.textFile(“file:///C:/Users/582767/Desktop/NewsArticle.txt”)
I needed to change all the \ to / character for the filepath.
To test if it worked, I typed:
textFile.foreach(println)
I'm running Windows 7 and I don't have Hadoop installed.
I used DecimalFormat for formatting the BigDecimal instead of formatting the String, seems no problems with it.
The code is something like this:
bd = bd.setScale(2, BigDecimal.ROUND_DOWN);
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(0);
df.setGroupingUsed(false);
String result = df.format(bd);
Just in case you actually mean discard changes whenever you use git stash
(and don't really use git stash to stash it temporarily), in that case you can use
git checkout -- <file>
[NOTE]
That git stash
is just a quicker and simple alternative to branching and doing stuff.
If you have compatibility with Object.keys
, and node does have compatibility, you should use that for sure.
However, if you do not have compatibility, and for any reason using a loop function is out of the question - like me, I used the following solution:
JSON.stringify(obj) === '{}'
Consider this solution a 'last resort' use only if must.
See in the comments "there are many ways in which this solution is not ideal".
I had a last resort scenario, and it worked perfectly.
Instead of setting async to false which is usually bad design, you may want to consider blocking the UI while the operation is pending.
This can be nicely achieved with jQuery promises as follows:
// same as $.ajax but settings can have a maskUI property
// if settings.maskUI==true, the UI will be blocked while ajax in progress
// if settings.maskUI is other than true, it's value will be used as the color value while bloking (i.e settings.maskUI='rgba(176,176,176,0.7)'
// in addition an hourglass is displayed while ajax in progress
function ajaxMaskUI(settings) {
function maskPageOn(color) { // color can be ie. 'rgba(176,176,176,0.7)' or 'transparent'
var div = $('#maskPageDiv');
if (div.length === 0) {
$(document.body).append('<div id="maskPageDiv" style="position:fixed;width:100%;height:100%;left:0;top:0;display:none"></div>'); // create it
div = $('#maskPageDiv');
}
if (div.length !== 0) {
div[0].style.zIndex = 2147483647;
div[0].style.backgroundColor=color;
div[0].style.display = 'inline';
}
}
function maskPageOff() {
var div = $('#maskPageDiv');
if (div.length !== 0) {
div[0].style.display = 'none';
div[0].style.zIndex = 'auto';
}
}
function hourglassOn() {
if ($('style:contains("html.hourGlass")').length < 1) $('<style>').text('html.hourGlass, html.hourGlass * { cursor: wait !important; }').appendTo('head');
$('html').addClass('hourGlass');
}
function hourglassOff() {
$('html').removeClass('hourGlass');
}
if (settings.maskUI===true) settings.maskUI='transparent';
if (!!settings.maskUI) {
maskPageOn(settings.maskUI);
hourglassOn();
}
var dfd = new $.Deferred();
$.ajax(settings)
.fail(function(jqXHR, textStatus, errorThrown) {
if (!!settings.maskUI) {
maskPageOff();
hourglassOff();
}
dfd.reject(jqXHR, textStatus, errorThrown);
}).done(function(data, textStatus, jqXHR) {
if (!!settings.maskUI) {
maskPageOff();
hourglassOff();
}
dfd.resolve(data, textStatus, jqXHR);
});
return dfd.promise();
}
with this you can now do:
ajaxMaskUI({
url: url,
maskUI: true // or try for example 'rgba(176,176,176,0.7)'
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log('error ' + textStatus);
}).done(function (data, textStatus, jqXHR) {
console.log('success ' + JSON.stringify(data));
});
And the UI will block until the ajax command returns
see jsfiddle
$ python -c "import os.path; print os.path.relpath('/foo/bar', '/foo/baz/foo')"
gives:
../../bar
All the above solutions work great if you develop and run the Java application outside any IDE like Eclipse or Netbeans.
If you are on Windows 7 and used Eclipse IDE for Development in Java, you might run into issues if using Command Prompt to run the class files built inside Eclipse.
E.g. Your source code in Eclipse is having the following package hierarchy: edu.sjsu.myapp.Main.java
You have json.jar as an external dependency for the Main.java
When you try running Main.java from within Eclipse, it will run without any issues.
But when you try running this using Command Prompt after compiling Main.java in Eclipse, it will shoot some weird errors saying "ClassNotDef Error blah blah".
I assume you are in the working directory of your source code !!
Use the following syntax to run it from command prompt:
javac -cp ".;json.jar" Main.java
java -cp ".;json.jar" edu.sjsu.myapp.Main
[Don't miss the . above]
This is because you have placed the Main.java inside the package edu.sjsu.myapp and java.exe will look for the exact pattern.
Hope it helps !!
In my system its the \ key. it's used for commands so that you can combine it with other chars.
This is probably too late, but I had a similar problem with dates that I wanted entered into cells from a text variable. Inevitably, it converted my variable text value to a date. What I finally had to do was concatentate a ' to the string variable and then put it in the cell like this:
prvt_rng_WrkSht.Cells(prvt_rng_WrkSht.Rows.Count, cnst_int_Col_Start_Date).Formula = "'" & _
param_cls_shift.Start_Date (string property of my class)
It's work for Iphone
<?php
$browser = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
if ($browser == true){
$browser = 'iphone';
}
?>
I discovered the same problem and after reading the first answer that supposed the problem is caused by the window name, changed it : first to '_blank', which worked fine (both compatibility and regular view), then to the previous value, only minus the space in the value :) - also worked. IMO, the problem (or part of it) is caused by IE being unable to use a normal string value as the wname. Hope this helps if anybody runs into the same problem.
best answer written by Dmitri Korotkevitch:
Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.
If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:
Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode
Go to security/logins, open SA login properties
a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password
b. Assign password to SA user
c. Open "Status" tab and enable login.
I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.
.NET 4.0 edit
Since .NET 4.0, it is possible to access a single line of a file directly. For instance, to access line 15:
string line = File.ReadLines(FileName).Skip(14).Take(1).First();
This will return only the line required
Since you can't predict the location (can you?) of the i-th line in the file, you'll have to read all previous lines too. If the line number is small, this can be more efficient than the ReadAllLines
method.
string GetLine(string fileName, int line)
{
using (var sr = new StreamReader(fileName)) {
for (int i = 1; i < line; i++)
sr.ReadLine();
return sr.ReadLine();
}
}
<table border="1">
<tr>
<td>one</td>
<td style="border-bottom-style: hidden;">two</td>
</tr>
<tr>
<td>one</td>
<td style="border-top-style: hidden;">two</td>
</tr>
</table>
_x000D_
Given that the HTML datalist tag is still not fully supported, an alternate approach that I used is the Dojo Toolkit ComboBox. It was easier to implement and better documented than other options I've explored. It also plays nicely with existing frameworks. In my case, I added this combobox to an existing website that's based on Codeigniter and Bootstrap with no problems You just need to be sure to apply the Dojo theme (e.g. class="claro") to the combo's parent element instead of the body tag to avoid styling conflicts.
First, include the CSS for one of the Dojo themes (such as 'Claro'). It's important that the CSS file is included prior to the JS files below.
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/dojo/1.9.6/dijit/themes/claro/claro.css" />
Next, include jQuery and Dojo Toolkit via CDN
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.10.3/dojo/dojo.js"></script>
Next, you can just follow Dojo's sample code or use the sample below to get a working combobox.
<body>
<!-- Dojo Dijit ComboBox with 'Claro' theme -->
<div class="claro"><input id="item_name_1" class=""/></div>
<script type="text/javascript">
$(document).ready(function () {
//In this example, dataStore is simply an array of JSON-encoded id/name pairs
dataStore = [{"id":"43","name":"Domain Name Renewal"},{"id":"42","name":"Hosting Renewal"}];
require(
[ "dojo/store/Memory", "dijit/form/ComboBox", "dojo/domReady!"],
function (Memory, ComboBox) {
var stateStore = new Memory({
data: dataStore
});
var combo = new ComboBox({
id: "item_name_1",
name: "desc_1",
store: stateStore,
searchAttr: "name"},
"item_name_1"
).startup();
});
});
</script>
</body>
As @Felix Kling suggested use action='store_true'
:
>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True
To base64 it and put it in your clipboard:
file="test.docx"
base64 -w 0 $file | xclip -selection clipboard
The answers to your two questions are related. I'll start with the second:
Once you have staged a file (often with git add
, though some other commands implicitly stage the changes as well, like git rm
) you can back out that change with git reset -- <file>
.
In your case you must have used git rm
to remove the file, which is equivalent to simply removing it with rm
and then staging that change. If you first unstage it with git reset -- <file>
you can then recover it with git checkout -- <file>
.
There are no JS callbacks for CSS assets.
You cannot set or read cookies on CORS requests through JavaScript. Although CORS allows cross-origin requests, the cookies are still subject to the browser's same-origin policy, which means only pages from the same origin can read/write the cookie. withCredentials
only means that any cookies set by the remote host are sent to that remote host. You will have to set the cookie from the remote server by using the Set-Cookie
header.
Laravel raw sql – Insert query:
lets create a get link to insert data which is accessible through url . so our link name is ‘insertintodb’ and inside that function we use db class . db class helps us to interact with database . we us db class static function insert . Inside insert function we will write our PDO query to insert data in database . in below query we will insert ‘ my title ‘ and ‘my content’ as data in posts table .
put below code in your web.php file inside routes directory :
Route::get('/insertintodb',function(){
DB::insert('insert into posts(title,content) values (?,?)',['my title','my content']);
});
Now fire above insert query from browser link below :
localhost/yourprojectname/insertintodb
You can see output of above insert query by going into your database table .you will find a record with id 1 .
Laravel raw sql – Read query :
Now , lets create a get link to read data , which is accessible through url . so our link name is ‘readfromdb’. we us db class static function read . Inside read function we will write our PDO query to read data from database . in below query we will read data of id ‘1’ from posts table .
put below code in your web.php file inside routes directory :
Route::get('/readfromdb',function() {
$result = DB::select('select * from posts where id = ?', [1]);
var_dump($result);
});
now fire above read query from browser link below :
localhost/yourprojectname/readfromdb
If it's not a local application powered by JavaScript with full access permissions, you can't get the size of any file just from the path name. Web pages running javascript do not have access to the local filesystem for security reasons.
You can use a graceful degrading file uploader like SWFUpload if you want to show a progress bar. HTML5 also has the File API, but that is not widely supported just yet. If a user selects the file for an input[type=file]
element, you can get details about the file from the files
collection:
alert(myInp.files[0].size);
with SAP, you might be referring to a popular business software:
http://en.wikipedia.org/wiki/SAP_AG
And according to Wikipedia, ABAP is a programming language (short for Advanced Business Application Programming) created by SAP AG.
Call Path.GetFullPath on the combined path http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx
> Path.GetFullPath(Path.Combine(@"C:\blah\",@"..\bling"))
C:\bling
(I agree Path.Combine ought to do this by itself)
A server socket listens on a single port. All established client connections on that server are associated with that same listening port on the server side of the connection. An established connection is uniquely identified by the combination of client-side and server-side IP/Port pairs. Multiple connections on the same server can share the same server-side IP/Port pair as long as they are associated with different client-side IP/Port pairs, and the server would be able to handle as many clients as available system resources allow it to.
On the client-side, it is common practice for new outbound connections to use a random client-side port, in which case it is possible to run out of available ports if you make a lot of connections in a short amount of time.
You probably already installed an older version of node.js using a different method, so you need to manually remove the files that are getting in brew's way.
Do brew link -n node
and manually delete those conflicting files and directories, then try brew link node
again.
One option is to write a C/C++ wrapper that executes the python script on a regular basis. Your end-user would run the C/C++ executable, which would remain running in the background, and periodically execute the python script. This may not be the best solution, and may not work if you don't know C/C++ or want to keep this 100% python. But it does seem like the most user-friendly approach, since people are used to clicking on executables. All of this assumes that python is installed on your end user's computer.
Another option is to use cron job/Task Scheduler but to put it in the installer as a script so your end user doesn't have to do it.
>>> import datetime
>>> dt = datetime.datetime.now()
>>> datetime.datetime.date(dt)
datetime.date(2019, 4, 2)
For "Arrays":
If you know the index:
array.splice(index, 1);
If you know the value:
function removeItem(array, value) {
var index = array.indexOf(value);
if (index > -1) {
array.splice(index, 1);
}
return array;
}
The most upvoted answer for delete
works well in case of objects but not for the real arrays. If I use delete
it removes elements from loops but keeps the element as empty
and length of array wont change. This may be a problem in some scenarios.
For example, if I do myArray.toString() on myArray after removal via delete
, it creates an empty entry, i.e. ,,
.
Yes, you can achieve it by find_elements_by_css_selector("*")
or find_elements_by_xpath(".//*")
.
However, this doesn't sound like a valid use case to find all children of an element. It is an expensive operation to get all direct/indirect children. Please further explain what you are trying to do. There should be a better way.
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.stackoverflow.com")
header = driver.find_element_by_id("header")
# start from your target element, here for example, "header"
all_children_by_css = header.find_elements_by_css_selector("*")
all_children_by_xpath = header.find_elements_by_xpath(".//*")
print 'len(all_children_by_css): ' + str(len(all_children_by_css))
print 'len(all_children_by_xpath): ' + str(len(all_children_by_xpath))
Refer this:
@RequestMapping(value="download", method=RequestMethod.GET)
public void getDownload(HttpServletResponse response) {
// Get your file stream from wherever.
InputStream myStream = someClass.returnFile();
// Set the content type and attachment header.
response.addHeader("Content-disposition", "attachment;filename=myfilename.txt");
response.setContentType("txt/plain");
// Copy the stream to the response's output stream.
IOUtils.copy(myStream, response.getOutputStream());
response.flushBuffer();
}
You could use Role Strategy plugin for that purpose. It works like a charm, just setup some roles and assign them. Even on project-specific level.
You'll need to use fs
for that: http://nodejs.org/api/fs.html
And in particular the fs.rename()
function:
var fs = require('fs');
fs.rename('/path/to/Afghanistan.png', '/path/to/AF.png', function(err) {
if ( err ) console.log('ERROR: ' + err);
});
Put that in a loop over your freshly-read JSON object's keys and values, and you've got a batch renaming script.
fs.readFile('/path/to/countries.json', function(error, data) {
if (error) {
console.log(error);
return;
}
var obj = JSON.parse(data);
for(var p in obj) {
fs.rename('/path/to/' + obj[p] + '.png', '/path/to/' + p + '.png', function(err) {
if ( err ) console.log('ERROR: ' + err);
});
}
});
(This assumes here that your .json
file is trustworthy and that it's safe to use its keys and values directly in filenames. If that's not the case, be sure to escape those properly!)
Put this inside your package's __init__.py file:
# For relative imports to work in Python 3.6
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
Assuming your package is like this:
+-- project
¦ +-- package
¦ ¦ +-- __init__.py
¦ ¦ +-- module1.py
¦ ¦ +-- module2.py
¦ +-- setup.py
Now use regular imports in you package, like:
# in module2.py
from module1 import class1
This works in both python 2 and 3.
use mydb
db.createUser( { user: "test", pwd: "secret", roles: [ "readWrite", "dbAdmin"],passwordDigestor:"server" } )
Another solution using DataFrame.apply()
, with slightly less typing and more scalable when you want to join more columns:
cols = ['foo', 'bar', 'new']
df['combined'] = df[cols].apply(lambda row: '_'.join(row.values.astype(str)), axis=1)
It only comes when your list or dictionary not available in the local function.
Storing a list of strings in Django model:
class Bar(models.Model):
foo = models.TextField(blank=True)
def set_list(self, element):
if self.foo:
self.foo = self.foo + "," + element
else:
self.foo = element
def get_list(self):
if self.foo:
return self.foo.split(",")
else:
None
and you can call it like this:
bars = Bar()
bars.set_list("str1")
bars.set_list("str2")
list = bars.get_list()
if list is not None:
for bar in list:
print bar
else:
print "List is empty."
I create a student
table with three column id, student,age
. show you this example
declare @id int
select @id = 1
while @id >=1 and @id <= 1000
begin
insert into student values(@id, 'jack' + convert(varchar(5), @id), 12)
select @id = @id + 1
end
this is the result about the example
Found easiest way for me. Here an example with fork for clarity that this way is useful for flow control.
import signal
import time
import sys
import os
def handle_exit(sig, frame):
raise(SystemExit)
def main():
time.sleep(120)
signal.signal(signal.SIGTERM, handle_exit)
p = os.fork()
if p == 0:
main()
os._exit()
try:
os.waitpid(p, 0)
except (KeyboardInterrupt, SystemExit):
print('exit handled')
os.kill(p, 15)
os.waitpid(p, 0)
Personally, I loathe the preprocessor, so I'd always go with const
.
The main advantage to a #define
is that it requires no memory to store in your program, as it is really just replacing some text with a literal value. It also has the advantage that it has no type, so it can be used for any integer value without generating warnings.
Advantages of "const
"s are that they can be scoped, and they can be used in situations where a pointer to an object needs to be passed.
I don't know exactly what you are getting at with the "static
" part though. If you are declaring globally, I'd put it in an anonymous namespace instead of using static
. For example
namespace {
unsigned const seconds_per_minute = 60;
};
int main (int argc; char *argv[]) {
...
}
This is the easiest one , Just define a Function and then a Tkinter Label & Button . Pressing the Button changes the text in the label. The difference that you would when defining the Label is that use the text variable instead of text. Code is tested and working.
from tkinter import *
master = Tk()
def change_text():
my_var.set("Second click")
my_var = StringVar()
my_var.set("First click")
label = Label(mas,textvariable=my_var,fg="red")
button = Button(mas,text="Submit",command = change_text)
button.pack()
label.pack()
master.mainloop()
Try it using CONCAT
CONCAT('site.com/path/','%', CAST(t1.id AS CHAR(25)), '%','/more')
I found this brilliant solution here, it uses the simple logic NAN!=NAN. https://www.codespeedy.com/check-if-a-given-string-is-nan-in-python/
Using above example you can simply do the following. This should work on different type of objects as it simply utilize the fact that NAN is not equal to NAN.
import numpy as np
s = pd.Series(['apple', np.nan, 'banana'])
s.apply(lambda x: x!=x)
out[252]
0 False
1 True
2 False
dtype: bool
I have made a very useful method to add a string in a certain position in Python:
def insertChar(mystring, position, chartoinsert ):
longi = len(mystring)
mystring = mystring[:position] + chartoinsert + mystring[position:]
return mystring
for example:
a = "Jorgesys was here!"
def insertChar(mystring, position, chartoinsert ):
longi = len(mystring)
mystring = mystring[:position] + chartoinsert + mystring[position:]
return mystring
#Inserting some characters with a defined position:
print(insertChar(a,0, '-'))
print(insertChar(a,9, '@'))
print(insertChar(a,14, '%'))
we will have as an output:
-Jorgesys was here!
Jorgesys @was here!
Jorgesys was h%ere!
You need to turn on Show All Files
option on solution pane toolbar and include this file manually.
There is equally formatDate
const format = 'dd/MM/yyyy';
const myDate = '2019-06-29';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);
According to the API it takes as param either a date string, a Date object, or a timestamp.
Gotcha: Out of the box, only en-US
is supported.
If you need to add another locale, you need to add it and register it in you app.module, for example for Spanish:
import { registerLocaleData } from '@angular/common';
import localeES from "@angular/common/locales/es";
registerLocaleData(localeES, "es");
Don't forget to add corresponding import:
import { formatDate } from "@angular/common";
We can't talk about virtual members without referring to polymorphism. In fact, a function, property, indexer or event in a base class marked as virtual will allow override from a derived class.
By default, members of a class are non-virtual and cannot be marked as that if static, abstract, private, or override modifiers.
Example Let's consider the ToString() method in System.Object. Because this method is a member of System.Object it's inherited in all classes and will provide the ToString() methods to all of them.
namespace VirtualMembersArticle
{
public class Company
{
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
Company company = new Company() { Name = "Microsoft" };
Console.WriteLine($"{company.ToString()}");
Console.ReadLine();
}
}
}
The output of the previous code is:
VirtualMembersArticle.Company
Let's consider that we want to change the standard behavior of the ToString() methods inherited from System.Object in our Company class. To achieve this goal it's enough to use the override keyword to declare another implementation of that method.
public class Company
{
...
public override string ToString()
{
return $"Name: {this.Name}";
}
}
Now, when a virtual method is invoked, the run-time will check for an overriding member in its derived class and will call it if present. The output of our application will then be:
Name: Microsoft
In fact, if you check the System.Object class you will find that the method is marked as virtual.
namespace System
{
[NullableContextAttribute(2)]
public class Object
{
....
public virtual string? ToString();
....
}
}
from https://docs.angularjs.org/api/ng/function/angular.element
angular.element
wraps a raw DOM element or HTML string as a jQuery element (If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite.")
So you simply could do:
angular.module('myApp.filters', []).
filter('htmlToPlaintext', function() {
return function(text) {
return angular.element(text).text();
}
}
);
Usage:
<div>{{myText | htmlToPlaintext}}</div>
Without your seeing your data (you can use the output of dput(head(survey))
to show us) this is a shot in the dark:
survey <- data.frame(date=c("2012/07/26","2012/07/25"),tx_start=c("2012/01/01","2012/01/01"))
survey$date_diff <- as.Date(as.character(survey$date), format="%Y/%m/%d")-
as.Date(as.character(survey$tx_start), format="%Y/%m/%d")
survey
date tx_start date_diff
1 2012/07/26 2012/01/01 207 days
2 2012/07/25 2012/01/01 206 days
Button button = new Button();
button.Click += (s,e) => { your code; };
//button.Click += new EventHandler(button_Click);
container.Controls.Add(button);
//protected void button_Click (object sender, EventArgs e) { }
In order to get the current timestamp and not the time of when a fixed variable is defined, the trick is to use a function and not a variable:
#!/bin/bash
# Define a timestamp function
timestamp() {
date +"%T" # current time
}
# do something...
timestamp # print timestamp
# do something else...
timestamp # print another timestamp
# continue...
If you don't like the format given by the %T
specifier you can combine the other time conversion specifiers accepted by date
. For GNU date
, you can find the complete list of these specifiers in the official documentation here: https://www.gnu.org/software/coreutils/manual/html_node/Time-conversion-specifiers.html#Time-conversion-specifiers
You need to provide the full path to the file:
git show 27cf8e84bb88e24ae4b4b3df2b77aab91a3735d8:full/repo/path/to/my_file.txt
I know exactly what you mean. The same thing in Swift will be no problem. The bottom line is use let
, not var
.
The fact that primitives are passed by value, but the fact that the value of var i
at the point of iteration is not copied into the anonymous function is quite surprising to say the least.
for (let i = 0; i < boxArray.length; i++) {
boxArray[i].onclick = function() { console.log(i) }; // Correctly prints the index
}
Here's my twist on it, with a runnable example. Note this will only work in the situation where Id
is unique, and you have duplicate values in other columns.
DECLARE @SampleData AS TABLE (Id int, Duplicate varchar(20))
INSERT INTO @SampleData
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'
DELETE FROM @SampleData WHERE Id IN (
SELECT Id FROM (
SELECT
Id
,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
-- Change the partition columns to include the ones that make the row distinct
FROM
@SampleData
) a WHERE ItemNumber > 1 -- Keep only the first unique item
)
SELECT * FROM @SampleData
And the results:
Id Duplicate
----------- ---------
1 ABC
3 LMN
4 XYZ
Not sure why that's what I thought of first... definitely not the simplest way to go but it works.
This is a convention that programmer usually use to identify different file names for include files. So that if the other developers is working on their code, he can easily identify why this file is there and what is purpose of this file by just seeing the name of the file.
Just make a selector for tables inside a MyClass.
.MyClass td {border: solid 1px red;}
.MyClass table td {border: none}
(To generically apply to all inner tables, you could also do table table td
.)
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
For gcc you want to omit any -O1 -O2 or -O3 options passed to the compiler or if you already have them you can append the -O0 option to turn it off again. It might also help you to add -g for debug so that you can see the c source and disassembled machine code in your debugger.
See also: http://sourceware.org/gdb/onlinedocs/gdb/Optimized-Code.html
I got the same exception when I locally tested. The problem was a URL schema in my request.
Change https:// to http:// in your client url.
Probably it helps.
IIUC you want the number of different ID
for every domain
, then you can try this:
output = df.drop_duplicates()
output.groupby('domain').size()
output:
domain
facebook.com 1
google.com 1
twitter.com 2
vk.com 3
dtype: int64
You could also use value_counts
, which is slightly less efficient.But the best is Jezrael's answer using nunique
:
%timeit df.drop_duplicates().groupby('domain').size()
1000 loops, best of 3: 939 µs per loop
%timeit df.drop_duplicates().domain.value_counts()
1000 loops, best of 3: 1.1 ms per loop
%timeit df.groupby('domain')['ID'].nunique()
1000 loops, best of 3: 440 µs per loop
There is also an experimental technology called Broadcast Channel API
that is designed specifically for communication between different browser contexts with same origin. You can post messages to and recieve messages from another browser context without having a reference to it:
var channel = new BroadcastChannel("foo");
channel.onmessage = function( e ) {
// Process messages from other contexts.
};
// Send message to other listening contexts.
channel.postMessage({ value: 42, type: "bar"});
Obviously this is experiental technology and is not supported accross all browsers yet.
We can resolve this problem without using JQuery and other libs.
I wrote following code for this purpose:
You have similar structure ->
<div class="parent">
<div class="child-one">
</div>
<div class="child-two">
</div>
</div>
JS:
scrollToElement() {
var parentElement = document.querySelector('.parent');
var childElement = document.querySelector('.child-two');
parentElement.scrollTop = childElement.offsetTop - parentElement.offsetTop;
}
We can easily rewrite this method for passing parent and child as an arguments
I know it is very late but following approach can also be used:
<select id="type" name="type" >
<option value="Permanent" id="permanent">I am here to stay.</option>
<option value="toremove" id="toremove">Remove me!</option>
<option value="Other" id="other">Other</option>
</select>
and if I have to remove second option (id=toremove), the script would look like
$('#toremove').hide();
Short answer: You can't. rm
removes files blindly, with no concept of 'trash'.
Some Unix and Linux systems try to limit its destructive ability by aliasing it to rm -i
by default, but not all do.
Long answer: Depending on your filesystem, disk activity, and how long ago the deletion occured, you may be able to recover some or all of what you deleted. If you're using an EXT3 or EXT4 formatted drive, you can check out extundelete
.
In the future, use rm
with caution. Either create a del
alias that provides interactivity, or use a file manager.
You, can also try like this, PictureBox1.Image = Image.FromFile("<your ImagePath>" or <Dialog box result>);
kw=(EditText)findViewById(R.id.kw);
btn=(Button)findViewById(R.id.btn);
cost=(TextView )findViewById(R.id.cost);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { cst = Double.valueOf(kw.getText().toString());
cst = cst*0.551;
cost.setText(cst.toString());
}
});
It's a unicode character. In this case \u003C
and \u003E
mean :
U+003C < Less-than sign
U+003E > Greater-than sign
See a list here
Form values in HTTP POSTs are sent in the request body, in the same format as the querystring.
For more information, see the spec.
<?php _x000D_
$con = mysqli_connect("localhost","root","root","EmpDB") or die(mysqli_error($con));_x000D_
if(isset($_POST[add]))_x000D_
{_x000D_
$sno = mysqli_real_escape_string($con,$_POST[sno]);_x000D_
$name = mysqli_real_escape_string($con,$_POST[sname]);_x000D_
$course = mysqli_real_escape_string($con,$_POST[course]);_x000D_
_x000D_
$query = "insert into students(sno,name,course) values($sno,'$name','$course')";_x000D_
//echo $query;_x000D_
$result = mysqli_query($con,$query);_x000D_
printf ("New Record has id %d.\n", mysqli_insert_id($con));_x000D_
mysqli_close($con);_x000D_
_x000D_
} _x000D_
?>_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<title>mysql_insert_id Example</title>_x000D_
</head>_x000D_
<body>_x000D_
<form action="" method="POST">_x000D_
Enter S.NO: <input type="text" name="sno"/><br/>_x000D_
Enter Student Name: <input type="text" name="sname"/><br/>_x000D_
Enter Course: <input type="text" name="course"/><br/>_x000D_
<input type="submit" name="add" value="Add Student"/>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
I found the answer.
You can configure IE8 to display application/json in the browser window by updating the registry. There's no need for an external tool. I haven't tested this broadly, but it works with IE8 on Vista.
To use this, remember, all the usual caveats about updating the registry apply. Stop IE. Then, cut and paste the following into a file, by the name of json-ie.reg
.
Windows Registry Editor Version 5.00
;
; Tell IE to open JSON documents in the browser.
; 25336920-03F9-11cf-8FD0-00AA00686F13 is the CLSID for the "Browse in place" .
;
[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00
[HKEY_CLASSES_ROOT\MIME\Database\Content Type\text/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00
Then double-click the .reg file. Restart IE. The new behavior you get when tickling a URL that returns a doc with Content-Type: application/json
or Content-Type: text/json
is like this:
What it does, why it works:
The 25336920-03F9-11cf-8FD0-00AA00686F13
is the CLSID for the "Browse in place" action. Basically this registry entry is telling IE that for docs that have a mime type of application/json, just view it in place. This won't affect any application/json documents downloaded via <script>
tags, or via XHR, and so on.
The CLSID and Encoding keys get the same values used for image/gif
, image/jpeg
, and text/html
.
This hint came from this site, and from Microsoft's article Handling MIME Types in Internet Explorer .
In FF, you don't need an external add-on either. You can just use the view-source:
pseudo-protocol. Enter a URL like this into the address bar:
view-source:http://myserver/MyUrl/That/emits/Application/json
This pseudo-protocol used to be supported in IE, also, until WinXP-sp2, when Microsoft disabled it for security reasons.
You functionally want this:
#include <sys/time.h>
struct timeval tv1, tv2;
gettimeofday(&tv1, NULL);
/* stuff to do! */
gettimeofday(&tv2, NULL);
printf ("Total time = %f seconds\n",
(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
(double) (tv2.tv_sec - tv1.tv_sec));
Note that this measures in microseconds, not just seconds.
This is an old question but encountered it myself.
I have semi-solutions that work situational for the former question("Children visible in overflow:hidden parent")
If the parent div does not need to be position:relative, simply set the children styles to visibility:visible.
If the parent div does need to be position:relative, the only way possible I found to show the children was position:fixed. This worked for me in my situation luckily enough but I would imagine it wouldn't work in others.
Here is a crappy example just post into a html file to view.
<div style="background: #ff00ff; overflow: hidden; width: 500px; height: 500px; position: relative;">
<div style="background: #ff0000;position: fixed; top: 10px; left: 10px;">asd
<div style="background: #00ffff; width: 200px; overflow: visible; position: absolute; visibility: visible; clear:both; height: 1000px; top: 100px; left: 10px;"> a</div>
</div>
</div>
Open Terminal and execute commands given below.
cd /etc
subl bashrc
subl denotes Sublime editor. You can replace subl with vi to open bashrc file in default editor. This will workout only if you have bashrc file, created earlier.
If you are using Sass:
$card-column-sizes: (
xs: 2,
sm: 3,
md: 4,
lg: 5,
);
@each $breakpoint-size, $column-count in $card-column-sizes {
@include media-breakpoint-up($breakpoint-size) {
.card-columns {
column-count: $column-count;
column-gap: 1.25rem;
.card {
display: inline-block;
width: 100%; // Don't let them exceed the column width
}
}
}
}
I'd recommend application/octet-stream
as RFC2046 says "The "octet-stream" subtype is used to indicate that a body contains arbitrary binary data" and "The recommended action for an implementation that receives an "application/octet-stream" entity is to simply offer to put the data in a file[...]".
I think that way you will get better handling from arbitrary programs, that might barf when encountering your unknown mime type.
For Windows/WSL/Cygwin etc users:
Make sure that your line endings are standard Unix line feeds, i.e. \n
(LF) only.
Using Windows line endings \r\n
(CRLF) line endings will break the command line break.
This is because having \
at the end of a line with Windows line ending translates to
\
\r
\n
.
As Mark correctly explains above:
The line-continuation will fail if you have whitespace after the backslash and before the newline.
This includes not just space () or tabs (
\t
) but also the carriage return (\r
).
Even better approach using array's join method
var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var list = '<ul class="myList"><li class="ui-menu-item" role="menuitem"><a class="ui-all" tabindex="-1">' + countries.join('</a></li><li>') + '</li></ul>';
In addition to Cody's useful comments it is worth noting that at times you won't know how big your array should be. The two options in this situation are
Redim Preserve
The code below provides an example of a routine that will dimension myArray
in line with the lngSize
variable, then add additional elements (equal to the initial array size) by use of a Mod
test whenever the upper bound is about to be exceeded
Option Base 1
Sub ArraySample()
Dim myArray() As String
Dim lngCnt As Long
Dim lngSize As Long
lngSize = 10
ReDim myArray(1 To lngSize)
For lngCnt = 1 To lngSize*5
If lngCnt Mod lngSize = 0 Then ReDim Preserve myArray(1 To UBound(myArray) + lngSize)
myArray(lngCnt) = "I am record number " & lngCnt
Next
End Sub
request parameter exist for both GET and POST ,For Get it will get appended as query string to URL but for POST it is within Request Body
Possibly not applicable for your situation, but here's the jQuery function I use for reloading external stylesheets:
/**
* Forces a reload of all stylesheets by appending a unique query string
* to each stylesheet URL.
*/
function reloadStylesheets() {
var queryString = '?reload=' + new Date().getTime();
$('link[rel="stylesheet"]').each(function () {
this.href = this.href.replace(/\?.*|$/, queryString);
});
}
I'm not sure if this works for you, but when I do small solo PHP projects with Eclipse, the first thing I set up is an Ant script for deploying the project to a remote testing environment. I code away locally, and whenever I want to test it, I just hit the shortcut which updates the remote site.
Eclipse has good Ant support out of the box, and the scripts aren't hard to make.
headers = { 'User-Agent' : 'Mozilla/5.0' }
req = urllib2.Request('www.example.com', None, headers)
html = urllib2.urlopen(req).read()
Or, a bit shorter:
req = urllib2.Request('www.example.com', headers={ 'User-Agent': 'Mozilla/5.0' })
html = urllib2.urlopen(req).read()
The Status Value being returned by a Stored Procedure can only be an INT datatype. You cannot return other datatypes in the RETURN statement.
From Lesson 2: Designing Stored Procedures:
Every stored procedure can return an integer value known as the execution status value or return code.
If you still want a table returned from the SP, you'll either have to work the record set returned from a SELECT within the SP or tie into an OUTPUT variable that passes an XML datatype.
HTH,
John
In this answer there is also the best answer I found to your question:
HTML table with fixed headers?
and based on pure CSS.
As of Python3 you no longer need to open devnull and can call subprocess.DEVNULL.
Your code would be updated as such:
import subprocess
text = 'Hello World.'
print(text)
subprocess.call(['espeak', text], stderr=subprocess.DEVNULL)
For the current date activity and complete activity for previous 30 days use this, since the SYSDATE is variable in a day the previous 30th day will not have the whole data for that day.
SELECT DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND SYSDATE()
I downloaded ant (http://ant.apache.org/bindownload.cgi), unzipped to my C drive, and used the windows 'doskey' command:
doskey ant=C:\apache-ant-1.9.6\bin\ant.bat $*
this will work as long as you use the same command console, to make it permanent is more difficult: http://darkforge.blogspot.com/2010/08/permanent-windows-command-line-aliases.html
AFNetworking for Android:
Fast Android Networking is here
Fast Android Networking Library supports all types of HTTP/HTTPS request like GET, POST, DELETE, HEAD, PUT, PATCH
Fast Android Networking Library supports downloading any type of file
Fast Android Networking Library supports uploading any type of file (supports multipart upload)
Fast Android Networking Library supports cancelling a request
Fast Android Networking Library supports setting priority to any request (LOW, MEDIUM, HIGH, IMMEDIATE)
Fast Android Networking Library supports RxJava
As it uses OkHttp as a networking layer, it supports:
Fast Android Networking Library supports HTTP/2 support allows all requests to the same host to share a socket
Fast Android Networking Library uses connection pooling which reduces request latency (if HTTP/2 isn’t available)
Transparent GZIP shrinks download sizes
Fast Android Networking Library supports response caching which avoids the network completely for repeat requests
Thanks: The library is created by me
Under the Links Tab ==> Edit the URL Item ==> Under the URL (Type the Web address)- format the value as follows:
Example: if the URL = http://www.abc.com ==> then suffix the value with ==>
SO, the final value should read as ==> http://www.abc.com#openinnewwindow/,'" target="http://www.abc.com'
DONE ==> this will open the URL in New Window
The for each
syntax is supported as an extension to native c++ in Visual Studio.
The example provided in msdn
#include <vector>
#include <iostream>
using namespace std;
int main()
{
int total = 0;
vector<int> v(6);
v[0] = 10; v[1] = 20; v[2] = 30;
v[3] = 40; v[4] = 50; v[5] = 60;
for each(int i in v) {
total += i;
}
cout << total << endl;
}
(works in VS2013) is not portable/cross platform but gives you an idea of how to use for each
.
The standard alternatives (provided in the rest of the answers) apply everywhere. And it would be best to use those.
K. Scott Allen has a nice writeup on the matter.
Basically, they differ on how they handle function arguments.
The apply() method is identical to call(), except apply() requires an array as the second parameter. The array represents the arguments for the target method."
So:
// assuming you have f
function f(message) { ... }
f.call(receiver, "test");
f.apply(receiver, ["test"]);
From another answer:
A little history
Remember, there is nothing inherently special about $
. It is a variable name just like any other. In earlier days, people used to write code using document.getElementById. Because JavaScript is case-sensitive, it was normal to make a mistake while writing document.getElementById
. Should I capital 'b'
of 'by'
? Should I capital 'i'
of Id?
You get the drift. Because functions are first-class citizens in JavaScript, you can always do this:
var $ = document.getElementById; //freedom from document.getElementById!
When Prototype library arrived, they named their function, which gets the DOM elements, as '$'
. Almost all the JavaScript libraries copied this idea. Prototype also introduced a $$
function to select elements using CSS selector.
jQuery also adapted $
function but expanded to make it accept all kinds of 'selectors' to get the elements you want. Now, if you are already using Prototype in your project and wanted to include jQuery, you will be in problem as '$'
could either refer to Prototype's implementation OR jQuery's implementation. That's why jQuery has the option of noConflict so that you can include jQuery in your project which uses Prototype and slowly migrate your code. I think this was a brilliant move on John's part! :)
Simply use the separator image as a background image on the li
.
To get it to only appear in between list items, position the image to the left of the li
, but not on the first one.
For example:
#nav li + li {
background:url('seperator.gif') no-repeat top left;
padding-left: 10px
}
This CSS adds the image to every list item that follows another list item - in other words all of them but the first.
NB. Be aware the adjacent selector (li + li) doesn't work in IE6, so you will have to just add the background image to the conventional li (with a conditional stylesheet) and perhaps apply a negative margin to one of the edges.
The state is the origin of truth, where your data lives. You can say the state manifests itself via props.
Providing props to components is what keeps your UI in sync with your data. A component is really just a function that returns markup.
Given the same props (data for it to display) it will always produce the same markup.
So the props are like the pipelines that carry the data from the origin to the functional components.
# or even faster copy paste answer if you have sudo on the host
sudo su - postgres -c "psql template1 -c 'CREATE EXTENSION IF NOT EXISTS \"dblink\";'"
This is a good case for using another thread:
// Call some method
this.Method();
Task.Factory.StartNew(() =>
{
Thread.Sleep(20000);
// Do things here.
// NOTE: You may need to invoke this to your main thread depending on what you're doing
});
The above code expects .NET 4.0 or above, otherwise try:
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
{
Thread.Sleep(20000);
// Do things here
}));
Here is a simplified running example of Seattle Ninja's solution.
var slideSource = document.getElementById('slideSource');_x000D_
_x000D_
document.getElementById('handle').onclick = function () {_x000D_
slideSource.classList.toggle('fade');_x000D_
}
_x000D_
#slideSource {_x000D_
opacity: 1;_x000D_
transition: opacity 1s; _x000D_
}_x000D_
_x000D_
#slideSource.fade {_x000D_
opacity: 0;_x000D_
}
_x000D_
<button id="handle">Fade</button> _x000D_
<div id="slideSource">Whatever you want here - images or text</div>
_x000D_
This worked for me:-
<!DOCTYPE html>
<html>
<head>
<title>CAR APPLICATION</title>
</head>
<body>
<center>
<h1>CAR APPLICATION</h1>
</center>
<table border="5" bordercolor="red" align="center">
<tr>
<th colspan="3">ABCD</th>
</tr>
<tr>
<th>Name</th>
<th>Origin</th>
<th>Photo</th>
</tr>
<tr>
<td>Bugatti Veyron Super Sport</th>
<td>Molsheim, Alsace, France</th>
<!-- considering it is on the same folder that .html file -->
<td><img src=".\A.jpeg" alt="" border=3 height=100 width=300></img></th>
</tr>
<tr>
<td>SSC Ultimate Aero TT TopSpeed</th>
<td>United States</th>
<td border=3 height=100 width=100>Photo1</th>
</tr>
<tr>
<td>Koenigsegg CCX</th>
<td>Ängelholm, Sweden</th>
<td border=4 height=100 width=300>Photo1</th>
</tr>
<tr>
<td>Saleen S7</th>
<td>Irvine, California, United States</th>
<td border=3 height=100 width=100>Photo1</th>
</tr>
<tr>
<td> McLaren F1</th>
<td>Surrey, England</th>
<td border=3 height=100 width=100>Photo1</th>
</tr>
<tr>
<td>Ferrari Enzo</th>
<td>Maranello, Italy</th>
<td border=3 height=100 width=100>Photo1</th>
</tr>
<tr>
<td> Pagani Zonda F Clubsport</th>
<td>Modena, Italy</th>
<td border=3 height=100 width=100>Photo1</th>
</tr>
</table>
</body>
<html>
#!/bin/bash
set -e
_onexit() {
[[ $TMPD ]] && rm -rf "$TMPD"
}
TMPD="$(mktemp -d)"
trap _onexit EXIT
_time_2() {
"$@" 2>&3
}
_time_1() {
time _time_2 "$@"
}
_time() {
declare time_label="$1"
shift
exec 3>&2
_time_1 "$@" 2>"$TMPD/timing.$time_label"
echo "time[$time_label]"
cat "$TMPD/timing.$time_label"
}
_time a _do_something
_time b _do_another_thing
_time c _finish_up
This has the benefit of not spawning sub shells, and the final pipeline has it's stderr restored to the real stderr.
Deleting this line fixes it, but the problem is the boostrap files are in bower_components
and not checked into source control.
So, every developer on the team will get the css file with the map reference when they pull the repo and do bower install
(which is part of using a new repo).
The file should not have the reference to a map that is not there.
I was facing the same problem, following code worked for me:
$params = (array) json_decode(file_get_contents('php://input'), TRUE);
print_r($params);
Actualy the Gabin Smith's answer needs to be changed a bit to work, because you can't resume with without an error.
Sub MyFunc()
...
For Each oSheet In ActiveWorkbook.Sheets
On Error GoTo errHandler:
Set qry = oSheet.ListObjects(1).QueryTable
oCmbBox.AddItem oSheet.name
...
NextSheet:
Next oSheet
...
Exit Sub
errHandler:
Resume NextSheet
End Sub
If you just want to process command line options yourself, the easiest way is to put:
vector<string> args(argv + 1, argv + argc);
at the top of your main()
. This copies all command-line arguments into a vector of std::string
s. Then you can use ==
to compare strings easily, instead of endless strcmp()
calls. For example:
int main(int argc, char **argv) {
vector<string> args(argv + 1, argv + argc);
string infname, outfname;
// Loop over command-line args
// (Actually I usually use an ordinary integer loop variable and compare
// args[i] instead of *i -- don't tell anyone! ;)
for (auto i = args.begin(); i != args.end(); ++i) {
if (*i == "-h" || *i == "--help") {
cout << "Syntax: foomatic -i <infile> -o <outfile>" << endl;
return 0;
} else if (*i == "-i") {
infname = *++i;
} else if (*i == "-o") {
outfname = *++i;
}
}
}
[EDIT: I realised I was copying argv[0]
, the name of the program, into args
-- fixed.]
Combining some answers here you can use something like the following.
class BaseActivity extends SherlockFragmentActivity
{
// Backwards compatible recreate().
@Override
public void recreate()
{
if (android.os.Build.VERSION.SDK_INT >= 11)
{
super.recreate();
}
else
{
startActivity(getIntent());
finish();
}
}
}
I tested it a bit, and there are some problems:
startActivity(...); finish();
just exist the app and doesn't restart the activity.super.recreate()
doesn't actually act the same way as totally recreating the activity. It is equivalent to rotating the device so if you have any Fragment
s with setRetainInstance(true)
they won't be recreated; merely paused and resumed.So currently I don't believe there is an acceptable solution.
Use numpy.append
:
>>> a = np.array([[1,2,3],[2,3,4]])
>>> a
array([[1, 2, 3],
[2, 3, 4]])
>>> z = np.zeros((2,1), dtype=int64)
>>> z
array([[0],
[0]])
>>> np.append(a, z, axis=1)
array([[1, 2, 3, 0],
[2, 3, 4, 0]])
I've created a library for parsing User Agent strings called Voodoo. But be aware that this should not be used instead of feature detection.
What Voodoo does, is that it parses the userAgent string, which is found in the Navigator object (window.navigator). It's not all browsers that passes a reliable userAgent string, so even though it's the normal way to do it, the userAgent can not always be trusted.
The solution you posted seems to work in stopping the zoom controls from appearing when the user drags, however there are situations where a user will pinch zoom and the zoom controls will appear. I've noticed that there are 2 ways that the webview will accept pinch zooming, and only one of them causes the zoom controls to appear despite your code:
User Pinch Zooms and controls appear:
ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_2_UP
ACTION_UP
User Pinch Zoom and Controls don't appear:
ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_1_UP
ACTION_POINTER_UP
ACTION_UP
Can you shed more light on your solution?
I've fixed that problem by creating test rails project and install all gems then I've replaced my current Gemfile.lock with the test and all thing works fine.
I think that this problem from bundler
versions with hosting, so please make sure that hosting bundler is the same version with your project.
If you're interested in a GUI for this, take a look at objbrowser. It uses the inspect module from the Python standard library for the object introspection underneath.
var myItem = myList.Find(item => item.property == "something");
var express = require('express')
app = module.exports = express();
var secureServer = require('http').createServer(app);
secureServer.listen(3001);
var aws = require('aws-sdk')
var multer = require('multer')
var multerS3 = require('multer-s3')
aws.config.update({
secretAccessKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
accessKeyId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
region: 'us-east-1'
});
s3 = new aws.S3();
var upload = multer({
storage: multerS3({
s3: s3,
dirname: "uploads",
bucket: "Your bucket name",
key: function (req, file, cb) {
console.log(file);
cb(null, "uploads/profile_images/u_" + Date.now() + ".jpg"); //use
Date.now() for unique file keys
}
})
});
app.post('/upload', upload.single('photos'), function(req, res, next) {
console.log('Successfully uploaded ', req.file)
res.send('Successfully uploaded ' + req.file.length + ' files!')
})
I was trying to map an IEnumerable to an object. This is way I got this error. Maybe it helps.
You should use $_FILES[$form_name]['error']
. It returns UPLOAD_ERR_NO_FILE
if no file was uploaded. Full list: PHP: Error Messages Explained
function isUploadOkay($form_name, &$error_message) {
if (!isset($_FILES[$form_name])) {
$error_message = "No file upload with name '$form_name' in form.";
return false;
}
$error = $_FILES[$form_name]['error'];
// List at: http://php.net/manual/en/features.file-upload.errors.php
if ($error != UPLOAD_ERR_OK) {
switch ($error) {
case UPLOAD_ERR_INI_SIZE:
$error_message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
break;
case UPLOAD_ERR_FORM_SIZE:
$error_message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
break;
case UPLOAD_ERR_PARTIAL:
$error_message = 'The uploaded file was only partially uploaded.';
break;
case UPLOAD_ERR_NO_FILE:
$error_message = 'No file was uploaded.';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$error_message = 'Missing a temporary folder.';
break;
case UPLOAD_ERR_CANT_WRITE:
$error_message = 'Failed to write file to disk.';
break;
case UPLOAD_ERR_EXTENSION:
$error_message = 'A PHP extension interrupted the upload.';
break;
default:
$error_message = 'Unknown error';
break;
}
return false;
}
$error_message = null;
return true;
}
Even though this question is answered, providing an example as to what "theirs" and "ours" means in the case of git rebase vs merge. See this link
Git Rebase
theirs
is actually the current branch in the case of rebase. So the below set of commands are actually accepting your current branch changes over the remote branch.
# see current branch
$ git branch
...
* branch-a
# rebase preferring current branch changes during conflicts
$ git rebase -X theirs branch-b
Git Merge
For merge, the meaning of theirs
and ours
is reversed. So, to get the same effect during a merge, i.e., keep your current branch changes (ours
) over the remote branch being merged (theirs
).
# assuming branch-a is our current version
$ git merge -X ours branch-b # <- ours: branch-a, theirs: branch-b
We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.
Check your linker flags:
Target > Build Settings > Other Linker Flags
You should see -lApptentiveConnect
listed as a linker flag:
... -ObjC -lApptentiveConnect ...
You should also see our required Frameworks listed:
UIKit
-ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit
WooCommerce has a number of options for modifying the cart, and checkout pages. Here are the three I'd recomend:
is_cart()
and is_checkout()
functions return true on their page. Example:
if ( is_cart() || is_checkout() ) {
echo "This is the cart, or checkout page!";
}
The main, cart template file is located at wp-content/themes/{current-theme}/woocommerce/cart/cart.php
The main, checkout template file is located at wp-content/themes/{current-theme}/woocommerce/checkout/form-checkout.php
To edit these, first copy them to your child theme.
wp-content/themes/{current-theme}/page-{slug}.php
page-{slug}.php
is the second template that will be used, coming after manually assigned ones through the WP dashboard.
This is safer than my other solutions, because if you remove WooCommerce, but forget to remove this file, the code inside (that may rely on WooCommerce functions) won't break, because it's never called (unless of cause you have a page with slug {slug}
).
For example:
wp-content/themes/{current-theme}/page-cart.php
wp-content/themes/{current-theme}/page-checkout.php
Easiar approach on datatable could be:
int minLavel = Convert.ToInt32(dt.Compute("min([AccountLevel])", string.Empty));
from php you can invoke jquery like this but my 2nd method is much cleaner and better for php
if($switchView) :?>
<script>$('.container').hide();</script>
<script>$('.confirm').show();</script>
<?php endif;
another way is to initiate your class and dynamically invoke the condition like this
$registerForm ='block';
then in your html use this
<div class="col" style="display: <?= $registerForm?>">
now you can play with the view with if and else easily without having a messed code example
if($condition) registerForm = 'none';
Make sure you use 'block' to show and 'none' to hide. This is far the easiest way with php
In addition to Shayne3000's answer you can also use a color resource (not only an int color). Kotlin version:
var indicatorViewDrawable = itemHolder.indicatorView.background
indicatorViewDrawable = DrawableCompat.wrap(indicatorViewDrawable)
val color = ResourcesCompat.getColor(context.resources, R.color.AppGreenColor, null) // get your color from resources
DrawableCompat.setTint(indicatorViewDrawable, color)
itemHolder.indicatorView.background = indicatorViewDrawable
To do this easily, the use of Stack
is better. Create a Stack
Then inside Stack add Align
or Positioned
and set position according to your needed, You can add multiple Container
.
Container
child: Stack(
children: <Widget>[
Align(
alignment: FractionalOffset.center,
child: Text(
"? 1000",
)
),
Positioned(
bottom: 0,
child: Container(
width: double.infinity,
height: 30,
child: Text(
"Balance", ,
)
),
)
],
)
)
Stack
a widget that positions its children relative to the edges of its box.
Stack
class is useful if you want to overlap several children in a simple way, for example having some text and an image, overlaid with a gradient and a button attached to the bottom.