We can get the details and status of session from below query as:
select ' Sid, Serial#, Aud sid : '|| s.sid||' , '||s.serial#||' , '||
s.audsid||chr(10)|| ' DB User / OS User : '||s.username||
' / '||s.osuser||chr(10)|| ' Machine - Terminal : '||
s.machine||' - '|| s.terminal||chr(10)||
' OS Process Ids : '||
s.process||' (Client) '||p.spid||' (Server)'|| chr(10)||
' Client Program Name : '||s.program "Session Info"
from v$process p,v$session s
where p.addr = s.paddr
and s.sid = nvl('&SID',s.sid)
and nvl(s.terminal,' ') = nvl('&Terminal',nvl(s.terminal,' '))
and s.process = nvl('&Process',s.process)
and p.spid = nvl('&spid',p.spid)
and s.username = nvl('&username',s.username)
and nvl(s.osuser,' ') = nvl('&OSUser',nvl(s.osuser,' '))
and nvl(s.machine,' ') = nvl('&machine',nvl(s.machine,' '))
and nvl('&SID',nvl('&TERMINAL',nvl('&PROCESS',nvl('&SPID',nvl('&USERNAME',
nvl('&OSUSER',nvl('&MACHINE','NO VALUES'))))))) <> 'NO VALUES'
/
For more details: https://ora-data.blogspot.in/2016/11/query-session-details.html
Thanks,
Dim a As String = Microsoft.VisualBasic.right("I will be going to school in 2011!", 5)
MsgBox("the value is:" & a)
If using a Mac
pbpaste|sort -u|wc -l
Linux users replace pbpaste
with xclip xsel or similar
Windows users, it's possible but would take some scripting... start with http://brianreiter.org/2010/09/03/copy-and-paste-with-clipboard-from-powershell/
Another option is to use one of my personal favorite CSS tools: box-shadow
.
A box shadow is really a drop-shadow on the node. It looks like this:
-moz-box-shadow: 1px 2px 3px rgba(0,0,0,.5);
-webkit-box-shadow: 1px 2px 3px rgba(0,0,0,.5);
box-shadow: 1px 2px 3px rgba(0,0,0,.5);
The arguments are:
1px: Horizontal offset of the effect. Positive numbers shift it right, negative left.
2px: Vertical offset of the effect. Positive numbers shift it down, negative up.
3px: The blur effect. 0 means no blur.
color: The color of the shadow.
So, you could leave your current design, and add a box-shadow like:
box-shadow: 0px -2px 2px rgba(34,34,34,0.6);
This should give you a 'blurry' top-edge.
This website will help with more information: http://css-tricks.com/snippets/css/css-box-shadow/
Since Java 11 has removed JavaEE you'll need to download some jars and add to the classpath:
JAXB: https://javaee.github.io/jaxb-v2/
JAF: https://www.oracle.com/technetwork/articles/java/index-135046.html
Then edit sdkmanager.bat so that set CLASSPATH=... ends with ;%CLASSPATH%
Set CLASSPATH to include JAXB and JAF:
set CLASSPATH=jaxb-core.jar;jaxb-impl.jar;jaxb-api.jar;activation.jar
Then sdkmanager.bat will work.
On Unix you can use valgrind
to find issues. It's free and powerful. If you'd rather do it yourself you can overload the new
and delete
operators to set up a configuration where you have 1 byte with 0xDEADBEEF
before and after each new object. Then track what happens at each iteration. This can fail to catch everything (you aren't guaranteed to even touch those bytes) but it has worked for me in the past on a Windows platform.
Nginx prefers prefix-based location matches (not involving regular expression), that's why in your code block, /stash redirects are going to /.
The algorithm used by Nginx to select which location to use is described thoroughly here: https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#matching-location-blocks
As an aside, if you have the pid of the container and want to get the docker id of that container, a good way is to use nsenter in combination with the sed magic above:
nsenter -n -m -t pid -- cat /proc/1/cgroup | grep -o -e "docker-.*.scope" | head -n 1 | sed "s/docker-\(.*\).scope/\\1/"
Note that cp A B; rm A
is exactly mv A B
. It'll be faster too, as you don't have to actually copy the bytes (assuming the destination is on the same filesystem), just rename the file. So you want cp A B; mv A C
I was working oh Chrome and had some problems, even though I use html attributes. I ended up with this js code
$("#element").on("input", function(){
var value = $(this).val();
$(this).val("");
$(this).val(parseInt(value));
return true;
});
To make it simpler to follow, I will summarize the above answers:
Let`s say the table is called Customer it has 4 columns/less or more...
you want to add a new column to the table where every time when there is insert... then that column keeps a record of the time the event happened.
Solution:
add a new column, let`s say timepurchase is the new column, to the table with data type datetime.
Then run the following alter:
ALTER TABLE Customer ADD CONSTRAINT DF_Customer DEFAULT GETDATE() FOR timePurchase
As an extension to @VinaySajip answer. There are additional nargs
worth mentioning.
parser.add_argument('dir', nargs=1, default=os.getcwd())
N (an integer). N arguments from the command line will be gathered together into a list
parser.add_argument('dir', nargs='*', default=os.getcwd())
'*'. All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with nargs='*'
, but multiple optional arguments with nargs='*'
is possible.
parser.add_argument('dir', nargs='+', default=os.getcwd())
'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.
parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())
argparse.REMAINDER
. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities
If the nargs
keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.
Edit (copied from a comment by @Acumenus) nargs='?'
The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.
If you use underscore.js then these type of null and undefined check are hidden by the library.
So your code will look like this -
var currentData = new Array();
if (_.isEmpty(currentData)) return false;
Ti.API.info("is exists " + currentData[index]);
return true;
It looks much more readable now.
You could also declaratively define a bean of type ServiceLocatorFactoryBean that will act as a Factory class. it supported by Spring 3.
A FactoryBean implementation that takes an interface which must have one or more methods with the signatures (typically, MyService getService() or MyService getService(String id)) and creates a dynamic proxy which implements that interface
Here's an example of implementing the Factory pattern using Spring
I faced the same 415
http error when sending objects, serialized into JSON, via PUT/PUSH requests to my JAX-rs services, in other words my server was not able to de-serialize the objects from JSON.
In my case, the server was able to serialize successfully the same objects in JSON when sending them into its responses.
As mentioned in the other responses I have correctly set the Accept
and Content-Type
headers to application/json
, but it doesn't suffice.
Solution
I simply forgot a default constructor with no parameters for my DTO objects. Yes this is the same reasoning behind @Entity objects, you need a constructor with no parameters for the ORM to instantiate objects and populate the fields later.
Adding the constructor with no parameters to my DTO objects solved my issue. Here follows an example that resembles my code:
Wrong
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
public NumberDTO(Number number) {
this.number = number;
}
private Number number;
public Number getNumber() {
return number;
}
public void setNumber(Number string) {
this.number = string;
}
}
Right
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
public NumberDTO() {
}
public NumberDTO(Number number) {
this.number = number;
}
private Number number;
public Number getNumber() {
return number;
}
public void setNumber(Number string) {
this.number = string;
}
}
I lost hours, I hope this'll save yours ;-)
I just got this error and it was caused by a duplicate static content MIME type in the web.config
This error was being returned only on static files - eg images, css, js files were all saying this error (text by itself, no other html or text in the response).
The way to debug this is to look in web config under static content. Here we have a json file extension loaded. This was required on IIS7 but will kill the app if used on IIS8 because json is now pre-loaded at the server level.
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
So solution is to remove any of these mimeType entries one at a time to confirm which are needed and which kill your app!
Update
Actually the best solution was provided by a commenter here. You can remove and then add, which will always work regardless of whether it is already defined or not. Like this:
<remove fileExtension=".json" />
<mimeMap fileExtension=".json" mimeType="application/json" />
DECLARE @CodeNameString varchar(max)
SET @CodeNameString=''
SELECT @CodeNameString=@CodeNameString+CodeName FROM AccountCodes ORDER BY Sort
SELECT @CodeNameString
Bear in mind, I've only experimented with MongoDB...
From what I've read, DynamoDB has come a long way in terms of features. It used to be a super-basic key-value store with extremely limited storage and querying capabilities. It has since grown, now supporting bigger document sizes + JSON support and global secondary indices. The gap between what DynamoDB and MongoDB offers in terms of features grows smaller with every month. The new features of DynamoDB are expanded on here.
Much of the MongoDB vs. DynamoDB comparisons are out of date due to the recent addition of DynamoDB features. However, this post offers some other convincing points to choose DynamoDB, namely that it's simple, low maintenance, and often low cost. Another discussion here of database choices was interesting to read, though slightly old.
My takeaway: if you're doing serious database queries or working in languages not supported by DynamoDB, use MongoDB. Otherwise, stick with DynamoDB.
You have to decompose the full object to reach the entry
array.
Assuming REPONSE_JSON_OBJECT
is already a parsed JSONObject
.
REPONSE_JSON_OBJECT.getJSONObject("result")
.getJSONObject("map")
.getJSONArray("entry");
I solved it by myself.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.7.Final</version>
</dependency>
Microsoft says the SQL Server 2005 it's not compatible with Windows 8, but I've run it without problems (only using SP3) except the installation.
After you run the install file SQLExpr.exe
look for a hidden folder recently created in the C drive. Copy the contents to another folder and cancel the installer (or use WinRar to open the file and extract the contents to a temp folder)
After that, find the file sqlncli_x64.msi
in the setup folder, and run it.
Now you are ready the run the setup.exe
file and install SQL server 2005 without errors
In my case the problem was 32-bit Putty and pageant.exe - it can't communicate with 64-bit TortoisePlink.exe. Replacing 32-bit Putty with a 64-bit version solved the problem.
Is it too late to go back and get the un-uppercased data?
The von Neumann's, McCain's, DeGuzman's, and the Johnson-Smith's of your client base may not like the result of your processing...
Also, I'm guessing that this is intended to be a one-time upgrade of the data? It might be easier to export, filter/modify, and re-import the corrected names into the db, and then you can use non-SQL approaches to name fixing...
This query will give you the exact output for current running jobs. This will also shows the duration of running job in minutes.
WITH
CTE_Sysession (AgentStartDate)
AS
(
SELECT MAX(AGENT_START_DATE) AS AgentStartDate FROM MSDB.DBO.SYSSESSIONS
)
SELECT sjob.name AS JobName
,CASE
WHEN SJOB.enabled = 1 THEN 'Enabled'
WHEN sjob.enabled = 0 THEN 'Disabled'
END AS JobEnabled
,sjob.description AS JobDescription
,CASE
WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL THEN 'Running'
WHEN ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NOT NULL AND HIST.run_status = 1 THEN 'Stopped'
WHEN HIST.run_status = 0 THEN 'Failed'
WHEN HIST.run_status = 3 THEN 'Canceled'
END AS JobActivity
,DATEDIFF(MINUTE,act.start_execution_date, GETDATE()) DurationMin
,hist.run_date AS JobRunDate
,run_DURATION/10000 AS Hours
,(run_DURATION%10000)/100 AS Minutes
,(run_DURATION%10000)%100 AS Seconds
,hist.run_time AS JobRunTime
,hist.run_duration AS JobRunDuration
,'tulsql11\dba' AS JobServer
,act.start_execution_date AS JobStartDate
,act.last_executed_step_id AS JobLastExecutedStep
,act.last_executed_step_date AS JobExecutedStepDate
,act.stop_execution_date AS JobStopDate
,act.next_scheduled_run_date AS JobNextRunDate
,sjob.date_created AS JobCreated
,sjob.date_modified AS JobModified
FROM MSDB.DBO.syssessions AS SYS1
INNER JOIN CTE_Sysession AS SYS2 ON SYS2.AgentStartDate = SYS1.agent_start_date
JOIN msdb.dbo.sysjobactivity act ON act.session_id = SYS1.session_id
JOIN msdb.dbo.sysjobs sjob ON sjob.job_id = act.job_id
LEFT JOIN msdb.dbo.sysjobhistory hist ON hist.job_id = act.job_id AND hist.instance_id = act.job_history_id
WHERE ACT.start_execution_date IS NOT NULL AND ACT.stop_execution_date IS NULL
ORDER BY ACT.start_execution_date DESC
I was running PHPUnit tests on PHP5, and then, I needed to support PHP7 as well. This is what I did:
In composer.json:
"phpunit/phpunit": "~4.8|~5.7"
In my PHPUnit bootstrap file (in my case, /tests/bootstrap.php
):
// PHPUnit 6 introduced a breaking change that
// removed PHPUnit_Framework_TestCase as a base class,
// and replaced it with \PHPUnit\Framework\TestCase
if (!class_exists('\PHPUnit_Framework_TestCase') && class_exists('\PHPUnit\Framework\TestCase'))
class_alias('\PHPUnit\Framework\TestCase', '\PHPUnit_Framework_TestCase');
In other words, this will work for tests written originally for PHPUnit 4 or 5, but then needed to work on PHPUnit 6 as well.
Here an approach to have count distinct over multiple columns. Let's have some data:
data = {'CLIENT_CODE':[1,1,2,1,2,2,3],
'YEAR_MONTH':[201301,201301,201301,201302,201302,201302,201302],
'PRODUCT_CODE': [100,150,220,400,50,80,100]
}
table = pd.DataFrame(data)
table
CLIENT_CODE YEAR_MONTH PRODUCT_CODE
0 1 201301 100
1 1 201301 150
2 2 201301 220
3 1 201302 400
4 2 201302 50
5 2 201302 80
6 3 201302 100
Now, list the columns of interest and use groupby in a slightly modified syntax:
columns = ['YEAR_MONTH', 'PRODUCT_CODE']
table[columns].groupby(table['CLIENT_CODE']).nunique()
We obtain:
YEAR_MONTH PRODUCT_CODE CLIENT_CODE
1 2 3
2 2 3
3 1 1
One way to do that is to use a counter:
ArrayList<Integer> list = new ArrayList<Integer>();
...
int size = list.size();
for (Integer i : list) {
...
if (--size == 0) {
// Last item.
...
}
}
Edit
Anyway, as Tom Hawtin said, it is sometimes better to use the "old" syntax when you need to get the current index information, by using a for
loop or the iterator
, as everything you win when using the Java5 syntax will be lost in the loop itself...
for (int i = 0; i < list.size(); i++) {
...
if (i == (list.size() - 1)) {
// Last item...
}
}
or
for (Iterator it = list.iterator(); it.hasNext(); ) {
...
if (!it.hasNext()) {
// Last item...
}
}
Can someone help me with the exact syntax?
It's a three-step process, and it involves modifying the openssl.cnf
file. You might be able to do it with only command line options, but I don't do it that way.
Find your openssl.cnf
file. It is likely located in /usr/lib/ssl/openssl.cnf
:
$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf
On my Debian system, /usr/lib/ssl/openssl.cnf
is used by the built-in openssl
program. On recent Debian systems it is located at /etc/ssl/openssl.cnf
You can determine which openssl.cnf
is being used by adding a spurious XXX
to the file and see if openssl
chokes.
First, modify the req
parameters. Add an alternate_names
section to openssl.cnf
with the names you want to use. There are no existing alternate_names
sections, so it does not matter where you add it.
[ alternate_names ]
DNS.1 = example.com
DNS.2 = www.example.com
DNS.3 = mail.example.com
DNS.4 = ftp.example.com
Next, add the following to the existing [ v3_ca ]
section. Search for the exact string [ v3_ca ]
:
subjectAltName = @alternate_names
You might change keyUsage
to the following under [ v3_ca ]
:
keyUsage = digitalSignature, keyEncipherment
digitalSignature
and keyEncipherment
are standard fare for a server certificate. Don't worry about nonRepudiation
. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.
In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.
Second, modify the signing parameters. Find this line under the CA_default
section:
# Extension copying option: use with caution.
# copy_extensions = copy
And change it to:
# Extension copying option: use with caution.
copy_extensions = copy
This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.
Third, generate your self-signed certificate:
$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...
Finally, examine the certificate:
$ openssl x509 -in certificate.pem -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 9647297427330319047 (0x85e215e5869042c7)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Validity
Not Before: Feb 1 05:23:05 2014 GMT
Not After : Feb 1 05:23:05 2016 GMT
Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (3072 bit)
Modulus:
00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
...
d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
72:1c:45:92:2c:88:a9:be:0b:f9
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Authority Key Identifier:
keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Key Usage:
Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
X509v3 Subject Alternative Name:
DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
Signature Algorithm: sha256WithRSAEncryption
3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
...
71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
8b:0a:bd:65:03:d1
I would suggest not to use JavaScript for this kind of simple interaction. CSS is capable of doing it (even in Internet Explorer 6) and it will be much more responsive than doing it with JavaScript.
You can use the ":hover" CSS pseudo-class but in order to make it work with Internet Explorer 6, you must use it on an "a" element.
.menuItem
{
display: inline;
background-color: #000;
/* width and height should not work on inline elements */
/* if this works, your browser is doing the rendering */
/* in quirks mode which will not be compatible with */
/* other browsers - but this will not work on touch mobile devices like android */
}
.menuItem a:hover
{
background-color:#F00;
}
Set DateTimePicker's Format property to custom and CustomFormat
prperty to M/dd/yyyy
.
I always use pseudo elements :before
and :after
for changing the appearance of checkboxes and radio buttons. it's works like a charm.
Refer this link for more info
Steps
visibility:hidden
or opacity:0
or position:absolute;left:-9999px
etc.:before
element and pass either an empty or a non-breaking space '\00a0'
;:checked
state, pass the unicode content: "\2713"
, which is a checkmark;:focus
style to make the checkbox accessible.Here is how I did it.
.box {_x000D_
background: #666666;_x000D_
color: #ffffff;_x000D_
width: 250px;_x000D_
padding: 10px;_x000D_
margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
margin: 1.5em 0;_x000D_
padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
visibility: hidden;_x000D_
}_x000D_
label {_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
border: 1px solid #333;_x000D_
content: "\00a0";_x000D_
display: inline-block;_x000D_
font: 16px/1em sans-serif;_x000D_
height: 16px;_x000D_
margin: 0 .25em 0 0;_x000D_
padding: 0;_x000D_
vertical-align: top;_x000D_
width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
background: #fff;_x000D_
color: #333;_x000D_
content: "\2713";_x000D_
text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
<div class="box">_x000D_
<p>_x000D_
<input type="checkbox" id="c1" name="cb">_x000D_
<label for="c1">Option 01</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c2" name="cb">_x000D_
<label for="c2">Option 02</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c3" name="cb">_x000D_
<label for="c3">Option 03</label>_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
Much more stylish using :before
and :after
body{_x000D_
font-family: sans-serif; _x000D_
}_x000D_
_x000D_
.container {_x000D_
margin-top: 50px;_x000D_
margin-left: 20px;_x000D_
margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
width: 100%;_x000D_
margin: 15px auto;_x000D_
position: relative;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
width: auto;_x000D_
opacity: 0.00000001;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
content: '';_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
margin: 4px;_x000D_
width: 22px;_x000D_
height: 22px;_x000D_
transition: transform 0.28s ease;_x000D_
border-radius: 3px;_x000D_
border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
content: '';_x000D_
display: block;_x000D_
width: 10px;_x000D_
height: 5px;_x000D_
border-bottom: 2px solid #7bbe72;_x000D_
border-left: 2px solid #7bbe72;_x000D_
-webkit-transform: rotate(-45deg) scale(0);_x000D_
transform: rotate(-45deg) scale(0);_x000D_
transition: transform ease 0.25s;_x000D_
will-change: transform;_x000D_
position: absolute;_x000D_
top: 12px;_x000D_
left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
-webkit-transform: rotate(-45deg) scale(1);_x000D_
transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
min-height: 34px;_x000D_
display: block;_x000D_
padding-left: 40px;_x000D_
margin-bottom: 0;_x000D_
font-weight: normal;_x000D_
cursor: pointer;_x000D_
vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
-webkit-transform: translateY(-50%);_x000D_
transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox" name="" value="">_x000D_
<label for="checkbox"><span>Checkbox</span></label>_x000D_
</div>_x000D_
_x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox2" name="" value="">_x000D_
<label for="checkbox2"><span>Checkbox</span></label>_x000D_
</div>_x000D_
</div>
_x000D_
As defined in App_start.BundleConfig, it's just calling
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
Nothing happens even if you remove that section.
I have another suggestion. When you want myDiv to have a height of 100%, use these extra 3 attributes on your div:
myDiv {
min-height: 100%;
overflow-y: hidden;
position: relative;
}
That should do the job!
Use geom_text
, with aes
label. You can play with hjust, vjust
to adjust text position.
ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
geom_point() +geom_text(aes(label=Name),hjust=0, vjust=0)
ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
geom_point() +
geom_text(aes(label=ifelse(PTS>24,as.character(Name),'')),hjust=0,vjust=0)
mingw32 exists as a package for Linux. You can cross-compile and -link Windows applications with it. There's a tutorial here at the Code::Blocks forum. Mind that the command changes to x86_64-w64-mingw32-gcc-win32
, for example.
Ubuntu, for example, has MinGW in its repositories:
$ apt-cache search mingw
[...]
g++-mingw-w64 - GNU C++ compiler for MinGW-w64
gcc-mingw-w64 - GNU C compiler for MinGW-w64
mingw-w64 - Development environment targeting 32- and 64-bit Windows
[...]
you can create an array that filled with your object fields and use an index on the array and access object properties via that
propertiesName:['pr1','pr2','pr3']
this.myObject[this.propertiesName[0]]
Line numbers are OK if you can guarantee the position of what you want. Over the years, my favorite flavor of this has been something like this:
sed "/First Line of Text/,/Last Line of Text/d" filename
which deletes all lines from the first matched line to the last match, including those lines.
Use sed -n with "p" instead of "d" to print those lines instead. Way more useful for me, as I usually don't know where those lines are.
The setting below has worked for me
Express 4.16.1
app.use(bodyParser.json({ limit: '50mb' }))
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: false,
}))
Nginx
client_max_body_size 50m
client_body_temp_path /data/temp
I had already used and styled a navbar when I was requested to change it to a hover interaction instead, so ended up with this as a fix using jQuery.
function bootstrapHoverMenu (bp = 768) {
// close all dropdowns that are open
$('body').click( function (e) {
$('.dropdown-menu.show').removeClass('show');
});
// show dropdown for the link clicked
$('.nav-item').hover(function (e) {
$('.dropdown-menu.show').removeClass('show');
if(( $(window).width() >= bp )) {
$dd = $(this).find('.dropdown-menu');
$dd.addClass('show');
}
});
// get href for top level link if clicked and open
$('.dropdown').click(function (e) {
if( $(window).width() < bp ) {
$('.dropdown-menu').css({'display': 'none'});
}
$href = $(this).find('.nav-link').attr('href');
window.open($href, '_self');
});
}
$(document).ready( function() {
// when page ready run the fix
bootstrapHoverMenu();
});
Downside is mobile only has top level links.
You could prepare the query for inserting one row using the mysqli_stmt class, and then iterate over the array of data. Something like:
$stmt = $db->stmt_init();
$stmt->prepare("INSERT INTO mytbl (fld1, fld2, fld3, fld4) VALUES(?, ?, ?, ?)");
foreach($myarray as $row)
{
$stmt->bind_param('idsb', $row['fld1'], $row['fld2'], $row['fld3'], $row['fld4']);
$stmt->execute();
}
$stmt->close();
Where 'idsb' are the types of the data you're binding (int, double, string, blob).
The better pattern is to create a standalone BroadcastReceiver
. This insures that your app can respond to the broadcast, whether or not the Service
is running. In fact, using this pattern may remove the need for a constant-running Service
altogether.
Register the BroadcastReceiver
in your Manifest, and create a separate class/file for it.
Eg:
<receiver android:name=".FooReceiver" >
<intent-filter >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
When the receiver runs, you simply pass an Intent
(Bundle
) to the Service
, and respond to it in onStartCommand()
.
Eg:
public class FooReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// do your work quickly!
// then call context.startService();
}
}
This is being made way more complicated than it actually is.
The algorithm is as follows:
Let B = depth of the lowest-level node
If abs(A-B) <= 1, then the tree is balanced
Thanks to @Pax Diablo, @bvmou and @Arachnid for the suggestion of using full datetimes throughout. If I have to accept datetime.time objects from an external source, then this seems to be an alternative add_secs_to_time()
function:
def add_secs_to_time(timeval, secs_to_add):
dummy_date = datetime.date(1, 1, 1)
full_datetime = datetime.datetime.combine(dummy_date, timeval)
added_datetime = full_datetime + datetime.timedelta(seconds=secs_to_add)
return added_datetime.time()
This verbose code can be compressed to this one-liner:
(datetime.datetime.combine(datetime.date(1, 1, 1), timeval) + datetime.timedelta(seconds=secs_to_add)).time()
but I think I'd want to wrap that up in a function for code clarity anyway.
I just want to add to the already accepted answer. I was stuck on this, but I was going a different route on handling the complete event. Rather than running await, I add a completed handler to the task.
Comments.AsAsyncAction().Completed += new AsyncActionCompletedHandler(CommentLoadComplete);
Where the event handler looks like this
private void CommentLoadComplete(IAsyncAction sender, AsyncStatus status )
{
if (status == AsyncStatus.Canceled)
{
return;
}
CommentsItemsControl.ItemsSource = Comments.Result;
CommentScrollViewer.ScrollToVerticalOffset(0);
CommentScrollViewer.Visibility = Visibility.Visible;
CommentProgressRing.Visibility = Visibility.Collapsed;
}
With this route, all the handling is already done for you, when the task is cancelled it just triggers the event handler and you can see if it was cancelled there.
In a modern language with the check if script has already been loaded, it would be:
function loadJs( url ){
return new Promise(( resolve, reject ) => {
if (document.querySelector( `head > script[ src = "${url}" ]`) !== null ){
console.warn( `script already loaded: ${url}` );
resolve();
}
const script = document.createElement( "script" );
script.src = url;
script.onload = resolve;
script.onerror = function( reason ){
// This can be useful for your error-handling code
reason.message = `error trying to load script ${url}`;
reject( reason );
};
document.head.appendChild( script );
});
}
Usage (async/await):
try { await loadJs("https://.../script.js"); }
catch(error) { console.log(error); }
or
await loadJs( "https://.../script.js" ).catch( err => {} );
Usage (Promise):
loadJs( "https://.../script.js" ).then( res => {} ).catch( err => {} );
set WRAP OFF
set PAGESIZE 0
Try using those settings.
Well, since liquibase is open source there's always the source code which you could check.
Some of the data type classes seem to have a method toDatabaseDataType()
which should give you information about what type works (is used) on a specific data base.
Check out this infographic: http://www.paintcodeapp.com/news/iphone-6-screens-demystified
It explains the differences between old iPhones, iPhone 6 and iPhone 6 Plus. You can see comparison of screen sizes in points, rendered pixels and physical pixels. You will also find answer to your question there:
iPhone 6 Plus - with Retina display HD. Scaling factor is 3 and the image is afterwards downscaled from rendered 2208 × 1242 pixels to 1920 × 1080 pixels.
The downscaling ratio is 1920 / 2208 = 1080 / 1242 = 20 / 23. That means every 23 pixels from the original render have to be mapped to 20 physical pixels. In other words the image is scaled down to approximately 87% of its original size.
Update:
There is an updated version of infographic mentioned above. It contains more detailed info about screen resolution differences and it covers all iPhone models so far, including 4 inch devices.
http://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
I think they updated the html5 video and deprecated some codecs. It worked for me after removing the codecs.
In the below example:
<video>_x000D_
<source src="sample-clip.mp4" type="video/mp4; codecs='avc1.42E01E, mp4a.40.2'">_x000D_
<source src="sample-clip.webm" type="video/webm; codecs='vp8, vorbis'"> _x000D_
</video>_x000D_
_x000D_
must be changed to_x000D_
_x000D_
<video>_x000D_
<source src="sample-clip.mp4" type="video/mp4">_x000D_
<source src="sample-clip.webm" type="video/webm">_x000D_
</video>
_x000D_
PowerShell's Select-String cmdlet was fine in v1.0, but is significantly better for v2.0. Having PowerShell built in to recent versions of Windows means your skills here will always useful, without first installing something.
New parameters added to Select-String: Select-String cmdlet now supports new parameters, such as:
- -Context: This allows you to see lines before and after the match line
- -AllMatches: which allows you to see all matches in a line (Previously, you could see only the first match in a line)
- -NotMatch: Equivalent to grep -v o
- -Encoding: to specify the character encoding
I find it expedient to create an function gcir
for Get-ChildItem -Recurse .
, with smarts to pass parameters correctly, and an alias ss
for Select-String
. So you an write:
gcir *.txt | ss foo
This is your code
$q = $this -> db
-> select('id')
-> where('email', $email)
-> limit(1)
-> get('users');
Try this
$id = $q->result()[0]->id;
or this one, it's simpler
$id = $q->row()->id;
I had the same problem. It turns out that, compiling a project I got from someone else, I haven't set the correct StartUp project (right click on the desired startup project in the solution explorer and pick "set as StartUp Project"). Maybe this will help, cheers.
I think the second one should be
var itemList = (from t in ctn.Items
where !t.Items && t.DeliverySelection
select t).OrderByDescending(c => c.Delivery.SubmissionDate);
If you cannot see the "ng serve" command running, then you can do the following on Mac OSX (This should work on any Linux and Uni software as well).
ps -ef | grep "ng serve"
From this, find out the PID of the process and then kill it with the following command.
kill -9 <PID>
Mat img;
img=Mat::zeros(size of image,CV_8UC3);
if you want it to be of an image img1
img=Mat::zeros(img1.size,CV_8UC3);
ID method will not work on older browsers, anchor name method will be deprecated in newer HTML versions... I'd go with id.
Simple URL :
https://www.google.com/maps/dir/?api=1&destination=lat,lng
This url is specific for routing.
Reference : https://developers.google.com/maps/documentation/urls/guide#directions-action
Step 1: Go to json.org to find the JSON library for whatever technology you're using to call this web service. Download and link to that library.
Step 2: Let's say you're using Java. You would use JSONArray like this:
JSONArray myArray=new JSONArray(queryResponse);
for (int i=0;i<myArray.length;i++){
JSONArray myInteriorArray=myArray.getJSONArray(i);
if (i==0) {
//this is the first one and is special because it holds the name of the query.
}else{
//do your stuff
String stateCode=myInteriorArray.getString(0);
String stateName=myInteriorArray.getString(1);
}
}
There is no 'array' type in batch files, which is both an upside and a downside at times, but there are workarounds.
Here's a link that offers a few suggestions for creating a system for yourself similar to an array in a batch: http://hypftier.de/en/batch-tricks-arrays.
echo variable >> filepath
works for echoing the contents of a variable to a file,echo.
(the period is not a typo) works for echoing a newline character.I think that these two together should work to accomplish what you need.
You should just install python 3.6. I tried it and it worked. Just install that version of python and just do the normal download process (pip install pyaudio
).
If you have 32-bit Windows, this method is not working without following settings.
- Run prompt cmd.exe (important : Run As Administrator)
- type bcdedit.exe and run
- Look at the "increaseuserva" params and there is no then write following statement
- bcdedit /set increaseuserva 3072
- and again step 2 and check params
We added this settings and this block started.
if exist "$(DevEnvDir)..\tools\vsvars32.bat" (
call "$(DevEnvDir)..\tools\vsvars32.bat"
editbin /largeaddressaware "$(TargetPath)"
)
More info - command increaseuserva
: https://docs.microsoft.com/en-us/windows-hardware/drivers/devtest/bcdedit--set
Here's a tutorial about ordering objects:
Although I will give some examples, I would recommend to read it anyway.
There are various way to sort an ArrayList
. If you want to define a natural (default) ordering, then you need to let Contact
implement Comparable
. Assuming that you want to sort by default on name
, then do (nullchecks omitted for simplicity):
public class Contact implements Comparable<Contact> {
private String name;
private String phone;
private Address address;
@Override
public int compareTo(Contact other) {
return name.compareTo(other.name);
}
// Add/generate getters/setters and other boilerplate.
}
so that you can just do
List<Contact> contacts = new ArrayList<Contact>();
// Fill it.
Collections.sort(contacts);
If you want to define an external controllable ordering (which overrides the natural ordering), then you need to create a Comparator
:
List<Contact> contacts = new ArrayList<Contact>();
// Fill it.
// Now sort by address instead of name (default).
Collections.sort(contacts, new Comparator<Contact>() {
public int compare(Contact one, Contact other) {
return one.getAddress().compareTo(other.getAddress());
}
});
You can even define the Comparator
s in the Contact
itself so that you can reuse them instead of recreating them everytime:
public class Contact {
private String name;
private String phone;
private Address address;
// ...
public static Comparator<Contact> COMPARE_BY_PHONE = new Comparator<Contact>() {
public int compare(Contact one, Contact other) {
return one.phone.compareTo(other.phone);
}
};
public static Comparator<Contact> COMPARE_BY_ADDRESS = new Comparator<Contact>() {
public int compare(Contact one, Contact other) {
return one.address.compareTo(other.address);
}
};
}
which can be used as follows:
List<Contact> contacts = new ArrayList<Contact>();
// Fill it.
// Sort by address.
Collections.sort(contacts, Contact.COMPARE_BY_ADDRESS);
// Sort later by phone.
Collections.sort(contacts, Contact.COMPARE_BY_PHONE);
And to cream the top off, you could consider to use a generic javabean comparator:
public class BeanComparator implements Comparator<Object> {
private String getter;
public BeanComparator(String field) {
this.getter = "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
}
public int compare(Object o1, Object o2) {
try {
if (o1 != null && o2 != null) {
o1 = o1.getClass().getMethod(getter, new Class[0]).invoke(o1, new Object[0]);
o2 = o2.getClass().getMethod(getter, new Class[0]).invoke(o2, new Object[0]);
}
} catch (Exception e) {
// If this exception occurs, then it is usually a fault of the developer.
throw new RuntimeException("Cannot compare " + o1 + " with " + o2 + " on " + getter, e);
}
return (o1 == null) ? -1 : ((o2 == null) ? 1 : ((Comparable<Object>) o1).compareTo(o2));
}
}
which you can use as follows:
// Sort on "phone" field of the Contact bean.
Collections.sort(contacts, new BeanComparator("phone"));
(as you see in the code, possibly null fields are already covered to avoid NPE's during sort)
In okhttp v4.* I got it working that way
// import the extensions!
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
// ...
json : String = "..."
val JSON : MediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody: RequestBody = json.toRequestBody(JSON)
// go on with Request.Builder() etc
My fix for this issue was to separate the primary key with the foreign key. If you are using eclipse and made the above changes please remember to refresh the database explorer. Then recreate the entities from the tables.
For python3 use either with xxxx = name
of yourfile
.
exec(open('./xxxx.py').read())
So I'm a pretty critical person, and figure if I'm going to invest in a library, I'd better know what I'm getting myself into. I figure it's better to go heavy on the criticism and light on the flattery when scrutinizing; what's wrong with it has many more implications for the future than what's right. So I'm going to go overboard here a little bit to provide the kind of answer that would have helped me and I hope will help others who may journey down this path. Keep in mind that this is based on what little reviewing/testing I've done with these libs. Oh and I stole some of the positive description from Reed.
I'll mention up top that I went with GMTL despite it's idiosyncrasies because the Eigen2 unsafeness was too big of a downside. But I've recently learned that the next release of Eigen2 will contain defines that will shut off the alignment code, and make it safe. So I may switch over.
Update: I've switched to Eigen3. Despite it's idiosyncrasies, its scope and elegance are too hard to ignore, and the optimizations which make it unsafe can be turned off with a define.
Benefits: LGPL MPL2, Clean, well designed API, fairly easy to use. Seems to be well maintained with a vibrant community. Low memory overhead. High performance. Made for general linear algebra, but good geometric functionality available as well. All header lib, no linking required.
Idiocyncracies/downsides: (Some/all of these can be avoided by some defines that are available in the current development branch Eigen3)
Benefits: LGPL, Fairly Simple API, specifically designed for graphics engines. Includes many primitive types geared towards rendering (such as planes, AABB, quatenrions with multiple interpolation, etc) that aren't in any other packages. Very low memory overhead, quite fast, easy to use. All header based, no linking necessary.
Idiocyncracies/downsides:
vec1 - vec2
does not return a
normal vector so length( vecA - vecB )
fails even though vecC = vecA -
vecB
works. You must wrap like: length( Vec( vecA - vecB ) )
length( makeCross( vecA, vecB ) )
gmtl::length( gmtl::makeCross( vecA, vecB ) )
vecA.cross( vecB ).length()
Can't tell because they seem to be more interested in the fractal image header of their web page than the content. Looks more like an academic project than a serious software project.
Latest release over 2 years ago.
Apparently no documentation in English though supposedly there is something in French somewhere.
Cant find a trace of a community around the project.
Benefits: Old and mature.
Downsides:
Install Python3 on mac
1. brew install python3
2. curl https://bootstrap.pypa.io/get-pip.py | python3
3. python3
Use pip3
to install modules
1. pip3 install ipython
2. python3 -m IPython
:)
As an alternative, you can use the environment variables LIBRARY_PATH
and CPLUS_INCLUDE_PATH
, which respectively indicate where to look for libraries and where to look for headers (CPATH
will also do the job), without specifying the -L and -I options.
Edit:
CPATH
includes header with -I
and CPLUS_INCLUDE_PATH
with -isystem
.
According to http://msdn.microsoft.com/en-us/library/cc288472(VS.85).aspx#html, IE8 will have "strong" HTML 5 support. I haven't seen anything discussing exactly what "strong support" entails, but I can say that yes, some HTML5 stuff is going to make it into IE8.
The rouine is pretty good, however it causes my app to hang, so I needed to add the case:
<xsl:when test="$text = '' or $replace = ''or not($replace)" >
<xsl:value-of select="$text" />
<!-- Prevent thsi routine from hanging -->
</xsl:when>
before the function gets called recursively.
I got the answer from here: When test hanging in an infinite loop
Thank you!
Something like:
$(".head h3").html("Public offers");
---
- hosts: all
tasks:
- name: Gather Version
debug:
msg: "The server Operating system is {{ ansible_distribution }} {{ ansible_distribution_major_version }}"
- name: Write Version
local_action: shell echo "This is {{ ansible_distribution }} {{ ansible_distribution_major_version }}" >> /tmp/output
To add on to what Alisson said you could check to see if a row is returned.
// Query stuff ...
$query = $this->db->get();
if ($query->num_rows() > 0)
{
$row = $query->row();
return $row->campaign_id;
}
return null; // or whatever value you want to return for no rows found
The JVM needs contiguous memory and depending on what else is running, what was running before, and how windows has managed memory you may be able to get up to 1.4GB of contiguous memory. I think 64bit Windows will allow larger heaps.
There are several ways to do this:
You can use the InStr
build-in function to test if a String contains a substring. InStr
will either return the index of the first match, or 0. So you can test if a String begins with a substring by doing the following:
If InStr(1, "Hello World", "Hello W") = 1 Then
MsgBox "Yep, this string begins with Hello W!"
End If
If InStr
returns 1
, then the String ("Hello World"), begins with the substring ("Hello W").
You can also use the like
comparison operator along with some basic pattern matching:
If "Hello World" Like "Hello W*" Then
MsgBox "Yep, this string begins with Hello W!"
End If
In this, we use an asterisk (*) to test if the String begins with our substring.
You can use two ways to resolve this problem, first way that i think it as best way is replace importing segment of your code with bellow one:
import Home from './layouts/Home'
or export your component without default which is called named export like this
import React, { Component } from 'react';
class Home extends Component{
render(){
return(
<p className="App-intro">
Hello Man
</p>
)
}
}
export {Home};
Whilst I recommend hyphens, I shall also postulate an answer that isn't on your list:
Nothing At All
/quotationrequests/
, /purchaseorders/
and so on.?q=foo+bar
- name: find inq.Linux*
find: paths="/appl/scripts/inq" recurse=yes patterns="inq.Linux*"
register: find_files
- name: set fact
set_fact:
all_files:
- "{{ find_files.files | map(attribute='path') | list }}"
when: find_files > 0
- name: copy files
copy:
src: "{{ item }}"
dest: /destination/
with_items: "{{ all_files }}"
when: find_files > 0
Actually the only two strategies you would want to choose are ours if you want to abandon changes brought by branch, but keep the branch in history, and subtree if you are merging independent project into subdirectory of superproject (like 'git-gui' in 'git' repository).
octopus merge is used automatically when merging more than two branches. resolve is here mainly for historical reasons, and for when you are hit by recursive merge strategy corner cases.
df = df.replace({np.nan: None})
Credit goes to this guy here on this Github issue.
This works for me, with Mac OS Sierra using Python,
options = webdriver.ChromeOptions()
options.add_argument("--kiosk")
driver = webdriver.Chrome(chrome_options=options)
$(".element").select2(/*Your code*/)
.on('change', function (e) {
var getID = $(this).select2('data');
alert(getID[0]['id']); // That's the selected ID :)
});
I was getting that exact message whenever my requests took more than 2 minutes to finish. The browser would disconnect from the request, but the request on the backend continued until it was finished. The server (ASP.NET Web API in my case) wouldn't detect the disconnect.
After an entire day searching, I finally found this answer, explaining that if you use the proxy config, it has a default timeout of 120 seconds (or 2 minutes).
So, you can edit your proxy configuration and set it to whatever you need:
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"timeout": 6000000
}
}
Now, I was using agentkeepalive to make it work with NTLM authentication, and didn't know that the agent's timeout has nothing to do with the proxy's timeout, so both have to be set. It took me a while to realize that, so here's an example:
const Agent = require('agentkeepalive');
module.exports = {
'/api/': {
target: 'http://localhost:3000',
secure: false,
timeout: 6000000, // <-- this is needed as well
agent: new Agent({
maxSockets: 100,
keepAlive: true,
maxFreeSockets: 10,
keepAliveMsecs: 100000,
timeout: 6000000, // <-- this is for the agentkeepalive
freeSocketTimeout: 90000
}),
onProxyRes: proxyRes => {
let key = 'www-authenticate';
proxyRes.headers[key] = proxyRes.headers[key] &&
proxyRes.headers[key].split(',');
}
}
};
For info, if you are binding to a class, you can do this in your type via DisplayNameAttribute
:
[DisplayName("Access key")]
public string AccessKey { get {...} set {...} }
Now the header-text on auto-generated columns will be "Access key".
Motion is an alternative to Zoneminder. It has a steeper setup curve as everything is configured via config files.However, the config files are nicely commented and it's easier than it sounds. It's very reliable once running as well.
To add a Foscam camera (mentioned above) use the following syntax to stream the video from the camera.
netcam_url http://<IPADDRESS>/videostream.cgi?user=admin?pwd=
Where the user is admin with a blank password (the default for Foscam cameras).
For really high uptime/reliablity consider using a monitoring tool such as Monit. This works well with Motion.
Use %0A
(URL encoding) instead of \n
(C encoding).
From WebService returns XML even when ResponseFormat set to JSON:
Make sure that the request is a POST request, not a GET. Scott Guthrie has a post explaining why.
Though it's written specifically for jQuery, this may also be useful to you:
Using jQuery to Consume ASP.NET JSON Web Services
import time
start_time = time.clock()
main()
print time.clock() - start_time, "seconds"
time.clock()
returns the processor time, which allows us to calculate only the time used by this process (on Unix anyway). The documentation says "in any case, this is the function to use for benchmarking Python or timing algorithms"
The two main differences are:
ArgumentCaptor
can capture more than once.To illustrate the latter, say you have:
final ArgumentCaptor<Foo> captor = ArgumentCaptor.forClass(Foo.class);
verify(x, times(4)).someMethod(captor.capture()); // for instance
Then the captor will be able to give you access to all 4 arguments, which you can then perform assertions on separately.
This or any number of arguments in fact, since a VerificationMode
is not limited to a fixed number of invocations; in any event, the captor will give you access to all of them, if you wish.
This also has the benefit that such tests are (imho) much easier to write than having to implement your own ArgumentMatcher
s -- particularly if you combine mockito with assertj.
Oh, and please consider using TestNG instead of JUnit.
Use something like this:
var myVar = null;
And then inside your function:
myVar = fldID;
And then:
setTimeout(setFocus,1000)
And then:
function setFocus(){ document.getElementById(fldID).focus(); }
Final code:
<html>
<head>
<script type="text/javascript">
function somefunction(){
var myVar = null;
myVar = document.getElementById('myInput');
if(myVar.value=='')
setTimeout(setFocusOnJobTitle,1000);
else
myVar.value='Success';
}
function setFocusOnJobTitle(){
document.getElementById('myInput').focus();
}
</script>
</head>
<body>
<label id="jobTitleId" for="myInput">Job Title</label>
<input id="myInput" onblur="somefunction();"></input>
</body>
</html>
You can't do it in a single query inside the package - you can't mix the SQL and PL/SQL types, and would need to define the types in the SQL layer as Tony, Marcin and Thio have said.
If you really want this done locally, and you can index the table type by VARCHAR instead of BINARY_INTEGER, you can do something like this:
-- dummy ITEM table as we don't know what the real ones looks like
create table item(
item_num number,
currency varchar2(9)
)
/
insert into item values(1,'GBP');
insert into item values(2,'AUD');
insert into item values(3,'GBP');
insert into item values(4,'AUD');
insert into item values(5,'CDN');
create package so_5165580 as
type exch_row is record(
exch_rt_eur number,
exch_rt_usd number);
type exch_tbl is table of exch_row index by varchar2(9);
exch_rt exch_tbl;
procedure show_items;
end so_5165580;
/
create package body so_5165580 as
procedure populate_rates is
rate exch_row;
begin
rate.exch_rt_eur := 0.614394;
rate.exch_rt_usd := 0.8494;
exch_rt('GBP') := rate;
rate.exch_rt_eur := 0.9817;
rate.exch_rt_usd := 1.3572;
exch_rt('AUD') := rate;
end;
procedure show_items is
cursor c0 is
select i.*
from item i;
begin
for r0 in c0 loop
if exch_rt.exists(r0.currency) then
dbms_output.put_line('Item ' || r0.item_num
|| ' Currency ' || r0.currency
|| ' EUR ' || exch_rt(r0.currency).exch_rt_eur
|| ' USD ' || exch_rt(r0.currency).exch_rt_usd);
else
dbms_output.put_line('Item ' || r0.item_num
|| ' Currency ' || r0.currency
|| ' ** no rates defined **');
end if;
end loop;
end;
begin
populate_rates;
end so_5165580;
/
So inside your loop, wherever you would have expected to use r0.exch_rt_eur
you instead use exch_rt(r0.currency).exch_rt_eur
, and the same for USD. Testing from an anonymous block:
begin
so_5165580.show_items;
end;
/
Item 1 Currency GBP EUR .614394 USD .8494
Item 2 Currency AUD EUR .9817 USD 1.3572
Item 3 Currency GBP EUR .614394 USD .8494
Item 4 Currency AUD EUR .9817 USD 1.3572
Item 5 Currency CDN ** no rates defined **
Based on the answer Stef posted, this doesn't need to be in a package at all; the same results could be achieved with an insert
statement. Assuming EXCH
holds exchange rates of other currencies against the Euro, including USD with currency_key=1
:
insert into detail_items
with rt as (select c.currency_cd as currency_cd,
e.exch_rt as exch_rt_eur,
(e.exch_rt / usd.exch_rt) as exch_rt_usd
from exch e,
currency c,
(select exch_rt from exch where currency_key = 1) usd
where c.currency_key = e.currency_key)
select i.doc,
i.doc_currency,
i.net_value,
i.net_value / rt.exch_rt_usd AS net_value_in_usd,
i.net_value / rt.exch_rt_eur as net_value_in_euro
from item i
join rt on i.doc_currency = rt.currency_cd;
With items valued at 19.99 GBP and 25.00 AUD, you get detail_items
:
DOC DOC_CURRENCY NET_VALUE NET_VALUE_IN_USD NET_VALUE_IN_EURO
--- ------------ ----------------- ----------------- -----------------
1 GBP 19.99 32.53611 23.53426
2 AUD 25 25.46041 18.41621
If you want the currency stuff to be more re-usable you could create a view:
create view rt as
select c.currency_cd as currency_cd,
e.exch_rt as exch_rt_eur,
(e.exch_rt / usd.exch_rt) as exch_rt_usd
from exch e,
currency c,
(select exch_rt from exch where currency_key = 1) usd
where c.currency_key = e.currency_key;
And then insert using values from that:
insert into detail_items
select i.doc,
i.doc_currency,
i.net_value,
i.net_value / rt.exch_rt_usd AS net_value_in_usd,
i.net_value / rt.exch_rt_eur as net_value_in_euro
from item i
join rt on i.doc_currency = rt.currency_cd;
in my case i made a custom view i added to custom view constructor
new RoomView(getAplicationContext());
the correct context is activity so changed it to:
new RoomView(getActivity());
or
new RoomView(this);
When I was started with express always wanted a solution to use import instead require
const express = require("express");
// to
import express from "express"
Many time go through this line:- Unfortunately, Node.js doesn't support ES6's import yet.
Now to help other I create new two solutions here
1) esm:-
The brilliantly simple, babel-less, bundle-less ECMAScript module loader. let's make it work
yarn add esm / npm install esm
create start.js or use your namespace
require = require("esm")(module/*, options*/)
// Import the rest of our application.
module.exports = require('./src/server.js')
// where server.js is express server start file
Change in your package.josn
pass path of start.js
"scripts": {
"start": "node start.js",
"start:dev": "nodemon start.js",
},
"dependencies": {
+ "esm": "^3.2.25",
},
"devDependencies": {
+ "nodemon": "^1.19.2"
}
2) Babel js:-
This can be divide into 2 part
a) Solution 1 thanks to timonweb.com
b) Solution 2
use Babel 6 (older version of babel-preset-stage-3 ^6.0)
create .babelrc
file at your root folder
{
"presets": ["env", "stage-3"]
}
Install babel-preset-stage-3
yarn add babel-cli babel-polyfill babel-preset-env bable-preset-stage-3 nodemon --dev
Change in package.json
"scripts": {
+ "start:dev": "nodemon --exec babel-node -- ./src/index.js",
+ "start": "npm run build && node ./build/index.js",
+ "build": "npm run clean && babel src -d build -s --source-maps --copy-files",
+ "clean": "rm -rf build && mkdir build"
},
"devDependencies": {
+ "babel-cli": "^6.26.0",
+ "babel-polyfill": "^6.26.0",
+ "babel-preset-env": "^1.7.0",
+ "babel-preset-stage-3": "^6.24.1",
+ "nodemon": "^1.19.4"
},
Start your server
yarn start / npm start
Oooh no we create new problem
regeneratorRuntime.mark(function _callee(email, password) {
^
ReferenceError: regeneratorRuntime is not defined
This error only come when you use async/await in your code.
Then use polyfill that includes a custom regenerator runtime and core-js.
add on top of index.js
import "babel-polyfill"
This allow you to use async/await
use Babel 7
Need to upto date every thing in your project let start with babel 7 .babelrc
{
"presets": ["@babel/preset-env"]
}
Some change in package.json
"scripts": {
+ "start:dev": "nodemon --exec babel-node -- ./src/index.js",
+ "start": "npm run build && node ./build/index.js",
+ "build": "npm run clean && babel src -d build -s --source-maps --copy-files",
+ "clean": "rm -rf build && mkdir build",
....
}
"devDependencies": {
+ "@babel/cli": "^7.0.0",
+ "@babel/core": "^7.6.4",
+ "@babel/node": "^7.0.0",
+ "@babel/polyfill": "^7.0.0",
+ "@babel/preset-env": "^7.0.0",
+ "nodemon": "^1.19.4"
....
}
and use import "@babel/polyfill"
on start point
import "@babel/polyfill"
import express from 'express'
const app = express()
//GET request
app.get('/', async (req, res) {
// await operation
res.send('hello world')
})
app.listen(4000, () => console.log(' Server listening on port 400!'))
Are you thinking why start:dev
Seriously. It is good question if you are new. Every change you are boar with start server every time
then use yarn start:dev
as development server every change restart server automatically for more on nodemon
I'm an early adopter and implemented a mid-large single page application using the Facebook Flux library.
As I'm a little late to the conversation I'll just point out that despite my best hopes Facebook seem to consider their Flux implementation to be a proof of concept and it has never received the attention it deserves.
I'd encourage you to play with it, as it exposes more of the inner working of the Flux architecture which is quite educational, but at the same time it does not provide many of the benefits that libraries like Redux provide (which aren't that important for small projects, but become very valuable for bigger ones).
We have decided that moving forward we will be moving to Redux and I suggest you do the same ;)
Another way to ensure you get the correct url regardless of server settings is to put the url into a hidden field on your page and reference it for the path:
<input type="hidden" id="GetIndexDataPath" value="@Url.Action("Index","Home")" />
Then you just get the value in your ajax call:
var path = $("#GetIndexDataPath").val();
$.ajax({
type: "GET",
url: path,
data: { id = e.value},
dataType: "html",
success : function (data) {
$('div#theNewView').html(data);
}
});
}
I have been using this for years to cope with server weirdness, as it always builds the correct url. It also makes keeping track of changing controller method calls a breeze if you put all the hidden fields together in one part of the html or make a separate razor partial to hold them.
You can get just the edition (plus under individual properties) using SERVERPROPERTY
e.g.
SELECT SERVERPROPERTY('Edition')
Quote (for "Edition"):
Installed product edition of the instance of SQL Server. Use the value of this property to determine the features and the limits, such as maximum number of CPUs, that are supported by the installed product.
Returns:
'Desktop Engine' (Not available for SQL Server 2005.)
'Developer Edition'
'Enterprise Edition'
'Enterprise Evaluation Edition'
'Personal Edition'(Not available for SQL Server 2005.)
'Standard Edition'
'Express Edition'
'Express Edition with Advanced Services'
'Workgroup Edition'
'Windows Embedded SQL'
Base data type: nvarchar(128)
This might not be as fast as the izip_longest solution (I didn't actually test it), but it will work with python < 2.6 (izip_longest was added in 2.6):
from itertools import imap
def grouper(n, iterable):
"grouper(3, 'ABCDEFG') --> ('A,'B','C'), ('D','E','F'), ('G',None,None)"
args = [iter(iterable)] * n
return imap(None, *args)
If you need to go earlier than 2.3, you can substitute the built-in map for imap. The disadvantage is that it provides no ability to customize the fill value.
ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.count).row
ActiveSheet can be replaced with WorkSheets(1)
or WorkSheets("name here")
Provide the source image (img) size as the first rectangle:
ctx.drawImage(img, 0, 0, img.width, img.height, // source rectangle
0, 0, canvas.width, canvas.height); // destination rectangle
The second rectangle will be the destination size (what source rectangle will be scaled to).
Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas
I had the same problem. I wanted to have the ability to overwrite an internal configuration file at startup with an external file, similar to the Spring Boot application.properties detection. In my case it's a user.properties file where my applications users are stored.
My requirements:
Load the file from the following locations (in this order)
I came up with the following solution:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import java.io.IOException;
import java.util.Properties;
import static java.util.Arrays.stream;
@Configuration
public class PropertiesConfig {
private static final Logger LOG = LoggerFactory.getLogger(PropertiesConfig.class);
private final static String PROPERTIES_FILENAME = "user.properties";
@Value("${properties.location:}")
private String propertiesLocation;
@Bean
Properties userProperties() throws IOException {
final Resource[] possiblePropertiesResources = {
new ClassPathResource(PROPERTIES_FILENAME),
new PathResource("config/" + PROPERTIES_FILENAME),
new PathResource(PROPERTIES_FILENAME),
new PathResource(getCustomPath())
};
// Find the last existing properties location to emulate spring boot application.properties discovery
final Resource propertiesResource = stream(possiblePropertiesResources)
.filter(Resource::exists)
.reduce((previous, current) -> current)
.get();
final Properties userProperties = new Properties();
userProperties.load(propertiesResource.getInputStream());
LOG.info("Using {} as user resource", propertiesResource);
return userProperties;
}
private String getCustomPath() {
return propertiesLocation.endsWith(".properties") ? propertiesLocation : propertiesLocation + PROPERTIES_FILENAME;
}
}
Now the application uses the classpath resource, but checks for a resource at the other given locations too. The last resource which exists will be picked and used. I'm able to start my app with java -jar myapp.jar --properties.location=/directory/myproperties.properties to use an properties location which floats my boat.
An important detail here: Use an empty String as default value for the properties.location in the @Value annotation to avoid errors when the property is not set.
The convention for a properties.location is: Use a directory or a path to a properties file as properties.location.
If you want to override only specific properties, a PropertiesFactoryBean with setIgnoreResourceNotFound(true) can be used with the resource array set as locations.
I'm sure that this solution can be extended to handle multiple files...
EDIT
Here my solution for multiple files :) Like before, this can be combined with a PropertiesFactoryBean.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toMap;
@Configuration
class PropertiesConfig {
private final static Logger LOG = LoggerFactory.getLogger(PropertiesConfig.class);
private final static String[] PROPERTIES_FILENAMES = {"job1.properties", "job2.properties", "job3.properties"};
@Value("${properties.location:}")
private String propertiesLocation;
@Bean
Map<String, Properties> myProperties() {
return stream(PROPERTIES_FILENAMES)
.collect(toMap(filename -> filename, this::loadProperties));
}
private Properties loadProperties(final String filename) {
final Resource[] possiblePropertiesResources = {
new ClassPathResource(filename),
new PathResource("config/" + filename),
new PathResource(filename),
new PathResource(getCustomPath(filename))
};
final Resource resource = stream(possiblePropertiesResources)
.filter(Resource::exists)
.reduce((previous, current) -> current)
.get();
final Properties properties = new Properties();
try {
properties.load(resource.getInputStream());
} catch(final IOException exception) {
throw new RuntimeException(exception);
}
LOG.info("Using {} as user resource", resource);
return properties;
}
private String getCustomPath(final String filename) {
return propertiesLocation.endsWith(".properties") ? propertiesLocation : propertiesLocation + filename;
}
}
Simply get it like this -
getFragmentManager() // This will also give you the SupportFragmentManager or FragmentManager based on which Fragment class you have extended - android.support.v4.app.Fragment OR android.app.Fragment.
OR
getActivity().getSupportFragmentManager();
in your Fragment's onActivityCreated() method and any method that is being called after onActivityCreated().
NUnit is probably the most supported by the 3rd party tools. It's also been around longer than the other three.
I personally don't care much about unit test frameworks, mocking libraries are IMHO much more important (and lock you in much more). Just pick one and stick with it.
In addition to the answers above.
I wrote following test.exe as console application
static void Main(string[] args) {
Console.WriteLine(
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
Console.WriteLine(
System.Reflection.Assembly.GetEntryAssembly().Location);
Console.WriteLine(
System.Reflection.Assembly.GetExecutingAssembly().Location);
Console.WriteLine(
System.Reflection.Assembly.GetCallingAssembly().Location);
}
Then I compiled the project and renamed its output to the test2.exe file. The output lines were correct and the same.
But, if I start it in the Visual Studio, the result is:
d:\test2.vhost.exe
d:\test2.exe
d:\test2.exe
C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll
The ReSharper plug-in to the Visual Studio has underlined the
System.Diagnostics.Process.GetCurrentProcess().MainModule
as possible System.NullReferenceException. If you look into documentation of the MainModule you will find that this property can throw also NotSupportedException, PlatformNotSupportedException and InvalidOperationException.
The GetEntryAssembly method is also not 100% "safe". MSDN:
The GetEntryAssembly method can return null when a managed assembly has been loaded from an unmanaged application. For example, if an unmanaged application creates an instance of a COM component written in C#, a call to the GetEntryAssembly method from the C# component returns null, because the entry point for the process was unmanaged code rather than a managed assembly.
For my solutions, I prefer the Assembly.GetEntryAssembly().Location
.
More interest is if need to solve the problem for the virtualization. For example, we have a project, where we use a Xenocode Postbuild to link the .net code into one executable. This executable must be renamed. So all the methods above didn't work, because they only gets the information for the original assembly or inner process.
The only solution I found is
var location = System.Reflection.Assembly.GetEntryAssembly().Location;
var directory = System.IO.Path.GetDirectoryName(location);
var file = System.IO.Path.Combine(directory,
System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");
You have installed the incorrect package named 'serial'.
pip uninstall serial
for python 2.x or pip3 uninstall serial
for python 3.x pip install pyserial
for python 2.x orpip3 install pyserial
for python 3.x.It does what you ask, SELECT 1 FROM table
will SELECT
(return) a 1
for every row in that table, if there were 3 rows in the table you would get
1
1
1
Take a look at Count(*) vs Count(1) which may be the issue you were described.
The answers so far are great! But I see a need for a solution with the following constraints:
Here it is:
public static T MaxBy<T, R>(this IEnumerable<T> en, Func<T, R> evaluate) where R : IComparable<R> {
return en.Select(t => new Tuple<T, R>(t, evaluate(t)))
.Aggregate((max, next) => next.Item2.CompareTo(max.Item2) > 0 ? next : max).Item1;
}
public static T MinBy<T, R>(this IEnumerable<T> en, Func<T, R> evaluate) where R : IComparable<R> {
return en.Select(t => new Tuple<T, R>(t, evaluate(t)))
.Aggregate((max, next) => next.Item2.CompareTo(max.Item2) < 0 ? next : max).Item1;
}
Usage:
IEnumerable<Tuple<string, int>> list = new[] {
new Tuple<string, int>("other", 2),
new Tuple<string, int>("max", 4),
new Tuple<string, int>("min", 1),
new Tuple<string, int>("other", 3),
};
Tuple<string, int> min = list.MinBy(x => x.Item2); // "min", 1
Tuple<string, int> max = list.MaxBy(x => x.Item2); // "max", 4
At a place where you want javadoc, type in /**
<NEWLINE> and it will create the template.
You can also use slice assignment to remove one or more elements from a list:
r = [1, 'blah', 9, 8, 2, 3, 4]
>>> r[1:4] = []
>>> r
[1, 2, 3, 4]
Let's fit the model:
> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)
Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)
Residuals:
Min 1Q Median 3Q Max
-245.74 -113.99 -32.05 104.96 484.81
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 811.2267 76.9755 10.539 2.29e-13 ***
body.weight 7.0595 0.9776 7.221 7.03e-09 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433
F-statistic: 52.15 on 1 and 42 DF, p-value: 7.025e-09
The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).
This can be computed using confint
:
> confint(fit, 'body.weight', level=0.95)
2.5 % 97.5 %
body.weight 5.086656 9.0324
Try this:
import React, { useCallback } from "react";
import { Linking } from "react-native";
OpenWEB = () => {
Linking.openURL(url);
};
const App = () => {
return <View onPress={() => OpenWeb}>OPEN YOUR WEB</View>;
};
Hope this will solve your problem.
In the codebase I'm working with (1 million + lines of code) we had a problem with long startup times, around 60 seconds. We were getting 12000+ FactoryBeanNotInitializedException.
What I did was set a conditional breakpoint in AbstractBeanFactory#doGetBean
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
where it does destroySingleton(beanName)
I printed the exception with conditional breakpoint code:
System.out.println(ex);
return false;
Apparently this happens when FactoryBeans are involved in a cyclic dependency graph. We solved it by implementing ApplicationContextAware and InitializingBean and manually injecting the beans.
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class A implements ApplicationContextAware, InitializingBean{
private B cyclicDepenency;
private ApplicationContext ctx;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
ctx = applicationContext;
}
@Override
public void afterPropertiesSet() throws Exception {
cyclicDepenency = ctx.getBean(B.class);
}
public void useCyclicDependency()
{
cyclicDepenency.doSomething();
}
}
This cut down the startup time to around 15 secs.
So don't always assume that spring can be good at solving these references for you.
For this reason I'd recommend disabling cyclic dependency resolution with AbstractRefreshableApplicationContext#setAllowCircularReferences(false) to prevent many future problems.
Do not use [^\w\s]
, this will remove letters with accents (like àèéìòù), not to mention to Cyrillic or Chinese, letters coming from such languages will be completed removed.
You really don't want remove these letters together with all the special characters. You have two chances:
[^èéòàùì\w\s]
.\p{...}
syntax.var str = "????::: résd,$%& adùf"
var search = XRegExp('([^?<first>\\pL ]+)');
var res = XRegExp.replace(str, search, '',"all");
console.log(res); // returns "????::: resd,adf"
console.log(str.replace(/[^\w\s]/gi, '') ); // returns " rsd adf"
console.log(str.replace(/[^\wèéòàùì\s]/gi, '') ); // returns " résd adùf"
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/3.1.1/xregexp-all.js"></script>
_x000D_
there is no way to specifically target an element with php, you can either embed the php code between a div tag or use jquery which would be longer.
I'd guess that Remove
and Substring
would tie for first place, since they both slurp up a fixed-size portion of the string, whereas TrimStart
does a scan from the left with a test on each character and then has to perform exactly the same work as the other two methods. Seriously, though, this is splitting hairs.
As with anything: if used with care, it can be an elegant tool.
However, I think the drawbacks more than justify not to use it, and finally not to allow it anymore (C#). Among the problems are:
Good use of a switch/case fall-through:
switch (x)
{
case 1:
case 2:
case 3:
Do something
break;
}
Baaaaad use of a switch/case fall-through:
switch (x)
{
case 1:
Some code
case 2:
Some more code
case 3:
Even more code
break;
}
This can be rewritten using if/else constructs with no loss at all in my opinion.
My final word: stay away from fall-through case labels as in the bad example, unless you are maintaining legacy code where this style is used and well understood.
The warning message
[WARNING] The requested profile "pom.xml" could not be activated because it does not exist.
means that you somehow passed -P pom.xml
to Maven which means "there is a profile called pom.xml
; find it and activate it". Check your environment and your settings.xml
for this flag and also look at all <profile>
elements inside the various XML files.
Usually, mvn help:effective-pom
is also useful to see what the real POM would look like.
Now the error means that you tried to configure Maven to build Java 8 code but you're not using a Java 8 runtime. Solutions:
JAVA_HOME
is your friendpom.xml
to a Java version which you actually have.Related:
If you want to concatenate a variable with a fixed path and a string as the dynamic path into a whole path to remove the folder, you may need the following command:
$fixPath = "C:\Users\myUserName\Desktop"
Remove-Item ("$fixPath" + "\Folder\SubFolder") -Recurse
In the variable $newPath
the concatenate path is now: "C:\Users\myUserName\Desktop\Folder\SubFolder"
So you can remove several directories from the starting point ("C:\Users\myUserName\Desktop"
), which is already defined and fixed in the variable $fixPath
.
$fixPath = "C:\Users\myUserName\Desktop"
Remote-Item ("$fixPath" + "\Folder\SubFolder") -Recurse
Remote-Item ("$fixPath" + "\Folder\SubFolder1") -Recurse
Remote-Item ("$fixPath" + "\Folder\SubFolder2") -Recurse
You can do it by listening to phone call events . You do it by having a BroadcastReceiver to PHONE_STATE and to NEW_OUTGOING_CALL. You find there what is the phone number.
Then when you decide to end the call, this is a bit tricky, because only from Android P it's guaranteed to work. Check here.
This type of Notification is deprecated as seen from documents:
@java.lang.Deprecated
public Notification(int icon, java.lang.CharSequence tickerText, long when) { /* compiled code */ }
public Notification(android.os.Parcel parcel) { /* compiled code */ }
@java.lang.Deprecated
public void setLatestEventInfo(android.content.Context context, java.lang.CharSequence contentTitle, java.lang.CharSequence contentText, android.app.PendingIntent contentIntent) { /* compiled code */ }
Better way
You can send a notification like this:
// prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
Notification n = new Notification.Builder(this)
.setContentTitle("New mail from " + "[email protected]")
.setContentText("Subject")
.setSmallIcon(R.drawable.icon)
.setContentIntent(pIntent)
.setAutoCancel(true)
.addAction(R.drawable.icon, "Call", pIntent)
.addAction(R.drawable.icon, "More", pIntent)
.addAction(R.drawable.icon, "And more", pIntent).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
Best way
Code above needs minimum API level 11 (Android 3.0).
If your minimum API level is lower than 11, you should you use support library's NotificationCompat class like this.
So if your minimum target API level is 4+ (Android 1.6+) use this:
import android.support.v4.app.NotificationCompat;
-------------
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.mylogo)
.setContentTitle("My Notification Title")
.setContentText("Something interesting happened");
int NOTIFICATION_ID = 12345;
Intent targetIntent = new Intent(this, MyFavoriteActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(NOTIFICATION_ID, builder.build());
Looks like this is on the bottom left now as an icon with overlapping windows and the "Undock into separate window." tooltip.
subprocess.Popen()
is strict super-set of os.system()
.
Using the suggested Maven properties plugin I was able to read in a buildNumber.properties file that I use to version my builds.
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0-alpha-1</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>${basedir}/../project-parent/buildNumber.properties</file>
</files>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
In addition to the above answers you can also use .once
in a similar way to .output
. This outputs only the next query to the specified file, so that you don't have to follow with .output stdout
.
So in the above example
.mode csv
.headers on
.once test.csv
select * from tbl1;
take look at my example
<tocheading language="EN">
<subj-group>
<subject>Editors Choice</subject>
<subject>creative common</subject>
</subj-group>
</tocheading>
now how to check if creative common
is exist
tocheading/subj-group/subject/text() = 'creative common'
hope this help you
var text ="";
for (var member in list) {
text += list[member];
}
SELECT IF('database_name' IN(SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA), 1, 0) AS found;
import java.util*;
Random rnd = new Random ();
long name = Math.abs(rnd.nextLong());
This should work
For those who needs to stop all Threads running and re-run all of them when any one of them is stopped on an Exception:
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// could be any function
getStockHistory();
}
public void getStockHistory() {
// fill a list of symbol to be scrapped
List<String> symbolListNYSE = stockEntityRepository
.findByExchangeShortNameOnlySymbol(ContextRefreshExecutor.NYSE);
storeSymbolList(symbolListNYSE, ContextRefreshExecutor.NYSE);
}
private void storeSymbolList(List<String> symbolList, String exchange) {
int total = symbolList.size();
// I create a list of Thread
List<Thread> listThread = new ArrayList<Thread>();
// For each 1000 element of my scrapping ticker list I create a new Thread
for (int i = 0; i <= total; i += 1000) {
int l = i;
Thread t1 = new Thread() {
public void run() {
// just a service that store in DB my ticker list
storingService.getAndStoreStockPrice(symbolList, l, 1000,
MULTIPLE_STOCK_FILL, exchange);
}
};
Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread thread, Throwable exception) {
// stop thread if still running
thread.interrupt();
// go over every thread running and stop every one of them
listThread.stream().forEach(tread -> tread.interrupt());
// relaunch all the Thread via the main function
getStockHistory();
}
};
t1.start();
t1.setUncaughtExceptionHandler(h);
listThread.add(t1);
}
}
To sum up :
You have a main function that create multiple thread, each of them has UncaughtExceptionHandler which is trigger by any Exception inside of a thread. You add every Thread to a List. If a UncaughtExceptionHandler is trigger it will loop through the List, stop every Thread and relaunch the main function recreation all the Thread.
I know this is an old question, but the following should work if you don't need the month name at the DB level:
SELECT EXTRACT(YEAR_MONTH FROM summaryDateTime) summary_year_month
FROM trading_summary
GROUP BY summary_year_month;
You will probably find this to be better performing.. and if you are building a JSON object in the application layer, you can do the formatting/ordering as you run through the results.
N.B. I wasn't aware you could add DESC to a GROUP BY clause in MySQL, perhaps you are missing an ORDER BY clause:
SELECT EXTRACT(YEAR_MONTH FROM summaryDateTime) summary_year_month
FROM trading_summary
GROUP BY summary_year_month
ORDER BY summary_year_month DESC;
For now, semantically closest one would be a tuple with fixed number of elements.
typealias buffer = (
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode)
But this is (1) very uncomfortable to use and (2) memory layout is undefined. (at least unknown to me)
Both, FILL_PARENT
and MATCH_PARENT
are the same properties. FILL_PARENT
was deprecated in API level 8.
I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy
and JoinColumn
were not working).
I think you were trying to do a bi-directional relationships.
First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post
side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:
(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
private List<Post> posts;
}
public class Post {
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="user_id")
private User user;
}
By doing so, the table for Post
will have a column user_id
which store the relationship. Hibernate is getting the relationship by the user
in Post
(Instead of posts
in User
. You will notice the difference if you have Post
's user
but missing User
's posts
).
You have mentioned mappedBy
and JoinColumn
is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.
Edit:
Just a bit extra information on the use of mappedBy
as it is usually confusing at first. In mappedBy
, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.
You need to alter your table. Increase the column width using a DDL statement.
please see here
http://dba-oracle.com/t_alter_table_modify_column_syntax_example.htm
For asynchronous version! And with the promise version! Here the clean simple way!
try {
await fsPromise.stat(filePath);
/**
* File exists!
*/
// do something
} catch (err) {
if (err.code = 'ENOENT') {
/**
* File not found
*/
} else {
// Another error!
}
}
A more practical snippet from my code to illustrate better:
try {
const filePath = path.join(FILES_DIR, fileName);
await fsPromise.stat(filePath);
/**
* File exists!
*/
const readStream = fs.createReadStream(
filePath,
{
autoClose: true,
start: 0
}
);
return {
success: true,
readStream
};
} catch (err) {
/**
* Mapped file doesn't exists
*/
if (err.code = 'ENOENT') {
return {
err: {
msg: 'Mapped file doesn\'t exists',
code: EErrorCode.MappedFileNotFound
}
};
} else {
return {
err: {
msg: 'Mapped file failed to load! File system error',
code: EErrorCode.MappedFileFileSystemError
}
};
}
}
The example above is just for demonstration! I could have used the error event of the read stream! To catch any errors! And skip the two calls!
Just for the sake of completeness, we can use the operators [
and [[
:
set.seed(1)
df <- data.frame(v1 = runif(10), v2 = letters[1:10])
Several options
df[df[1] < 0.5 | df[2] == "g", ]
df[df[[1]] < 0.5 | df[[2]] == "g", ]
df[df["v1"] < 0.5 | df["v2"] == "g", ]
df$name is equivalent to df[["name", exact = FALSE]]
Using dplyr
:
library(dplyr)
filter(df, v1 < 0.5 | v2 == "g")
Using sqldf
:
library(sqldf)
sqldf('SELECT *
FROM df
WHERE v1 < 0.5 OR v2 = "g"')
Output for the above options:
v1 v2
1 0.26550866 a
2 0.37212390 b
3 0.20168193 e
4 0.94467527 g
5 0.06178627 j
Use some css hack, it seems the display: table-column;
can come to rescue:
<div class="myTable">
<div class="flexibleCell">A very long piece of content in first cell, long enough that it would normally wrap into multiple lines.</div>
<div class="staticCell">Less content</div>
</div>
.myTable {
display: table;
width: 100%;
}
.myTable:before {
display: table-column;
width: 100%;
content: '';
}
.flexibleCell {
display: table-cell;
max-width:1px;
white-space: nowrap;
text-overflow:ellipsis;
overflow: hidden;
}
.staticCell {
white-space: nowrap;
}
JSFiddle: http://jsfiddle.net/blai/7u59asyp/
struct arg_struct *args = (struct arg_struct *)args;
--> this assignment is wrong, I mean the variable argument should be used in this context. Cheers!!!
i just made a proxy graber and also can connect with same grabed proxy without any input here is :
#Import Modules
from termcolor import colored
from selenium import webdriver
import requests
import os
import sys
import time
#Proxy Grab
options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.sslproxies.org/")
tbody = driver.find_element_by_tag_name("tbody")
cell = tbody.find_elements_by_tag_name("tr")
for column in cell:
column = column.text.split(" ")
print(colored(column[0]+":"+column[1],'yellow'))
driver.quit()
print("")
os.system('clear')
os.system('cls')
#Proxy Connection
print(colored('Getting Proxies from graber...','green'))
time.sleep(2)
os.system('clear')
os.system('cls')
proxy = {"http": "http://"+ column[0]+":"+column[1]}
url = 'https://mobile.facebook.com/login'
r = requests.get(url, proxies=proxy)
print("")
print(colored('Connecting using proxy' ,'green'))
print("")
sts = r.status_code
You have to click and hold until the other icon shows up, then slide the mouse down to the icon.
IF EXIST "somefile.txt" (
IF EXIST "someotherfile.txt" (
SET var="somefile.txt","someotherfile.txt"
)
) ELSE (
CALL :SUB
)
:SUB
ECHO Sorry... nothin' there.
GOTO:EOF
Is this feasible?
SETLOCAL ENABLEDELAYEDEXPANSION
IF EXIST "somefile.txt" (
SET var="somefile.txt"
IF EXIST "someotherfile.txt" (
SET var=!var!,"someotherfile.txt"
)
) ELSE (
IF EXIST "someotherfile.txt" (
SET var="someotherfile.txt"
) ELSE (
GOTO:EOF
)
)
Unless you need an actual clone of every single object inside your List<T>
, the best way to clone a list is to create a new list with the old list as the collection parameter.
List<T> myList = ...;
List<T> cloneOfMyList = new List<T>(myList);
Changes to myList
such as insert or remove will not affect cloneOfMyList
and vice versa.
The actual objects the two Lists contain are still the same however.
There is an open source jar available know as Lombok , you just add jar and then annotate your POJO with @Getter & @Setter it will create getters and setters automatically.
Apart from this we can use other features like @ToString ,@EqualsAndHashCode and pretty other cool stuff which removes vanilla code from your application
Probably not exactly your issue..
Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments
sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /
You can use the Console API (which made its appearance in Java 6) as follows:
Console cons = System.console();
if(cons != null) {
char c = (char) cons.reader().read(); // Checking for EOF omitted
...
}
If you just need a single line you don't even need to go through the reader object:
String s = cons.readLine();
Just in case if you wanna check user's group belongs to a predefined group list:
def is_allowed(user):
allowed_group = set(['admin', 'lead', 'manager'])
usr = User.objects.get(username=user)
groups = [ x.name for x in usr.groups.all()]
if allowed_group.intersection(set(groups)):
return True
return False
So the first part of the answer is how to do what the subject asks as this was how I initially interpreted it and a few people seemed to find helpful. The question was since clarified and I've extended the answer to address that.
Setting a timer
First you need to create a Timer (I'm using the java.util
version here):
import java.util.Timer;
..
Timer timer = new Timer();
To run the task once you would do:
timer.schedule(new TimerTask() {
@Override
public void run() {
// Your database code here
}
}, 2*60*1000);
// Since Java-8
timer.schedule(() -> /* your database code here */, 2*60*1000);
To have the task repeat after the duration you would do:
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Your database code here
}
}, 2*60*1000, 2*60*1000);
// Since Java-8
timer.scheduleAtFixedRate(() -> /* your database code here */, 2*60*1000, 2*60*1000);
Making a task timeout
To specifically do what the clarified question asks, that is attempting to perform a task for a given period of time, you could do the following:
ExecutorService service = Executors.newSingleThreadExecutor();
try {
Runnable r = new Runnable() {
@Override
public void run() {
// Database task
}
};
Future<?> f = service.submit(r);
f.get(2, TimeUnit.MINUTES); // attempt the task for two minutes
}
catch (final InterruptedException e) {
// The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
// Took too long!
}
catch (final ExecutionException e) {
// An exception from within the Runnable task
}
finally {
service.shutdown();
}
This will execute normally with exceptions if the task completes within 2 minutes. If it runs longer than that, the TimeoutException will be throw.
One issue is that although you'll get a TimeoutException after the two minutes, the task will actually continue to run, although presumably a database or network connection will eventually time out and throw an exception in the thread. But be aware it could consume resources until that happens.
This writes a Byte Order Mark at the start of the file, which is unnecessary in a UTF-8 file and some applications (in my case, SAP) don't like it. Solution here: Can I export excel data with UTF-8 without BOM?
It's important to evaluate the different ways you can create an HttpClient, and part of that is understanding HttpClientFactory.
This is not a direct answer I know - but you're better off starting here than ending up with new HttpClient(...)
everywhere.
I was able to fully export my project along with all commits, branches and tags to gitlab via following commands run locally on my computer:
To illustrate my example, I will be using https://github.com/raveren/kint as the source repository that I want to import into gitlab. I created an empty project named
Kint
(under namespaceraveren
) in gitlab beforehand and it told me the http git url of the newly created project there is http://gitlab.example.com/raveren/kint.gitThe commands are OS agnostic.
In a new directory:
git clone --mirror https://github.com/raveren/kint
cd kint.git
git remote add gitlab http://gitlab.example.com/raveren/kint.git
git push gitlab --mirror
Now if you have a locally cloned repository that you want to keep using with the new remote, just run the following commands* there:
git remote remove origin
git remote add origin http://gitlab.example.com/raveren/kint.git
git fetch --all
*This assumes that you did not rename your remote master from origin
, otherwise, change the first two lines to reflect it.
Here are two functions to get the page height and the scroll amounts (x,y) without the use of the (bloated) dimensions plugin:
// getPageScroll() by quirksmode.com
function getPageScroll() {
var xScroll, yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
xScroll = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop) {
yScroll = document.documentElement.scrollTop;
xScroll = document.documentElement.scrollLeft;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
xScroll = document.body.scrollLeft;
}
return new Array(xScroll,yScroll)
}
// Adapted from getPageSize() by quirksmode.com
function getPageHeight() {
var windowHeight
if (self.innerHeight) { // all except Explorer
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) {
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowHeight = document.body.clientHeight;
}
return windowHeight
}
$(function(){
$(document).find('div').siblings().each(function(){
var obj = $(this);
obj.find('div').each(function(){
var obj1 = $(this);
if(!obj1.children().length > 0){
alert(obj1.html());
}
});
});
});
<div id="2">
<div>
<div>
<div>XYZ Pvt. Ltd.</div>
</div>
</div>
</div>
<div id="3">
<div>
<div>
<div>ABC Pvt Ltd.</div>
</div>
</div>
</div>
using an custom dtype definition, what worked for me was:
import numpy
# define custom dtype
type1 = numpy.dtype([('freq', numpy.float64, 1), ('amplitude', numpy.float64, 1)])
# declare empty array, zero rows but one column
arr = numpy.empty([0,1],dtype=type1)
# store row data, maybe inside a loop
row = numpy.array([(0.0001, 0.002)], dtype=type1)
# append row to the main array
arr = numpy.row_stack((arr, row))
# print values stored in the row 0
print float(arr[0]['freq'])
print float(arr[0]['amplitude'])
There's also solution for Node JS app. CORS Anywhere is a NodeJS proxy which adds CORS headers to the proxied request.
The url to proxy is literally taken from the path, validated and proxied. The protocol part of the proxied URI is optional, and defaults to "http". If port 443 is specified, the protocol defaults to "https".
This package does not put any restrictions on the http methods or headers, except for cookies. Requesting user credentials is disallowed. The app can be configured to require a header for proxying a request, for example to avoid a direct visit from the browser. https://robwu.nl/cors-anywhere.html
Make an event when it's clicked and then manually change the value of true to the name of what the check box represents, then the name or true will evaluate the same and you can get all the values instead of a list of true/false. Ex:
component.html
<form [formGroup]="customForm" (ngSubmit)="onSubmit()">
<div class="form-group" *ngFor="let parameter of parameters"> <!--I iterate here to list all my checkboxes -->
<label class="control-label" for="{{parameter.Title}}"> {{parameter.Title}} </label>
<div class="checkbox">
<input
type="checkbox"
id="{{parameter.Title}}"
formControlName="{{parameter.Title}}"
(change)="onCheckboxChange($event)"
> <!-- ^^THIS^^ is the important part -->
</div>
</div>
</form>
component.ts
onCheckboxChange(event) {
//We want to get back what the name of the checkbox represents, so I'm intercepting the event and
//manually changing the value from true to the name of what is being checked.
//check if the value is true first, if it is then change it to the name of the value
//this way when it's set to false it will skip over this and make it false, thus unchecking
//the box
if(this.customForm.get(event.target.id).value) {
this.customForm.patchValue({[event.target.id] : event.target.id}); //make sure to have the square brackets
}
}
This catches the event after it was already changed to true or false by Angular Forms, if it's true I change the name to the name of what the checkbox represents, which if needed will also evaluate to true if it's being checked for true/false as well.
public enum Gender {
MALE,
FEMALE
}
I've finally managed to do it. Answer in code snippet below:
var querystring = require('querystring');
var request = require('request');
var form = {
username: 'usr',
password: 'pwd',
opaque: 'opaque',
logintype: '1'
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'http://myUrl',
body: formData,
method: 'POST'
}, function (err, res, body) {
//it works!
});
document.getElementById("elementID").scrollHeight
$("elementID").scrollHeight
Note: On *nix systems, consider using the following command to add read permission for an image:
chmod o+r imagedirectoryAddress/imageName.extension
or this command to add read permission for all images:
chmod o+r imagedirectoryAddress/*.extension
If you need more information, refer to this post.
Convert the message to a character array, then use a for loop to change it to a string
string message = "This Is A Test";
string[] result = new string[message.Length];
char[] temp = new char[message.Length];
temp = message.ToCharArray();
for (int i = 0; i < message.Length - 1; i++)
{
result[i] = Convert.ToString(temp[i]);
}
Running ASP.NET Core 2.1 behind a Traefik reverse Proxy on Ubuntu, I need to set its gateway IP in KnownProxies
after installing the official Microsoft.AspNetCore.HttpOverrides
package
var forwardedOptions = new ForwardedHeadersOptions {
ForwardedHeaders = ForwardedHeaders.XForwardedFor,
};
forwardedOptions.KnownProxies.Add(IPAddress.Parse("192.168.3.1"));
app.UseForwardedHeaders(forwardedOptions);
According to the documentation, this is required if the reverse proxy is not running on localhost. The docker-compose.yml
of Traefik has assigned a static IP address:
networks:
my-docker-network:
ipv4_address: 192.168.3.2
Alternatively, it should be enough to make sure a known network is defined here to specify its gateway in .NET Core.
I think buffers are e.g. useful when interfacing python to native libraries. (Guido van Rossum explains buffer
in this mailinglist post).
For example, numpy seems to use buffer for efficient data storage:
import numpy
a = numpy.ndarray(1000000)
the a.data
is a:
<read-write buffer for 0x1d7b410, size 8000000, offset 0 at 0x1e353b0>
import paramiko
import time
ssh = paramiko.SSHClient()
#ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.106.104.24', port=22, username='admin', password='')
time.sleep(5)
print('connected')
stdin, stdout, stderr = ssh.exec_command(" ")
def execute():
stdin.write('xcommand SystemUnit Boot Action: Restart\n')
print('success')
execute()
There's no easy way (in terms of performance) to do what you want to do.
Reflection works with assemblys and types mainly so you'll have to get all the types of the assembly and query them for the right interface. Here's an example:
Assembly asm = Assembly.Load("MyAssembly");
Type[] types = asm.GetTypes();
Type[] result = types.where(x => x.GetInterface("IMyInterface") != null);
That will get you all the types that implement the IMyInterface in the Assembly MyAssembly
DO Not Use EventEmitter for your service communication.
You should use one of the Observable types. I personally like BehaviorSubject.
Simple example:
You can pass initial state, here I passing null
let subject = new BehaviorSubject(null);
When you want to update the subject
subject.next(myObject)
Observe from any service or component and act when it gets new updates.
subject.subscribe(this.YOURMETHOD);
Is there any reason not to use threads? You can use the threading
class.
Instead of finished()
function use the isAlive()
. The result()
function could join()
the thread and retrieve the result. And, if you can, override the run()
and __init__
functions to call the function specified in the constructor and save the value somewhere to the instance of the class.
Use @@ROWCOUNT:
SELECT * FROM service s WHERE s.service_id = ?;
IF @@ROWCOUNT > 0
-- do stuff here.....
According to SQL Server Books Online:
Returns the number of rows affected by the last statement. If the number of rows is more than 2 billion, use ROWCOUNT_BIG.
Try to encode backslash between domain and user
pip --proxy https://domain%5Cuser:password@proxy:port install -r requirements.txt
#include <iostream>
#include <iomanip>
#include <sstream>
int main()
{
int x, y;
std::stringstream stream;
std::cin >> x;
stream << x;
stream >> std::hex >> y;
std::cout << y;
return 0;
}
For the next visitor coming along: use the recursive array walk; it visits every "leaf" in the multidimensional array. Here's for inspiration:
function getMDArrayValueByKey($a, $k) {
$r = [];
array_walk_recursive ($a,
function ($item, $key) use ($k, &$r) {if ($key == $k) $r[] = $item;}
);
return $r;
}
Whenever you want to redirect, send the headers:
header("Location: http://www.example.com/");
Remember you cant send data to the client before that, though.
import android.app.Activity;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.json.JSONObject;
import java.util.ArrayList;
public class OurteamAdapter extends BaseAdapter {
Context cont;
ArrayList<OurteamModel> llist;
OurteamAdapter madap;
LayoutInflater inflater;
JsonHelper Jobj;
String Id;
JSONObject obj = null;
int position = 0;
public OurteamAdapter(Context c,ArrayList<OurteamModel> Mi)
{
this.cont = c;
this.llist = Mi;
}
@Override
public int getCount()
{
// TODO Auto-generated method stub
return llist.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return llist.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
if(convertView == null)
{
LayoutInflater in = (LayoutInflater) cont.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = in.inflate(R.layout.doctorlist, null);
}
TextView category = (TextView) convertView.findViewById(R.id.button1);
TextView title = (TextView) convertView.findViewById(R.id.button2);
ImageView i1=(ImageView) convertView.findViewById(R.id.imageView1);
category.setText(Html.fromHtml(llist.get(position).getGalleryName()));
title.setText(Html.fromHtml(llist.get(position).getGalleryDetail()));
if(llist.get(position).getImagesrc()!=null)
{
i1.setImageBitmap(llist.get(position).getImagesrc());
}
else
{
i1.setImageResource(R.drawable.anandlogo);
}
return convertView;
}
}
Android Official Solution
Since Android Design Support v28 was introduced, it's easy to create a bordered button using MaterialButton
. This class supplies updated Material styles for the button in the constructor. Using app:strokeColor
and app:strokeWidth
you can create a custom border as following:
androidx
:build.gradle
dependencies {
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.0.0'
}
• Bordered Button:
<com.google.android.material.button.MaterialButton
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MATERIAL BUTTON"
android:textSize="15sp"
app:strokeColor="@color/green"
app:strokeWidth="2dp" />
• Unfilled Bordered Button:
<com.google.android.material.button.MaterialButton
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UNFILLED MATERIAL BUTTON"
android:textColor="@color/green"
android:textSize="15sp"
app:backgroundTint="@android:color/transparent"
app:cornerRadius="8dp"
app:rippleColor="#33AAAAAA"
app:strokeColor="@color/green"
app:strokeWidth="2dp" />
appcompat
:build.gradle
dependencies {
implementation 'com.android.support:design:28.0.0'
}
style.xml
Ensure your application theme inherits from Theme.MaterialComponents
instead of Theme.AppCompat
.
<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
• Bordered Button:
<android.support.design.button.MaterialButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MATERIAL BUTTON"
android:textSize="15sp"
app:strokeColor="@color/green"
app:strokeWidth="2dp" />
• Unfilled Bordered Button:
<android.support.design.button.MaterialButton
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UNFILLED MATERIAL BUTTON"
android:textColor="@color/green"
android:textSize="15sp"
app:backgroundTint="@android:color/transparent"
app:cornerRadius="8dp"
app:rippleColor="#33AAAAAA"
app:strokeColor="@color/green"
app:strokeWidth="2dp" />
For those using Altap Salamander (2 panels file manager) : in the Options of the Copy popup, just specify the file names or masks. Easy.
Code Snippet for Hiding a TabPage
private void HideTab1_Click(object sender, EventArgs e)
{
tabControl1.TabPages.Remove(tabPage1);
}
Code Snippet for Showing a TabPage
private void ShowTab1_Click(object sender, EventArgs e)
{
tabControl1.TabPages.Add(tabPage1);
}
since you set your itemsource to your collection, your textbox is tied to each individual item in that collection. the selected item property is useful in this scenario if you were trying to do a master-detail form, having 2 listboxes. you would bind the second listbox's itemsource to the child collection of rules. in otherwords the selected item alerts outside controls that your source has changed, internal controls(those inside your datatemplate already are aware of the change.
and to answer your question yes in most circumstances setting the itemsource is the same as setting the datacontext of the control.
This is entirely untested but it should do what you need.
Update : here's a jsfiddle to look at. Seems to be working. link
You would past it into a js file and reference it after your jquery reference. You would then call it like this..
$("textarea").characterCounter(200);
A brief explanation of what is going on..
On every keyup event the function is checking what type of key is pressed. If it is acceptable the the counter will check the count, trim any excess and prevent any further input once the limit is reached.
The plugin should handle pasting into the target too.
; (function ($) {
$.fn.characterCounter = function (limit) {
return this.filter("textarea, input:text").each(function () {
var $this = $(this),
checkCharacters = function (event) {
if ($this.val().length > limit) {
// Trim the string as paste would allow you to make it
// more than the limit.
$this.val($this.val().substring(0, limit))
// Cancel the original event
event.preventDefault();
event.stopPropagation();
}
};
$this.keyup(function (event) {
// Keys "enumeration"
var keys = {
BACKSPACE: 8,
TAB: 9,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40
};
// which normalizes keycode and charcode.
switch (event.which) {
case keys.UP:
case keys.DOWN:
case keys.LEFT:
case keys.RIGHT:
case keys.TAB:
break;
default:
checkCharacters(event);
break;
}
});
// Handle cut/paste.
$this.bind("paste cut", function (event) {
// Delay so that paste value is captured.
setTimeout(function () { checkCharacters(event); event = null; }, 150);
});
});
};
} (jQuery));
to order after the colsum :
order(colSums(people),decreasing=TRUE)
if more than 20+ columns
order(colSums(people[,c(5:25)],decreasing=TRUE) ##in case of keeping the first 4 columns remaining.
It is also clarifying from https://www.programiz.com/python-programming/methods/built-in/getattr
class Person:
age = 23
name = "Adam"
person = Person()
print('The age is:', getattr(person, "age"))
print('The age is:', person.age)
The age is: 23
The age is: 23
class Person:
age = 23
name = "Adam"
person = Person()
# when default value is provided
print('The sex is:', getattr(person, 'sex', 'Male'))
# when no default value is provided
print('The sex is:', getattr(person, 'sex'))
The sex is: Male
AttributeError: 'Person' object has no attribute 'sex'
start "" "c:\path with spaces\app.exe" "C:\path parameter\param.exe"
When I used above suggestion, I've got:
'c:\path' is not recognized a an internal or external command, operable program or batch file.
I think second qoutation mark prevent command to run. After some search below solution save my day:
start "" CALL "c:\path with spaces\app.exe" "C:\path parameter\param.exe"
I have one function that lpad with x decimals: CREATE FUNCTION [dbo].[LPAD_DEC] ( -- Add the parameters for the function here @pad nvarchar(MAX), @string nvarchar(MAX), @length int, @dec int ) RETURNS nvarchar(max) AS BEGIN -- Declare the return variable here DECLARE @resp nvarchar(max)
IF LEN(@string)=@length
BEGIN
IF CHARINDEX('.',@string)>0
BEGIN
SELECT @resp = CASE SIGN(@string)
WHEN -1 THEN
-- Nros negativos grandes con decimales
concat('-',SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec)))
ELSE
-- Nros positivos grandes con decimales
concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(@string,@length,@dec)))
END
END
ELSE
BEGIN
SELECT @resp = CASE SIGN(@string)
WHEN -1 THEN
--Nros negativo grande sin decimales
concat('-',SUBSTRING(replicate(@pad,@length),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))
ELSE
-- Nros positivos grandes con decimales
concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(@string,@length,@dec)))
END
END
END
ELSE
IF CHARINDEX('.',@string)>0
BEGIN
SELECT @resp =CASE SIGN(@string)
WHEN -1 THEN
-- Nros negativos con decimales
concat('-',SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec)))
ELSE
--Ntos positivos con decimales
concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec)))
END
END
ELSE
BEGIN
SELECT @resp = CASE SIGN(@string)
WHEN -1 THEN
-- Nros Negativos sin decimales
concat('-',SUBSTRING(replicate(@pad,@length-3),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))
ELSE
-- Nros Positivos sin decimales
concat(SUBSTRING(replicate(@pad,@length),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))
END
END
RETURN @resp
END
Another reason to the error may be if you are running a cron job that updates a subversion working copy and then has attempted to run a versioned script that was in a conflicted state after the update...
Here you go. Just specify the chars you want to allow on the first line.
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 20; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
System.out.println(output);
If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use
java.security.SecureRandom
instead. Values produced byjava.util.Random
andjava.util.concurrent.ThreadLocalRandom
are mathematically predictable.
I think your questions will all be answered if you understand how Sets, and in particular HashSets work. A set is a collection of unique objects, with Java defining uniqueness in that it doesn't equal anything else (equals returns false).
The HashSet takes advantage of hashcodes to speed things up. It assumes that two objects that equal eachother will have the same hash code. However it does not assume that two objects with the same hash code mean they are equal. This is why when it detects a colliding hash code, it only compares with other objects (in your case one) in the set with the same hash code.
If you use TortoiseGit (it provides GUI for Git), you can right click your Git repo folder then click Git Sync
.
You can select your branches to compare if not selected. Than you can view differences commit. You can also right click any commit then Compare with previous revision
to view differences side by side.
I just came across this issue in some of my scripts too, and it seemed to be happening because I was applying json_encode to an array wrapped inside another array which was also json encoded. It's easy to do if you have multiple foreach loops in a script that creates the data. Always apply json_encode at the end.
Here is what was happening. If you do:
$data[] = json_encode(['test' => 'one', 'test' => '2']);
$data[] = json_encode(['test' => 'two', 'test' => 'four']);
echo json_encode($data);
The result is:
["{\"test\":\"2\"}","{\"test\":\"four\"}"]
So, what you actually need to do is:
$data[] = ['test' => 'one', 'test' => '2'];
$data[] = ['test' => 'two', 'test' => 'four'];
echo json_encode($data);
And this will return
[{"test":"2"},{"test":"four"}]
How you'd find a line break varies between operating system encodings. Windows would be \r\n
, but Linux just uses \n
and Apple uses \r
.
I found this in JavaScript line breaks:
someText = someText.replace(/(\r\n|\n|\r)/gm, "");
That should remove all kinds of line breaks.
Here's an example of how to do it in C.
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void segfault_sigaction(int signal, siginfo_t *si, void *arg)
{
printf("Caught segfault at address %p\n", si->si_addr);
exit(0);
}
int main(void)
{
int *foo = NULL;
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sigemptyset(&sa.sa_mask);
sa.sa_sigaction = segfault_sigaction;
sa.sa_flags = SA_SIGINFO;
sigaction(SIGSEGV, &sa, NULL);
/* Cause a seg fault */
*foo = 1;
return 0;
}
string founded = FindStringTakeX("UID: 994zxfa6q", "UID:", 9);
string FindStringTakeX(string strValue,string findKey,int take,bool ignoreWhiteSpace = true)
{
int index = strValue.IndexOf(findKey) + findKey.Length;
if (index >= 0)
{
if (ignoreWhiteSpace)
{
while (strValue[index].ToString() == " ")
{
index++;
}
}
if(strValue.Length >= index + take)
{
string result = strValue.Substring(index, take);
return result;
}
}
return string.Empty;
}
I wanted to change the column value in a specific row. Thanks to above answers and after some serching able to come up with below,
var dataTable = $("#yourtableid");
var rowNumber = 0;
var columnNumber= 2;
dataTable[0].rows[rowNumber].cells[columnNumber].innerHTML = 'New Content';
public static void main(String arg[])
{
HashMap<String, ArrayList<String>> hashmap =
new HashMap<String, ArrayList<String>>();
ArrayList<String> arraylist = new ArrayList<String>();
arraylist.add("Hello");
arraylist.add("World.");
hashmap.put("my key", arraylist);
arraylist = hashmap.get("not inserted");
System.out.println(arraylist);
arraylist = hashmap.get("my key");
System.out.println(arraylist);
}
null
[Hello, World.]
Works fine... maybe you find your mistake in my code.
public static void main(String[] args) {
try {
File file = new File("test.txt");
System.out.println(file.length());
} catch (Exception e) {
}
}
Problem is synchronization. Separate out regions of conflict.
Name the file as : (server-name)_(thread/process-name)_(millisecond/timestamp).(extension)
example : aws1_t1_1447402821007.png
Easy enough to use underscore:
_.escape(string)
Underscore is a utility library that provides a lot of features that native js doesn't provide. There's also lodash which is the same API as underscore but was rewritten to be more performant.
You need to use built-in pathMatcher
:
@RequestMapping("/{id}/**")
public void test(HttpServletRequest request, @PathVariable long id) throws Exception {
ResourceUrlProvider urlProvider = (ResourceUrlProvider) request
.getAttribute(ResourceUrlProvider.class.getCanonicalName());
String restOfUrl = urlProvider.getPathMatcher().extractPathWithinPattern(
String.valueOf(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)),
String.valueOf(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)));
it's also a good thing to make sure you have the right import
I had an issue like that and I found out that the bean was using
javax.faces.view.ViewScoped;
^
instead of
javax.faces.bean.ViewScoped;
^
If you want absolute urls, you have the third parameter.
$product_url = $this->generateUrl('product_detail',
array(
'slug' => 'slug'
),
UrlGeneratorInterface::ABSOLUTE_URL
);
Remember to include UrlGeneratorInterface.
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
Try SET GLOBAL slow_query_log = 'ON';
and perhaps FLUSH LOGS;
This assumes you are using MySQL 5.1 or later. If you are using an earlier version, you'll need to restart the server. This is documented in the MySQL Manual. You can configure the log either in the config file or on the command line.
Why is everyone complicating this?
The only problem is Math.atan2( x , y)
The corret answer is Math.atan2( y, x)
All they did was mix the variable order for Atan2 causing it to reverse the degree of rotation.
All you had to do was look up the syntax https://www.google.com/amp/s/www.geeksforgeeks.org/java-lang-math-atan2-java/amp/