Replace the username and password with Integrated Security=SSPI;
So the connection string should be
<connectionStrings>
<add name="NorthwindContex"
connectionString="data source=localhost;
initial catalog=northwind;persist security info=True;
Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
If your URL has dots in the domain name, IE will treat it like it's an internet address and not local. You have at least two options:
Go to the site and cancel the login dialog. Let this happen:
In IE’s settings:
I had just upgraded to VS 2013 from VS 2012 and the current user identity (HttpContext.User.Identity) was coming through as anonymous.
I tried changing the IIS express applicationhost.config, no difference.
The solution was to look at the properties of the web project, hit F4 to get the project properties when you have the top level of the project selected. Do not right click on the project and select properties, this is something entirely different.
Change Anonymous Authentication to be Disabled and Windows Authentication to be Enabled.
Works like gravy :)
These are the different variables you have access to and their values, depending on the IIS configuration.
Scenario 1: Anonymous Authentication in IIS with impersonation off.
HttpContext.Current.Request.LogonUserIdentity.Name SERVER1\IUSR_SERVER1
HttpContext.Current.Request.IsAuthenticated False
HttpContext.Current.User.Identity.Name –
System.Environment.UserName ASPNET
Security.Principal.WindowsIdentity.GetCurrent().Name SERVER1\ASPNET
Scenario 2: Windows Authentication in IIS, impersonation off.
HttpContext.Current.Request.LogonUserIdentity.Name MYDOMAIN\USER1
HttpContext.Current.Request.IsAuthenticated True
HttpContext.Current.User.Identity.Name MYDOMAIN\USER1
System.Environment.UserName ASPNET
Security.Principal.WindowsIdentity.GetCurrent().Name SERVER1\ASPNET
Scenario 3: Anonymous Authentication in IIS, impersonation on
HttpContext.Current.Request.LogonUserIdentity.Name SERVER1\IUSR_SERVER1
HttpContext.Current.Request.IsAuthenticated False
HttpContext.Current.User.Identity.Name –
System.Environment.UserName IUSR_SERVER1
Security.Principal.WindowsIdentity.GetCurrent().Name SERVER1\IUSR_SERVER1
Scenario 4: Windows Authentication in IIS, impersonation on
HttpContext.Current.Request.LogonUserIdentity.Name MYDOMAIN\USER1
HttpContext.Current.Request.IsAuthenticated True
HttpContext.Current.User.Identity.Name MYDOMAIN\USER1
System.Environment.UserName USER1
Security.Principal.WindowsIdentity.GetCurrent().Name MYDOMAIN\USER1
Legend
SERVER1\ASPNET
: Identity of the running process on server.
SERVER1\IUSR_SERVER1
: Anonymous guest user defined in IIS.
MYDOMAIN\USER1
: The user of the remote client.
If you're using .NET 3.5 SP1+ the better way to do this is to take a look at the
System.DirectoryServices.AccountManagement namespace.
It has methods to find people and you can pretty much pass in any username format you want and then returns back most of the basic information you would need. If you need help on loading the more complex objects and properties check out the source code for http://umanage.codeplex.com its got it all.
Brent
Two-stage authentication is not supported with IIS7 Integrated mode. Authentication is now modularized, so rather than IIS performing authentication followed by asp.net performing authentication, it all happens at the same time.
You can either:
In IIS 7 (not IIS 7.5), sites access files and folders based on the account set on the application pool for the site. By default, in IIS7, this account is NETWORK SERVICE
.
Specify an Identity for an Application Pool (IIS 7)
In IIS 7.5 (Windows 2008 R2 and Windows 7), the application pools run under the ApplicationPoolIdentity which is created when the application pool starts. If you want to set ACLS for this account, you need to choose IIS AppPool\ApplicationPoolName
instead of NT Authority\Network Service
.
Ran into this issue where the linked server would work for users who were local admins on the server, but not for anyone else. After many hours of messing around, I managed to fix the problem using the following steps:
I'm using visual studio 2019 develop against ASP.Net application. Here's what been worked for us:
<authentication mode="Windows"></authentication>p
_x000D_
And I didn't change application.config in iis express.
The solutions like cmd /c pause
cause a new command interpreter to start and run in the background. Although acceptable in some cases, this isn't really ideal.
The solutions using Read-Host
force the user to press Enter and are not really "any key".
This solution will give you a true "press any key to continue" interface and will not start a new interpreter, which will essentially mimic the original pause
command.
Write-Host "Press any key to continue..."
[void][System.Console]::ReadKey($true)
Just by one line-
var select_button_text = $('#SelectQButton option:selected')
.toArray().map(item => item.text);
Output: ["text1", "text2"]
var select_button_text = $('#SelectQButton option:selected')
.toArray().map(item => item.value);
Output: ["value1", "value2"]
If you use .join()
var select_button_text = $('#SelectQButton option:selected')
.toArray().map(item => item.text).join();
Output: text1,text2,text3
You need to specify the format it already has, in order to parse it:
$InvoiceDate = [datetime]::ParseExact($invoice, "dd-MMM-yy", $null)
Now you can output it in the format you need:
$InvoiceDate.ToString('yyyy-MM-dd')
or
'{0:yyyy-MM-dd}' -f $InvoiceDate
For example:
String myInput = null;
Scanner myscan = new Scanner(System.in).useDelimiter("\\n");
System.out.println("Enter your input: ");
myInput = myscan.next();
System.out.println(myInput);
This will let you use Enter as a delimiter.
Thus, if you input:
Hello world (ENTER)
it will print 'Hello World'.
It's good to know the differences between margin
and padding
. Here are some differences:
Margin is outer space of an element, while padding is inner space of an element.
Margin is the space outside the border of an element, while padding is the space inside the border of it.
Margin accepts the value of auto: margin: auto
, but you can't set padding to auto.
Margin can be set to any number, but padding must be non-negative.
When you style an element, padding will also be affected (e.g. background color), but not margin.
from datetime import datetime
listA = range(10000000)
setA = set(listA)
tupA = tuple(listA)
#Source Code
def calc(data, type):
start = datetime.now()
if data in type:
print ""
end = datetime.now()
print end-start
calc(9999, listA)
calc(9999, tupA)
calc(9999, setA)
Output after comparing 10 iterations for all 3 : Comparison
The key takeaway is to check the .err file, by default on Mac OSX it's in /usr/local/var/mysql
.
That log filed revealed to me that I had to delete the following files:
ibdata1
ib_logfile0
ib_logfile1
Running MySQL with mysql.start
worked successfully after that. Note that deleting those files will likely causes data loss.
You could just use
DataGridView1.CurrentRow.Cells["ColumnName"].Value
If there are are no duplicate elements or you don't care about them, then you can use the Set class:
a1 = Set.new [5, 1, 6, 14, 2, 8]
a2 = Set.new [2, 6, 15]
a1.subset?(a2)
=> false
Behind the scenes this uses
all? { |o| set.include?(o) }
To give the simplest answer I can think of:
Suppose we have a problem that takes a certain number of inputs, and has various potential solutions, which may or may not solve the problem for given inputs. A logic puzzle in a puzzle magazine would be a good example: the inputs are the conditions ("George doesn't live in the blue or green house"), and the potential solution is a list of statements ("George lives in the yellow house, grows peas, and owns the dog"). A famous example is the Traveling Salesman problem: given a list of cities, and the times to get from any city to any other, and a time limit, a potential solution would be a list of cities in the order the salesman visits them, and it would work if the sum of the travel times was less than the time limit.
Such a problem is in NP if we can efficiently check a potential solution to see if it works. For example, given a list of cities for the salesman to visit in order, we can add up the times for each trip between cities, and easily see if it's under the time limit. A problem is in P if we can efficiently find a solution if one exists.
(Efficiently, here, has a precise mathematical meaning. Practically, it means that large problems aren't unreasonably difficult to solve. When searching for a possible solution, an inefficient way would be to list all possible potential solutions, or something close to that, while an efficient way would require searching a much more limited set.)
Therefore, the P=NP problem can be expressed this way: If you can verify a solution for a problem of the sort described above efficiently, can you find a solution (or prove there is none) efficiently? The obvious answer is "Why should you be able to?", and that's pretty much where the matter stands today. Nobody has been able to prove it one way or another, and that bothers a lot of mathematicians and computer scientists. That's why anybody who can prove the solution is up for a million dollars from the Claypool Foundation.
We generally assume that P does not equal NP, that there is no general way to find solutions. If it turned out that P=NP, a lot of things would change. For example, cryptography would become impossible, and with it any sort of privacy or verifiability on the Internet. After all, we can efficiently take the encrypted text and the key and produce the original text, so if P=NP we could efficiently find the key without knowing it beforehand. Password cracking would become trivial. On the other hand, there's whole classes of planning problems and resource allocation problems that we could solve effectively.
You may have heard the description NP-complete. An NP-complete problem is one that is NP (of course), and has this interesting property: if it is in P, every NP problem is, and so P=NP. If you could find a way to efficiently solve the Traveling Salesman problem, or logic puzzles from puzzle magazines, you could efficiently solve anything in NP. An NP-complete problem is, in a way, the hardest sort of NP problem.
So, if you can find an efficient general solution technique for any NP-complete problem, or prove that no such exists, fame and fortune are yours.
If none of the other solutions work for you, try (backing up) and deleting your ~/.PyCharm40 folder, then reopening PyCharm. This will kill all your preferences as well.
On Mac you want to delete ~/Library/Caches/Pycharm40 and ~/Library/Preferences/PyCharm40.
And on Windows: C:\Users\$USER.PyCharm40.
import re
import sys
prog = re.compile('([A-Z]\d+)+')
while True:
line = sys.stdin.readline()
if not line: break
if prog.match(line):
print 'matched'
else:
print 'not matched'
Arrays.copyOfRange(..)
was added in Java 1.6. So perhaps you don't have the latest version. If it's not possible to upgrade, look at System.arraycopy(..)
Something I recently discovered for styling Radio Buttons AND Checkboxes. Before, I had to use jQuery and other things. But this is stupidly simple.
input[type=radio] {
padding-left:5px;
padding-right:5px;
border-radius:15px;
-webkit-appearance:button;
border: double 2px #00F;
background-color:#0b0095;
color:#FFF;
white-space: nowrap;
overflow:hidden;
width:15px;
height:15px;
}
input[type=radio]:checked {
background-color:#000;
border-left-color:#06F;
border-right-color:#06F;
}
input[type=radio]:hover {
box-shadow:0px 0px 10px #1300ff;
}
You can do the same for a checkbox, obviously change the input[type=radio]
to input[type=checkbox]
and change border-radius:15px;
to border-radius:4px;
.
Hope this is somewhat useful to you.
The $.ajax() function returns a XMLHttpRequest object. Store that in a variable that's accessible from the Submit button's "OnClick" event. When a submit click is processed check to see if the XMLHttpRequest variable is:
1) null, meaning that no request has been sent yet
2) that the readyState value is 4 (Loaded). This means that the request has been sent and returned successfully.
In either of those cases, return true and allow the submit to continue. Otherwise return false to block the submit and give the user some indication of why their submit didn't work. :)
This is reviving an old question, but in Python 3, you can just use bytes
directly:
>>> bytes([17, 24, 121, 1, 12, 222, 34, 76])
b'\x11\x18y\x01\x0c\xde"L'
This has been fully answered here.
See Oracle's docs on SELECT to see how subquery factoring works, and Mark's example:
WITH employee AS (SELECT * FROM Employees)
SELECT * FROM employee WHERE ID < 20
UNION ALL
SELECT * FROM employee WHERE Sex = 'M'
I would suggest instead of creating a new table, you just use a view that combines the two tables, this way if any of the data in table 1 or table 2 changes, you don't need to update the third table:
CREATE VIEW dbo.YourView
AS
SELECT t1.Name, t1.Age, t1.Sex, t1.City, t1.ID, t2.Number
FROM Table1 t1
INNER JOIN Table2 t2
ON t1.ID = t2.ID;
If you could have records in one table, and not in the other, then you would need to use a full join:
CREATE VIEW dbo.YourView
AS
SELECT t1.Name, t1.Age, t1.Sex, t1.City, ID = ISNULL(t1.ID, t2.ID), t2.Number
FROM Table1 t1
FULL JOIN Table2 t2
ON t1.ID = t2.ID;
If you know all records will be in table 1 and only some in table 2, then you should use a LEFT JOIN
:
CREATE VIEW dbo.YourView
AS
SELECT t1.Name, t1.Age, t1.Sex, t1.City, t1.ID, t2.Number
FROM Table1 t1
LEFT JOIN Table2 t2
ON t1.ID = t2.ID;
If you know all records will be in table 2 and only some in table 2 then you could use a RIGHT JOIN
CREATE VIEW dbo.YourView
AS
SELECT t1.Name, t1.Age, t1.Sex, t1.City, t2.ID, t2.Number
FROM Table1 t1
RIGHT JOIN Table2 t2
ON t1.ID = t2.ID;
Or just reverse the order of the tables and use a LEFT JOIN (I find this more logical than a right join but it is personal preference):
CREATE VIEW dbo.YourView
AS
SELECT t1.Name, t1.Age, t1.Sex, t1.City, t2.ID, t2.Number
FROM Table2 t2
LEFT JOIN Table1 t1
ON t1.ID = t2.ID;
The port for the Vue-cli webpack template is found in your app root's myApp/config/index.js
.
All you have to do is modify the port
value inside the dev
block:
dev: {
proxyTable: {},
env: require('./dev.env'),
port: 4545,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
cssSourceMap: false
}
Now you can access your app with localhost:4545
also if you have .env
file better to set it from there
Well it also can be :
SELECT t.col1, t.col2, ('test' + t.col3) as test_col3
FROM table t;
where for concatenation in oracle is used the operator ||
not +
.
In this case you get : ORA-01722: invalid number ...
I had the chance to use Compuware DevPartner Studio in the past and that was really good, but it's quite expensive. A cheaper solution could be GlowCode, i just worked with a 5.x version and, despite some problems in attaching to a process i needed to debug, it worked quite well.
tar -cvzf filename.tar.gz directory_to_compress/
Most tar
commands have a z
option to create a gzip
ed version.
Though seems to me the question is how to circumvent Google. I'm not sure if renaming your output file would fool Google, but you could try. I.e.,
tar -cvzf filename.bla directory_to_compress/
and then send the filename.bla
- contents will would be a zipped tar, so at the other end it could be retrieved as usual.
if we know the table and colum names but want to find out the number of times string is appearing for each schema:
Declare
owner VARCHAR2(1000);
tbl VARCHAR2(1000);
cnt number;
ct number;
str_sql varchar2(1000);
reason varchar2(1000);
x varchar2(1000):='%string_to_be_searched%';
cursor csr is select owner,table_name
from all_tables where table_name ='table_name';
type rec1 is record (
ct VARCHAR2(1000));
type rec is record (
owner VARCHAR2(1000):='',
table_name VARCHAR2(1000):='');
rec2 rec;
rec3 rec1;
begin
for rec2 in csr loop
--str_sql:= 'select count(*) from '||rec.owner||'.'||rec.table_name||' where CTV_REMARKS like '||chr(39)||x||chr(39);
--dbms_output.put_line(str_sql);
--execute immediate str_sql
execute immediate 'select count(*) from '||rec2.owner||'.'||rec2.table_name||' where column_name like '||chr(39)||x||chr(39)
into rec3;
if rec3.ct <> 0 then
dbms_output.put_line(rec2.owner||','||rec3.ct);
else null;
end if;
end loop;
end;
There is no official API to do that, no.
You need to use platform API to kill the thread, e.g. pthread_kill, or TerminateThread. You can access such API e.g. through pythonwin, or through ctypes.
Notice that this is inherently unsafe. It will likely lead to uncollectable garbage (from local variables of the stack frames that become garbage), and may lead to deadlocks, if the thread being killed has the GIL at the point when it is killed.
Window->Show View->Navigator, should pop up the navigator panel on the left hand side, showing the projects list.
It's probably already open in the workspace, but you may have closed the navigator panel, so it looks like you don't have the project open.
Eclipse using ADT Build v22.0.0-675183 on Linux.
I've found that in the majority of cases doing block clauses on one line is a bad idea.
It will, again as a generality, reduce the quality of the form of the code. High quality code form is a key language feature for python.
In some cases python will offer ways todo things on one line that are definitely more pythonic. Things such as what Nick D mentioned with the list comprehension:
newlist = [splitColon.split(a) for a in someList]
although unless you need a reusable list specifically you may want to consider using a generator instead
listgen = (splitColon.split(a) for a in someList)
note the biggest difference between the two is that you can't reiterate over a generator, but it is more efficient to use.
There is also a built in ternary operator in modern versions of python that allow you to do things like
string_to_print = "yes!" if "exam" in "example" else ""
print string_to_print
or
iterator = max_value if iterator > max_value else iterator
Some people may find these more readable and usable than the similar if (condition):
block.
When it comes down to it, it's about code style and what's the standard with the team you're working on. That's the most important, but in general, i'd advise against one line blocks as the form of the code in python is so very important.
Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.
Use string
instead of string?
in all places in your code.
The Nullable<T>
type requires that T is a non-nullable value type, for example int
or DateTime
. Reference types like string
can already be null. There would be no point in allowing things like Nullable<string>
so it is disallowed.
Also if you are using C# 3.0 or later you can simplify your code by using auto-implemented properties:
public class WordAndMeaning
{
public string Word { get; set; }
public string Meaning { get; set; }
}
Use genfromtxt
instead. It's a much more general method than loadtxt
:
import numpy as np
print np.genfromtxt('col.txt',dtype='str')
Using the file col.txt
:
foo bar
cat dog
man wine
This gives:
[['foo' 'bar']
['cat' 'dog']
['man' 'wine']]
If you expect that each row has the same number of columns, read the first row and set the attribute filling_values
to fix any missing rows.
UDP is not "safe", so the question is not great - however -
If you send 9217 or more (mac) or 65508+ (linux/windows), the socket send function returns with an error.
The above answers discussing fragmentation and MTU and so on are off topic - that all takes place at a lower level, is "invisible" to you, and does not affect "safety" on typical connections to a significant degree.
To answer the actual question meaning though - do not use UDP - use raw sockets so you get better control of everything; since you're writing a game, you need to delve into the flags to get priority into your traffic anyhow, so you may as well get rid of UDP issues at the same time.
If you have milliseconds in the date string, you can use the following.
select TO_TIMESTAMP(SUBSTR('2020-09-10T09:37:28.378-07:00',1,23), 'YYYY-MM-DD"T"HH24:MI:SS:FF3')From Dual;
And then convert it to Date with:
select trunc(TO_TIMESTAMP(SUBSTR('2020-09-10T09:37:28.378-07:00',1,23), 'YYYY-MM-DD"T"HH24:MI:SS:FF3')) From Dual;
It worked for me, hope it will help you as well.
format : assert Expression[,arguments] When assert encounters a statement,Python evaluates the expression.If the statement is not true,an exception is raised(assertionError). If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback. Example:
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
When the above code is executed, it produces the following result:
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!
I have put @Sharon's code together into the following, which works for me on the iPad with two-finger scrolling. The only thing you should have to change to get it working is the src attribute on the iframe (I used a PDF document).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Pdf Scrolling in mobile Safari</title>
</head>
<body>
<div id="scroller" style="height: 400px; width: 100%; overflow: auto;">
<iframe height="100%" id="iframe" scrolling="no" width="100%" id="iframe" src="data/testdocument.pdf" />
</div>
<script type="text/javascript">
setTimeout(function () {
var startY = 0;
var startX = 0;
var b = document.body;
b.addEventListener('touchstart', function (event) {
parent.window.scrollTo(0, 1);
startY = event.targetTouches[0].pageY;
startX = event.targetTouches[0].pageX;
});
b.addEventListener('touchmove', function (event) {
event.preventDefault();
var posy = event.targetTouches[0].pageY;
var h = parent.document.getElementById("scroller");
var sty = h.scrollTop;
var posx = event.targetTouches[0].pageX;
var stx = h.scrollLeft;
h.scrollTop = sty - (posy - startY);
h.scrollLeft = stx - (posx - startX);
startY = posy;
startX = posx;
});
}, 1000);
</script>
</body>
</html>
If you want to customize the message that being shown on empty table use this:
$('#example').dataTable( {
"oLanguage": {
"sEmptyTable": "My Custom Message On Empty Table"
}
} );
Since Datatable 1.10 you can do the following:
$('#example').DataTable( {
"language": {
"emptyTable": "My Custom Message On Empty Table"
}
} );
For the complete availble datatables custom messages for the table take a look at the following link reference/option/language
For me none of earlier answer works. I did need to convert my static class to enum. Like this:
export enum MyConstants {
MyFirstConstant = 'MyFirstConstant',
MySecondConstant = 'MySecondConstant'
}
Then in my component I add new property as suggested in other answers
export class MyComponent {
public MY_CONTANTS = MyConstans;
constructor() { }
}
Then in my component's template I use it this way
<div [myDirective]="MY_CONTANTS.MyFirstConstant"> </div>
EDIT: Sorry. My problem was different than OP's. I still leave this here if someelse have same problem than I.
It happens when you mix UNIX and Windows git clients because Windows doesn't really have the concept of the "x" bit so your checkout of a rw-r--r--
(0644) file under Windows is "promoted" by the msys POSIX layer to be rwx-r-xr-x
(0755). git considers that mode difference to be basically the same as a textual difference in the file, so your patch does not directly apply. I think your only good option here is to set core.filemode
to false
(using git-config
).
Here's a msysgit issue with some related info: http://code.google.com/p/msysgit/issues/detail?id=164 (rerouted to archive.org's 3 Dec 2013 copy)
public class MainActivity extends AppCompatActivity implements OnClickListener {
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1= (Button) findViewById(R.id.button);
b2= (Button) findViewById(R.id.button2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
if(v.getId()==R.id.button)
{
Intent intent=new Intent(getApplicationContext(),SignIn.class);
startActivity(intent);
}
else if (v.getId()==R.id.button2)
{
Intent in=new Intent(getApplicationContext(),SignUpactivity.class);
startActivity(in);
}
}
}
rbind()
needs the two object names to be the same. For example, the first object names: ID Age
, the next object names: ID Gender
,if you want to use rbind()
, it will print out:
names do not match previous names
After more than five years I answer my question. I think that the problem with a negative duration can be solved by a simple correction:
LocalDateTime fromDateTime = LocalDateTime.of(2014, 9, 9, 7, 46, 45);
LocalDateTime toDateTime = LocalDateTime.of(2014, 9, 10, 6, 46, 45);
Period period = Period.between(fromDateTime.toLocalDate(), toDateTime.toLocalDate());
Duration duration = Duration.between(fromDateTime.toLocalTime(), toDateTime.toLocalTime());
if (duration.isNegative()) {
period = period.minusDays(1);
duration = duration.plusDays(1);
}
long seconds = duration.getSeconds();
long hours = seconds / SECONDS_PER_HOUR;
long minutes = ((seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE);
long secs = (seconds % SECONDS_PER_MINUTE);
long time[] = {hours, minutes, secs};
System.out.println(period.getYears() + " years "
+ period.getMonths() + " months "
+ period.getDays() + " days "
+ time[0] + " hours "
+ time[1] + " minutes "
+ time[2] + " seconds.");
Note: The site https://www.epochconverter.com/date-difference now correctly calculates the time difference.
Thank you all for your discussion and suggestions.
This code will works:
your_path= ActiveWorkbook.Path & "\your_python_file.py"
Shell "RunDll32.Exe Url.Dll,FileProtocolHandler " & your_path, vbNormalFocus
ActiveWorkbook.Path return the current directory of the workbook. The shell command open the file through the shell of Windows.
so divide1=me.getValue()/2;
int divide1 = (Integer) me.getValue()/2;
you can use ng-keydown , ng-keyup , ng-press such as this .
to triger a function :
<input type="text" ng-keypress="function()"/>
or if you have one condion such as when he press escape (27 is the key code for escape)
<form ng-keydown=" event.which=== 27?cancelSplit():0">
....
</form>
I had the same problem for days until I noticed (how could I look at it and not read the code :-(..) that config.inc.php
is calling config-db.php
** MySql Server version: 5.7.5-m15
** Apache/2.4.10 (Ubuntu)
** phpMyAdmin 4.2.9.1deb0.1
/etc/phpmyadmin/config-db.php:
$dbuser='yourDBUserName';
$dbpass='';
$basepath='';
$dbname='phpMyAdminDBName';
$dbserver='';
$dbport='';
$dbtype='mysql';
Here you need to define your username, password, dbname and others that are showing empty' use default unless you changed their configuration.
That solved the issue for me.
U hope it helps you.
latest.phpmyadmin.docs
nano ~/.profile
add these lines:
export PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"
save the file:
Ctrl + X
then Y
then Enter
then render the changes:
source ~/.profile
I saw that someone was wondering how to do it for another controller.
In my case I had all of my email templates in the Views/Email folder, but you could modify this to pass in the controller in which you have views associated for.
public static string RenderViewToString(Controller controller, string viewName, object model)
{
var oldController = controller.RouteData.Values["controller"].ToString();
if (controller.GetType() != typeof(EmailController))
controller.RouteData.Values["controller"] = "Email";
var oldModel = controller.ViewData.Model;
controller.ViewData.Model = model;
try
{
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName,
null);
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
//Cleanup
controller.ViewData.Model = oldModel;
controller.RouteData.Values["controller"] = oldController;
return sw.GetStringBuilder().ToString();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
throw ex;
}
}
Essentially what this does is take a controller, such as AccountController and modify it to think it's an EmailController so that the code will look in the Views/Email
folder. It's necessary to do this because the FindView
method doesn't take a straight up path as a parameter, it wants a ControllerContext
.
Once done rendering the string, it returns the AccountController back to its initial state to be used by the Response object.
JOIN t2 ON t1.id=t2.id AND t1.date=t2.date
If you install the "cssnext" Post CSS plugin, then you can safely start using the syntax that you want to use right now.
Using cssnext will turn this:
input:not([type="radio"], [type="checkbox"]) {
/* css here */
}
Into this:
input:not([type="radio"]):not([type="checkbox"]) {
/* css here */
}
application/xml
is seen by svn
as binary type whereas text/xml
as text file for which a diff can be displayed.
below solution worked for me in case of required number is float. Solution:
table=sorted(table,key=lambda x: float(x[5]))
for row in table[:]:
Ntable.add_row(row)
'
Same problem for me. It turns out that the cause of the problem was the new JungleDisk 3.0, which rudely installs three overlays named "1Sync..." "2Sync..." and "3Sync..." pushing the Tortoise ones off the end.
Just delete those JungleDisk keys in the reg hive listed at the top (or prefix them with z_) and re-start the system and Tortoise should work fine again.
Given that this overlay limit exists in Windows and is easily hit with current tools, tool vendors really should ask during advanced installation if the user wants to install them. I have no need nor desire for the new "Sync" feature and don't really care for the tactic of stuffing the icons at the top of the list with clever naming. Shame on JungleDisk.
You could also use missing()
to test whether or not the argument y
was supplied:
fooBar <- function(x,y){
if(missing(y)) {
x
} else {
x + y
}
}
fooBar(3,1.5)
# [1] 4.5
fooBar(3)
# [1] 3
Cuando se use Windows en Español, el código debe quedar asi (when using Windows in Spanish, code is):
for /F "tokens=3 delims=: " %%H in ('sc query MYSERVICE ^| findstr " ESTADO"') do (
if /I "%%H" NEQ "RUNNING" (
REM Put your code you want to execute here
REM For example, the following line
net start MYSERVICE
)
)
Reemplazar MYSERVICE con el nombre del servicio que se desea procesar. Puedes ver el nombre del servicio viendo las propiedades del servicio. (Replace MYSERVICE with the name of the service to be processed. You can see the name of the service on service properties.)
I found it works different among different jpa versions, for debug, you'd better add this configurations to show generated sql, it will save your time a lot !
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
for spring boot 2.1.6.RELEASE, it works good!
Sort sort = new Sort(Sort.Direction.DESC, "column_name");
int pageNumber = 3, pageSize = 5;
Pageable pageable = PageRequest.of(pageNumber - 1, pageSize, sort);
@Query(value = "select * from integrity_score_view " +
"where (?1 is null or data_hour >= ?1 ) " +
"and (?2 is null or data_hour <= ?2 ) " +
"and (?3 is null or ?3 = '' or park_no = ?3 ) " +
"group by park_name, data_hour ",
countQuery = "select count(*) from integrity_score_view " +
"where (?1 is null or data_hour >= ?1 ) " +
"and (?2 is null or data_hour <= ?2 ) " +
"and (?3 is null or ?3 = '' or park_no = ?3 ) " +
"group by park_name, data_hour",
nativeQuery = true
)
Page<IntegrityScoreView> queryParkView(Date from, Date to, String parkNo, Pageable pageable);
you DO NOT write order by
and limit
, it generates the right sql
Javascript will throw an exception if you attempt to use a break;
statement inside an if else. It is used mainly for loops. You can "break" out of an if else statement with a condition, which does not make sense to include a "break" statement.
You can try to set_time_limit(n)
. However, if your PHP setup is running in safe mode, you can only change it from the php.ini
file.
You can try the external lib called "sh" (http://amoffat.github.io/sh/).
import sh
print sh.which('ls') # prints '/bin/ls' depending on your setup
print sh.which('xxx') # prints None
In Java, according to the JSSE Reference Guide, there is no default for the keystore
, the default for the truststore
is "jssecacerts, if it exists. Otherwise, cacerts".
A few applications use ~/.keystore
as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).
I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.
An alternative :
// shape
var shape = function(type){
this.type = type;
}
shape.prototype.display = function(){
console.log(this.type);
}
// circle
var circle = new shape('circle');
// override
circle.display = function(a,b){
// call implementation of the super class
this.__proto__.display.apply(this,arguments);
}
Having requirements in requirements.txt
and egg_dir
as a directory
you can build your local cache:
$ pip download -r requirements.txt -d eggs_dir
then, using that "cache" is simple like:
$ pip install -r requirements.txt --find-links=eggs_dir
Assuming no SecurityManager
is preventing you from doing this, you can use setAccessible
to get around private
and resetting the modifier to get rid of final
, and actually modify a private static final
field.
Here's an example:
import java.lang.reflect.*;
public class EverythingIsTrue {
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
public static void main(String args[]) throws Exception {
setFinalStatic(Boolean.class.getField("FALSE"), true);
System.out.format("Everything is %s", false); // "Everything is true"
}
}
Assuming no SecurityException
is thrown, the above code prints "Everything is true"
.
What's actually done here is as follows:
boolean
values true
and false
in main
are autoboxed to reference type Boolean
"constants" Boolean.TRUE
and Boolean.FALSE
public static final Boolean.FALSE
to refer to the Boolean
referred to by Boolean.TRUE
false
is autoboxed to Boolean.FALSE
, it refers to the same Boolean
as the one refered to by Boolean.TRUE
"false"
now is "true"
static final File.separatorChar
for unit testingInteger
's cache, mutating a String
, etcExtreme care should be taken whenever you do something like this. It may not work because a SecurityManager
may be present, but even if it doesn't, depending on usage pattern, it may or may not work.
JLS 17.5.3 Subsequent Modification of Final Fields
In some cases, such as deserialization, the system will need to change the
final
fields of an object after construction.final
fields can be changed via reflection and other implementation dependent means. The only pattern in which this has reasonable semantics is one in which an object is constructed and then thefinal
fields of the object are updated. The object should not be made visible to other threads, nor should thefinal
fields be read, until all updates to thefinal
fields of the object are complete. Freezes of afinal
field occur both at the end of the constructor in which thefinal
field is set, and immediately after each modification of afinal
field via reflection or other special mechanism.Even then, there are a number of complications. If a
final
field is initialized to a compile-time constant in the field declaration, changes to thefinal
field may not be observed, since uses of thatfinal
field are replaced at compile time with the compile-time constant.Another problem is that the specification allows aggressive optimization of
final
fields. Within a thread, it is permissible to reorder reads of afinal
field with those modifications of a final field that do not take place in the constructor.
private static final boolean
, because it's inlineable as a compile-time constant and thus the "new" value may not be observableEssentially,
field.getModifiers() & ~Modifier.FINAL
turns off the bit corresponding to Modifier.FINAL
from field.getModifiers()
. &
is the bitwise-and, and ~
is the bitwise-complement.
Still not being able to solve this?, have fallen onto depression like I did for it? Does your code looks like this?
public class A {
private final String myVar = "Some Value";
}
Reading the comments on this answer, specially the one by @Pshemo, it reminded me that Constant Expressions are handled different so it will be impossible to modify it. Hence you will need to change your code to look like this:
public class A {
private final String myVar;
private A() {
myVar = "Some Value";
}
}
if you are not the owner of the class... I feel you!
For more details about why this behavior read this?
Using cin's >> operator will drop leading whitespace and stop input at the first trailing whitespace. To grab an entire line of input, including spaces, try cin.getline()
. To grab one character at a time, you can use cin.get()
.
I had the same issue with VS2017. Following solved the issue.
reg add HKLM\Software\WOW6432Node\Microsoft\InetStp /v MajorVersion /t REG_DWORD /d 10 /f
reg add HKLM\Software\Microsoft\InetStp /v MajorVersion /t REG_DWORD /d 10 /f
This should solve your problem. Refer to this link for more details.
There don't seem to be any perfect libraries or ways to do this yourself, unless you have to time to send an email to the email address and wait for a response (this might not be an option though). I ended up using a suggestion from here http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/ and adjusting the code so it would work in Java.
public static boolean isValidEmailAddress(String email) {
boolean stricterFilter = true;
String stricterFilterString = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
String laxString = ".+@.+\\.[A-Za-z]{2}[A-Za-z]*";
String emailRegex = stricterFilter ? stricterFilterString : laxString;
java.util.regex.Pattern p = java.util.regex.Pattern.compile(emailRegex);
java.util.regex.Matcher m = p.matcher(email);
return m.matches();
}
<?php
$timestamp=1486830234542;
echo date('Y-m-d H:i:s', $timestamp/1000);
?>
Here is an extension version and nullable version of il_guru's answer.
public static int GetIso8601WeekOfYear(this DateTime time)
{
var day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}
return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
public static int? GetIso8601WeekOfYear(this DateTime? time)
{
return time?.GetIso8601WeekOfYear();
}
new DateTime(2019, 03, 15).GetIso8601WeekOfYear(); //returns 11
((DateTime?) new DateTime(2019, 03, 15)).GetIso8601WeekOfYear(); //returns 11
((DateTime?) null).GetIso8601WeekOfYear(); //returns null
To see all tables:
.tables
To see a particular table:
.schema [tablename]
I use the DataGridView's Invalidate()
function. However, that will refresh the entire DataGridView. If you want to refresh a particular row, you use dgv.InvalidateRow(rowIndex)
. If you want to refresh a particular cell, you can use dgv.InvalidateCell(columnIndex, rowIndex)
. This is of course assuming you're using a binding source or data source.
I suggest you look into getting composer
. https://getcomposer.org
Composer makes getting third-party libraries a LOT easier and using a single autoloader for all of them. It also standardizes on where all your dependencies are located, along with some automatization capabilities.
Download https://getcomposer.org/composer.phar to C:\Inetpub\wwwroot\php
Delete your C:\Inetpub\wwwroot\php\PHPMailer\
directory.
Use composer.phar
to get the phpmailer package using the command line to execute
cd C:\Inetpub\wwwroot\php
php composer.phar require phpmailer/phpmailer
After it is finished it will create a C:\Inetpub\wwwroot\php\vendor
directory along with all of the phpmailer files and generate an autoloader.
Next in your main project configuration file you need to include the autoload file.
require_once 'C:\Inetpub\wwwroot\php\vendor\autoload.php';
The vendor\autoload.php
will include the information for you to use $mail = new \PHPMailer;
Additional information on the PHPMailer package can be found at https://packagist.org/packages/phpmailer/phpmailer
I came up with the following approach. It utilizes the onbeforeunload event to detect whether the browser starts leaving the page or not. If it does not in a certain timespan it'll just redirect to the fallback.
var goBack = function goBack(fallback){
var useFallback = true;
window.addEventListener("beforeunload", function(){
useFallback = false;
});
window.history.back();
setTimeout(function(){
if (useFallback){ window.location.href = fallback; }
}, 100);
}
You can call this function using goBack("fallback.example.org")
.
This question is quite older. The Questioner might have been turned into an experienced Java Developer by this time. Yet I want to add some opinion here which would help beginners.
For JDK 7 users, Here using
Objects.requireNotNull(object[, optionalMessage]);
is not safe. This function throws NullPointerException
if it finds null
object and which is a RunTimeException
.
That will terminate the whole program!!. So better check null
using ==
or !=
.
Also, use List
instead of Array
. Although access speed is same, yet using Collections
over Array
has some advantages like if you ever decide to change the underlying implementation later on, you can do it flexibly. For example, if you need synchronized access, you can change the implementation to a Vector
without rewriting all your code.
public static double calculateInventoryTotal(List<Book> books) {
if (books == null || books.isEmpty()) {
return 0;
}
double total = 0;
for (Book book : books) {
if (book != null) {
total += book.getPrice();
}
}
return total;
}
Also, I would like to upvote @1ac0 answer. We should understand and consider the purpose of the method too while writing. Calling method could have further logics to implement based on the called method's returned data.
Also if you are coding with JDK 8, It has introduced a new way to handle null check and protect the code from NullPointerException
. It defined a new class called Optional
. Have a look at this for detail
Finally, Pardon my bad English.
The simpliest way
Scanner in = new Scanner(System.in);
System.out.println("Enter seconds");
int s = in.nextInt();
int sec = s % 60;
int min = (s / 60)%60;
int hours = (s/60)/60;
System.out.println(hours + ":" + min + ":" + sec);
You should never use an exception if you don't have to - the overhead is horrible.
The variations on TryParse solve the problem - if you want to get creative (to make your code look more elegant) you could probably do something with an extension method in 3.5 but the code would be more or less the same.
There is no good answer as Python and Java are both specifications for which there are many different implementations. For example, CPython, IronPython, Jython, and PyPy are just a handful of Python implementations out there. For Java, there is the HotSpot VM, the Mac OS X Java VM, OpenJRE, etc. Jython generates Java bytecode, and so it would be using more-or-less the same underlying Java. CPython implements quite a handful of things directly in C, so it is very fast, but then again Java VMs also implement many functions in C. You would probably have to measure on a function-by-function basis and across a variety of interpreters and VMs in order to make any reasonable statement.
Another way of dealing with this situation if your files ARE already checked in, and your files have been merged (but not committed, so the merge conflicts are inserted into the file) is to run:
git reset
This will switch to HEAD, and tell git to forget any merge conflicts, and leave the working directory as is. Then you can edit the files in question (search for the "Updated upstream" notices). Once you've dealt with the conflicts, you can run
git add -p
which will allow you to interactively select which changes you want to add to the index. Once the index looks good (git diff --cached
), you can commit, and then
git reset --hard
to destroy all the unwanted changes in your working directory.
If you are utilizing arrays too much then you should include cstring.h
because it has too many functions including finding substrings.
If you want to retain the last one of the duplicates you could use
tac a.csv | sort -u -t, -r -k1,1 |tac
Which was my requirement
here
tac
will reverse the file line by line
You can also build up a list of lists and convert it to a dataframe -
import pandas as pd
columns = ['i','double','square']
rows = []
for i in range(6):
row = [i, i*2, i*i]
rows.append(row)
df = pd.DataFrame(rows, columns=columns)
giving
i double square 0 0 0 0 1 1 2 1 2 2 4 4 3 3 6 9 4 4 8 16 5 5 10 25
A great way of handling this is with regular expressions.
string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");
This will replace any of the 3 legal types of newline with the html tag.
PHP sends the html5 video tag together with a session where the key is a random string and the value is the filename.
ini_set('session.use_cookies',1);
session_start();
$ogv=uniqid();
$_SESSION[$ogv]='myVideo.ogv';
$webm=uniqid();
$_SESSION[$webm]='myVideo.webm';
echo '<video autoplay="autoplay">'
.'<source src="video.php?video='.$ogv.' type="video/ogg">'
.'<source src="video.php?video='.$webm.' type="video/webm">'
.'</video>';
Now PHP is asked to send the video. PHP recovers the filename; deletes the session and sends the video instantly. Additionally all the 'no cache' and mime-type headers must be present.
ini_set('session.use_cookies',1);
session_start();
$file='myhiddenvideos/'.$_SESSION[$_GET['video']];
$_SESSION=array();
$params = session_get_cookie_params();
setcookie(session_name(),'', time()-42000,$params["path"],$params["domain"],
$params["secure"], $params["httponly"]);
if(!file_exists($file) or $file==='' or !is_readable($file)){
header('HTTP/1.1 404 File not found',true);
exit;
}
readfile($file);
exit:
Now if the user copy the url in a new tab or use the context menu he will have no luck.
To go up a directory in a link, use ..
. This means "go up one directory", so your link will look something like this:
<a href="../index.html">Home</a>
Here's a good metrics plugin that displays number of lines of code and much more:
http://metrics.sourceforge.net/
It says it requires Eclipse 3.1, although I imagine they mean 3.1+
Here's another metrics plugin that's been tested on Ganymede:
Jerry's answer is great. However, it doesn't handle large responses. A simple change to handle this:
memset(response, 0, sizeof(response));
total = sizeof(response)-1;
received = 0;
do {
printf("RESPONSE: %s\n", response);
// HANDLE RESPONSE CHUCK HERE BY, FOR EXAMPLE, SAVING TO A FILE.
memset(response, 0, sizeof(response));
bytes = recv(sockfd, response, 1024, 0);
if (bytes < 0)
printf("ERROR reading response from socket");
if (bytes == 0)
break;
received+=bytes;
} while (1);
If you want the text color to change in the selected item only, then this can be a possible workaround. It worked for me and should work for you as well.
spinner.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
((TextView) spinner.getSelectedView()).setTextColor(Color.WHITE);
}
});
I am just doing this without even trying it. Would this work?
myDiv = getElementById("myDiv");
myDiv.querySelectorAll(this.id + " > .foo");
Give it a try, maybe it works maybe not. Apolovies, but I am not on a computer now to try it (responding from my iPhone).
I'll answer the more general question of how to have a canvas dynamically adapt in size upon window resize. The accepted answer appropriately handles the case where width and height are both supposed to be 100%, which is what was asked for, but which also will change the aspect ratio of the canvas. Many users will want the canvas to resize on window resize, but while keeping the aspect ratio untouched. It's not the exact question, but it "fits in", just putting the question into a slightly more general context.
The window will have some aspect ratio (width / height), and so will the canvas object. How you want these two aspect ratios to relate to each other is one thing you'll have to be clear about, there is no "one size fits all" answer to that question - I'll go through some common cases of what you might want.
Most important thing you have to be clear about: the html canvas object has a width attribute and a height attribute; and then, the css of the same object also has a width and a height attribute. Those two widths and heights are different, both are useful for different things.
Changing the width and height attributes is one method with which you can always change the size of your canvas, but then you'll have to repaint everything, which will take time and is not always necessary, because some amount of size change you can accomplish via the css attributes, in which case you do not redraw the canvas.
I see 4 cases of what you might want to happen on window resize (all starting with a full screen canvas)
1: you want the width to remain 100%, and you want the aspect ratio to stay as it was. In that case, you do not need to redraw the canvas; you don't even need a window resize handler. All you need is
$(ctx.canvas).css("width", "100%");
where ctx is your canvas context. fiddle: resizeByWidth
2: you want width and height to both stay 100%, and you want the resulting change in aspect ratio to have the effect of a stretched-out image. Now, you still don't need to redraw the canvas, but you need a window resize handler. In the handler, you do
$(ctx.canvas).css("height", window.innerHeight);
fiddle: messWithAspectratio
3: you want width and height to both stay 100%, but the answer to the change in aspect ratio is something different from stretching the image. Then you need to redraw, and do it the way that is outlined in the accepted answer.
fiddle: redraw
4: you want the width and height to be 100% on page load, but stay constant thereafter (no reaction to window resize.
fiddle: fixed
All fiddles have identical code, except for line 63 where the mode is set. You can also copy the fiddle code to run on your local machine, in which case you can select the mode via a querystring argument, as ?mode=redraw
you may forgot to wrap your object with $()
var tableChild = children[i];
tableChild.val("my Value");// this is wrong
and the ccorrect one is
$(tableChild).val("my Value");// this is correct
Swift 4.X and Xcode 10
let lbl = UILabel(frame: CGRect(x: 10, y: 50, width: 230, height: 21))
lbl.textAlignment = .center //For center alignment
lbl.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
lbl.textColor = .white
lbl.backgroundColor = .lightGray//If required
lbl.font = UIFont.systemFont(ofSize: 17)
//To display multiple lines in label
lbl.numberOfLines = 0 //If you want to display only 2 lines replace 0(Zero) with 2.
lbl.lineBreakMode = .byWordWrapping //Word Wrap
// OR
lbl.lineBreakMode = .byCharWrapping //Charactor Wrap
lbl.sizeToFit()//If required
yourView.addSubview(lbl)
If you have multiple labels in your class use extension to add properties.
//Label 1
let lbl1 = UILabel(frame: CGRect(x: 10, y: 50, width: 230, height: 21))
lbl1.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
lbl1.myLabel()//Call this function from extension to all your labels
view.addSubview(lbl1)
//Label 2
let lbl2 = UILabel(frame: CGRect(x: 10, y: 150, width: 230, height: 21))
lbl2.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
lbl2.myLabel()//Call this function from extension to all your labels
view.addSubview(lbl2)
extension UILabel {
func myLabel() {
textAlignment = .center
textColor = .white
backgroundColor = .lightGray
font = UIFont.systemFont(ofSize: 17)
numberOfLines = 0
lineBreakMode = .byCharWrapping
sizeToFit()
}
}
Here is what I ended up doing and it worked great.
First I moved the file input outside of the form so that it is not submitted:
<input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos(\'#{imageUploadUrl}\')" />
<form id="uploadImageForm" enctype="multipart/form-data">
<input id="name" value="#{name}" />
... a few more inputs ...
</form>
Then I changed the uploadPhotos
function to handle only the resizing:
window.uploadPhotos = function(url){
// Read in file
var file = event.target.files[0];
// Ensure it's an image
if(file.type.match(/image.*/)) {
console.log('An image has been loaded');
// Load the image
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {
// Resize the image
var canvas = document.createElement('canvas'),
max_size = 544,// TODO : pull max size from a site config
width = image.width,
height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
var resizedImage = dataURLToBlob(dataUrl);
$.event.trigger({
type: "imageResized",
blob: resizedImage,
url: dataUrl
});
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
}
};
As you can see I'm using canvas.toDataURL('image/jpeg');
to change the resized image into a dataUrl adn then I call the function dataURLToBlob(dataUrl);
to turn the dataUrl into a blob that I can then append to the form. When the blob is created, I trigger a custom event. Here is the function to create the blob:
/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = parts[1];
return new Blob([raw], {type: contentType});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {type: contentType});
}
/* End Utility function to convert a canvas to a BLOB */
Finally, here is my event handler that takes the blob from the custom event, appends the form and then submits it.
/* Handle image resized events */
$(document).on("imageResized", function (event) {
var data = new FormData($("form[id*='uploadImageForm']")[0]);
if (event.blob && event.url) {
data.append('image_data', event.blob);
$.ajax({
url: event.url,
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
//handle errors...
}
});
}
});
Interesting I never spent too much time adjusting the colours in IntelliJ although tried once.
See link below with an already defined colour scheme you can import.
Where can I download IntelliJ IDEA 10 Color Schemes?
http://devnet.jetbrains.net/docs/DOC-1154
Download the jar file, file import the jar where you will see a what to import ;)
I had the same problem when I changed from Websphere 8.5 to WebSphere Liberty.
I utilized FileInputStream
instead of getResourceAsStream()
, because for some reason WebSphere Liberty can't locate the file in the WEB-INF
folder.
The script was :
FileInputStream fis = new FileInputStream(getServletContext().getRealPath("/")
+ "\WEBINF\properties\myProperties.properties")
Note: I used this script only for development.
import platform
print(platform.python_version())
This prints something like
3.7.2
Object does not have forEach
, it belongs to Array
prototype. If you want to iterate through each key-value pair in the object and take the values. You can do this:
Object.keys(a).forEach(function (key){
console.log(a[key]);
});
Usage note: For an object v = {"cat":"large", "dog": "small", "bird": "tiny"};
, Object.keys(v)
gives you an array of the keys so you get ["cat","dog","bird"]
Old question but for a simple API and light-weight solution; you can use perfy which uses high-resolution real time (process.hrtime
) internally.
var perfy = require('perfy');
function end(label) {
return function (err, saved) {
console.log(err ? 'Error' : 'Saved');
console.log( perfy.end(label).time ); // <——— result: seconds.milliseconds
};
}
for (var i = 1; i < LIMIT; i++) {
var label = 'db-save-' + i;
perfy.start(label); // <——— start and mark time
db.users.save({ id: i, name: 'MongoUser [' + i + ']' }, end(label));
}
Note that each time perfy.end(label)
is called, that instance is auto-destroyed.
Disclosure: Wrote this module, inspired by D.Deriso's answer. Docs here.
The for
loop runs immediately to completion while all your asynchronous operations are started. When they complete some time in the future and call their callbacks, the value of your loop index variable i
will be at its last value for all the callbacks.
This is because the for
loop does not wait for an asynchronous operation to complete before continuing on to the next iteration of the loop and because the async callbacks are called some time in the future. Thus, the loop completes its iterations and THEN the callbacks get called when those async operations finish. As such, the loop index is "done" and sitting at its final value for all the callbacks.
To work around this, you have to uniquely save the loop index separately for each callback. In Javascript, the way to do that is to capture it in a function closure. That can either be done be creating an inline function closure specifically for this purpose (first example shown below) or you can create an external function that you pass the index to and let it maintain the index uniquely for you (second example shown below).
As of 2016, if you have a fully up-to-spec ES6 implementation of Javascript, you can also use let
to define the for
loop variable and it will be uniquely defined for each iteration of the for
loop (third implementation below). But, note this is a late implementation feature in ES6 implementations so you have to make sure your execution environment supports that option.
Use .forEach() to iterate since it creates its own function closure
someArray.forEach(function(item, i) {
asynchronousProcess(function(item) {
console.log(i);
});
});
Create Your Own Function Closure Using an IIFE
var j = 10;
for (var i = 0; i < j; i++) {
(function(cntr) {
// here the value of i was passed into as the argument cntr
// and will be captured in this function closure so each
// iteration of the loop can have it's own value
asynchronousProcess(function() {
console.log(cntr);
});
})(i);
}
Create or Modify External Function and Pass it the Variable
If you can modify the asynchronousProcess()
function, then you could just pass the value in there and have the asynchronousProcess()
function the cntr back to the callback like this:
var j = 10;
for (var i = 0; i < j; i++) {
asynchronousProcess(i, function(cntr) {
console.log(cntr);
});
}
Use ES6 let
If you have a Javascript execution environment that fully supports ES6, you can use let
in your for
loop like this:
const j = 10;
for (let i = 0; i < j; i++) {
asynchronousProcess(function() {
console.log(i);
});
}
let
declared in a for
loop declaration like this will create a unique value of i
for each invocation of the loop (which is what you want).
Serializing with promises and async/await
If your async function returns a promise, and you want to serialize your async operations to run one after another instead of in parallel and you're running in a modern environment that supports async
and await
, then you have more options.
async function someFunction() {
const j = 10;
for (let i = 0; i < j; i++) {
// wait for the promise to resolve before advancing the for loop
await asynchronousProcess();
console.log(i);
}
}
This will make sure that only one call to asynchronousProcess()
is in flight at a time and the for
loop won't even advance until each one is done. This is different than the previous schemes that all ran your asynchronous operations in parallel so it depends entirely upon which design you want. Note: await
works with a promise so your function has to return a promise that is resolved/rejected when the asynchronous operation is complete. Also, note that in order to use await
, the containing function must be declared async
.
Run asynchronous operations in parallel and use Promise.all()
to collect results in order
function someFunction() {
let promises = [];
for (let i = 0; i < 10; i++) {
promises.push(asynchonousProcessThatReturnsPromise());
}
return Promise.all(promises);
}
someFunction().then(results => {
// array of results in order here
console.log(results);
}).catch(err => {
console.log(err);
});
your elemId
as its name suggests, is an Id
attribute, these are all you can do to check if it exists:
Vanilla JavaScript: in case you have more advanced selectors:
//you can use it for more advanced selectors
if(document.querySelectorAll("#elemId").length){}
if(document.querySelector("#elemId")){}
//you can use it if your selector has only an Id attribute
if(document.getElementById("elemId")){}
jQuery:
if(jQuery("#elemId").length){}
HTML
<a href="#top">Top</a>
<a href="#middle">Middle</a>
<a href="#bottom">Bottom</a>
<div id="top"><a href="top"></a>Top</div>
<div id="middle"><a href="middle"></a>Middle</div>
<div id="bottom"><a href="bottom"></a>Bottom</div>
CSS
#top,#middle,#bottom{
height: 600px;
width: 300px;
background: green;
}
Example http://jsfiddle.net/x4wDk/
May 2018 react-native version 0.55.2
secureTextEntry={true} works
password={true} does not work
You are opening an asynchronous connection, yet you have written your code as if it was synchronous. The reqListener
callback function will not execute synchronously with your code (that is, before React.createClass
), but only after your entire snippet has run, and the response has been received from your remote location.
Unless you are on a zero-latency quantum-entanglement connection, this is well after all your statements have run. For example, to log the received data, you would:
function reqListener(e) {
data = JSON.parse(this.responseText);
console.log(data);
}
I'm not seeing the use of data
in the React component, so I can only suggest this theoretically: why not update your component in the callback?
bool doesL1ContainsL2 = l1.Intersect(l2).Count() == l2.Count;
L1 and L2 are both List<T>
According to this thread in MSDN forums: VS2012 RC installation breaks VS2010 C++ projects, simply, take cvtres.exe
from VS2010 SP1
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\cvtres.exe
or from VS2012
C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\cvtres.exe
and copy it over the cvtres.exe
in VS2010 RTM installation (the one without SP1)
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\cvtres.exe
This way, you will effectively use the corrected version of cvtres.exe
which is 11.0.51106.1.
Repeat the same steps for 64-bit version of the tool in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64\cvtres.exe
.
This solution is an alternative to installation of SP1 for VS2010 - in some cases you simply can't install SP1 (i.e. if you need to support pre-SP1 builds).
I had to encounter a situation as such, and simply, the
str_replace("\/","/",$variable)
did work for me.
this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.
to check either a pointer is initialized or not you can try something like
Class *pointer = new Class();
if(pointer!=nullptr){
pointer->myFunction();
}
There's no built-in method for doing this in Python 2. If you need this, you need to write a prepend()
method/function that operates on the OrderedDict
internals with O(1) complexity.
For Python 3.2 and later, you should use the move_to_end
method. The method accepts a last
argument which indicates whether the element will be moved to the bottom (last=True
) or the top (last=False
) of the OrderedDict
.
Finally, if you want a quick, dirty and slow solution, you can just create a new OrderedDict
from scratch.
Details for the four different solutions:
OrderedDict
and add a new instance methodfrom collections import OrderedDict
class MyOrderedDict(OrderedDict):
def prepend(self, key, value, dict_setitem=dict.__setitem__):
root = self._OrderedDict__root
first = root[1]
if key in self:
link = self._OrderedDict__map[key]
link_prev, link_next, _ = link
link_prev[1] = link_next
link_next[0] = link_prev
link[0] = root
link[1] = first
root[1] = first[0] = link
else:
root[1] = first[0] = self._OrderedDict__map[key] = [root, first, key]
dict_setitem(self, key, value)
Demo:
>>> d = MyOrderedDict([('a', '1'), ('b', '2')])
>>> d
MyOrderedDict([('a', '1'), ('b', '2')])
>>> d.prepend('c', 100)
>>> d
MyOrderedDict([('c', 100), ('a', '1'), ('b', '2')])
>>> d.prepend('a', d['a'])
>>> d
MyOrderedDict([('a', '1'), ('c', 100), ('b', '2')])
>>> d.prepend('d', 200)
>>> d
MyOrderedDict([('d', 200), ('a', '1'), ('c', 100), ('b', '2')])
OrderedDict
objectsThis function does the same thing by accepting the dict object, key and value. I personally prefer the class:
from collections import OrderedDict
def ordered_dict_prepend(dct, key, value, dict_setitem=dict.__setitem__):
root = dct._OrderedDict__root
first = root[1]
if key in dct:
link = dct._OrderedDict__map[key]
link_prev, link_next, _ = link
link_prev[1] = link_next
link_next[0] = link_prev
link[0] = root
link[1] = first
root[1] = first[0] = link
else:
root[1] = first[0] = dct._OrderedDict__map[key] = [root, first, key]
dict_setitem(dct, key, value)
Demo:
>>> d = OrderedDict([('a', '1'), ('b', '2')])
>>> ordered_dict_prepend(d, 'c', 100)
>>> d
OrderedDict([('c', 100), ('a', '1'), ('b', '2')])
>>> ordered_dict_prepend(d, 'a', d['a'])
>>> d
OrderedDict([('a', '1'), ('c', 100), ('b', '2')])
>>> ordered_dict_prepend(d, 'd', 500)
>>> d
OrderedDict([('d', 500), ('a', '1'), ('c', 100), ('b', '2')])
OrderedDict.move_to_end()
(Python >= 3.2)Python 3.2 introduced the OrderedDict.move_to_end()
method. Using it, we can move an existing key to either end of the dictionary in O(1) time.
>>> d1 = OrderedDict([('a', '1'), ('b', '2')])
>>> d1.update({'c':'3'})
>>> d1.move_to_end('c', last=False)
>>> d1
OrderedDict([('c', '3'), ('a', '1'), ('b', '2')])
If we need to insert an element and move it to the top, all in one step, we can directly use it to create a prepend()
wrapper (not presented here).
OrderedDict
- slow!!!If you don't want to do that and performance is not an issue then easiest way is to create a new dict:
from itertools import chain, ifilterfalse
from collections import OrderedDict
def unique_everseen(iterable, key=None):
"List unique elements, preserving order. Remember all elements ever seen."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
seen = set()
seen_add = seen.add
if key is None:
for element in ifilterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element
d1 = OrderedDict([('a', '1'), ('b', '2'),('c', 4)])
d2 = OrderedDict([('c', 3), ('e', 5)]) #dict containing items to be added at the front
new_dic = OrderedDict((k, d2.get(k, d1.get(k))) for k in \
unique_everseen(chain(d2, d1)))
print new_dic
output:
OrderedDict([('c', 3), ('e', 5), ('a', '1'), ('b', '2')])
Perhaps my method will help you.
public static bool IsNumber(string s)
{
return s.All(char.IsDigit);
}
I had the same problem with Java 7 u51. Only after I reset Internet Explorer it work again, Java was enabled in browser etc.
Internet options -> Advanced -> Reset...
With PHP 5.6 on Amazon Linux (should be the same on RedHat or CentOS):
yum install php56-opcache
and then restart apache.
Some conventions list all the public methods first, and then all the private ones - that means it's easy to separate the API from the implementation, even when there's no interface involved, if you see what I mean.
Another idea is to group related methods together - this makes it easier to spot seams where you could split your existing large class into several smaller, more targeted ones.
Because in 2nd case you adding same reference twice and HashSet
have check against this in HashMap.put()
on which HashSet
is based:
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
As you can see, equals
will be called only if hash of key being added equals to the key already present in set and references of these two are different.
You simply need to do a SUBSTR on the string in col3....
Select col1, col2, REPLACE(substr(col3, instr(col3, 'Client Name'),
(instr(col3, '|', instr(col3, 'Client Name') -
instr(col3, 'Client Name'))
),
'Client Name = ',
'')
from Table01
And yes, that is a bad DB design for the reasons stated in the original issue
You have also to ensure you have the correct SDK platform version installed in your environment by using SDK Manager.
This can be achieved using div. It can be done with table too. But i always prefer div.
<body id="doc-body" style="width: 100%; height: 100%; overflow: hidden; position: fixed" onload="InitApp()">
<div>
<!--If you don't need header background color you don't need this div.-->
<div id="div-header-hack" style="height: 20px; position: absolute; background-color: gray"></div>
<div id="div-header" style="position: absolute; top: 0px; overflow: hidden; height: 20px; background-color: gray">
</div>
<div id="div-item" style="position: absolute; top: 20px; overflow: auto" onscroll="ScrollHeader()">
</div>
</div>
</body>
Javascript:
please refer jsFiddle for this part. Else this answer becomes very lengthy.
Update 2019
In Bootstrap 4, flexbox can be used to get a full height layout that fills the remaining space.
First of all, the container (parent) needs to be full height:
Option 1_ Add a class for min-height: 100%;
. Remember that min-height will only work if the parent has a defined height:
html, body {
height: 100%;
}
.min-100 {
min-height: 100%;
}
https://codeply.com/go/dTaVyMah1U
Option 2_ Use vh
units:
.vh-100 {
min-height: 100vh;
}
https://codeply.com/go/kMahVdZyGj
Also of Bootstrap 4.1, the vh-100
and min-vh-100
classes are included in Bootstrap so there is no need to for the extra CSS
Then, use flexbox direction column d-flex flex-column
on the container, and flex-grow-1
on any child divs (ie: row
) that you want to fill the remaining height.
Also see:
Bootstrap 4 Navbar and content fill height flexbox
Bootstrap - Fill fluid container between header and footer
How to make the row stretch remaining height
Your selector is looking for any descendants of a checkbox element that have a class of .myClass
.
Try this instead:
$("input.myClass:checkbox")
I also tested this:
$("input:checkbox.myClass")
And it will also work properly. In my humble opinion this syntax really looks rather ugly, as most of the time I expect :
style selectors to come last. As I said, though, either one will work.
The provided answers didn't work for me. I'm adding another answer because this is where I ended up when searching for radio stream urls.
Radio Browser is a searchable site with streaming urls for radio stations around the world:
http://www.radio-browser.info/
Search for a station like FIP, Pinguin Radio or Radio Paradise, then click the save button, which downloads a PLS file that you can open in your radioplayer (Rhythmbox), or you open the file in a text editor and copy the URL to add in Goodvibes.
My guess is that you simply need to URL-encode your Base64 string when you include it in the querystring.
Base64 encoding uses some characters which must be encoded if they're part of a querystring (namely +
and /
, and maybe =
too). If the string isn't correctly encoded then you won't be able to decode it successfully at the other end, hence the errors.
You can use the HttpUtility.UrlEncode
method to encode your Base64 string:
string msg = "Please click on the link below or paste it into a browser "
+ "to verify your email account.<br /><br /><a href=\""
+ _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
+ HttpUtility.UrlEncode(userName.Encrypt("verify")) + "\">"
+ _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
+ HttpUtility.UrlEncode(userName.Encrypt("verify")) + "</a>";
You can achieve you goal with below ways :-
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
or
// create a java calendar instance
Calendar calendar = Calendar.getInstance();
// get a java date (java.util.Date) from the Calendar instance.
// this java date will represent the current date, or "now".
java.util.Date currentDate = calendar.getTime();
// now, create a java.sql.Date from the java.util.Date
java.sql.Date date = new java.sql.Date(currentDate.getTime());
Get highlighted text this way:
window.getSelection().toString()
and of course a special treatment for ie:
document.selection.createRange().htmlText
Unless you're browsing through a proxy, the web servers hosting the sites you want to access must be configured to listen to a port other than 80 or 8080.
That usually happens when you call
onClick={this.handleButton
()}
- notice the () instead of:
onClick={this.handleButton
} - notice here we are not calling the function when we initialize it
The Android API already provides a method to achieve that. Try this:
Rect offsetViewBounds = new Rect();
//returns the visible bounds
childView.getDrawingRect(offsetViewBounds);
// calculates the relative coordinates to the parent
parentViewGroup.offsetDescendantRectToMyCoords(childView, offsetViewBounds);
int relativeTop = offsetViewBounds.top;
int relativeLeft = offsetViewBounds.left;
Here is the doc
Just simply use isset($_POST['radio']) so that whenever i click any of the radio button, the one that is clicked is set to the post.
<form method="post" action="sample.php">
select sex:
<input type="radio" name="radio" value="male">
<input type="radio" name="radio" value="female">
<input type="submit" value="submit">
</form>
<?php
if (isset($_POST['radio'])){
$Sex = $_POST['radio'];
}
?>
Using a double-tilde (double bitwise NOT) - ~~
- does some interesting things in JavaScript. For instance you can use it instead of Math.floor
or even as an alternative to parseInt("123", 10)
! It's been discussed a lot over the web, so I won't go in why it works here, but if you're interested: What is the "double tilde" (~~) operator in JavaScript?
We can exploit this property of a double-tilde to convert NaN
to a number, and happily that number is zero!
console.log(~~NaN); // 0
I solved it after changing the ssh port & MaxStartups variable in /etc/ssh/sshd_config to ,
port 2244
MaxStartups 100
Then, restart the service
service sshd restart
If still it does not work, restart you system.
You can directly use the S3 path. I am using Pandas 0.24.1
In [1]: import pandas as pd
In [2]: df = pd.DataFrame( [ [1, 1, 1], [2, 2, 2] ], columns=['a', 'b', 'c'])
In [3]: df
Out[3]:
a b c
0 1 1 1
1 2 2 2
In [4]: df.to_csv('s3://experimental/playground/temp_csv/dummy.csv', index=False)
In [5]: pd.__version__
Out[5]: '0.24.1'
In [6]: new_df = pd.read_csv('s3://experimental/playground/temp_csv/dummy.csv')
In [7]: new_df
Out[7]:
a b c
0 1 1 1
1 2 2 2
S3 File Handling
pandas now uses s3fs for handling S3 connections. This shouldn’t break any code. However, since s3fs is not a required dependency, you will need to install it separately, like boto in prior versions of pandas. GH11915.
Try implementing the interface as anonymous.
public class MyClass extends MySuperClass implements MyInterface{
MyInterface myInterface = new MyInterface(){
/* Overrided method from interface */
@override
public void method1(){
}
};
/* Overrided method from superclass*/
@override
public void method1(){
}
}
Ian Kemp has the answer (have some points btw..), this is to simply add some meat to one of his steps.
The reason I ended up here was that dev's machines were building fine, but the build server simply wasn't pulling down the packages required (empty packages folder) and therefore the build was failing. Logging onto the build server and manually building the solution worked, however.
To fulfil the second of Ians 3 point steps (running nuget restore), you can create an MSBuild target running the exec command to run the nuget restore command, as below (in this case nuget.exe is in the .nuget folder, rather than on the path), which can then be run in a TeamCity build step (other CI available...) immediately prior to building the solution
<Target Name="BeforeBuild">
<Exec Command="..\.nuget\nuget restore ..\MySolution.sln"/>
</Target>
For the record I'd already tried the "nuget installer" runner type but this step was hanging on web projects (worked for DLL's and Windows projects)
If you want to open it to read and write, I'm assuming you don't want to truncate it as you open it and you want to be able to read the file right after opening it. So this is the solution I'm using:
file = open('myfile.dat', 'a+')
file.seek(0, 0)
That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87
Double check your table definition. Maybe you just missed adding something.
I also tried google-ing this problem and saw this:
http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode
The is no API for adding a shortcut to the home screen in iOS, so no third-party browser is capable of providing that functionality.
git checkout -f
This is suffice for your question. Only thing is, once its done, its done. There is no undo.
Try this:
public void test(){
// net.sf.json.JSONObject, net.sf.json.JSONArray
List objList = new ArrayList();
objList.add("obj1");
objList.add("obj2");
objList.add("obj3");
HashMap objMap = new HashMap();
objMap.put("key1", "value1");
objMap.put("key2", "value2");
objMap.put("key3", "value3");
System.out.println("JSONArray :: "+(JSONArray)JSONSerializer.toJSON(objList));
System.out.println("JSONObject :: "+(JSONObject)JSONSerializer.toJSON(objMap));
}
you can find API here.
Just in case anyone is having the same problem... I was getting this error, and it turned out to be my <Application.Resources>
in my App.xaml file. I had a resource outside my resource dictionary tags, and that caused this error.
I thinks it is vary helpful way.
models.py
from django.db import models
class User(models.Model):
user_name = models.CharField(max_length=100)
password = models.CharField(max_length=32)
forms.py
from django import forms
from Admin.models import *
class User_forms(forms.ModelForm):
class Meta:
model= User
fields=[
'user_name',
'password'
]
widgets = {
'password': forms.PasswordInput()
}
this is Postgres UPDATE JOIN format:
UPDATE address
SET cid = customers.id
FROM customers
WHERE customers.id = address.id
Here's the other variations: http://mssql-to-postgresql.blogspot.com/2007/12/updates-in-postgresql-ms-sql-mysql.html
round(x[, n]): values are rounded to the closest multiple of 10 to the power minus n. So if n is negative...
def round5(x):
return int(round(x*2, -1)) / 2
Since 10 = 5 * 2, you can use integer division and multiplication with 2, rather than float division and multiplication with 5.0. Not that that matters much, unless you like bit shifting
def round5(x):
return int(round(x << 1, -1)) >> 1
Having been bitten by this, I have a habit of including locally defined variables in the innermost scope which I use to transfer to any closure. In your example:
foreach (var s in strings)
query = query.Where(i => i.Prop == s); // access to modified closure
I do:
foreach (var s in strings)
{
string search = s;
query = query.Where(i => i.Prop == search); // New definition ensures unique per iteration.
}
Once you have that habit, you can avoid it in the very rare case you actually intended to bind to the outer scopes. To be honest, I don't think I have ever done so.
I recently ran into this issue and none of the solutions proposed fixed it. The issue turned out to be an excessive use of datasets stored in the session. There was a flaw in the code that results in the session size to increase 10x.
There is an article on the msdn blog that also talks about this. http://blogs.msdn.com/b/johan/archive/2006/11/20/sessionstate-performance.aspx
I used a function to write custom trace messages to measure the size of the session data on the live site.
I know this question is too old, but still, I think this approach would be cleaner:
cat = $.URLDecode(cat);
$('#cbCategory option:contains("' + cat + '")').prop('selected', true);
In this case you wont need to go over the entire options with each()
.
Although by that time prop()
didn't exist so for older versions of jQuery use attr()
.
UPDATE
You have to be certain when using contains
because you can find multiple options, in case of the string inside cat
matches a substring of a different option than the one you intend to match.
Then you should use:
cat = $.URLDecode(cat);
$('#cbCategory option')
.filter(function(index) { return $(this).text() === cat; })
.prop('selected', true);
Try this:
implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
Using BoxDecoration() is the best way to show border.
Container(
decoration: BoxDecoration(
border: Border.all(
color: Color(0xff000000),
width: 4,
)),
child: //Your child widget
),
You can also view full format here
Another less-conventional but arguably easier way of doing this is with JXplorer. Although this tool is designed to browse LDAP directories, it has an easy-to-use GUI for manipulating keystores. One such function on the GUI can export private keys from a JKS keystore.
Lots of answers. May be this one will also help-
Intent intent = new Intent(activity, SignInActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
this.finish();
Kotlin version-
Intent(this, SignInActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}.also { startActivity(it) }
finish()
Oracle has a different syntax for parameters than Sql-Server. So use :
instead of @
using(var con=new OracleConnection(connectionString))
{
con.open();
var sql = "insert into users values (:id,:name,:surname,:username)";
using(var cmd = new OracleCommand(sql,con)
{
OracleParameter[] parameters = new OracleParameter[] {
new OracleParameter("id",1234),
new OracleParameter("name","John"),
new OracleParameter("surname","Doe"),
new OracleParameter("username","johnd")
};
cmd.Parameters.AddRange(parameters);
cmd.ExecuteNonQuery();
}
}
When using named parameters in an OracleCommand you must precede the parameter name with a colon (:).
http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.parameters.aspx
Basically unmanaged code is code which does not run under the .NET CLR (aka not VB.NET, C#, etc.). My guess is that NUnit has a runner/wrapper which is not .NET code (aka C++).
FYI for for anyone coming across the problem described in the title (as I did) who is also using the AngularUI Router plugin...
As asked and answered in this SO question, the angular-ui router jumps to the bottom of the page when you change routes.
Can't figure out why page loads at bottom? Angular UI-Router autoscroll Issue
However, as the answer states, you can turn off this behavior by saying autoscroll="false"
on your ui-view
.
For example:
<div ui-view="pagecontent" autoscroll="false"></div>
<div ui-view="sidebar" autoscroll="false"></div>
http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-view
Typically, you'd use a built-in layout control appropriate for your scenario (e.g. use a grid as a parent if you want scaling relative to the parent). If you want to do it with an arbitrary parent element, you can create a ValueConverter do it, but it probably won't be quite as clean as you'd like. However, if you absolutely need it, you could do something like this:
public class PercentageConverter : IValueConverter
{
public object Convert(object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
return System.Convert.ToDouble(value) *
System.Convert.ToDouble(parameter);
}
public object ConvertBack(object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Which can be used like this, to get a child textbox 10% of the width of its parent canvas:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<local:PercentageConverter x:Key="PercentageConverter"/>
</Window.Resources>
<Canvas x:Name="canvas">
<TextBlock Text="Hello"
Background="Red"
Width="{Binding
Converter={StaticResource PercentageConverter},
ElementName=canvas,
Path=ActualWidth,
ConverterParameter=0.1}"/>
</Canvas>
</Window>
The #
part gives you a 0x
in the output string. The 0
and the x
count against your "8" characters listed in the 08
part. You need to ask for 10 characters if you want it to be the same.
int i = 7;
printf("%#010x\n", i); // gives 0x00000007
printf("0x%08x\n", i); // gives 0x00000007
printf("%#08x\n", i); // gives 0x000007
Also changing the case of x
, affects the casing of the outputted characters.
printf("%04x", 4779); // gives 12ab
printf("%04X", 4779); // gives 12AB
Kinda late to the party, but in case anyone else is struggling. None of the Google searches I've found for the past two days have come up with anything that works, but I came up with a concise and elegant solution that will always work no matter how many nested tags you have:
function cursor_position() {_x000D_
var sel = document.getSelection();_x000D_
sel.modify("extend", "backward", "paragraphboundary");_x000D_
var pos = sel.toString().length;_x000D_
if(sel.anchorNode != undefined) sel.collapseToEnd();_x000D_
_x000D_
return pos;_x000D_
}_x000D_
_x000D_
// Demo:_x000D_
var elm = document.querySelector('[contenteditable]');_x000D_
elm.addEventListener('click', printCaretPosition)_x000D_
elm.addEventListener('keydown', printCaretPosition)_x000D_
_x000D_
function printCaretPosition(){_x000D_
console.log( cursor_position(), 'length:', this.textContent.trim().length )_x000D_
}
_x000D_
<div contenteditable>some text here <i>italic text here</i> some other text here <b>bold text here</b> end of text</div>
_x000D_
It selects all the way back to the beginning of the paragraph and then counts the length of the string to get the current position and then undoes the selection to return the cursor to the current position. If you want to do this for an entire document (more than one paragraph), then change paragraphboundary
to documentboundary
or whatever granularity for your case. Check out the API for more details. Cheers! :)
Every Set has an iterator(). A normal HashSet's iterator is quite random, a TreeSet does it by sort order, a LinkedHashSet iterator iterates by insert order.
You can't replace an element in a LinkedHashSet, however. You can remove one and add another, but the new element will not be in the place of the original. In a LinkedHashMap, you can replace a value for an existing key, and then the values will still be in the original order.
Also, you can't insert at a certain position.
Maybe you'd better use an ArrayList with an explicit check to avoid inserting duplicates.
You can type them manually but the editor will assist you.
http://developer.android.com/reference/android/Manifest.permission.html
You can see the snap sot below.
As soon as you type "a" inside the quotes you get a list of permissions and also hint to move caret up and down to select the same.
Why get so fancy about it? Just invoke the .msi file:
& <path>\filename.msi
or
Start-Process <path>\filename.msi
Edit: Full list of Start-Process parameters
TL;DR
Use Promise.all
for the parallel function calls, the answer behaviors not correctly when the error occurs.
First, execute all the asynchronous calls at once and obtain all the Promise
objects. Second, use await
on the Promise
objects. This way, while you wait for the first Promise
to resolve the other asynchronous calls are still progressing. Overall, you will only wait for as long as the slowest asynchronous call. For example:
// Begin first call and store promise without waiting
const someResult = someCall();
// Begin second call and store promise without waiting
const anotherResult = anotherCall();
// Now we await for both results, whose async processes have already been started
const finalResult = [await someResult, await anotherResult];
// At this point all calls have been resolved
// Now when accessing someResult| anotherResult,
// you will have a value instead of a promise
JSbin example: http://jsbin.com/xerifanima/edit?js,console
Caveat: It doesn't matter if the await
calls are on the same line or on different lines, so long as the first await
call happens after all of the asynchronous calls. See JohnnyHK's comment.
Update: this answer has a different timing in error handling according to the @bergi's answer, it does NOT throw out the error as the error occurs but after all the promises are executed.
I compare the result with @jonny's tip: [result1, result2] = Promise.all([async1(), async2()])
, check the following code snippet
const correctAsync500ms = () => {_x000D_
return new Promise(resolve => {_x000D_
setTimeout(resolve, 500, 'correct500msResult');_x000D_
});_x000D_
};_x000D_
_x000D_
const correctAsync100ms = () => {_x000D_
return new Promise(resolve => {_x000D_
setTimeout(resolve, 100, 'correct100msResult');_x000D_
});_x000D_
};_x000D_
_x000D_
const rejectAsync100ms = () => {_x000D_
return new Promise((resolve, reject) => {_x000D_
setTimeout(reject, 100, 'reject100msError');_x000D_
});_x000D_
};_x000D_
_x000D_
const asyncInArray = async (fun1, fun2) => {_x000D_
const label = 'test async functions in array';_x000D_
try {_x000D_
console.time(label);_x000D_
const p1 = fun1();_x000D_
const p2 = fun2();_x000D_
const result = [await p1, await p2];_x000D_
console.timeEnd(label);_x000D_
} catch (e) {_x000D_
console.error('error is', e);_x000D_
console.timeEnd(label);_x000D_
}_x000D_
};_x000D_
_x000D_
const asyncInPromiseAll = async (fun1, fun2) => {_x000D_
const label = 'test async functions with Promise.all';_x000D_
try {_x000D_
console.time(label);_x000D_
let [value1, value2] = await Promise.all([fun1(), fun2()]);_x000D_
console.timeEnd(label);_x000D_
} catch (e) {_x000D_
console.error('error is', e);_x000D_
console.timeEnd(label);_x000D_
}_x000D_
};_x000D_
_x000D_
(async () => {_x000D_
console.group('async functions without error');_x000D_
console.log('async functions without error: start')_x000D_
await asyncInArray(correctAsync500ms, correctAsync100ms);_x000D_
await asyncInPromiseAll(correctAsync500ms, correctAsync100ms);_x000D_
console.groupEnd();_x000D_
_x000D_
console.group('async functions with error');_x000D_
console.log('async functions with error: start')_x000D_
await asyncInArray(correctAsync500ms, rejectAsync100ms);_x000D_
await asyncInPromiseAll(correctAsync500ms, rejectAsync100ms);_x000D_
console.groupEnd();_x000D_
})();
_x000D_
I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.
Associative Arrays in JavaScript don't really work the same as they do in other languages. for each
statements are complicated (because they enumerate inherited prototype properties). You could declare properties on an object/associative array as Pointy mentioned, but really for this sort of thing you should use an array with the push
method:
jsArr = [];
for (var i = 1; i <= 10; i++) {
jsArr.push('example ' + 1);
}
Just don't forget that indexed arrays are zero-based so the first element will be jsArr[0], not jsArr[1].
(answered Nov 23 '10 at 19:48) I'm not really a big Pythoner - but I found this syntax once, forgot where from, so I thought I'd document it:
if you use sys.stdout.write
instead of print
(the difference being, sys.stdout.write
takes arguments as a function, in parenthesis - whereas print
doesn't), then for a one-liner, you can get away with inverting the order of the command and the for
, removing the semicolon, and enclosing the command in square brackets, i.e.:
python -c "import sys; [sys.stdout.write('rob\n') for r in range(10)]"
Have no idea how this syntax would be called in Python :)
Hope this helps,
Cheers!
(EDIT Tue Apr 9 20:57:30 2013) Well, I think I finally found what these square brackets in one-liners are about; they are "list comprehensions" (apparently); first note this in Python 2.7:
$ STR=abc
$ echo $STR | python -c "import sys,re; a=(sys.stdout.write(line) for line in sys.stdin); print a"
<generator object <genexpr> at 0xb771461c>
So the command in round brackets/parenthesis is seen as a "generator object"; if we "iterate" through it by calling next()
- then the command inside the parenthesis will be executed (note the "abc" in the output):
$ echo $STR | python -c "import sys,re; a=(sys.stdout.write(line) for line in sys.stdin); a.next() ; print a"
abc
<generator object <genexpr> at 0xb777b734>
If we now use square brackets - note that we don't need to call next()
to have the command execute, it executes immediately upon assignment; however, later inspection reveals that a
is None
:
$ echo $STR | python -c "import sys,re; a=[sys.stdout.write(line) for line in sys.stdin]; print a"
abc
[None]
This doesn't leave much info to look for, for the square brackets case - but I stumbled upon this page which I think explains:
Python Tips And Tricks – First Edition - Python Tutorials | Dream.In.Code:
If you recall, the standard format of a single line generator is a kind of one line 'for' loop inside brackets. This will produce a 'one-shot' iterable object which is an object you can iterate over in only one direction and which you can't re-use once you reach the end.
A 'list comprehension' looks almost the same as a regular one-line generator, except that the regular brackets - ( ) - are replaced by square brackets - [ ]. The major advanatge of alist comprehension is that produces a 'list', rather than a 'one-shot' iterable object, so that you can go back and forth through it, add elements, sort, etc.
And indeed it is a list - it's just its first element becomes none as soon as it is executed:
$ echo $STR | python -c "import sys,re; print [sys.stdout.write(line) for line in sys.stdin].__class__"
abc
<type 'list'>
$ echo $STR | python -c "import sys,re; print [sys.stdout.write(line) for line in sys.stdin][0]"
abc
None
List comprehensions are otherwise documented in 5. Data Structures: 5.1.4. List Comprehensions — Python v2.7.4 documentation as "List comprehensions provide a concise way to create lists"; presumably, that's where the limited "executability" of lists comes into play in one-liners.
Well, hope I'm not terribly too off the mark here ...
EDIT2: and here is a one-liner command line with two non-nested for-loops; both enclosed within "list comprehension" square brackets:
$ echo $STR | python -c "import sys,re; a=[sys.stdout.write(line) for line in sys.stdin]; b=[sys.stdout.write(str(x)) for x in range(2)] ; print a ; print b"
abc
01[None]
[None, None]
Notice that the second "list" b
now has two elements, since its for loop explicitly ran twice; however, the result of sys.stdout.write()
in both cases was (apparently) None
.
For Windows Server® 2008, Windows 7, Windows Server 2003, Windows Vista®, or Windows XP run "control userpasswords2"
Click the Start button, then click Run (Windows XP, Server 2003 or below)
Type control userpasswords2 and press Enter on your keyboard.
Note: For Windows 7 and Windows Vista, this command will not run by typing it in the Serach box on the Start Menu - it must be run using the Run option. To add the Run command to your Start menu, right-click on it and choose the option to customize it, then go to the Advanced options. Check to option to add the Run command.
You will see a window of user details!
Use and empty()
whit negation (for test if not empty)
if(!empty($_GET['id'])) {
// if get id is not empty
}
//an easy way:
str := fmt.Sprint(data)
One way for me to understand wildcards is to think that the wildcard isn't specifying the type of the possible objects that given generic reference can "have", but the type of other generic references that it is is compatible with (this may sound confusing...) As such, the first answer is very misleading in it's wording.
In other words, List<? extends Serializable>
means you can assign that reference to other Lists where the type is some unknown type which is or a subclass of Serializable. DO NOT think of it in terms of A SINGLE LIST being able to hold subclasses of Serializable (because that is incorrect semantics and leads to a misunderstanding of Generics).
Here's one more approach by using SET
and FOR /F
@echo off
set "var=<?xml version="1.0" encoding="utf-8" ?>"
for /f "tokens=1* delims==" %%a in ('set var') do echo %%b
and you can beautify it like:
@echo off
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "print{[=for /f "tokens=1* delims==" %%a in ('set " & set "]}=') do echo %%b"
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "xml_line.1=<?xml version="1.0" encoding="utf-8" ?>"
set "xml_line.2=<root>"
set "xml_line.3=</root>"
%print{[% xml_line %]}%
Parsing means we are analyzing an object specifically. For example, when we enter some keywords in a search engine, they parse the keywords and give back results by searching for each word. So it is basically taking a string from the file and processing it to extract the information we want.
Example of parsing using indexOf
to calculate the position of a string in another string:
String s="What a Beautiful day!";
int i=s.indexOf("day");//value of i would be 17
int j=s.indexOf("be");//value of j would be -1
int k=s.indexOf("ea");//value of k would be 8
paresInt
essentially converts a String
to a Integer
.
String s="9876543";
int a=new Integer(s);//uses constructor
System.out.println("Constructor method: " + a);
a=Integer.parseInt(s);//uses parseInt() method
System.out.println("parseInt() method: " + a);
Output:
Constructor method: 9876543 parseInt() method: 9876543
;C:\Program Files (x86)\Git\bin;C:\Program Files (x86)\Git\cmd
add above path in environment variables
note: path may differ but you should add both bin
and cmd
If you are using jQuery then by using plugin formInteract, you just need to do this:
// Just keep the HTML as it is.
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
At bottom of the page just include this plugin file and write this code:
// Initialize one time at the bottom of the page.
var search= $("#searchTxt).formInteract();
search.getAjax("http://www.myurl.com/search/", function(rsp){
// Now do whatever you want to with your response
});
Or if using a parameterized URL then use this:
$.get("http://www.myurl.com/search/"+search.get().searchTxt, {}, function(rsp){
// Now do work with your response;
})
Here is the link to project https://bitbucket.org/ranjeet1985/forminteract
You can use this plugin for many purposes like getting the value of a form, putting values into a form, validation of forms and many more. You can see some example of code in the index.html file of the project.
Of course I am the author of this project and all are welcome to make it better.
Just a little expansion to Nathan's Linq Expression solution. Use multi generic param so that the property doesn't limited to string.
void GetString<TClass, TProperty>(string input, TClass outObj, Expression<Func<TClass, TProperty>> outExpr)
{
if (!string.IsNullOrEmpty(input))
{
var expr = (MemberExpression) outExpr.Body;
var prop = (PropertyInfo) expr.Member;
if (!prop.GetValue(outObj).Equals(input))
{
prop.SetValue(outObj, input, null);
}
}
}
$(document).ready(function(){_x000D_
_x000D_
$(".btn1").click(function(){_x000D_
$("div.test:not(:first)").hide();_x000D_
});_x000D_
_x000D_
$(".btn2").click(function(){_x000D_
$("div.test").show();_x000D_
$("div.test:not(:first):not(:last)").hide();_x000D_
});_x000D_
_x000D_
$(".btn3").click(function(){_x000D_
$("div.test").hide();_x000D_
$("div.test:not(:first):not(:last)").show();_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button class="btn1">Hide All except First</button>_x000D_
<button class="btn2">Hide All except First & Last</button>_x000D_
<button class="btn3">Hide First & Last</button>_x000D_
_x000D_
<br/>_x000D_
_x000D_
<div class='test'>First</div>_x000D_
<div class='test'>Second</div>_x000D_
<div class='test'>Third</div>_x000D_
<div class='test'>Last</div>
_x000D_
If using GitHub on Windows:
This is why, before you start making changes of your own, that you should create a branch for each set of changes you plan to put into a pull request. That way, once you make the pull request, you can then make another branch and continue work on some other task/feature/bugfix without affecting the previous pull request.
The usage from the official documentation:
https://maven.apache.org/plugins/maven-dependency-plugin/usage.html#dependency:get
For my case, see the answer below:
mvn dependency:get -Dartifact=$2:$3:$4:$5 -DremoteRepositories=$1 -Dtransitive=false
mvn dependency:copy -Dartifact=$2:$3:$4:$5 -DremoteRepositories=$1 -Dtransitive=false -DoutputDirectory=$6
#mvn dependency:get -Dartifact=com.huya.mtp:hynswup:1.0.88-SNAPSHOT:jar -DremoteRepositories=http://nexus.google.com:8081/repository/maven-snapshots/ -Dtransitive=false
#mvn dependency:copy -Dartifact=com.huya.mtp:hynswup:1.0.88-SNAPSHOT:jar -DremoteRepositories=http://nexus.google.com:8081/repository/maven-snapshots/ -Dtransitive=false -DoutputDirectory=.
Use the command mvn dependency:get
to download the specific artifact and use
the command mvn dependency:copy
to copy the downloaded artifact to the destination directory -DoutputDirectory
.
You have just to enter:
First a IBOutlet:
@IBOutlet var appsTableView : UITableView
Then in a Action func:
self.appsTableView.reloadData()
Also to put it in simple terms, it happens because of the "Erasure" property of the generics.Which means that although we define ArrayList<Integer>
and ArrayList<String>
, at the compile time it stays as two different concrete types but at the runtime the JVM erases generic types and creates only one ArrayList class instead of two classes. So when we define a static type method or anything for a generic, it is shared by all instances of that generic, in my example it is shared by both ArrayList<Integer>
and ArrayList<String>
.That's why you get the error.A Generic Type Parameter of a Class Is Not Allowed in a Static Context!
Load the multicol package, like this \usepackage{multicol}
. Then use:
\begin{multicols}{2}
Column 1
\columnbreak
Column 2
\end{multicols}
If you omit the \columnbreak
, the columns will balance automatically.
This fixed it for me: Open maven projects tab on the right. Add the pom if not yet present, then click refresh on the top left of the tab.
window.addEventListener("scroll", function(evt) {
var pos_top = document.body.scrollTop;
if(pos_top == 0){
$('#divID').css('position','fixed');
}
else if(pos_top > 0){
$('#divId').css('position','static');
}
});
You need to save the PID of the background process at the time you start it:
foo &
FOO_PID=$!
# do other stuff
kill $FOO_PID
You cannot use job control, since that is an interactive feature and tied to a controlling terminal. A script will not necessarily have a terminal attached at all so job control will not necessarily be available.
The main reason for primary and foreign keys is to enforce data consistency.
A primary key enforces the consistency of uniqueness of values over one or more columns. If an ID column has a primary key then it is impossible to have two rows with the same ID value. Without that primary key, many rows could have the same ID value and you wouldn't be able to distinguish between them based on the ID value alone.
A foreign key enforces the consistency of data that points elsewhere. It ensures that the data which is pointed to actually exists. In a typical parent-child relationship, a foreign key ensures that every child always points at a parent and that the parent actually exists. Without the foreign key you could have "orphaned" children that point at a parent that doesn't exist.
equals
can take any Object as a parameter but compareTo
can only take String.
when cometo null,compareTo
will throw a exception
when you want to know where the diff happen,you can use compareTo
.
Can you clarify your question? What is "ohHover" in this case and how does it correspond to a delay in hover time?
That said, I think what you probably want is...
var timeout;
element.onmouseover = function(e) {
timeout = setTimeout(function() {
// ...
}, delayTimeMs)
};
element.onmouseout = function(e) {
if(timeout) {
clearTimeout(timeout);
}
};
Or addEventListener
/attachEvent
or your favorite library's event abstraction method.
For me the following steps worked:
Quick and dirty - Turn it off:
USE_TZ = False
in your settings.py
You're making this a little more complicated than it has to be. Let's start with the end of your example:
String parameterString = "";
if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," );
if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );
With the small change of using a StringBuilder instead of a String, this becomes:
StringBuilder parameterString = new StringBuilder();
if (condition) parameterString.append("elementName").append(",");
if (anotherCondition) parameterString.append("anotherElementName").append(",");
...
When you're done (I assume you have to check a few other conditions as well), just make sure you remove the tailing comma with a command like this:
if (parameterString.length() > 0)
parameterString.deleteCharAt(parameterString.length() - 1);
And finally, get the string you want with
parameterString.toString();
You could also replace the "," in the second call to append with a generic delimiter string that can be set to anything. If you have a list of things you know you need to append (non-conditionally), you could put this code inside a method that takes a list of strings.
- What is the most typical/common way of doing this with an object C++ (that doesn't involve overloading the == operator)?
- Is this even the right approach? ie. should I not write functions that take an object as an argument, but rather, write member functions? (But even if so, please answer the original question.)
No, references cannot be null (unless Undefined Behavior has already happened, in which case all bets are already off). Whether you should write a method or non-method depends on other factors.
- Between a function that takes a reference to an object, or a function that takes a C-style pointer to an object, are there reasons to choose one over the other?
If you need to represent "no object", then pass a pointer to the function, and let that pointer be NULL:
int silly_sum(int const* pa=0, int const* pb=0, int const* pc=0) {
/* Take up to three ints and return the sum of any supplied values.
Pass null pointers for "not supplied".
This is NOT an example of good code.
*/
if (!pa && (pb || pc)) return silly_sum(pb, pc);
if (!pb && pc) return silly_sum(pa, pc);
if (pc) return silly_sum(pa, pb) + *pc;
if (pa && pb) return *pa + *pb;
if (pa) return *pa;
if (pb) return *pb;
return 0;
}
int main() {
int a = 1, b = 2, c = 3;
cout << silly_sum(&a, &b, &c) << '\n';
cout << silly_sum(&a, &b) << '\n';
cout << silly_sum(&a) << '\n';
cout << silly_sum(0, &b, &c) << '\n';
cout << silly_sum(&a, 0, &c) << '\n';
cout << silly_sum(0, 0, &c) << '\n';
return 0;
}
If "no object" never needs to be represented, then references work fine. In fact, operator overloads are much simpler because they take overloads.
You can use something like boost::optional.
It is defined as:
typedef unsigned long DWORD;
However, according to the MSDN:
On 32-bit platforms, long is synonymous with int.
Therefore, DWORD is 32bit on a 32bit operating system. There is a separate define for a 64bit DWORD:
typdef unsigned _int64 DWORD64;
Hope that helps.
You could use sed -n 5p file
.
You can also get a range, e.g., sed -n 5,10p file
.
Subtract from another date object
var d = new Date();
d.setHours(d.getHours() - 2);
Note: This is some explanation and pseudocode as to how to implement a very trivial server that can handle incoming and outcoming WebSocket messages as per the definitive framing format. It does not include the handshaking process. Furthermore, this answer has been made for educational purposes; it is not a full-featured implementation.
(In other words, server → browser)
The frames you're sending need to be formatted according to the WebSocket framing format. For sending messages, this format is as follows:
The first byte will be 1000 0001
(or 129
) for a text frame.
The second byte has its first bit set to 0
because we're not encoding the data (encoding from server to client is not mandatory).
It is necessary to determine the length of the raw data so as to send the length bytes correctly:
0 <= length <= 125
, you don't need additional bytes126 <= length <= 65535
, you need two additional bytes and the second byte is 126
length >= 65536
, you need eight additional bytes, and the second byte is 127
The length has to be sliced into separate bytes, which means you'll need to bit-shift to the right (with an amount of eight bits), and then only retain the last eight bits by doing AND 1111 1111
(which is 255
).
After the length byte(s) comes the raw data.
This leads to the following pseudocode:
bytesFormatted[0] = 129
indexStartRawData = -1 // it doesn't matter what value is
// set here - it will be set now:
if bytesRaw.length <= 125
bytesFormatted[1] = bytesRaw.length
indexStartRawData = 2
else if bytesRaw.length >= 126 and bytesRaw.length <= 65535
bytesFormatted[1] = 126
bytesFormatted[2] = ( bytesRaw.length >> 8 ) AND 255
bytesFormatted[3] = ( bytesRaw.length ) AND 255
indexStartRawData = 4
else
bytesFormatted[1] = 127
bytesFormatted[2] = ( bytesRaw.length >> 56 ) AND 255
bytesFormatted[3] = ( bytesRaw.length >> 48 ) AND 255
bytesFormatted[4] = ( bytesRaw.length >> 40 ) AND 255
bytesFormatted[5] = ( bytesRaw.length >> 32 ) AND 255
bytesFormatted[6] = ( bytesRaw.length >> 24 ) AND 255
bytesFormatted[7] = ( bytesRaw.length >> 16 ) AND 255
bytesFormatted[8] = ( bytesRaw.length >> 8 ) AND 255
bytesFormatted[9] = ( bytesRaw.length ) AND 255
indexStartRawData = 10
// put raw data at the correct index
bytesFormatted.put(bytesRaw, indexStartRawData)
// now send bytesFormatted (e.g. write it to the socket stream)
(In other words, browser → server)
The frames you obtain are in the following format:
The first byte usually does not matter - if you're just sending text you are only using the text type. It will be 1000 0001
(or 129
) in that case.
The second byte and the additional two or eight bytes need some parsing, because you need to know how many bytes are used for the length (you need to know where the real data starts). The length itself is usually not necessary since you have the data already.
The first bit of the second byte is always 1
which means the data is masked (= encoded). Messages from the client to the server are always masked. You need to remove that first bit by doing secondByte AND 0111 1111
. There are two cases in which the resulting byte does not represent the length because it did not fit in the second byte:
0111 1110
, or 126
, means the following two bytes are used for the length0111 1111
, or 127
, means the following eight bytes are used for the lengthThe four mask bytes are used for decoding the actual data that has been sent. The algorithm for decoding is as follows:
decodedByte = encodedByte XOR masks[encodedByteIndex MOD 4]
where encodedByte
is the original byte in the data, encodedByteIndex
is the index (offset) of the byte counting from the first byte of the real data, which has index 0
. masks
is an array containing of the four mask bytes.
This leads to the following pseudocode for decoding:
secondByte = bytes[1]
length = secondByte AND 127 // may not be the actual length in the two special cases
indexFirstMask = 2 // if not a special case
if length == 126 // if a special case, change indexFirstMask
indexFirstMask = 4
else if length == 127 // ditto
indexFirstMask = 10
masks = bytes.slice(indexFirstMask, 4) // four bytes starting from indexFirstMask
indexFirstDataByte = indexFirstMask + 4 // four bytes further
decoded = new array
decoded.length = bytes.length - indexFirstDataByte // length of real data
for i = indexFirstDataByte, j = 0; i < bytes.length; i++, j++
decoded[j] = bytes[i] XOR masks[j MOD 4]
// now use "decoded" to interpret the received data
You can use the following script if you don't wish to use Wizard;
RESTORE DATABASE myDB
FROM DISK = N'C:\BackupDB.bak'
WITH REPLACE,RECOVERY,
MOVE N'HRNET' TO N'C:\MSSQL\Data\myDB.mdf',
MOVE N'HRNET_LOG' TO N'C:\MSSQL\Data\myDB.ldf'
VirtualBox is a virtualizer, not an emulator. (The name kinda gives it away.) I.e. it can only virtualize a CPU that is actually there, not emulate one that isn't. In particular, VirtualBox can only virtualize x86 and AMD64 CPUs. iOS only runs on ARM CPUs.
You can also face this situation if your upstream server uses a domain name, and its IP address changes (e.g.: your upstream points to an AWS Elastic Load Balancer)
The problem is that nginx will resolve the IP address once, and keep it cached for subsequent requests until the configuration is reloaded.
You can tell nginx to use a name server to re-resolve the domain once the cached entry expires:
location /mylocation {
# use google dns to resolve host after IP cached expires
resolver 8.8.8.8;
set $upstream_endpoint http://your.backend.server/;
proxy_pass $upstream_endpoint;
}
The docs on proxy_pass explain why this trick works:
Parameter value can contain variables. In this case, if an address is specified as a domain name, the name is searched among the described server groups, and, if not found, is determined using a resolver.
Kudos to "Nginx with dynamic upstreams" (tenzer.dk) for the detailed explanation, which also contains some relevant information on a caveat of this approach regarding forwarded URIs.
Is this what you are looking for ?
Sub getRowCol()
Range("A1").Select ' example
Dim col, row
col = Split(Selection.Address, "$")(1)
row = Split(Selection.Address, "$")(2)
MsgBox "Column is : " & col
MsgBox "Row is : " & row
End Sub
try this for a basic function, no libraries required
Date.prototype.CustomformatDate = function() {
var tmp = new Date(this.valueOf());
var mm = tmp.getMonth() + 1;
if (mm < 10) mm = "0" + mm;
var dd = tmp.getDate();
if (dd < 10) dd = "0" + dd;
return mm + "/" + dd + "/" + tmp.getFullYear();
};
This is what I am using,
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr="+latitude_cur+","+longitude_cur+"&daddr="+latitude+","+longitude));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_LAUNCHER );
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
To get it to work with Apache, we needed one extra step.
openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes -out domain_encrypted.key
openssl rsa -in domain_encrypted.key -out domain.key
The final command decrypts the key for use with Apache. The domain.key file should look like this:
-----BEGIN RSA PRIVATE KEY-----
MjQxODIwNTFaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3d3d3
LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxp
YWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEG
A1UEAxMqRW50cnVzdC5uZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgp
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArU1LqRKGsuqjIAcVFmQq
-----END RSA PRIVATE KEY-----
SELECT set_config('log_statement', 'all', true);
With a corresponding user right may use the query above after connect. This will affect logging until session ends.
If you have fresh installation / update of Xcode, it is possible that your git binary can't be executed (I had mine under /usr/bin/git
). To fix this problem just run the Xcode and "Accept" license conditions and try again, it should work.
I had the same problem in my rails project:
Incorrect string value: '\xF0\xA9\xB8\xBDs ...' for column 'subject' at row1
Solution 1: before saving to db convert string to base64 by Base64.encode64(subject)
and after fetching from db use Base64.decode64(subject)
Solution 2:
Step 1: Change the character set (and collation) for subject column by
ALTER TABLE t1 MODIFY
subject VARCHAR(255)
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
Step 2: In database.yml use
encoding :utf8mb4
You guys are going to laugh at this. I had an extra Listen 443 in ports.conf that shouldn't have been there. Removing that solved this.
# How To Add Google Apps and ARM Support to Genymotion v2.0+ #
Note(Feb 2nd): Contrary to previous reports, it's been discovered that Android 4.4 does in fact work with ARM translation, although it is buggy. Follow the steps the same as before, just make sure you download the 4.4 GApps.
UPDATE-v1.1: I've gotten more up-to-date builds of libhoudini and have updated the ZIP file. This fixes a lot of app crashes and hangs. Just flash the new one, and it should work.
This guide is for getting back both ARM translation/support (this is what causes the "INSTALL_FAILED_CPU_ABI_INCOMPATIBLE" errors) and Google Play apps in your Genymotion VM.
adb reboot
) or an app like ROM Toolbox. If nescessary you can simply close the VM window, but I don't recommend it.I've tested this on Genymotion v2.0.1-v2.1 using Android 4.3 and 4.4 images. Feel free to skip the GApps steps if you only want the ARM support. It'll work perfectly fine by itself.
Old Zips: v1.0. Don't download these as they will not solve your issues. It is left for archival and experimental purposes.
To make it simple, let us say that we can use constructor based dependency injection for mandatory dependencies and setter based injection for optional dependencies. It is a rule of thumb!!
Let's say for example.
If you want to instantiate a class you always do it with its constructor. So if you are using constructor based injection, the only way to instantiate the class is through that constructor. If you pass the dependency through constructor it becomes evident that it is a mandatory dependency.
On the other hand, if you have a setter method in a POJO class, you may or may not set value for your class variable using that setter method. It is completely based on your need. i.e. it is optional. So if you pass the dependency through setter method of a class it implicitly means that it is an optional dependency. Hope this is clear!!