setTimeout(() => { // your code here }, 0);
I wrapped my code in setTimeout and it worked
This answer may help you if you are using Karma:
I've did exactly as it's mentioned in @wmnitin's answer, but the error was always there. When use "ng serve" instead of "karma start", it works !
This is how I do it...
import pyodbc
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=server_name;"
"Database=db_name;"
"Trusted_Connection=yes;")
cursor = cnxn.cursor()
cursor.execute('SELECT * FROM Table')
for row in cursor:
print('row = %r' % (row,))
Relevant resources:
Tested in Ubuntu 16.04
# Create the docker group and add your user to the docker group
groupadd docker
usermod -aG docker $USER
newgrp docker
# Configure docker service to be exposed
mkdir -p /etc/systemd/system/docker.service.d
echo -e '[Service]\nExecStart=\nExecStart=/usr/bin/dockerd -H fd:// -H tcp://0.0.0.0:2376' >> /etc/systemd/system/docker.service.d/override.conf
# restart service
systemctl daemon-reload
service docker restart
That error means that a function call is only matched by an existing function if all its arguments are of the same type and passed in same order. So if the next f()
function
create function f() returns integer as $$
select 1;
$$ language sql;
is called as
select f(1);
It will error out with
ERROR: function f(integer) does not exist
LINE 1: select f(1);
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
because there is no f()
function that takes an integer as argument.
So you need to carefully compare what you are passing to the function to what it is expecting. That long list of table columns looks like bad design.
Make sure you have closed your MSAccess file before running the java program.
I came across this because I was trying to load a JSON file dumped from MongoDB. It was giving me an error
JSONDecodeError: Extra data: line 2 column 1
The MongoDB JSON dump has one object per line, so what worked for me is:
import json
data = [json.loads(line) for line in open('data.json', 'r')]
I fixed this problem with sql command line:
connect system/<password>
alter system set processes=300 scope=spfile;
alter system set sessions=300 scope=spfile;
Restart database.
Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.
import java.sql.*;
public class UserLogin
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// C:\\databaseFileName.accdb" - location of your database
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";
// specify url, username, pasword - make sure these are valid
Connection conn = DriverManager.getConnection(url, "username", "password");
System.out.println("Connection Succesfull");
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
The immediate cause of the problem is that the JDBC driver has attempted to read from a network Socket that has been closed by "the other end".
This could be due to a few things:
If the remote server has been configured (e.g. in the "SQLNET.ora" file) to not accept connections from your IP.
If the JDBC url is incorrect, you could be attempting to connect to something that isn't a database.
If there are too many open connections to the database service, it could refuse new connections.
Given the symptoms, I think the "too many connections" scenario is the most likely. That suggests that your application is leaking connections; i.e. creating connections and then failing to (always) close them.
One possibility that I haven't seen widely discussed is that there may be a problem resolving the hostname on the host machine itself. If there is no entry for $(hostname) in /etc/hosts, the Oracle listener gets confused and wont come up.
That turned out to be my problem, and adding the hostname and ip address in /etc/hosts resolved the problem.
First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.
At first I tried Berislav Lopac's answer, but I got Connection problem or invalid MMI code.
when I tried to dial *#9900#
. I was using CyanogenMod on the phone, and I believe phones with custom ROMs don't use the stock dialer, so they lack the SysDump functionality.
Basically, Delete dumpstate/logcat
in SysDump clears out the log files in /data/log
. But you can also do this manually without SysDump. (This is assuming your phone has been rooted, which will be the case if your phone is running CyanogenMod or any other non-stock ROM.)
su
, hit return.cd /data/log
, followed by return.data/log
directory by typing in pwd
, followed by return. It should print out the present working directory you are in: /data/log
. It is very important to make sure you are in the right directory as the next step removes all files in whatever working directory you presently are in.rm *
, followed by return.exit
to leave the su
session.I deleted roughly 1,500 1 MB files like this and fixed my "Insufficient Storage Available" problem.
As with the other posters, I own a Galaxy S II, so it seems to be a problem with that model.
If anyone knows of the permanent solution to stop the log files building up, please let me know.
NOTE: Some file managers will falsely list /data/log
to be empty as they are running unprivileged and hence lack the permissions to view the files inside.
In the case of nested tables, some DBMS require to use an alias like MySQL and Oracle but others do not have such a strict requirement, but still allow to add them to substitute the result of the inner query.
if you have only one xml in your table, you can convert it in 2 steps:
CREATE TABLE Batches(
BatchID int,
RawXml xml
)
declare @xml xml=(select top 1 RawXml from @Batches)
SELECT --b.BatchID,
x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM @xml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol)
If you are using eclipse, you should modify the context.xml, from the server project created in your eclipse package explorer. When using tomcat in eclipse it is the only one valid, the others are ignored or overwriten
As far as a clean process is concerned you can use ByteArrayOutputStream object...
ByteArrayOutputStream bObj = new ByteArrayOutputStream();
bObj.reset();
//write all the values to bObj one by one using
bObj.write(byte value)
// when done you can get the byte[] using
CDRIVES = bObj.toByteArray();
//than you can repeat the similar process for CMYDOCS and IEFRAME as well,
NOTE This is not an efficient solution if you really have small array.
It can be done using CSS alone. It works perfect on my machine in Firefox, Chrome and Opera browser under Ubuntu 12.04.
CSS :
.hover_img a { position:relative; }
.hover_img a span { position:absolute; display:none; z-index:99; }
.hover_img a:hover span { display:block; }
HTML :
<div class="hover_img">
<a href="#">Show Image<span><img src="images/01.png" alt="image" height="100" /></span></a>
</div>
I had a similar error with Tomcat 8.0 / MySQL . Changing the jdbc url value from localhost to 127.0.0.1 resolved the issue.
I ran into this problem when upgrading to a windows 7 server with some legacy CLASP applications. Trying to run a 32bit application on a 64 bit machine.
Try setting the application pools 32bit compatibility to True and/or create dsn's in 32 and 64 bit.
Open the odbc datasource window in both versions from the run box. C:\Windows\SysWOW64\odbcad32.exe C:\Windows\system32\odbcad32.exe
Update 2018
Bootstrap 4
Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col
class on the fluid column.
.sidebar {
width: 180px;
min-height: 100vh;
}
<div class="row">
<div class="sidebar p-2">Fixed width</div>
<div class="col bg-dark text-white pt-2">
Content
</div>
</div>
http://www.codeply.com/go/7LzXiPxo6a
Bootstrap 3..
One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...
@media (min-width:768px) {
#sidebar {
min-width: 300px;
max-width: 300px;
}
#main {
width:calc(100% - 300px);
}
}
Working Bootstrap 3 Fixed-Fluid Demo
Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?
When a client connects to an Oracle server, it first connnects to the Oracle listener service. It often redirects the client to another port. So the client has to open another connection on a different port, which is blocked by the firewall.
So you might in fact have encountered a firewall problem due to Oracle port redirection. It should be possible to diagnose it with a network monitor on the client machine or with the firewall management software on the firewall.
Yet another way to do this, although Darbio's defer method is more flexible.
(function() {
var nTimer = setInterval(function() {
if (window.jQuery) {
// Do something with jQuery
clearInterval(nTimer);
}
}, 100);
})();
<Resource>
tag with your DB details inside <GlobalNamingResources>
<Resource name="jdbc/mydb"
global="jdbc/mydb"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test"
username="root"
password=""
maxActive="10"
maxIdle="10"
minIdle="5"
maxWait="10000"/>
<ResourceLink>
inside the <Context>
tag.<ResourceLink name="jdbc/mydb"
global="jdbc/mydb"
auth="Container"
type="javax.sql.DataSource" />
Adding:
-------
<property name="connection.datasource">java:comp/env/jdbc/mydb</property>
Removing:
--------
<!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> -->
<!--<property name="connection.username">root</property> -->
<!--<property name="connection.password"></property> -->
You can also use 'name' instead of 'href' for a cleaner url:
$('a[name^=#]').click(function(){
var target = $(this).attr('name');
if (target == '#')
$('html, body').animate({scrollTop : 0}, 600);
else
$('html, body').animate({
scrollTop: $(target).offset().top - 100
}, 600);
});
With a = subprocess.Popen("cdrecord --help",stdout = subprocess.PIPE)
, you need to either use a list or use shell=True
;
Either of these will work. The former is preferable.
a = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE)
a = subprocess.Popen('cdrecord --help', shell=True, stdout=subprocess.PIPE)
Also, instead of using Popen.stdout.read
/Popen.stderr.read
, you should use .communicate()
(refer to the subprocess documentation for why).
proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
You entity is not correctly annotated, you must use the @javax.persistence.Entity
annotation. You can use the Hibernate extension @org.hibernate.annotations.Entity
to go beyond what JPA has to offer but the Hibernate annotation is not a replacement, it's a complement.
So change your code into:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
public class Message {
...
}
Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.
e.g. if you do this:
SELECT 1 / 2
you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.
e.g.
SELECT CAST(1 AS DECIMAL) / 2
gives 0.500000
It's hard to say, but if I would check the actual version of the JDBC driver. Make sure it's 11.1.0.6.
Oracle doesn't include the database version in the filename. So the driver for 11.2 is the exact same name as the driver for 11.1 - ojdbc5.jar. I would extract the driver jar file, and find the MANIFEST.MF file, this will contain some version information. Make sure the version of the JDBC driver matches the version of your database. I suspect it may be a version issue, since there isn't a jar file named ojdbc14.jar on Oracle's 11.1.0.6 download page.
If the version matches - I'm out of ideas :)
This worked for me:
<html>
<head>
<title>scroll</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<style>
div.container {
overflow:hidden;
width:200px;
height:200px;
}
div.content {
position:relative;
width:200px;
height:200px;
overflow:hidden;
top:0;
}
</style>
<div class="container">
<p>
<a href="javascript:up();"><img src="/images/img_flecha_left.png" class="up" /></a>
<a href="javascript:down();"><img src="/images/img_flecha_left.png" class="down" /></a>
</p>
<div class="content">
<p>Hello World</p><p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
</div>
</div>
<script>
function up() {
var topVal = $(".content").css("top"); //alert(topVal);
var val=parseInt(topVal.replace("px",""));
val=val-20;
$(".content").css("top", val+"px");
}
function down() {
var topVal = $(".content").css("top"); //alert(topVal);
var val=parseInt(topVal.replace("px",""));
val=val+20;
$(".content").css("top", val+"px");
}
</script>
</body>
</html>
If you select two dates from 'your_table' and want too see the result as a single column output (eg. 'days - hh:mm:ss') you could use something like this. First you could calculate the interval between these two dates and after that export all the data you need from that interval:
select extract (day from numtodsinterval (second_date
- add_months (created_date,
floor (months_between (second_date,created_date))),
'day'))
|| ' days - '
|| extract (hour from numtodsinterval (second_date
- add_months (created_date,
floor (months_between (second_date,created_date))),
'day'))
|| ':'
|| extract (minute from numtodsinterval (second_date
- add_months (created_date,
floor (months_between (second_date, created_date))),
'day'))
|| ':'
|| extract (second from numtodsinterval (second_date
- add_months (created_date,
floor (months_between (second_date, created_date))),
'day'))
from your_table
And that should give you result like this: 0 days - 1:14:55
If you look at your original connection string:
<property name="url" value="jdbc:hsqldb:hsql://localhost"/>
The Hypersonic docs suggest that you're missing an alias after localhost:
In addition to the above:
@Autowired
beans is Singleton whereas using JSR 330 @Inject
annotation it is like Spring's prototype.@Inject
.@Inject
.The main reason for the error is the process is not stopped. to resolve it start task manager go to services and see if you are still able to see your service than go to the process of that service and end process. Than the issue will be solved completely.
Yes it is valid according to xhtml1-strict.dtd
. The following XHTML passes the validation:
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
<ul>
<li><div>test</div></li>
</ul>
</body>
</html>
EF 4.1 to EF 6
There is a strongly typed .Include
which allows the required depth of eager loading to be specified by providing Select expressions to the appropriate depth:
using System.Data.Entity; // NB!
var company = context.Companies
.Include(co => co.Employees.Select(emp => emp.Employee_Car))
.Include(co => co.Employees.Select(emp => emp.Employee_Country))
.FirstOrDefault(co => co.companyID == companyID);
The Sql generated is by no means intuitive, but seems performant enough. I've put a small example on GitHub here
EF Core
EF Core has a new extension method, .ThenInclude()
, although the syntax is slightly different:
var company = context.Companies
.Include(co => co.Employees)
.ThenInclude(emp => emp.Employee_Car)
.Include(co => co.Employees)
.ThenInclude(emp => emp.Employee_Country)
With some notes
Employees.Employee_Car
and Employees.Employee_Country
), if you need to include 2 or more child properties of an intermediate child collection, you'll need to repeat the .Include
navigation for the collection for each child of the collection..ThenInclude
to preserve your sanity.Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx
You can also use command line utility net
to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code
kk: (01-24) will look like 01, 02..24.
HH:(00-23) will look like 00, 01..23.
hh:(01-12 in AM/PM) will look like 01, 02..12.
so the last printout (working2
) is a bit weird. It should say 12:00:00
(edit: if you were setting the working2
timezone and format, which (as kdagli pointed out) you are not)
Text element inside Center of SizedBox work much better way, below Sample code
Widget build(BuildContext context) {
return RawMaterialButton(
fillColor: Colors.green,
splashColor: Colors.greenAccent,
shape: new CircleBorder(),
child: Padding(
padding: EdgeInsets.all(10.0),
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SizedBox(
width: 100.0,
height: 100.0,
child: Center(
child: Text(
widget.buttonText,
maxLines: 1,
style: TextStyle(color: Colors.white)
),
)
)]
),
),
onPressed: widget.onPressed
);
}
Enjoy coding ?
hope this would help:
window.location.href = '/url_after_domain';
As said, there's no way. However, a bit decent IDE can autogenerate delegate methods. For example Eclipse can do. First setup a template:
public class MultipleInterfaces implements InterFaceOne, InterFaceTwo {
private InterFaceOne if1;
private InterFaceTwo if2;
}
then rightclick, choose Source > Generate Delegate Methods and tick the both if1
and if2
fields and click OK.
See also the following screens:
One missing difference is:
std::unique_lock
can be moved but std::lock_guard
can't be moved.
Note: Both cant be copied.
For me, I installed it on a Mac via Homebrew and it is not set up as a service. To run the memcached
server, I simply execute memcached -d
. This will establish Memcached server on the default port, 11211.
> memcached -d
> telnet localhost 11211
Trying ::1...
Connected to localhost.
Escape character is '^]'.
version
VERSION 1.4.20
Unfortunately as I am forced to use a windows server I have been unable to get openssl working in the way the above answer suggests.
However I was able to get a similar program called stunnel (which can be downloaded from here) to work. I got the idea from www.tech-and-dev.com but I had to change the instructions slightly. Here is what I did:
stunnel.conf
config file, which in my case I installed to C:\Program Files (x86)\stunnel
Then, you need to open this file in a text viewer such as notepad. Look for [gmail-smtp]
and remove the semicolon on the client line below (in the stunnel.conf file, every line that starts with a semicolon is a comment). You should end up with something like:
[gmail-smtp]
client = yes
accept = 127.0.0.1:25
connect = smtp.gmail.com:465
Once you have done this save the stunnel.conf
file and reload the config (to do this use the stunnel GUI program, and click on configuration=>Reload).
Now you should be ready to send email in the windows telnet client!
Go to Start=>run=>cmd.
Once cmd is open type in the following and press Enter:
telnet localhost 25
You should then see something similar to the following:
220 mx.google.com ESMTP f14sm1400408wbe.2
You will then need to reply by typing the following and pressing enter:
helo google
This should give you the following response:
250 mx.google.com at your service
If you get this you then need to type the following and press enter:
ehlo google
This should then give you the following response:
250-mx.google.com at your service, [212.28.228.49]
250-SIZE 35651584
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH
250 ENHANCEDSTATUSCODES
Now you should be ready to authenticate with your Gmail details. To do this type the following and press enter:
AUTH LOGIN
This should then give you the following response:
334 VXNlcm5hbWU6
This means that we are ready to authenticate by using our gmail address and password.
However since this is an encrypted session, we're going to have to send the email and password encoded in base64. To encode your email and password, you can use a converter program or an online website to encode it (for example base64 or search on google for ’base64 online encoding’). I reccomend you do not touch the cmd/telnet session again until you have done this.
For example [email protected] would become dGVzdEBnbWFpbC5jb20= and password would become cGFzc3dvcmQ=
Once you have done this copy and paste your converted base64 username into the cmd/telnet session and press enter. This should give you following response:
334 UGFzc3dvcmQ6
Now copy and paste your converted base64 password into the cmd/telnet session and press enter. This should give you following response if both login credentials are correct:
235 2.7.0 Accepted
You should now enter the sender email (should be the same as the username) in the following format and press enter:
MAIL FROM:<[email protected]>
This should give you the following response:
250 2.1.0 OK x23sm1104292weq.10
You can now enter the recipient email address in a similar format and press enter:
RCPT TO:<[email protected]>
This should give you the following response:
250 2.1.5 OK x23sm1104292weq.10
Now you will need to type the following and press enter:
DATA
Which should give you the following response:
354 Go ahead x23sm1104292weq.10
Now we can start to compose the message! To do this enter your message in the following format (Tip: do this in notepad and copy the entire message into the cmd/telnet session):
From: Test <[email protected]>
To: Me <[email protected]>
Subject: Testing email from telnet
This is the body
Adding more lines to the body message.
When you have finished the email enter a dot:
.
This should give you the following response:
250 2.0.0 OK 1288307376 x23sm1104292weq.10
And now you need to end your session by typing the following and pressing enter:
QUIT
This should give you the following response:
221 2.0.0 closing connection x23sm1104292weq.10
Connection to host lost.
And your email should now be in the recipient’s mailbox!
A complete example.
<?php
$units = explode(' ','B KB MB GB TB PB');
echo("<html><body>");
echo('file size: ' . format_size(filesize("example.txt")));
echo("</body></html>");
function format_size($size) {
$mod = 1024;
for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}
$endIndex = strpos($size, ".")+3;
return substr( $size, 0, $endIndex).' '.$units[$i];
}
?>
It's an encoding error - so if it's a unicode string, this ought to fix it:
text.encode("windows-1252").decode("utf-8")
If it's a plain string, you'll need an extra step:
text.decode("utf-8").encode("windows-1252").decode("utf-8")
Both of these will give you a unicode string.
By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:
>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}
import sys
sys.path
The previous answers did not work for me, so I decided to improve this.
You should work with url('')
, and not with value.
<li *ngFor="let item of items">
<div
class="img-wrapper"
[ngStyle]="{'background-image': !item.featured ? 'url(\'images/img1.png\')' : 'url(\'images/img2.png\')'}">
</div>
</li>
Getting shell variables into
awk
may be done in several ways. Some are better than others. This should cover most of them. If you have a comment, please leave below. v1.5
-v
(The best way, most portable)Use the -v
option: (P.S. use a space after -v
or it will be less portable. E.g., awk -v var=
not awk -vvar=
)
variable="line one\nline two"
awk -v var="$variable" 'BEGIN {print var}'
line one
line two
This should be compatible with most awk
, and the variable is available in the BEGIN
block as well:
If you have multiple variables:
awk -v a="$var1" -v b="$var2" 'BEGIN {print a,b}'
Warning. As Ed Morton writes, escape sequences will be interpreted so \t
becomes a real tab
and not \t
if that is what you search for. Can be solved by using ENVIRON[]
or access it via ARGV[]
PS If you like three vertical bar as separator |||
, it can't be escaped, so use -F"[|][|][|]"
Example on getting data from a program/function inn to
awk
(here date is used)
awk -v time="$(date +"%F %H:%M" -d '-1 minute')" 'BEGIN {print time}'
Here we get the variable after the awk
code. This will work fine as long as you do not need the variable in the BEGIN
block:
variable="line one\nline two"
echo "input data" | awk '{print var}' var="${variable}"
or
awk '{print var}' var="${variable}" file
awk '{print a,b,$0}' a="$var1" b="$var2" file
FS
for each file.awk 'some code' FS=',' file1.txt FS=';' file2.ext
BEGIN
block:echo "input data" | awk 'BEGIN {print var}' var="${variable}"
Variable can also be added to awk
using a here-string from shells that support them (including Bash):
awk '{print $0}' <<< "$variable"
test
This is the same as:
printf '%s' "$variable" | awk '{print $0}'
P.S. this treats the variable as a file input.
ENVIRON
inputAs TrueY writes, you can use the ENVIRON
to print Environment Variables.
Setting a variable before running AWK, you can print it out like this:
X=MyVar
awk 'BEGIN{print ENVIRON["X"],ENVIRON["SHELL"]}'
MyVar /bin/bash
ARGV
inputAs Steven Penny writes, you can use ARGV
to get the data into awk:
v="my data"
awk 'BEGIN {print ARGV[1]}' "$v"
my data
To get the data into the code itself, not just the BEGIN:
v="my data"
echo "test" | awk 'BEGIN{var=ARGV[1];ARGV[1]=""} {print var, $0}' "$v"
my data test
You can use a variable within the awk
code, but it's messy and hard to read, and as Charles Duffy
points out, this version may also be a victim of code injection. If someone adds bad stuff to the variable, it will be executed as part of the awk
code.
This works by extracting the variable within the code, so it becomes a part of it.
If you want to make an awk
that changes dynamically with use of variables, you can do it this way, but DO NOT use it for normal variables.
variable="line one\nline two"
awk 'BEGIN {print "'"$variable"'"}'
line one
line two
Here is an example of code injection:
variable='line one\nline two" ; for (i=1;i<=1000;++i) print i"'
awk 'BEGIN {print "'"$variable"'"}'
line one
line two
1
2
3
.
.
1000
You can add lots of commands to awk
this way. Even make it crash with non valid commands.
It's always good to double quote variable "$variable"
If not, multiple lines will be added as a long single line.
Example:
var="Line one
This is line two"
echo $var
Line one This is line two
echo "$var"
Line one
This is line two
Other errors you can get without double quote:
variable="line one\nline two"
awk -v var=$variable 'BEGIN {print var}'
awk: cmd. line:1: one\nline
awk: cmd. line:1: ^ backslash not last character on line
awk: cmd. line:1: one\nline
awk: cmd. line:1: ^ syntax error
And with single quote, it does not expand the value of the variable:
awk -v var='$variable' 'BEGIN {print var}'
$variable
define "display it dynamically" ? that implies the table is being built via javascript and some sort of Ajax-y update .. if you just want to build the table using PHP that's really not what I would call 'dynamic'
Use seaborn instead i am using distplot of seaborn with mean=5 std=3 of 1000 values
value = np.random.normal(loc=5,scale=3,size=1000)
sns.distplot(value)
You will get a normal distribution curve
I ran into this when I reduced the number of user-input parameters in userInput from 3 to 1. This changed the variable output type of userInput from an array to a primitive.
Example:
myvar1 = userInput['param1']
myvar2 = userInput['param2']
to:
myvar = userInput
To use arrow functions with function.prototype.call
, I made a helper function on the object prototype:
// Using
// @func = function() {use this here} or This => {use This here}
using(func) {
return func.call(this, this);
}
usage
var obj = {f:3, a:2}
.using(This => This.f + This.a) // 5
Edit
You don't NEED a helper. You could do:
var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5
yes you can (for version 2)
load like this inside your controller
$this->load->library('../controllers/whathever');
and call the following method:
$this->whathever->functioname();
I believe you want to set the Content
property. This has more information on what is available to a label.
With Trackpad:
Tested with Xcode 3.2.5.
You can try:
node.offsetTop - window.scrollY
It works on Opera with viewport meta tag defined.
in case of a similar issue when I'm creating dockerfile I faced the same scenario:- I used below changed in mysql_connect function as:-
if($CONN = @mysqli_connect($DBHOST, $DBUSER, $DBPASS)){ //mysql_query("SET CHARACTER SET 'gbk'", $CONN);
You have two ways to do this, I'll call it dirty way and clean way:
1. The dirty way
Create a box from your current virtual environment, using vagrant package
command:
http://docs.vagrantup.com/v2/cli/package.html
Then copy the box to the other pc, add it using vagrant box add
and run it using vagrant up
as usual.
Keep in mind that files in your working directory (the one with the Vagrantfile
) are shared when the virtual machine boots, so you need to copy it to the other pc as well.
2. The clean way
Theoretically it should never be necessary to do export/import with Vagrant. If you have the foresight to use provisioning for configuring the virtual environment (chef, puppet, ansible), and a version control system like git for your working directory, copying an environment would be at this point simple as running:
git clone <your_repo>
vagrant up
While performance is an issue, I think modern database designs have made it much less of an issue for small files.
Performance aside, it also depends on just how tightly-coupled the data is. If the file contains data that is closely related to the fields of the database, then it conceptually belongs close to it and may be stored in a blob. If it contains information which could potentially relate to multiple records or may have some use outside of the context of the database, then it belongs outside. For example, an image on a web page is fetched on a separate request from the page that links to it, so it may belong outside (depending on the specific design and security considerations).
Our compromise, and I don't promise it's the best, has been to store smallish XML files in the database but images and other files outside it.
Synchronous Execution
My boss is a busy man. He tells me to write the code. I tell him: Fine. I get started and he's watching me like a vulture, standing behind me, off my shoulder. I'm like "Dude, WTF: why don't you go and do something while I finish this?"
he's like: "No, I'm waiting right here until you finish." This is synchronous.
Asynchronous Execution
The boss tells me to do it, and rather than waiting right there for my work, the boss goes off and does other tasks. When I finish my job I simply report to my boss and say: "I'm DONE!" This is Asynchronous Execution.
(Take my advice: NEVER work with the boss behind you.)
You can do this in layout file:
android:id="@+id/listViewContent"
android:layout_width="wrap_content"
android:layout_height="381dp"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll">
You can use the required
html attribute if you want:
@Html.TextBoxFor(m => m.ShortName,
new { @class = "form-control", placeholder = "short name", required="required"})
or you can use the RequiredAttribute class in .Net. With jQuery the RequiredAttribute
can Validate on the front end and server side. If you want to go the MVC route, I'd suggest reading Data annotations MVC3 Required attribute.
OR
You can get really advanced:
@{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = new Dictionary<string, object>(
Html.GetUnobtrusiveValidationAttributes(ViewData.TemplateInfo.HtmlFieldPrefix));
attributes.Add("class", "form-control");
attributes.Add("placeholder", "short name");
if (ViewData.ModelMetadata.ContainerType
.GetProperty(ViewData.ModelMetadata.PropertyName)
.GetCustomAttributes(typeof(RequiredAttribute), true)
.Select(a => a as RequiredAttribute)
.Any(a => a != null))
{
attributes.Add("required", "required");
}
@Html.TextBoxFor(m => m.ShortName, attributes)
}
or if you need it for multiple editor templates:
public static class ViewPageExtensions
{
public static IDictionary<string, object> GetAttributes(this WebViewPage instance)
{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = new Dictionary<string, object>(
instance.Html.GetUnobtrusiveValidationAttributes(
instance.ViewData.TemplateInfo.HtmlFieldPrefix));
if (ViewData.ModelMetadata.ContainerType
.GetProperty(ViewData.ModelMetadata.PropertyName)
.GetCustomAttributes(typeof(RequiredAttribute), true)
.Select(a => a as RequiredAttribute)
.Any(a => a != null))
{
attributes.Add("required", "required");
}
}
}
then in your templates:
@{
// if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
var attributes = this.GetAttributes();
attributes.Add("class", "form-control");
attributes.Add("placeholder", "short name");
@Html.TextBoxFor(m => m.ShortName, attributes)
}
Update 1 (for Tomas who is unfamilar with ViewData).
What's the difference between ViewData and ViewBag?
Excerpt:
So basically it (ViewBag) replaces magic strings:
ViewData["Foo"]
with magic properties:
ViewBag.Foo
2016 Update: The node-windows/mac/linux series uses a common API across all operating systems, so it is absolutely a relevant solution. However; node-linux generates systemv init files. As systemd continues to grow in popularity, it is realistically a better option on Linux. PR's welcome if anyone wants to add systemd support to node-linux :-)
Original Thread:
This is a pretty old thread now, but node-windows provides another way to create background services on Windows. It is loosely based on the nssm
concept of using an exe
wrapper around your node script. However; it uses winsw.exe
instead and provides a configurable node wrapper for more granular control over how the process starts/stops on failures. These processes are available like any other service:
The module also bakes in some event logging:
Daemonizing your script is accomplished through code. For example:
var Service = require('node-windows').Service;
// Create a new service object
var svc = new Service({
name:'Hello World',
description: 'The nodejs.org example web server.',
script: 'C:\\path\\to\\my\\node\\script.js'
});
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
svc.start();
});
// Listen for the "start" event and let us know when the
// process has actually started working.
svc.on('start',function(){
console.log(svc.name+' started!\nVisit http://127.0.0.1:3000 to see it in action.');
});
// Install the script as a service.
svc.install();
The module supports things like capping restarts (so bad scripts don't hose your server) and growing time intervals between restarts.
Since node-windows services run like any other, it is possible to manage/monitor the service with whatever software you already use.
Finally, there are no make
dependencies. In other words, a straightforward npm install -g node-windows
will work. You don't need Visual Studio, .NET, or node-gyp magic to install this. Also, it's MIT and BSD licensed.
In full disclosure, I'm the author of this module. It was designed to relieve the exact pain the OP experienced, but with tighter integration into the functionality the Operating System already provides. I hope future viewers with this same question find it useful.
I know that's an old question with good answers, but I believe I can add my 2 cents.
The simplest and most flexible way which works for me is just using an almost "Plain and Old Java Object" class2D to create each "row" of your array.
The below example has some explanations and is executable (you can copy and paste it, but remember to check the package name):
package my2darraylist;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
public class My2DArrayList
{
public static void main(String[] args)
{
// This is your "2D" ArrayList
//
List<Box> boxes = new ArrayList<>();
// Add your stuff
//
Box stuff = new Box();
stuff.setAString( "This is my stuff");
stuff.addString("My Stuff 01");
stuff.addInteger( 1 );
boxes.add( stuff );
// Add other stuff
//
Box otherStuff = new Box();
otherStuff.setAString( "This is my other stuff");
otherStuff.addString("My Other Stuff 01");
otherStuff.addInteger( 1 );
otherStuff.addString("My Other Stuff 02");
otherStuff.addInteger( 2 );
boxes.add( otherStuff );
// List the whole thing
for ( Box box : boxes)
{
System.out.println( box.getAString() );
System.out.println( box.getMyStrings().size() );
System.out.println( box.getMyIntegers().size() );
}
}
}
class Box
{
// Each attribute is a "Column" in you array
//
private String aString;
private List<String> myStrings = new ArrayList<>() ;
private List<Integer> myIntegers = new ArrayList<>();
// Use your imagination...
//
private JPanel jpanel;
public void addString( String s )
{
myStrings.add( s );
}
public void addInteger( int i )
{
myIntegers.add( i );
}
// Getters & Setters
public String getAString()
{
return aString;
}
public void setAString(String aString)
{
this.aString = aString;
}
public List<String> getMyStrings()
{
return myStrings;
}
public void setMyStrings(List<String> myStrings)
{
this.myStrings = myStrings;
}
public List<Integer> getMyIntegers()
{
return myIntegers;
}
public void setMyIntegers(List<Integer> myIntegers)
{
this.myIntegers = myIntegers;
}
public JPanel getJpanel()
{
return jpanel;
}
public void setJpanel(JPanel jpanel)
{
this.jpanel = jpanel;
}
}
UPDATE - To answer the question from @Mohammed Akhtar Zuberi, I've created the simplified version of the program, to make it easier to show the results.
import java.util.ArrayList;
public class My2DArrayListSimplified
{
public static void main(String[] args)
{
ArrayList<Row> rows = new ArrayList<>();
Row row;
// Insert the columns for each row
// First Name, Last Name, Age
row = new Row("John", "Doe", 30);
rows.add(row);
row = new Row("Jane", "Doe", 29);
rows.add(row);
row = new Row("Mary", "Doe", 1);
rows.add(row);
// Show the Array
//
System.out.println("First\t Last\tAge");
System.out.println("----------------------");
for (Row printRow : rows)
{
System.out.println(
printRow.getFirstName() + "\t " +
printRow.getLastName() + "\t" +
printRow.getAge());
}
}
}
class Row
{
// REMEMBER: each attribute is a column
//
private final String firstName;
private final String lastName;
private final int age;
public Row(String firstName, String lastName, int age)
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public int getAge()
{
return age;
}
}
The code above produces the following result (I ran it on NetBeans):
run:
First Last Age
----------------------
John Doe 30
Jane Doe 29
Mary Doe 1
BUILD SUCCESSFUL (total time: 0 seconds)
I'm by know means an expert, but I'm incredibly proud of myself for having worked something out about this code. If you do:
div {
display: none;
}
a:hover > div {
display: block;
}
(Note the '>') You can contain the whole thing in an a tag, then, as long as your trigger (which can be in it's own div, or straight up in the a tag, or anything you want) is physically touching the revealed div, you can move your mouse from one to the other.
Maybe this isn't useful for a great deal, but I had to set my revealed div to overflow: auto, so sometimes it had scroll bars, which couldn't be used as soon as you move away from the div.
In fact, after finally working out how to make the revealed div, (although it is now a child of the trigger, not a sibling), sit behind the trigger, in terms of z-index, (with a little help from this page: How to get a parent element to appear above child) you don't even have to roll over the revealed div to scroll it, just stay hovering over the trigger and use your wheel, or whatever.
My revealed div covers most of the page, so this technique makes it a lot more permanent, rather than the screen flashing from one state to another with every move of the mouse. It's really intuitive actually, hence why I'm really quite proud of myself.
The only downside is that you can't put links within the whole thing, but you can use the whole thing as one big link.
Below query will provide exactly the same result as given in the desired response:
db.books.aggregate([
{
$group: {
_id: { addresses: "$addr", books: "$book" },
num: { $sum :1 }
}
},
{
$group: {
_id: "$_id.addresses",
bookCounts: { $push: { bookName: "$_id.books",count: "$num" } }
}
},
{
$project: {
_id: 1,
bookCounts:1,
"totalBookAtAddress": {
"$sum": "$bookCounts.count"
}
}
}
])
The response will be looking like below:
/* 1 */
{
"_id" : "address4",
"bookCounts" : [
{
"bookName" : "book3",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 2 */
{
"_id" : "address90",
"bookCounts" : [
{
"bookName" : "book33",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 3 */
{
"_id" : "address15",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 4 */
{
"_id" : "address3",
"bookCounts" : [
{
"bookName" : "book9",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 5 */
{
"_id" : "address5",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 6 */
{
"_id" : "address1",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 3
},
{
"bookName" : "book5",
"count" : 1
}
],
"totalBookAtAddress" : 4
},
/* 7 */
{
"_id" : "address2",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 2
},
{
"bookName" : "book5",
"count" : 1
}
],
"totalBookAtAddress" : 3
},
/* 8 */
{
"_id" : "address77",
"bookCounts" : [
{
"bookName" : "book11",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 9 */
{
"_id" : "address9",
"bookCounts" : [
{
"bookName" : "book99",
"count" : 1
}
],
"totalBookAtAddress" : 1
}
It depends of the language, and of the architecture you are using.
For example, in a php platform, you can format almost language with GeSHi
As bluish comments, GeSHi is a generic syntax highlighter, with no beautification feature. It is more used on the server side, and combine it with a beautification tool can be tricky, as illustrated with this GeSHi drupal ticket.
For Xcode 9, use UIColor
with RGB values.
shareBtn.backgroundColor = UIColor( red: CGFloat(92/255.0), green: CGFloat(203/255.0), blue: CGFloat(207/255.0), alpha: CGFloat(1.0) )
Preview:
See additional Apple documentation on UIColor.
In addition to selecting all elements with an attribute $('[someAttribute]')
or $('input[someAttribute]')
you can also use a function for doing boolean checks on an object such as in a click handler:
if(! this.hasAttribute('myattr') ) { ...
If you choose to use a generic collection, such as List<MyObject>
instead of ArrayList
, you'll find that the List<MyObject>
will provide both generic and non-generic enumerators that you can use.
using System.Collections;
class MyObjects : IEnumerable<MyObject>
{
List<MyObject> mylist = new List<MyObject>();
public MyObject this[int index]
{
get { return mylist[index]; }
set { mylist.Insert(index, value); }
}
public IEnumerator<MyObject> GetEnumerator()
{
return mylist.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
You can combine pseudo-elements! Sorry guys, I figured this one out myself shortly after posting the question. Maybe it's less commonly used because of compatibility issues.
li:last-child:before { content: "and "; }
li:last-child:after { content: "."; }
This works swimmingly. CSS is kind of amazing.
You want to use timeout. timeout 10 will sleep 10 seconds
In the format of unutbu's answer; I made a utility module that handles things like this, with more intuitive syntax. Can be installed with pip.
import datetime
import saturn
unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0)
now_aware = saturn.fix_naive(unaware)
now_aware_madrid = saturn.fix_naive(unaware, 'Europe/Madrid')
If you want to change the color of your toolbar all throughout your app, leverage the styles.xml. In general, I avoid altering ui components in my java code unless I am trying to do something programatically. If this is a one time set, then you should be doing it in xml to make your code cleaner. Here is what your styles.xml will look like:
<!-- Base application theme. -->
<style name="YourAppName.AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Color Primary will be your toolbar color -->
<item name="colorPrimary">@color/colorPrimary</item>
<!-- Color Primary Dark will be your default status bar color -->
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
</style>
Make sure you use the above style in your AndroidManifext.xml as such:
<application
android:theme="@style/YourAppName.AppTheme">
</application>
I wanted different toolbar colors for different activities. So I leveraged styles again like this:
<style name="YourAppName.AppTheme.Activity1">
<item name="colorPrimary">@color/activity1_primary</item>
<item name="colorPrimaryDark">@color/activity1_primaryDark</item>
</style>
<style name="YourAppName.AppTheme.Activity2">
<item name="colorPrimary">@color/activity2_primary</item>
<item name="colorPrimaryDark">@color/activity2_primaryDark</item>
</style>
again, apply the styles to each activity in your AndroidManifest.xml as such:
<activity
android:name=".Activity2"
android:theme="@style/YourAppName.AppTheme.Activity2"
</activity>
<activity
android:name=".Activity1"
android:theme="@style/YourAppName.AppTheme.Activity1"
</activity>
public boolean isInt(String str){
return (str.lastIndexOf("-") == 0 && !str.equals("-0")) ? str.substring(1).matches(
"\\d+") : str.matches("\\d+");
}
Here is what needs to go in D1: =VLOOKUP(C1, $A$1:$B$4, 2, FALSE)
You should then be able to copy this down to the rest of column D.
I just want to make a specific point about the for in loop in Ruby. It might seem like a construct similar to other languages, but in fact it is an expression like every other looping construct in Ruby. In fact, the for in works with Enumerable objects just as the each iterator.
The collection passed to for in can be any object that has an each iterator method. Arrays and hashes define the each method, and many other Ruby objects do, too. The for/in loop calls the each method of the specified object. As that iterator yields values, the for loop assigns each value (or each set of values) to the specified variable (or variables) and then executes the code in body.
This is a silly example, but illustrates the point that the for in loop works with ANY object that has an each method, just like how the each iterator does:
class Apple
TYPES = %w(red green yellow)
def each
yield TYPES.pop until TYPES.empty?
end
end
a = Apple.new
for i in a do
puts i
end
yellow
green
red
=> nil
And now the each iterator:
a = Apple.new
a.each do |i|
puts i
end
yellow
green
red
=> nil
As you can see, both are responding to the each method which yields values back to the block. As everyone here stated, it is definitely preferable to use the each iterator over the for in loop. I just wanted to drive home the point that there is nothing magical about the for in loop. It is an expression that invokes the each method of a collection and then passes it to its block of code. Hence, it is a very rare case you would need to use for in. Use the each iterator almost always (with the added benefit of block scope).
I created a reusable function for this. It actually parses an entire directory of requirements files and sets them to extras_require.
Latest always available here: https://gist.github.com/akatrevorjay/293c26fefa24a7b812f5
import glob
import itertools
import os
# This is getting ridiculous
try:
from pip._internal.req import parse_requirements
from pip._internal.network.session import PipSession
except ImportError:
try:
from pip._internal.req import parse_requirements
from pip._internal.download import PipSession
except ImportError:
from pip.req import parse_requirements
from pip.download import PipSession
def setup_requirements(
patterns=[
'requirements.txt', 'requirements/*.txt', 'requirements/*.pip'
],
combine=True):
"""
Parse a glob of requirements and return a dictionary of setup() options.
Create a dictionary that holds your options to setup() and update it using this.
Pass that as kwargs into setup(), viola
Any files that are not a standard option name (ie install, tests, setup) are added to extras_require with their
basename minus ext. An extra key is added to extras_require: 'all', that contains all distinct reqs combined.
Keep in mind all literally contains `all` packages in your extras.
This means if you have conflicting packages across your extras, then you're going to have a bad time.
(don't use all in these cases.)
If you're running this for a Docker build, set `combine=True`.
This will set `install_requires` to all distinct reqs combined.
Example:
>>> import setuptools
>>> _conf = dict(
... name='mainline',
... version='0.0.1',
... description='Mainline',
... author='Trevor Joynson <[email protected],io>',
... url='https://trevor.joynson.io',
... namespace_packages=['mainline'],
... packages=setuptools.find_packages(),
... zip_safe=False,
... include_package_data=True,
... )
>>> _conf.update(setup_requirements())
>>> # setuptools.setup(**_conf)
:param str pattern: Glob pattern to find requirements files
:param bool combine: Set True to set install_requires to extras_require['all']
:return dict: Dictionary of parsed setup() options
"""
session = PipSession()
# Handle setuptools insanity
key_map = {
'requirements': 'install_requires',
'install': 'install_requires',
'tests': 'tests_require',
'setup': 'setup_requires',
}
ret = {v: set() for v in key_map.values()}
extras = ret['extras_require'] = {}
all_reqs = set()
files = [glob.glob(pat) for pat in patterns]
files = itertools.chain(*files)
for full_fn in files:
# Parse
reqs = {
str(r.req)
for r in parse_requirements(full_fn, session=session)
# Must match env marker, eg:
# yarl ; python_version >= '3.0'
if r.match_markers()
}
all_reqs.update(reqs)
# Add in the right section
fn = os.path.basename(full_fn)
barefn, _ = os.path.splitext(fn)
key = key_map.get(barefn)
if key:
ret[key].update(reqs)
extras[key] = reqs
extras[barefn] = reqs
if 'all' not in extras:
extras['all'] = list(all_reqs)
if combine:
extras['install'] = ret['install_requires']
ret['install_requires'] = list(all_reqs)
def _listify(dikt):
ret = {}
for k, v in dikt.items():
if isinstance(v, set):
v = list(v)
elif isinstance(v, dict):
v = _listify(v)
ret[k] = v
return ret
ret = _listify(ret)
return ret
__all__ = ['setup_requirements']
if __name__ == '__main__':
reqs = setup_requirements()
print(reqs)
You can also make your own nodeJS endpoint, publish it with something like heroku, and access it
require("http").createServer(function (q,r) {
r.setHeader("accees-control-allow-origin","*")
r.end(Date.now())
}).listen(process.env.PORT || 80)
Then just access it on JS
fetch ("http://someGerokuApp")
.then(r=>r.text)
. then (r=>console.log(r))
This will still be relative to whatever computer the node app is hosted on, but perhaps you can get the location somehow and provide different endpoints fit the other timezones based on the current one (for example if the server happens to be in California then for a new York timezone just add 1000*60*60*3
milliseconds to Date.now() to add 3 hours)
For simplicity, if it's possible to get the location from the server and send it as a response header, you can just do the calculations for the different time zones in the client side
In fact using heroku they allow you to specify a region that it should be deployed at https://devcenter.heroku.com/articles/regions#specifying-a-region you can use this as reference..
EDIT just realized the timezone is in the date string itself, can just pay the whole thing as a header to be read by the client
require("http").createServer(function (q,r) {
var d= new Date()
r.setHeader("accees-control-allow-origin","*")
r.setHeader("zman", d.toString())
r.end(d.getTime())
}).listen(process.env.PORT || 80)
Well in SQL Server, generally, primary key is automatically indexed. This is true, but it not guaranteed of faster query. The primary key will give you excellent performance when there is only 1 field as primary key. But, when there are multiple field as primary key, then the index is based on those fields.
For example: Field A, B, C are the primary key, thus when you do query based on those 3 fields in your WHERE CLAUSE, the performance is good, BUT when you want to query with Only C field in the WHERE CLAUSE, you wont get good performance. Thus, to get your performance up and running, you will need to index C field manually.
Most of the time, you wont see the issue till you hits more than 1 million records.
I think that the most elegant way to do it is to implement custom Flash Scope in Spring MVC.
the main idea for the flash scope is to store data from one controller till next redirect in second controller
Please refer to my answer on the custom scope question:
The only thing that is missing in this code is the following xml configuration:
<bean id="flashScopeInterceptor" class="com.vanilla.springMVC.scope.FlashScopeInterceptor" />
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list><ref bean="flashScopeInterceptor"/></list>
</property>
</bean>
The answer is already posted but note that this will pass the ArrayList by reference. So if you make any changes to the list in the function it will be affected to the original list also.
<access-modfier> <returnType> AnalyseArray(ArrayList<Integer> list)
{
//analyse the list
//return value
}
call it like this:
x=AnalyseArray(list);
or pass a copy of ArrayList:
x=AnalyseArray(list.clone());
matches
tries to match the expression against the entire string and implicitly add a ^
at the start and $
at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:
public static void main(String[] args) throws ParseException {
Pattern p = Pattern.compile("\\d\\d\\d");
Matcher m = p.matcher("a123b");
System.out.println(m.find());
System.out.println(m.matches());
p = Pattern.compile("^\\d\\d\\d$");
m = p.matcher("123");
System.out.println(m.find());
System.out.println(m.matches());
}
/* output:
true
false
true
true
*/
123
is a substring of a123b
so the find()
method outputs true. matches()
only 'sees' a123b
which is not the same as 123
and thus outputs false.
There is an algorithm that I studied in school that you can use to compute exact square roots (or of arbitrarily large precision if the root is an irrational number). It is definitely slower than Newton's algorithms but it is exact. Lets say you want to compute the square root of 531.3025
First thing is you divide your number starting from the decimal point into groups of 2 digits:
{5}{31}.{30}{25}
Then:
1) Find the closest square root for first group that is smaller or equal to the actual square root of first group: sqrt({5}) >= 2. This square root is the first digit of your final answer. Lets denote the digits we have already found of our final square root as B. So at the moment B = 2.
2) Next compute the difference between {5} and B^2: 5 - 4 = 1.
3) For all subsequent 2 digit groups do the following:
Multiply the remainder by 100, then add it to the second group: 100 + 31 = 131.
Find X - next digit of your root, such that 131 >=((B*20) + X)*X. X = 3. 43 * 3 = 129 < 131. Now B = 23. Also because you have no more 2-digit groups to the left of decimal points, you have found all integer digits of your final root.
4)Repeat the same for {30} and {25}. So you have:
{30} : 131 - 129 = 2. 2 * 100 + 30 = 230 >= (23*2*10 + X) * X -> X = 0 -> B = 23.0
{25} : 230 - 0 = 230. 230 * 100 + 25 = 23025. 23025 >= (230 * 2 * 10 + X) * X -> X = 5 -> B = 23.05
Final result = 23.05.
The algorithm looks complicated this way but it is much simpler if you do it on paper using the same notation you use for "long division" you have studied in school, except that you don't do division but instead compute the square root.
Is there a way we can get the list of supported timeZone from MySQL ? ex - serverTimezone=America/New_York. That can solve many such issue. I believe every time you need to specify the correct time zone from the Application irrespective of the DB TimeZone.
The map()
function is there to apply the same procedure to every item in an iterable data structure, like lists, generators, strings, and other stuff.
Let's look at an example:
map()
can iterate over every item in a list and apply a function to each item, than it will return (give you back) the new list.
Imagine you have a function that takes a number, adds 1 to that number and returns it:
def add_one(num):
new_num = num + 1
return new_num
You also have a list of numbers:
my_list = [1, 3, 6, 7, 8, 10]
if you want to increment every number in the list, you can do the following:
>>> map(add_one, my_list)
[2, 4, 7, 8, 9, 11]
Note: At minimum map()
needs two arguments. First a function name and second something like a list.
Let's see some other cool things map()
can do.
map()
can take multiple iterables (lists, strings, etc.) and pass an element from each iterable to a function as an argument.
We have three lists:
list_one = [1, 2, 3, 4, 5]
list_two = [11, 12, 13, 14, 15]
list_three = [21, 22, 23, 24, 25]
map()
can make you a new list that holds the addition of elements at a specific index.
Now remember map()
, needs a function. This time we'll use the builtin sum()
function. Running map()
gives the following result:
>>> map(sum, list_one, list_two, list_three)
[33, 36, 39, 42, 45]
REMEMBER:
In Python 2 map()
, will iterate (go through the elements of the lists) according to the longest list, and pass None
to the function for the shorter lists, so your function should look for None
and handle them, otherwise you will get errors. In Python 3 map()
will stop after finishing with the shortest list. Also, in Python 3, map()
returns an iterator, not a list.
Bootstrap 4 includes flexbox, so the method of vertical centering is much easier and doesn't require extra CSS.
Just use the d-flex
and align-items-center
utility classes..
<div class="jumbotron d-flex align-items-center">
<div class="container">
content
</div>
</div>
http://www.codeply.com/go/ui6ABmMTLv
Important: Vertical centering is relative to height. The parent container of the items you're attempting to center must have a defined height. If you want the height of the page use vh-100
or min-vh-100
on the parent! For example:
<div class="jumbotron d-flex align-items-center min-vh-100">
<div class="container text-center">
I am centered vertically
</div>
</div>
Basically I solved it by NOT-ing the isReplyFormOpen
value whenever it is clicked:
<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>
<div ng-init="isReplyFormOpen = false" ng-show="isReplyFormOpen" id="replyForm">
<!-- Form -->
</div>
All these functions for adding date are wrong. You are passing the wrong month to the Date function. More information about the problem : http://www.domdigger.com/blog/?p=9
Something like the following bash script will retrieve the lastest com.company:artifact
snapshot from the snapshot
repo:
# Artifactory location
server=http://artifactory.company.com/artifactory
repo=snapshot
# Maven artifact location
name=artifact
artifact=com/company/$name
path=$server/$repo/$artifact
version=$(curl -s $path/maven-metadata.xml | grep latest | sed "s/.*<latest>\([^<]*\)<\/latest>.*/\1/")
build=$(curl -s $path/$version/maven-metadata.xml | grep '<value>' | head -1 | sed "s/.*<value>\([^<]*\)<\/value>.*/\1/")
jar=$name-$build.jar
url=$path/$version/$jar
# Download
echo $url
wget -q -N $url
It feels a bit dirty, yes, but it gets the job done.
If you need to separate certain elements with spaces you could do something like
print "hello", "there"
Notice the comma between "hello" and "there".
If you want to print a new line (i.e. \n
) you could just use print
without any arguments.
My fairly short code to read JSON from an URL. (requires Guava due to usage of CharStreams
).
private static class VersionTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... strings) {
String result = null;
URL url;
HttpURLConnection connection = null;
try {
url = new URL("https://api.github.com/repos/user_name/repo_name/releases/latest");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
result = CharStreams.toString(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8));
} catch (IOException e) {
Log.d("VersionTask", Log.getStackTraceString(e));
} finally {
if (connection != null) {
connection.disconnect();
}
}
return result;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
String version = "";
try {
version = new JSONObject(result).optString("tag_name").trim();
} catch (JSONException e) {
Log.e("VersionTask", Log.getStackTraceString(e));
}
if (version.startsWith("v")) {
//process version
}
}
}
}
PS: This code gets the latest release version (based on tag name) for a given GitHub repo.
You need a Python DictReader class. More help can be found from here
import csv
with open('file_name.csv', 'rt') as f:
reader = csv.DictReader(f)
for row in reader:
print row
I encountered the same error for a silly reason, which I think was this:
Working in R Studio, if you try to assign a new object to an existing name, and you currently have an object with the existing name open with View(), it throws this error.
Close the object 'View' panel, and then it works.
Since for some reason white isn't available for selection, I have found that mat-palette($mat-grey, 50)
was close enough to white, for my needs at least.
You need not specify the classes folder. Intellij should be able to load it. You will get this error if "Project Compiler output" is blank.
Just make sure that below value is set: Project Settings -> Project -> Project Compiler output to your projectDir/out folder
This works for me using Postgres 9+:
SELECT *
FROM your_table
ORDER BY name = 'core' DESC, priority DESC
Postman is a good solution and so is php fiddle. However to avoid putting in the GCM URL and the header information every time, you can also use this nifty GCM Notification Test Tool
A combination of answers by Beorn Harris and loentar gives one more interesting one-liner test:
delim=$'\x1F' # define a control code to be used as more or less reliable delimiter
if [[ "${delim}${array[@]}${delim}" =~ "${delim}a string to test${delim}" ]]; then
echo "contains 'a string to test'"
fi
This one does not use extra functions, does not make replacements for testing and adds extra protection against occasional false matches using a control code as a delimiter.
UPD: Thanks to @ChrisCogdon note, this incorrect code was re-written and published as https://stackoverflow.com/a/58527681/972463 .
Do this:
Go and right click on Deployment Descriptor and click Generate Deployment Descriptor Stub.
Why Pandas ? Have you tried Standard Python ?
The use of standard library python. Pandas is subject to frequent updates, even with the recent release of the stable version.
Using the standard python library your code will always run.
One way of doing it is to have an idea of the way you want your data to be stored , and which questions you want to solve regarding the data. Then draw a schema of how you can organise your data (think tables) that will help you query the data, not necessarily normalisation.
You can make good use of :
Ram and HDD is becoming cheaper and cheaper with time and standard python 3 is widely available and stable.
The fondamental question you are trying to solve is "how to query large sets of data ?". The hdfs architecture is more or less what I am describing here (data modelling with data being stored on disk).
Let's say you have 1000 petabytes of data, there no way you will be able to store it in Dask or Pandas, your best chances here is to store it on disk and process it with generators.
I am using xcode with ios 8 just uncheck the connect harware keyboard option in your Simulator-> Hardware-> Keyboard-> Connect Hardware Keyboard.
This will solve the issue.
Email address: RFC 2822 Format
Matches a normal email address. Does not check the top-level domain.
Requires the "case insensitive" option to be ON.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
Usage :
bool isEmail = Regex.IsMatch(emailString, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);
You need to set up the parent-child relationship between your components. The problem is that you might simply inject the child components in the constructor of the parent component and store it in a local variable.
Instead, you should declare the child components in your parent component by using the @ViewChild
property declarator.
This is how your parent component should look like:
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ListComponent } from './list.component';
import { DetailComponent } from './detail.component';
@Component({
selector: 'app-component',
template: '<list-component></list-component><detail-component></detail-component>',
directives: [ListComponent, DetailComponent]
})
class AppComponent implements AfterViewInit {
@ViewChild(ListComponent) listComponent:ListComponent;
@ViewChild(DetailComponent) detailComponent: DetailComponent;
ngAfterViewInit() {
// afther this point the children are set, so you can use them
this.detailComponent.doSomething();
}
}
https://angular.io/docs/ts/latest/api/core/index/ViewChild-var.html
https://angular.io/docs/ts/latest/cookbook/component-communication.html#parent-to-view-child
Beware, the child component will not be available in the constructor of the parent component, just after the ngAfterViewInit
lifecycle hook is called. To catch this hook simple implement the AfterViewInit
interface in you parent class the same way you would do with OnInit
.
But, there are other property declarators as explained in this blog note: http://blog.mgechev.com/2016/01/23/angular2-viewchildren-contentchildren-difference-viewproviders/
You accomplish executing code using exec, as with the following IDLE session:
>>> kw = {}
>>> exec( "ret = 4" ) in kw
>>> kw['ret']
4
One more way of running an R script from the command line would be:
R < scriptName.R --no-save
or with --save
.
See also What's the best way to use R scripts on the command line (terminal)?.
Use the backslash \
or choose a different delimiter, ie m#.\d#
instead of /.\d/
"In Perl, you can change the / regular expression delimiter to almost any other special character if you preceed it with the letter m (for match);"
Update 2018
Bootstrap 4
Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col
class on the fluid column.
.sidebar {
width: 180px;
min-height: 100vh;
}
<div class="row">
<div class="sidebar p-2">Fixed width</div>
<div class="col bg-dark text-white pt-2">
Content
</div>
</div>
http://www.codeply.com/go/7LzXiPxo6a
Bootstrap 3..
One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...
@media (min-width:768px) {
#sidebar {
min-width: 300px;
max-width: 300px;
}
#main {
width:calc(100% - 300px);
}
}
Working Bootstrap 3 Fixed-Fluid Demo
Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?
For newer versions of Eclipse:
open the Debug perspective (Window > Open Perspective > Debug)
select process in Devices list (bottom right)
Hit Stop button (top right of Devices pane)
You can use .filter()
method of the Array
object:
var filtered = workItems.filter(function(element) {
// Create an array using `.split()` method
var cats = element.category.split(' ');
// Filter the returned array based on specified filters
// If the length of the returned filtered array is equal to
// length of the filters array the element should be returned
return cats.filter(function(cat) {
return filtersArray.indexOf(cat) > -1;
}).length === filtersArray.length;
});
Some old browsers like IE8 doesn't support .filter()
method of the Array
object, if you are using jQuery you can use .filter()
method of jQuery object.
jQuery version:
var filtered = $(workItems).filter(function(i, element) {
var cats = element.category.split(' ');
return $(cats).filter(function(_, cat) {
return $.inArray(cat, filtersArray) > -1;
}).length === filtersArray.length;
});
Try using fake sendmail to send emails in a WAMP enviroment.
Add timeout of your SqlCommand
. Please note time is in second.
// Setting command timeout to 1 second
scGetruntotals.CommandTimeout = 1;
You want sessions if you have data you want to have the data held for longer than one page.
$_GET
for just one page.
<a href='page.php?var=data'>Data link</a>
on page.php
<?php
echo $_GET['var'];
?>
will output: data
I am also facing this problem.
Problem in IE is newWin.document.write(divToPrint.innerHTML);
when we remove this line print function in IE is working. but again problem still exist about the content of page.
You can open the page using window.open, and write the content in that page. then print function will work in IE.This is alternate solution.
Best luck.
@Pratik
max-age=0, must-revalidate
and no-cache
aren't exactly identical. With must-revalidate
, if the server doesn't respond to a revalidation request, the browser/proxy is supposed to return a 504 error. With no-cache
, it would just show the cached content, which would be probably preferred by the user (better to have something stale than nothing at all). This is why must-revalidate
is intended for critical transactions only.
usually when i work with remote location teams it is important for me that i have prior knowledge what change done by other teams in same file, before i follow git stages untrack-->staged-->commit for that i wrote an bash script which help me to avoid unnecessary resolve merge conflict with remote team or make new local branch and compare and merge on main branch
#set -x
branchname=`git branch | grep -F '*' | awk '{print $2}'`
echo $branchname
git fetch origin ${branchname}
for file in `git status | grep "modified" | awk "{print $2}" `
do
echo "PLEASE CHECK OUT GIT DIFF FOR "$file
git difftool FETCH_HEAD $file ;
done
in above script i fetch remote main branch (not necessary its master branch)to FETCH_HEAD them make a list of my modified file only and compare modified files to git difftool
here many difftool supported by git, i configure 'Meld Diff Viewer' for good GUI comparison .
C# 6 has monadic null checking :)
before:
if (points != null) {
var next = points.FirstOrDefault();
if (next != null && next.X != null) return next.X;
}
return -1;
after:
var bestValue = points?.FirstOrDefault()?.X ?? -1;
I hope this still helps someone as many people might get to this article. If you need a computed column, why not just expose your desired columns in a view ? Don't just save data or overload the performance with triggers... simply expose the data you need already formatted/calculated in a view.
Hope this helps...
Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"
@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;
Doing something with each child looks like:
this.customComponentChildren.forEach((child) => { child.stuff = 'y' })
There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild
ul.nav li a, ul.nav li a:visited {
color: #anycolor !important;
}
ul.nav li a:hover, ul.nav li a:active {
color: #anycolor !important;
}
ul.nav li.active a {
color: #anycolor !important;
}
Change the styles as you wish.
I have the same warning (it's make my app cannot build). When I add C function
in Objective-C's .m file
, But forgot to declared it at .h
file.
I vote for the dictionary.
I find that if I make a function that returns anything more than 2-3 variables I'll fold them up in a dictionary. Otherwise I tend to forget the order and content of what I'm returning.
Also, introducing a 'special' structure makes your code more difficult to follow. (Someone else will have to search through the code to find out what it is)
If your concerned about type look up, use descriptive dictionary keys, for example, 'x-values list'.
def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return {'y0':y0, 'y1':y1 ,'y2':y2 }
I got the same trouble, in mobile device with Microsoft's Edge browser. I can solve the problem with: aria-haspopup="true"
. It need to add to the div and the :hover
, :active
, :focus
for the other mobile browsers.
Example html:
<div class="left_bar" aria-haspopup="true">
CSS:
.left_bar:hover, .left_bar:focus, .left_bar:active{
left: 0%;
}
You have a recent presentation "Monadologie -- professional help on type anxiety" by Christopher League (July 12th, 2010), which is quite interesting on topics of continuation and monad.
The video going with this (slideshare) presentation is actually available at vimeo.
The Monad part start around 37 minutes in, on this one hour video, and starts with slide 42 of its 58 slide presentation.
It is presented as "the leading design pattern for functional programming", but the language used in the examples is Scala, which is both OOP and functional.
You can read more on Monad in Scala in the blog post "Monads - Another way to abstract computations in Scala", from Debasish Ghosh (March 27, 2008).
A type constructor M is a monad if it supports these operations:
# the return function
def unit[A] (x: A): M[A]
# called "bind" in Haskell
def flatMap[A,B] (m: M[A]) (f: A => M[B]): M[B]
# Other two can be written in term of the first two:
def map[A,B] (m: M[A]) (f: A => B): M[B] =
flatMap(m){ x => unit(f(x)) }
def andThen[A,B] (ma: M[A]) (mb: M[B]): M[B] =
flatMap(ma){ x => mb }
So for instance (in Scala):
Option
is a monaddef unit[A] (x: A): Option[A] = Some(x) def flatMap[A,B](m:Option[A])(f:A =>Option[B]): Option[B] = m match { case None => None case Some(x) => f(x) }
List
is Monaddef unit[A] (x: A): List[A] = List(x) def flatMap[A,B](m:List[A])(f:A =>List[B]): List[B] = m match { case Nil => Nil case x::xs => f(x) ::: flatMap(xs)(f) }
Monad are a big deal in Scala because of convenient syntax built to take advantage of Monad structures:
for
comprehension in Scala:
for {
i <- 1 to 4
j <- 1 to i
k <- 1 to j
} yield i*j*k
is translated by the compiler to:
(1 to 4).flatMap { i =>
(1 to i).flatMap { j =>
(1 to j).map { k =>
i*j*k }}}
The key abstraction is the flatMap
, which binds the computation through chaining.
Each invocation of flatMap
returns the same data structure type (but of different value), that serves as the input to the next command in chain.
In the above snippet, flatMap takes as input a closure (SomeType) => List[AnotherType]
and returns a List[AnotherType]
. The important point to note is that all flatMaps take the same closure type as input and return the same type as output.
This is what "binds" the computation thread - every item of the sequence in the for-comprehension has to honor this same type constraint.
If you take two operations (that may fail) and pass the result to the third, like:
lookupVenue: String => Option[Venue]
getLoggedInUser: SessionID => Option[User]
reserveTable: (Venue, User) => Option[ConfNo]
but without taking advantage of Monad, you get convoluted OOP-code like:
val user = getLoggedInUser(session)
val confirm =
if(!user.isDefined) None
else lookupVenue(name) match {
case None => None
case Some(venue) =>
val confno = reserveTable(venue, user.get)
if(confno.isDefined)
mailTo(confno.get, user.get)
confno
}
whereas with Monad, you can work with the actual types (Venue
, User
) like all the operations work, and keep the Option verification stuff hidden, all because of the flatmaps of the for syntax:
val confirm = for {
venue <- lookupVenue(name)
user <- getLoggedInUser(session)
confno <- reserveTable(venue, user)
} yield {
mailTo(confno, user)
confno
}
The yield part will only be executed if all three functions have Some[X]
; any None
would directly be returned to confirm
.
So:
Monads allow ordered computation within Functional Programing, that allows us to model sequencing of actions in a nice structured form, somewhat like a DSL.
And the greatest power comes with the ability to compose monads that serve different purposes, into extensible abstractions within an application.
This sequencing and threading of actions by a monad is done by the language compiler that does the transformation through the magic of closures.
By the way, Monad is not only model of computation used in FP:
Category theory proposes many models of computation. Among them
- the Arrow model of computations
- the Monad model of computations
- the Applicative model of computations
The example below shows the basic usage of the FileReader
to read the contents of an uploaded file. Here is a working Plunker of this example.
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body onload="init()">
<input id="fileInput" type="file" name="file" />
<pre id="fileContent"></pre>
</body>
</html>
script.js
function init(){
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event){
const reader = new FileReader()
reader.onload = handleFileLoad;
reader.readAsText(event.target.files[0])
}
function handleFileLoad(event){
console.log(event);
document.getElementById('fileContent').textContent = event.target.result;
}
I found a way to cover the shadow with ":after", here is my code:
#div:after {
content:"";
position:absolute;
width:5px;
background:#fff;
height:38px;
top:1px;
right:-5px;
}
I presume that your problem with background-image
is that it would be inefficient with a source for each image inside a stylesheet. My suggestion is to set the source inline:
<div style = 'background-image: url(image.gif)'></div>
div {
background-repeat: no-repeat;
background-position: 50%;
border-radius: 50%;
width: 100px;
height: 100px;
}
Example to get the last input element:
document.querySelector(".groups-container >div:last-child input")
function Notification({ text, status }) {
return (
<div>
{(() => {
switch (status) {
case 'info':
return <Info text={text} />;
case 'warning':
return <Warning text={text} />;
case 'error':
return <Error text={text} />;
default:
return null;
}
})()}
</div>
);
}
I use HAVING for constraining a query based on the results of an aggregate function. E.G. select * in blahblahblah group by SOMETHING having count(SOMETHING)>0
If you only want to change the font in the TEXTAREA then you only need to change the changeFont() function in the original code to:
function changeFont(_name) {
document.getElementById("mytextarea").style.fontFamily = _name;
}
Then selecting a font will change on the font only in the TEXTAREA.
if you set your context model as code first based on exist database so you have to for set migration:
Add-Migration InitialCreate –IgnoreChanges
Update-database -force
and then change your context model and set:
Add-migration RemoveIspositive
Update-database -force
Swift 3
// Default state (previously `.Normal`)
button.setImage(UIImage(named: "image1"), for: [])
// Highlighted
button.setImage(UIImage(named: "image2"), for: .highlighted)
// Selected
button.setImage(UIImage(named: "image3"), for: .selected)
// Selected + Highlighted
button.setImage(UIImage(named: "image4"), for: [.selected, .highlighted])
To set the background image we can use setBackgroundImage(_:for:)
Swift 2.x
// Normal
button.setImage(UIImage(named: "image1"), forState: .Normal)
// Highlighted
button.setImage(UIImage(named: "image2"), forState: .Highlighted)
// Selected
button.setImage(UIImage(named: "image3"), forState: .Selected)
// Selected + Highlighted
button.setImage(UIImage(named: "image4"), forState: [.Selected, .Highlighted])
Navigate to Settings > About Phone > scroll to the bottom > tap Build number seven (7) times. You'll get a short pop-up in the lower area of your display saying that you're now a developer. 2. Go back and now access the Developer options menu, check 'USB debugging' and click OK on the prompt. This Guide Might Help You : How to Enable USB Debugging in Android Phones
If You want i create that for random numbers. this is extension of number Int and Double, Float
/**
Arc Random for Double and Float
*/
public func arc4random <T: IntegerLiteralConvertible> (type: T.Type) -> T {
var r: T = 0
arc4random_buf(&r, UInt(sizeof(T)))
return r
}
public extension Int {
/**
Create a random num Int
:param: lower number Int
:param: upper number Int
:return: random number Int
By DaRkDOG
*/
public static func random (#lower: Int , upper: Int) -> Int {
return lower + Int(arc4random_uniform(upper - lower + 1))
}
}
public extension Double {
/**
Create a random num Double
:param: lower number Double
:param: upper number Double
:return: random number Double
By DaRkDOG
*/
public static func random(#lower: Double, upper: Double) -> Double {
let r = Double(arc4random(UInt64)) / Double(UInt64.max)
return (r * (upper - lower)) + lower
}
}
public extension Float {
/**
Create a random num Float
:param: lower number Float
:param: upper number Float
:return: random number Float
By DaRkDOG
*/
public static func random(#lower: Float, upper: Float) -> Float {
let r = Float(arc4random(UInt32)) / Float(UInt32.max)
return (r * (upper - lower)) + lower
}
}
USE :
let randomNumDouble = Double.random(lower: 0.00, upper: 23.50)
let randomNumInt = Int.random(lower: 56, upper: 992)
let randomNumInt =Float.random(lower: 6.98, upper: 923.09)
PermGen space is replaced by MetaSpace in Java 8. The PermSize and MaxPermSize JVM arguments are ignored and a warning is issued if present at start-up.
Most allocations for the class metadata are now allocated out of native memory. * The classes that were used to describe class metadata have been removed.
Main difference between old PermGen and new MetaSpace is, you don't have to mandatory define upper limit of memory usage. You can keep MetaSpace space limit unbounded. Thus when memory usage increases you will not get OutOfMemoryError error. Instead the reserved native memory is increased to full-fill the increase memory usage.
You can define the max limit of space for MetaSpace, and then it will throw OutOfMemoryError : Metadata space. Thus it is important to define this limit cautiously, so that we can avoid memory waste.
Here is mine solution (hope it is plug-n-play enough too):
// SlideAlongScroll_x000D_
var SlideAlongScroll = function(el) {_x000D_
var _this = this;_x000D_
this.el = el;_x000D_
// elements original position_x000D_
this.elpos_original = el.parent().offset().top; _x000D_
// scroller timeout_x000D_
this.scroller_timeout;_x000D_
// scroller calculate function_x000D_
this.scroll = function() {_x000D_
// 20px gap for beauty_x000D_
var windowpos = $(window).scrollTop() + 20;_x000D_
// targeted destination_x000D_
var finaldestination = windowpos - this.elpos_original;_x000D_
// define stopper object and correction amount_x000D_
var stopper = ($('.footer').offset().top); // $(window).height() if you dont need it_x000D_
var stophere = stopper - el.outerHeight() - this.elpos_original - 20;_x000D_
// decide what to do_x000D_
var realdestination = 0;_x000D_
if(windowpos > this.elpos_original) {_x000D_
if(finaldestination >= stophere) {_x000D_
realdestination = stophere;_x000D_
} else {_x000D_
realdestination = finaldestination;_x000D_
}_x000D_
}_x000D_
el.css({'top': realdestination });_x000D_
};_x000D_
// scroll listener_x000D_
$(window).on('scroll', function() {_x000D_
// debounce it_x000D_
clearTimeout(_this.scroller_timeout);_x000D_
// set scroll calculation timeout_x000D_
_this.scroller_timeout = setTimeout(function() { _this.scroll(); }, 300);_x000D_
});_x000D_
// initial position (in case page is pre-scrolled by browser after load)_x000D_
this.scroll();_x000D_
};_x000D_
// init action, little timeout for smoothness_x000D_
$(document).ready(function() {_x000D_
$('.slide-along-scroll').each(function(i, el) {_x000D_
setTimeout(function(el) { new SlideAlongScroll(el); }, 300, $(el));_x000D_
});_x000D_
});
_x000D_
/* part you need */_x000D_
.slide-along-scroll {_x000D_
padding: 20px;_x000D_
background-color: #CCCCCC;_x000D_
transition: top 300ms ease-out;_x000D_
position: relative;_x000D_
}_x000D_
/* just demo */_x000D_
div { _x000D_
box-sizing: border-box;_x000D_
}_x000D_
.side-column {_x000D_
float: left;_x000D_
width: 20%; _x000D_
}_x000D_
.main-column {_x000D_
padding: 20px;_x000D_
float: right;_x000D_
width: 75%;_x000D_
min-height: 1200px;_x000D_
background-color: #EEEEEE;_x000D_
}_x000D_
.body { _x000D_
padding: 20px 0; _x000D_
}_x000D_
.body:after {_x000D_
content: ' ';_x000D_
clear: both;_x000D_
display: table;_x000D_
}_x000D_
.header {_x000D_
padding: 20px;_x000D_
text-align: center;_x000D_
border-bottom: 2px solid #CCCCCC; _x000D_
}_x000D_
.footer {_x000D_
padding: 20px;_x000D_
border-top: 2px solid #CCCCCC;_x000D_
min-height: 300px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<div class="header">_x000D_
<h1>Your super-duper website</h1>_x000D_
</div>_x000D_
<div class="body"> _x000D_
<div class="side-column">_x000D_
<!-- part you need -->_x000D_
<div class="slide-along-scroll">_x000D_
Side menu content_x000D_
<ul>_x000D_
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>_x000D_
<li>Aliquam tincidunt mauris eu risus.</li>_x000D_
<li>Vestibulum auctor dapibus neque.</li>_x000D_
</ul> _x000D_
</div>_x000D_
</div>_x000D_
<div class="main-column">_x000D_
Main content area (1200px)_x000D_
</div>_x000D_
</div>_x000D_
<div class="footer">_x000D_
Footer (slide along is limited by it)_x000D_
</div>_x000D_
</div>
_x000D_
If you just use round then the two end numbers (1 and 9) will occur less frequently, to get an even distribution of integers between 1 and 9 then:
SELECT MOD(Round(DBMS_RANDOM.Value(1, 99)), 9) + 1 FROM DUAL
I received the same error with RENAME USER
and GRANTS aren't covered by the currently accepted solution:
The most reliable way seems to be to run SHOW GRANTS
for the old user, find/replace what you want to change regarding the user's name and/or host and run them and then finally DROP USER
the old user. Not forgetting to run FLUSH PRIVILEGES
(best to run this after adding the new users' grants, test the new user, then drop the old user and flush again for good measure).
> SHOW GRANTS FOR 'olduser'@'oldhost'; +-----------------------------------------------------------------------------------+ | Grants for olduser@oldhost | +-----------------------------------------------------------------------------------+ | GRANT USAGE ON *.* TO 'olduser'@'oldhost' IDENTIFIED BY PASSWORD '*PASSHASH' | | GRANT SELECT ON `db`.* TO 'olduser'@'oldhost' | +-----------------------------------------------------------------------------------+ 2 rows in set (0.000 sec) > GRANT USAGE ON *.* TO 'newuser'@'newhost' IDENTIFIED BY PASSWORD '*SAME_PASSHASH'; Query OK, 0 rows affected (0.006 sec) > GRANT SELECT ON `db`.* TO 'newuser'@'newhost'; Query OK, 0 rows affected (0.007 sec) > DROP USER 'olduser'@'oldhost'; Query OK, 0 rows affected (0.016 sec)
Update 2019
The :has()
pseudo-selector is propsed in the CSS Selectors 4 spec, and will address this use case once implemented.
To use it, we will write something like:
.foo > .bar:has(> .baz) { /* style here */ }
In a structure like:
<div class="foo">
<div class="bar">
<div class="baz">Baz!</div>
</div>
</div>
This CSS will target the .bar
div - because it both has a parent .foo
and from its position in the DOM, > .baz
resolves to a valid element target.
Original Answer (left for historical purposes) - this portion is no longer accurate
For completeness, I wanted to point out that in the Selectors 4 specification (currently in proposal), this will become possible. Specifically, we will gain Subject Selectors, which will be used in the following format:
!div > span { /* style here */
The !
before the div
selector indicates that it is the element to be styled, rather than the span
. Unfortunately, no modern browsers (as of the time of this posting) have implemented this as part of their CSS support. There is, however, support via a JavaScript library called Sel, if you want to go down the path of exploration further.
For me it was the "Start In" - I copied the values from an older server, and updated the path to the new .exe location, but I forgot to update the "start in" location - if it doesn't exist, you get this error too
Quoting @hans-passant 's comment from above, because it is valuable to debugging this issue:
Convert the error code to hex to get 0x8007010B. The 7 makes it a Windows error. Which makes 010B error code 267. "The directory name is invalid". Sure, that happens.
Nop... I believe you have to make as many calls as the file types you want.
I would create a function myself taking an array on strings with the extensions I need and then iterate on that array making all the necessary calls. That function would return a generic list of the files matching the extensions I'd sent.
Hope it helps.
That's because exceptions are local to a thread, and your main thread doesn't actually see the run
method. I suggest you read more about how threading works, but to quickly summarize: your call to start
starts up a different thread, totally unrelated to your main thread. The call to join
simply waits for it to be done. An exception that is thrown in a thread and never caught terminates it, which is why join
returns on your main thread, but the exception itself is lost.
If you want to be aware of these uncaught exceptions you can try this:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("Caught " + e);
}
});
More information about uncaught exception handling can be found here.
In android studio open View > Tool Windows > Terminal and execute the following commands
On Windows:
gradlew cleanBuildCache
On Mac or Linux:
./gradlew cleanBuildCache
if you want to disable the cache from your project add this into the gradle build properties
(Warning: this may slow your PC performance if there is no cache than same time will consume after every time during the run app)
android.enableBuildCache=false
Here's a solution to your problem using dplyr's filter
function.
Although you can pass your data frame as the first argument to any dplyr function, I've used its %>%
operator, which pipes your data frame to one or more dplyr functions (just filter in this case).
Once you are somewhat familiar with dplyr, the cheat sheet is very handy.
> print(df <- data.frame(sub=rep(1:3, each=4), day=1:4))
sub day
1 1 1
2 1 2
3 1 3
4 1 4
5 2 1
6 2 2
7 2 3
8 2 4
9 3 1
10 3 2
11 3 3
12 3 4
> print(df <- df %>% filter(!((sub==1 & day==2) | (sub==3 & day==4))))
sub day
1 1 1
2 1 3
3 1 4
4 2 1
5 2 2
6 2 3
7 2 4
8 3 1
9 3 2
10 3 3
The following is working code with two ways of achieving this:
using System;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Method1();
Method2();
}
public static void Method1()
{
Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailItem = outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.Subject = "This is the subject";
mailItem.To = "[email protected]";
string imageSrc = "D:\\Temp\\test.jpg"; // Change path as needed
var attachments = mailItem.Attachments;
var attachment = attachments.Add(imageSrc);
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x370E001F", "image/jpeg");
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "myident"); // Image identifier found in the HTML code right after cid. Can be anything.
mailItem.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/id/{00062008-0000-0000-C000-000000000046}/8514000B", true);
// Set body format to HTML
mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
string msgHTMLBody = "<html><head></head><body>Hello,<br><br>This is a working example of embedding an image unsing C#:<br><br><img align=\"baseline\" border=\"1\" hspace=\"0\" src=\"cid:myident\" width=\"\" 600=\"\" hold=\" /> \"></img><br><br>Regards,<br>Tarik Hoshan</body></html>";
mailItem.HTMLBody = msgHTMLBody;
mailItem.Send();
}
public static void Method2()
{
// Create the Outlook application.
Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
//Add an attachment.
String attachmentDisplayName = "MyAttachment";
// Attach the file to be embedded
string imageSrc = "D:\\Temp\\test.jpg"; // Change path as needed
Outlook.Attachment oAttach = mailItem.Attachments.Add(imageSrc, Outlook.OlAttachmentType.olByValue, null, attachmentDisplayName);
mailItem.Subject = "Sending an embedded image";
string imageContentid = "someimage.jpg"; // Content ID can be anything. It is referenced in the HTML body
oAttach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", imageContentid);
mailItem.HTMLBody = String.Format(
"<body>Hello,<br><br>This is an example of an embedded image:<br><br><img src=\"cid:{0}\"><br><br>Regards,<br>Tarik</body>",
imageContentid);
// Add recipient
Outlook.Recipient recipient = mailItem.Recipients.Add("[email protected]");
recipient.Resolve();
// Send.
mailItem.Send();
}
}
}
just run in linux terminal to get phpinfo .
php -r 'phpinfo();'
and to run file like index.php
php -f index.php
The following can be used to get the date:
function date_date() {
var date = new Date();
var year = date.getYear();
var month = date.getMonth() + 1; if(month.toString().length==1){var month =
'0'+month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0'+day;}
var hour = date.getHours(); if(hour.toString().length==1){var hour = '0'+hour;}
var minu = date.getMinutes(); if(minu.toString().length==1){var minu = '0'+minu;}
var seco = date.getSeconds(); if(seco.toString().length==1){var seco = '0'+seco;}
var date = year+'·'+month+'·'+day+'·'+hour+'·'+minu+'·'+seco;
Logger.log(date);
}
What's the difference?
The difference is that hashing is a one way function, where encryption is a two-way function.
So, how do you ascertain that the password is right?
Therefore, when a user submits a password, you don't decrypt your stored hash, instead you perform the same bcrypt
operation on the user input and compare the hashes. If they're identical, you accept the authentication.
Should you hash or encrypt passwords?
What you're doing now -- hashing the passwords -- is correct. If you were to simply encrypt passwords, a breach of security of your application could allow a malicious user to trivially learn all user passwords. If you hash (or better, salt and hash) passwords, the user needs to crack passwords (which is computationally expensive on bcrypt
) to gain that knowledge.
As your users probably use their passwords in more than one place, this will help to protect them.
You can use +
if you know all the values are strings. Jinja also provides the ~
operator, which will ensure all values are converted to string first.
{% set my_string = my_string ~ stuff ~ ', '%}
Just remove the throw
from the catch block — change it to an echo
or otherwise handle the error.
It's not telling you that objects can only be thrown in the catch block, it's telling you that only objects can be thrown, and the location of the error is in the catch block — there is a difference.
In the catch block you are trying to throw something you just caught — which in this context makes little sense anyway — and the thing you are trying to throw is a string.
A real-world analogy of what you are doing is catching a ball, then trying to throw just the manufacturer's logo somewhere else. You can only throw a whole object, not a property of the object.
Besides the previous post instructions, I had to install the package Microsoft.jQuery.Unobtrusive.Ajax and add to the view the following line
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
What you want to do is put the console into "raw" mode (line editing bypassed and no enter key required) as opposed to "cooked" mode (line editing with enter key required.) On UNIX systems, the 'stty' command can change modes.
Now, with respect to Java... see Non blocking console input in Python and Java. Excerpt:
If your program must be console based, you have to switch your terminal out of line mode into character mode, and remember to restore it before your program quits. There is no portable way to do this across operating systems.
One of the suggestions is to use JNI. Again, that's not very portable. Another suggestion at the end of the thread, and in common with the post above, is to look at using jCurses.
Sohnee solutions is cleaner, but you can also try
window["bootbox"]
The itertools module has lots of great stuff in it. So if a standard slice (as used by Levon) does not do what you want, then try the islice
function:
from itertools import islice
l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
iterator = islice(l, 10)
for item in iterator:
print item
If the image is in a container with a responsive width:
HTML
<div class="img-container">
<img src="" alt="">
</div>
CSS
.img-container {
position: relative;
&::after {
content: "";
display: block;
padding-bottom: 100%;
}
img {
position: absolute;
width: 100%;
height: 100%;
object-fit: cover;
}
}
Try the following:
var count=Object.keys(result).length;
Does not work IE8 and lower.
The problem must be with the value Model.Id which is null. You can confirm by assigning a value, e.g
@{
var blogPostId = 1;
}
If the error disappers, then u need to make sure that your model Id has a value before passing it to the view
In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.
So to convert string limit="100"
to a number, you need to do
limit = int(limit) # will return new object (integer) and assign to "limit"
If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:
def int_in_place(mutable):
mutable[0] = int(mutable[0])
mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer
But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).
top
refers to the window object which contains all the current frames ( father of the rest of the windows ). window
is the current window
.
http://www.howtocreate.co.uk/tutorials/javascript/browserinspecific
so top.location.href
can contain the "master" page link containing all the frames, while window.location.href
just contains the "current" page link.
the loginuser class uses a trait called AuthenticatesUsers
if you open that trait you will see the functions (this applies for other controllers)
Illuminate\Foundation\Auth\AuthenticatesUsers;
here is the trait code https://github.com/laravel/framework/blob/5.1/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
sorry for the bad format, im using my phone
also Auth::routes()
it just calls a function that returns the auth routes thats it (i think)
The equivalent of null
in VB is Nothing
so your check wants to be:
If editTransactionRow.pay_id IsNot Nothing Then
stTransactionPaymentID = editTransactionRow.pay_id
End If
Or possibly, if you are actually wanting to check for a SQL null value:
If editTransactionRow.pay_id <> DbNull.Value Then
...
End If
Yes, should try reinstall mysql, but use the --reinstall
flag to force a package reconfiguration. So the operating system service configuration is not skipped:
sudo apt --reinstall install mysql-server
Send the data from the form:
$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
type: "PUT"
url: url
dataType: "script"
data: postData
You could subscribe for the onkeypress event:
<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />
and then define the isNumber
function:
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
You can see it in action here.
In Kotlin will be :
activity?.applicationContext?.let {
it//<- you context
}
Maybe you'd find Redux suiting your needs. It's no overkill and comes packed solely with bare features most of us would require. The dev and contributors were very strict on what code was contributed.
This is the official page
You should pass length into fwrite instead of sizeof(buffer).
pkill NAMEofAPP
Non rooted marshmallow, termux & terminal emulator.
A very lean solution based on Scanner
:
Scanner scanner = new Scanner( new File("poem.txt") );
String text = scanner.useDelimiter("\\A").next();
scanner.close(); // Put this call in a finally block
Or, if you want to set the charset:
Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" );
String text = scanner.useDelimiter("\\A").next();
scanner.close(); // Put this call in a finally block
Or, with a try-with-resources block, which will call scanner.close()
for you:
try (Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" )) {
String text = scanner.useDelimiter("\\A").next();
}
Remember that the Scanner
constructor can throw an IOException
. And don't forget to import java.io
and java.util
.
Source: Pat Niemeyer's blog
Answers here seem outdated. Pandas now has a factorize()
function and you can create categories as:
df.col.factorize()
Function signature:
pandas.factorize(values, sort=False, na_sentinel=- 1, size_hint=None)
Fetch vs Pull
Git fetch just updates your repo data, but a git pull will basically perform a fetch and then merge the branch pulled
What is the difference between 'git pull' and 'git fetch'?
Merge vs Rebase
from Atlassian SourceTree Blog, Merge or Rebase:
Merging brings two lines of development together while preserving the ancestry of each commit history.
In contrast, rebasing unifies the lines of development by re-writing changes from the source branch so that they appear as children of the destination branch – effectively pretending that those commits were written on top of the destination branch all along.
Also, check out Learn Git Branching, which is a nice game that has just been posted to HackerNews (link to post) and teaches a lot of branching and merging tricks. I believe it will be very helpful in this matter.
Use this CSS (jsFiddle example):
input:disabled.btn:hover,
input:disabled.btn:active,
input:disabled.btn:focus {
color: green
}
You have to write the most outer element on the left and the most inner element on the right.
.btn:hover input:disabled
would select any disabled input elements contained in an element with a class btn
which is currently hovered by the user.
I would prefer :disabled
over [disabled]
, see this question for a discussion: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?
By the way, Laravel (PHP) generates the HTML - not the browser.
To ensure an enum value exists and then parse it, you can also do the following.
// Fake Day of Week
string strDOWFake = "SuperDay";
// Real Day of Week
string strDOWReal = "Friday";
// Will hold which ever is the real DOW.
DayOfWeek enmDOW;
// See if fake DOW is defined in the DayOfWeek enumeration.
if (Enum.IsDefined(typeof(DayOfWeek), strDOWFake))
{
// This will never be reached since "SuperDay"
// doesn't exist in the DayOfWeek enumeration.
enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWFake);
}
// See if real DOW is defined in the DayOfWeek enumeration.
else if (Enum.IsDefined(typeof(DayOfWeek), strDOWReal))
{
// This will parse the string into it's corresponding DOW enum object.
enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWReal);
}
// Can now use the DOW enum object.
Console.Write("Today is " + enmDOW.ToString() + ".");
public void convert(int s)
{
System.out.println(NumberFormat.getNumberInstance(Locale.US).format(s));
}
public static void main(String args[])
{
LocalEx n=new LocalEx();
n.convert(10000);
}
<style>
.dotted {border: 1px dotted #ff0000; border-style: none none dotted; color: #fff; background-color: #fff; }
</style>
<hr class='dotted' />
I've been looking for a solution that i can use on bootstrap 4 navbars and other groups of links.
For one reason or another most solutions didn't work especially the ones that try to add 'active' to links onclick because of course once the link is clicked if it takes you to another page then the 'active' you added won't be there because the DOM has changed. Many of the other solutions didn't work either because they often did not match the link or they matched more than one.
This elegant solution is fine for links that are different ie: about.php, index.php, etc...
$(function() {
$('nav a[href^="' + location.pathname.split("/")[2] + '"]').addClass('active');
});
However when it came to the same links with different query strings such as index.php?tag=a, index.php?tag=b, index.php?tag=c it would set all of them to active whichever was clicked as it's matching the pathname not the query as well.
So i tried this code which matched the pathname and the query string and it worked on all the links with query strings but when a link like index.php was clicked it would set the similar query string links active as well. This is because my function is returning an empty string if there is no query string in the link, again just matching the pathname.
$(function() {
$('nav a[href^="' + location.pathname.split("/")[2] + returnQueryString(location.href.split("?")[1]) + '"]').addClass('active');
});
/** returns a query string if there, else an empty string */
function returnQueryString (element) {
if (element === undefined)
return "";
else
return '?' + element;
}
So in the end i abandoned this route and kept it simple and wrote this.
$('.navbar a').each(function(index, element) {
//console.log(index+'-'+element.href);
//console.log(location.href);
/** look at each href in the navbar
* if it matches the location.href then set active*/
if (element.href === location.href){
//console.log("---------MATCH ON "+index+" --------");
$(element).addClass('active');
}
});
It works on all links with or without query strings because element.href and location.href both return the full path. For other menus etc you can simply change the parent class selector (navbar) for another ie:
$('.footer a').each(function(index, element)...
One last thing which also seems important and that is the js & css library's you are using however that's another post perhaps. I hope this helps and contributes.
If you are using MySQL interactively, you can set your pager to use sed
like this:
$ mysql -u <user> p<password>
mysql> pager sed 's/,/\n/g'
PAGER set to 'sed 's/,/\n/g''
mysql> SELECT blah FROM blah WHERE blah = blah
.
.
.
"blah":"blah"
"blah":"blah"
"blah":"blah"
If you don't use sed
as the pager, the output is like this:
"blah":"blah","blah":"blah","blah":"blah"
probably graded as a non-pythonic way to do this but this'll give the result you want in a line:
new_df = pd.DataFrame(zip(email,list))
Result:
email list
0 [email protected] [1.0, 0.0, 0.0]
1 [email protected] [2.0, 0.0, 0.0]
2 [email protected] [1.0, 0.0, 0.0]
3 [email protected] [4.0, 0.0, 3.0]
4 [email protected] [1.0, 5.0, 0.0]
This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.
So, which XML parsing module to pick?
Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.
Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.
Update 2015-10-24: it seems somebody found a solution to use node-gyp on Windows without installing VS: https://github.com/nodejs/node-gyp/issues/629#issuecomment-138276692
401 means "Unauthorized", so there must be something with your credentials.
I think that java URL
does not support the syntax you are showing. You could use an Authenticator instead.
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(login, password.toCharArray());
}
});
and then simply invoking the regular url, without the credentials.
The other option is to provide the credentials in a Header:
String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);
PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.
As an addition and observation to the other useful answers, it's worth noticing that actually doing [:10]
as slicing will return the first 10 elements of the list, not the last 10...
To get the last 10 you should do [-10:]
instead (see here). This will help you avoid using order_by('-id')
with the -
to reverse the elements.
You can use the _contains function from the underscore.js library to achieve this:
if (_.contains(haystack, needle)) {
console.log("Needle found.");
};
If you want to connect to SQL server remotly you need to use a software - like Sql Server Management studio.
The computers doesn't need to be on the same network - but they must be able to connect each other using a communication protocol like tcp/ip, and the server must be set up to support incoming connection of the type you choose.
if you want to connect to another computer (to browse files ?) you use other tools, and not sql server (you can map a drive and access it through there ect...)
To Enable SQL connection using tcp/ip read this article:
For Sql Express: express For Sql 2008: 2008
Make sure you enable access through the machine firewall as well.
You might need to install either SSMS or Toad on the machine your using to connect to the server. both you can download from their's company web site.
By default, it begins by processing the first target that does not begin with a .
aka the default goal; to do that, it may have to process other targets - specifically, ones the first target depends on.
The GNU Make Manual covers all this stuff, and is a surprisingly easy and informative read.
To see all tables:
.tables
To see a particular table:
.schema [tablename]
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
if(data==<when do you want to clear the form>){
$('#<form Id>').find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
});
Just adding for who might need.. Don't forget to alter the table!
ALTER TABLE table_name ADD FULLTEXT(column_name);
you need to create a type and make the attribute of that type:
<xs:simpleType name="curr">
<xs:restriction base="xs:string">
<xs:enumeration value="pounds" />
<xs:enumeration value="euros" />
<xs:enumeration value="dollars" />
</xs:restriction>
</xs:simpleType>
then:
<xs:complexType>
<xs:attribute name="currency" type="curr"/>
</xs:complexType>
The name
property is marked as protected
. This was added in TypeScript 1.3 and is now firmly established.
The makeSound
method is marked as abstract
, as is the class. You cannot directly instantiate an Animal
now, because it is abstract. This is part of TypeScript 1.6, which is now officially live.
abstract class Animal {
constructor(protected name: string) { }
abstract makeSound(input : string) : string;
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
makeSound(input : string) : string {
return "sssss"+input;
}
move() {
alert("Slithering...");
super.move(5);
}
}
The old way of mimicking an abstract method was to throw an error if anyone used it. You shouldn't need to do this any more once TypeScript 1.6 lands in your project:
class Animal {
constructor(public name) { }
makeSound(input : string) : string {
throw new Error('This method is abstract');
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
constructor(name) { super(name); }
makeSound(input : string) : string {
return "sssss"+input;
}
move() {
alert("Slithering...");
super.move(5);
}
}
node -v
v9.10.1
If you try to console log query object directly you will get error TypeError: Cannot convert object to primitive value
So I would suggest use JSON.stringify
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const path = parsedUrl.pathname, query = parsedUrl.query;
const method = req.method;
res.end("hello world\n");
console.log(`Request received on: ${path} + method: ${method} + query:
${JSON.stringify(query)}`);
console.log('query: ', query);
});
server.listen(3000, () => console.log("Server running at port 3000"));
So doing curl http://localhost:3000/foo\?fizz\=buzz
will return Request received on: /foo + method: GET + query: {"fizz":"buzz"}
import inspect
def func(a,b,c=5):
pass
inspect.getargspec(func) # inspect.signature(func) in Python 3
(['a', 'b', 'c'], None, None, (5,))
Firstly, your example is looking quite correct and works well on my machine. You may go another way.
curl $CURLARGS $RVMHTTP > ./install.sh
All output now storing in ./install.sh
file, which you can edit and execute.
You could just try using return false (return false overrides default behaviour on every DOM element) like that :
myform.onsubmit = function ()
{
// do what you want
return false
}
and then submit your form using myform.submit()
or alternatively :
mybutton.onclick = function ()
{
// do what you want
return false
}
Also, if you use type="button"
your form will not be submitted.
Create a new .bashrc file in your ~ directory.
There you can put your commands that you want executed everytime you start the bash
Four years passed, Google gave me this answer. With the standard C++11 (aka C++0x) there is actually a new pleasant way of doing this (at the price of breaking backward compatibility): the new auto
keyword. It saves you the pain of having to explicitly specify the type of the iterator to use (repeating the vector type again), when it is obvious (to the compiler), which type to use. With v
being your vector
, you can do something like this:
for ( auto i = v.begin(); i != v.end(); i++ ) {
std::cout << *i << std::endl;
}
C++11 goes even further and gives you a special syntax for iterating over collections like vectors. It removes the necessity of writing things that are always the same:
for ( auto &i : v ) {
std::cout << i << std::endl;
}
To see it in a working program, build a file auto.cpp
:
#include <vector>
#include <iostream>
int main(void) {
std::vector<int> v = std::vector<int>();
v.push_back(17);
v.push_back(12);
v.push_back(23);
v.push_back(42);
for ( auto &i : v ) {
std::cout << i << std::endl;
}
return 0;
}
As of writing this, when you compile this with g++, you normally need to set it to work with the new standard by giving an extra flag:
g++ -std=c++0x -o auto auto.cpp
Now you can run the example:
$ ./auto
17
12
23
42
Please note that the instructions on compiling and running are specific to gnu c++ compiler on Linux, the program should be platform (and compiler) independent.
git rev-list --max-parents=0 HEAD
(from tiho's comment. As Chris Johnsen notices, --max-parents
was introduced after this answer was posted.)
Technically, there may be more than one root commit. This happens when multiple previously independent histories are merged together. It is common when a project is integrated via a subtree merge.
The git.git
repository has six root commits in its history graph (one each for Linus’s initial commit, gitk, some initially separate tools, git-gui, gitweb, and git-p4). In this case, we know that e83c516
is the one we are probably interested in. It is both the earliest commit and a root commit.
It is not so simple in the general case.
Imagine that libfoo has been in development for a while and keeps its history in a Git repository (libfoo.git
). Independently, the “bar” project has also been under development (in bar.git
), but not for as long libfoo (the commit with the earliest date in libfoo.git
has a date that precedes the commit with the earliest date in bar.git
). At some point the developers of “bar” decide to incorporate libfoo into their project by using a subtree merge. Prior to this merge it might have been trivial to determine the “first” commit in bar.git
(there was probably only one root commit). After the merge, however, there are multiple root commits and the earliest root commit actually comes from the history of libfoo, not “bar”.
You can find all the root commits of the history DAG like this:
git rev-list --max-parents=0 HEAD
For the record, if --max-parents
weren't available, this does also work:
git rev-list --parents HEAD | egrep "^[a-f0-9]{40}$"
If you have useful tags in place, then git name-rev
might give you a quick overview of the history:
git rev-list --parents HEAD | egrep "^[a-f0-9]{40}$" | git name-rev --stdin
Use this often? Hard to remember? Add a git alias for quick access
git config --global alias.first "rev-list --max-parents=0 HEAD"
Now you can simply do
git first
Less than or equal:
User.objects.filter(userprofile__level__lte=0)
Greater than or equal:
User.objects.filter(userprofile__level__gte=0)
Likewise, lt
for less than and gt
for greater than. You can find them all in the documentation.
Try display phpinfo() by file and check this var.
I had a problem where the images would not show and it wasn't the relative path. I even hard coded the actual path and the image still did not show. I had changed my webserver to run on port 8080 and neither
<img src="c:/public/images/<?php echo $image->filename; ?>" width="100" />
<img src="c:/public/images/mypic.jpg" width="100" />
would not work.
<img src="../../images/<?php echo $photo->filename; ?>" width="100" />
Did not work either. This did work :
<img src="http://localhost:8080/public/images/<?php echo $image->filename; ?>" width="100" />
You could decompose the date into it's constituent parts and then concatenate them together like this:
MsgBox(Now.Day & "/" & Now.Month & "/" & Now.Year)
Personally I like the exception approach although I would make it a little more terse:
class String
def integer?(str)
!!Integer(str) rescue false
end
end
However, as others have already stated, this doesn't work with Octal strings.
This is my favourite way of decoding HTML characters. The advantage of using this code is that tags are also preserved.
function decodeHtml(html) {
var txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
Example: http://jsfiddle.net/k65s3/
Input:
Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>
Output:
Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>
First use this Namespace:
using System.Drawing;
Add this anywhere on your form:
listBox.DrawMode = DrawMode.OwnerDrawFixed;
listBox.DrawItem += listBox_DrawItem;
Here is the Event Handler:
private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
Graphics g = e.Graphics;
g.FillRectangle(new SolidBrush(Color.White), e.Bounds);
ListBox lb = (ListBox)sender;
g.DrawString(lb.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), new PointF(e.Bounds.X, e.Bounds.Y));
e.DrawFocusRectangle();
}
For those looking for an Excel formula based on WGS-84 & GRS-80 standards:
=ACOS(COS(RADIANS(90-Lat1))*COS(RADIANS(90-Lat2))+SIN(RADIANS(90-Lat1))*SIN(RADIANS(90-Lat2))*COS(RADIANS(Long1-Long2)))*6371
If you want to view the information in a slice in the same format that you'd use to type it in (something like ["one", "two", "three"]
), here's a code example showing how to do that:
package main
import (
"fmt"
"strings"
)
func main() {
test := []string{"one", "two", "three"} // The slice of data
semiformat := fmt.Sprintf("%q\n", test) // Turn the slice into a string that looks like ["one" "two" "three"]
tokens := strings.Split(semiformat, " ") // Split this string by spaces
fmt.Printf(strings.Join(tokens, ", ")) // Join the Slice together (that was split by spaces) with commas
}
I provide another answer that I found by api-client-library
by Google
try {
DateTime dateTime = DateTime.parseRfc3339(date);
dateTime = new DateTime(new Date(dateTime.getValue()), TimeZone.getDefault());
long timestamp = dateTime.getValue(); // get date in timestamp
int timeZone = dateTime.getTimeZoneShift(); // get timezone offset
} catch (NumberFormatException e) {
e.printStackTrace();
}
Installation guide,
https://developers.google.com/api-client-library/java/google-api-java-client/setup#download
Here is API reference,
https://developers.google.com/api-client-library/java/google-http-java-client/reference/1.20.0/com/google/api/client/util/DateTime
Source code of DateTime
Class,
https://github.com/google/google-http-java-client/blob/master/google-http-client/src/main/java/com/google/api/client/util/DateTime.java
DateTime
unit tests,
https://github.com/google/google-http-java-client/blob/master/google-http-client/src/test/java/com/google/api/client/util/DateTimeTest.java#L121
Ok, I've gone back and figured some things out. This is a ROUGH SOLUTION to what I was proposing, but it seems to be functional.
First, I made the numbers a series of unordered lists. An unordered list will normally have a disc at the beginning of each list item (
Then, I made the whole list display: table-row. Here, why don't I just paste you the code instead of gabbing about it?
<html>
<head>
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
<title>Result</title>
</head>
<body>
<div><ul>
<li>1.</li>
<li><p>2.</p></li>
<li>10.</li>
<li><p>110.</p></li>
<li>1000.</li>
</ul>
</div>
<div>
<p>Some author</p>
<p>Another author</p>
<p>Author #10</p>
<p>Author #110</p>
<p>The one thousandth author today will win a free i-Pod!!!! This line also wraps around so that we can see how hanging indents look.</p>
</div>
</body>
</html>'
CSS:
ul li{
list-style: none;
display: table-row;
text-align: right;
}
div {
float: left;
display: inline-block;
margin: 0.2em;
}
This seems to align the text in the 2nd div with the numbers in the ordered list in the first div. I've surrounded both the list and the text with a tag so that I can just tell all divs to display as inline-blocks. This lined them up nicely.
The margin is there to put a space between the period and the start of the text. Otherwise, they run right up against one another and it looks like an eyesore.
My employer wanted wrapped-around text (for longer bibliograhical entries) to line up with the start of the first line, not the left-hand margin. Originally I was fidgeting with a positive margin and a negative text indent, but then I realized that when I switched to two different divs, this had the effect of making it so that the text all lined up because the left-hand margin of the div was the margin where text naturally began. Thus, all I needed was a 0.2em margin to add some space, and everything else lined up swimmingly.
I hope this helps if OP was having a similar issue...I had a hard time understanding him/her.
You can look into UglifyJS
: http://jstarrdewar.com/blog/2013/02/28/use-uglify-to-automatically-strip-debug-messages-from-your-javascript/, https://github.com/mishoo/UglifyJS
I haven't tried it yet.
Quoting,
if (typeof DEBUG === 'undefined') DEBUG = true; // will be removed
function doSomethingCool() {
DEBUG && console.log("something cool just happened"); // will be removed }
...The log message line will be removed by Uglify's dead-code remover (since it will erase any conditional that will always evaluate to false). So will that first conditional. But when you are testing as uncompressed code, DEBUG will start out undefined, the first conditional will set it to true, and all your console.log() messages will work.
As of Git 2.23 you can use git blame --ignore-rev
For the example given in the question this would be:
git blame -L10,+1 src/options.cpp --ignore-rev fe25b6d
(however it's a trick question because fe25b6d is the file's first revision!)
I saw this error
Only local connections are allowed
And I updated both the selenium webdriver, and the google-chrome-stable
package
webdriver-manager update
zypper install google-chrome-stable
This site reports the latest version of the chrome driver https://sites.google.com/a/chromium.org/chromedriver/
My working versions are chromedriver 2.41 and google-chrome-stable 68
I don't understand why Nick is using margin-left: 200px;
instead off floating the other div
to the left
or right
, I've just tweaked his markup, you can use float
for both elements instead of using margin-left
.
#main {
margin: auto;
width: 400px;
}
#sidebar {
width: 100px;
min-height: 400px;
background: red;
float: left;
}
#page-wrap {
width: 300px;
background: #0f0;
min-height: 400px;
float: left;
}
.clear:after {
clear: both;
display: table;
content: "";
}
Also, I've used .clear:after
which am calling on the parent element, just to self clear the parent.
I resolved my problem doing this:
json_encode($array, JSON_UNESCAPED_UNICODE)
to encode the data;The result is a .json file encoded to ANSI as UTF-8.
Apart from following the optimizations mentioned in existing answers (not much helpful, was still painfully slow), doing below did the trick for me.
HP Notebook with 6 GM RAM and i5 processor I have, still android studio was terribly slow. After checking task manager for memory usage, noticed that there is a software called "HP Touchpoint Analytics Client" that was taking more than 1 GB memory. Found that it's a spyware installed by HP in Windows 10 after searching about it in Google.
Uninstalled a bunch of HP software which does nothing and slows down the system. Now, Android studio is considerably fast - Gradle build completes in less than 30 seconds when compared to more than 2 minutes before. Every keystroke would take 5 seconds to respond, now it is real time and performance is comparable with Eclipse.
This might be true for Laptops from other vendors as well like Dell, etc. HP really messed up the user experience with their spyware for Windows 10 users. Uninstall them, it will help Android studio and improves the overall laptop experience as well.
Hope this helps someone. Thanks.
You can add comments to the end of a batch file with this syntax:
@echo off
:: Start of code
...
:: End of code
(I am a comment
So I am!
This can be only at the end of batch files
Just make sure you never use a closing parentheses.
Attributions: Leo Guttirez Ramirez on https://www.robvanderwoude.com/comments.php
After figuring out which ViewPager methods are called by ViewPager and which are for other purposes, I came up with a solution. I present it here since I see a lot of people have struggled with this and I didn't see any other relevant answers.
First, here's my adapter; hopefully comments within the code are sufficient:
public class MainPagerAdapter extends PagerAdapter
{
// This holds all the currently displayable views, in order from left to right.
private ArrayList<View> views = new ArrayList<View>();
//-----------------------------------------------------------------------------
// Used by ViewPager. "Object" represents the page; tell the ViewPager where the
// page should be displayed, from left-to-right. If the page no longer exists,
// return POSITION_NONE.
@Override
public int getItemPosition (Object object)
{
int index = views.indexOf (object);
if (index == -1)
return POSITION_NONE;
else
return index;
}
//-----------------------------------------------------------------------------
// Used by ViewPager. Called when ViewPager needs a page to display; it is our job
// to add the page to the container, which is normally the ViewPager itself. Since
// all our pages are persistent, we simply retrieve it from our "views" ArrayList.
@Override
public Object instantiateItem (ViewGroup container, int position)
{
View v = views.get (position);
container.addView (v);
return v;
}
//-----------------------------------------------------------------------------
// Used by ViewPager. Called when ViewPager no longer needs a page to display; it
// is our job to remove the page from the container, which is normally the
// ViewPager itself. Since all our pages are persistent, we do nothing to the
// contents of our "views" ArrayList.
@Override
public void destroyItem (ViewGroup container, int position, Object object)
{
container.removeView (views.get (position));
}
//-----------------------------------------------------------------------------
// Used by ViewPager; can be used by app as well.
// Returns the total number of pages that the ViewPage can display. This must
// never be 0.
@Override
public int getCount ()
{
return views.size();
}
//-----------------------------------------------------------------------------
// Used by ViewPager.
@Override
public boolean isViewFromObject (View view, Object object)
{
return view == object;
}
//-----------------------------------------------------------------------------
// Add "view" to right end of "views".
// Returns the position of the new view.
// The app should call this to add pages; not used by ViewPager.
public int addView (View v)
{
return addView (v, views.size());
}
//-----------------------------------------------------------------------------
// Add "view" at "position" to "views".
// Returns position of new view.
// The app should call this to add pages; not used by ViewPager.
public int addView (View v, int position)
{
views.add (position, v);
return position;
}
//-----------------------------------------------------------------------------
// Removes "view" from "views".
// Retuns position of removed view.
// The app should call this to remove pages; not used by ViewPager.
public int removeView (ViewPager pager, View v)
{
return removeView (pager, views.indexOf (v));
}
//-----------------------------------------------------------------------------
// Removes the "view" at "position" from "views".
// Retuns position of removed view.
// The app should call this to remove pages; not used by ViewPager.
public int removeView (ViewPager pager, int position)
{
// ViewPager doesn't have a delete method; the closest is to set the adapter
// again. When doing so, it deletes all its views. Then we can delete the view
// from from the adapter and finally set the adapter to the pager again. Note
// that we set the adapter to null before removing the view from "views" - that's
// because while ViewPager deletes all its views, it will call destroyItem which
// will in turn cause a null pointer ref.
pager.setAdapter (null);
views.remove (position);
pager.setAdapter (this);
return position;
}
//-----------------------------------------------------------------------------
// Returns the "view" at "position".
// The app should call this to retrieve a view; not used by ViewPager.
public View getView (int position)
{
return views.get (position);
}
// Other relevant methods:
// finishUpdate - called by the ViewPager - we don't care about what pages the
// pager is displaying so we don't use this method.
}
And here's some snips of code showing how to use the adapter.
class MainActivity extends Activity
{
private ViewPager pager = null;
private MainPagerAdapter pagerAdapter = null;
//-----------------------------------------------------------------------------
@Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView (R.layout.main_activity);
... do other initialization, such as create an ActionBar ...
pagerAdapter = new MainPagerAdapter();
pager = (ViewPager) findViewById (R.id.view_pager);
pager.setAdapter (pagerAdapter);
// Create an initial view to display; must be a subclass of FrameLayout.
LayoutInflater inflater = context.getLayoutInflater();
FrameLayout v0 = (FrameLayout) inflater.inflate (R.layout.one_of_my_page_layouts, null);
pagerAdapter.addView (v0, 0);
pagerAdapter.notifyDataSetChanged();
}
//-----------------------------------------------------------------------------
// Here's what the app should do to add a view to the ViewPager.
public void addView (View newPage)
{
int pageIndex = pagerAdapter.addView (newPage);
// You might want to make "newPage" the currently displayed page:
pager.setCurrentItem (pageIndex, true);
}
//-----------------------------------------------------------------------------
// Here's what the app should do to remove a view from the ViewPager.
public void removeView (View defunctPage)
{
int pageIndex = pagerAdapter.removeView (pager, defunctPage);
// You might want to choose what page to display, if the current page was "defunctPage".
if (pageIndex == pagerAdapter.getCount())
pageIndex--;
pager.setCurrentItem (pageIndex);
}
//-----------------------------------------------------------------------------
// Here's what the app should do to get the currently displayed page.
public View getCurrentPage ()
{
return pagerAdapter.getView (pager.getCurrentItem());
}
//-----------------------------------------------------------------------------
// Here's what the app should do to set the currently displayed page. "pageToShow" must
// currently be in the adapter, or this will crash.
public void setCurrentPage (View pageToShow)
{
pager.setCurrentItem (pagerAdapter.getItemPosition (pageToShow), true);
}
}
Finally, you can use the following for your activity_main.xml
layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.support.v4.view.ViewPager>
If all other options have failed, trying recreating the data import task and/or the connection manager. If you've made any changes since the task was originally created, this can sometimes do the trick. I know it's the equivalent of rebooting, but, hey, if it works, it works.
Spring MVC will give you the HttpRequest if you just add it to your controller method signature:
For instance:
/**
* Generate a PDF report...
*/
@RequestMapping(value = "/report/{objectId}", method = RequestMethod.GET)
public @ResponseBody void generateReport(
@PathVariable("objectId") Long objectId,
HttpServletRequest request,
HttpServletResponse response) {
// ...
// Here you can use the request and response objects like:
// response.setContentType("application/pdf");
// response.getOutputStream().write(...);
}
As you see, simply adding the HttpServletRequest
and HttpServletResponse
objects to the signature makes Spring MVC to pass those objects to your controller method. You'll want the HttpSession
object too.
EDIT: It seems that HttpServletRequest/Response are not working for some people under Spring 3. Try using Spring WebRequest/WebResponse objects as Eduardo Zola pointed out.
I strongly recommend you to have a look at the list of supported arguments that Spring MVC is able to auto-magically inject to your handler methods.
I came up with this idea and it works perfectly. Okay so basically we want to get rid of the videos first frame from the display and then resize the poster to the videos actual size. If we then set the dimensions we have completed one of these tasks. Then only one remains. So now, the only way I know to get rid of the first frame is to actually define a poster. However we are going to give the video a faked one, one that doesn't exist. This will result in a blank display with the background transparent. I.e. our parent div's background will be visible.
Simple to use, however it might not work with all web browsers if you want to resize the dimension of the background of the div to the dimension of the video since my code is using "background-size".
HTML/HTML5:
<div class="video_poster">
<video poster="dasdsadsakaslmklda.jpg" controls>
<source src="videos/myvideo.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<div>
CSS:
video{
width:694px;
height:390px;
}
.video_poster{
width:694px;
height:390px;
background-size:694px 390px;
background-image:url(images/myvideo_poster.jpg);
}
Use this code:
'{:x}'.format(int(line))
it allows you to specify a number of digits too:
'{:06x}'.format(123)
# '00007b'
For Python 2.6 use
'{0:x}'.format(int(line))
or
'{0:06x}'.format(int(line))
Use facebook feed dialog instead of share dialog.
Example:
The error "client denied by server configuration" generally means that somewhere in your configuration are Allow from
and Deny from
directives that are preventing access. Read the mod_authz_host documentation for more details.
You should be able to solve this in your VirtualHost by adding something like:
<Location />
Allow from all
Order Deny,Allow
</Location>
Or alternatively with a Directory
directive:
<Directory "D:/Devel/matysart/matysart_dev1">
Allow from all
Order Deny,Allow
</Directory>
Some investigation of your Apache configuration files will probably turn up default restrictions on the default DocumentRoot.
In here, We can define user defined comparator:
Below code :
import java.util.*;
import java.util.Collections;
import java.util.Comparator;
class Checker implements Comparator<String>
{
public int compare(String str1, String str2)
{
if (str1.length() < str2.length()) return -1;
else return 1;
}
}
class Main
{
public static void main(String args[])
{
PriorityQueue<String> queue=new PriorityQueue<String>(5, new Checker());
queue.add("india");
queue.add("bangladesh");
queue.add("pakistan");
while (queue.size() != 0)
{
System.out.printf("%s\n",queue.remove());
}
}
}
Output :
india pakistan bangladesh
Difference between the offer and add methods : link
As others mentioned, it's only possible via reflection in certain circumstances.
If you really need the type, this is the usual (type-safe) workaround pattern:
public class GenericClass<T> {
private final Class<T> type;
public GenericClass(Class<T> type) {
this.type = type;
}
public Class<T> getMyType() {
return this.type;
}
}
As it seems impossible to filter the XPath message data (it isn't in the XML to filter), you can also use powershell to search:
Get-WinEvent -LogName System | Where-Object {$_.Message -like "*recycle*"}
From this, I can see that the event Id for recycling seems to be 5074, so you can filter on this as well. I hope this helps someone as this information seemed to take a lot longer than expected to work out.
This along with @BlackHawkDesign comment should help you find what you need.
I had the same issue. Maybe interesting to mention is that you have to configure in which cases the app pool recycle event is logged. By default it's in a couple of cases, not all of them. You can do that in IIS > app pools > select the app pool > advanced settings > expand generate recycle event log entry – BlackHawkDesign Jan 14 '15 at 10:00
I know this is an old post, probably no one would scroll this far, I know I didn't. So, after hours of trying different stuff, I found this blog and dude killed it. Simplest way to do this, tried it and it works like a charm.
In the ViewModel:
...
public bool CanClose { get; set; }
private RelayCommand closeCommand;
public ICommand CloseCommand
{
get
{
if(closeCommand == null)
(
closeCommand = new RelayCommand(param => Close(), param => CanClose);
)
}
}
public void Close()
{
this.Close();
}
...
add an Action property to the ViewModel, but define it from the View’s code-behind file. This will let us dynamically define a reference on the ViewModel that points to the View.
On the ViewModel, we’ll simply add:
public Action CloseAction { get; set; }
And on the View, we’ll define it as such:
public View()
{
InitializeComponent() // this draws the View
ViewModel vm = new ViewModel(); // this creates an instance of the ViewModel
this.DataContext = vm; // this sets the newly created ViewModel as the DataContext for the View
if ( vm.CloseAction == null )
vm.CloseAction = new Action(() => this.Close());
}
I improved code i used
public static float getAPIVerison() {
float f=1f;
try {
StringBuilder strBuild = new StringBuilder();
strBuild.append(android.os.Build.VERSION.RELEASE.substring(0, 2));
f= Float.valueOf(strBuild.toString());
} catch (NumberFormatException e) {
Log.e("myApp", "error retriving api version" + e.getMessage());
}
return f;
}
Change display:inline to display:inline-block
.test {
width:200px;
display:inline-block;
overflow: auto;
white-space: nowrap;
margin:0px auto;
border:1px red solid;
}