It seems to me the simplest way to do it with Selenium is to intercept the XHR that sends back the browser fingerprint.
But since this is a Selenium-only problem, its better just to use something else. Selenium is supposed to make things like this easier, not way harder.
Not the most beautiful way of doing it I guess:
git log --pretty=oneline | wc -l
This gives you a number then
git log HEAD~<The number minus one>
by this you can load html file which is in your project Assets(bundle) to webView.
UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
[web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];
may be this is useful to you.
Here is a complete test case that simulates the click
event, calls all handlers attached (however they have been attached), maintains the "target"
attribute ("srcElement"
in IE), bubbles like a normal event would, and emulates IE's recursion-prevention. Tested in FF 2, Chrome 2.0, Opera 9.10 and of course IE (6):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function fakeClick(event, anchorObj) {
if (anchorObj.click) {
anchorObj.click()
} else if(document.createEvent) {
if(event.target !== anchorObj) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var allowDefault = anchorObj.dispatchEvent(evt);
// you can check allowDefault for false to see if
// any handler called evt.preventDefault().
// Firefox will *not* redirect to anchorObj.href
// for you. However every other browser will.
}
}
}
</script>
</head>
<body>
<div onclick="alert('Container clicked')">
<a id="link" href="#" onclick="alert((event.target || event.srcElement).innerHTML)">Normal link</a>
</div>
<button type="button" onclick="fakeClick(event, document.getElementById('link'))">
Fake Click on Normal Link
</button>
<br /><br />
<div onclick="alert('Container clicked')">
<div onclick="fakeClick(event, this.getElementsByTagName('a')[0])"><a id="link2" href="#" onclick="alert('foo')">Embedded Link</a></div>
</div>
<button type="button" onclick="fakeClick(event, document.getElementById('link2'))">Fake Click on Embedded Link</button>
</body>
</html>
It avoids recursion in non-IE browsers by inspecting the event object that is initiating the simulated click, by inspecting the target
attribute of the event (which remains unchanged during propagation).
Obviously IE does this internally holding a reference to its global event
object. DOM level 2 defines no such global variable, so for that reason the simulator must pass in its local copy of event
.
Apparently the thread you refer is about C++
.
In C
your snippet will always work. I like the simpler if (p) { /* ... */ }
.
I think you're looking for a method like this:
public static IEnumerable<TResult> CompareSequences<T1, T2, TResult>(IEnumerable<T1> seq1,
IEnumerable<T2> seq2, Func<T1, T2, TResult> comparer)
{
var enum1 = seq1.GetEnumerator();
var enum2 = seq2.GetEnumerator();
while (enum1.MoveNext() && enum2.MoveNext())
{
yield return comparer(enum1.Current, enum2.Current);
}
}
It's untested, but it should do the job nonetheless. Note that what's particularly useful about this method is that it's full generic, i.e. it can take two sequences of arbitrary (and different) types and return objects of any type.
This solution of course assumes that you want to compare the nth item of seq1
with the nth item in seq2
. If you want to do match the elements in the two sequences based on a particular property/comparison, then you'll want to perform some sort of join operation (as suggested by danbruc using Enumerable.Join
. Do let me know if it neither of these approaches is quite what I'm after and maybe I can suggest something else.
Edit:
Here's an example of how you might use the CompareSequences
method with the comparer function you originally posted.
// Prints out to the console all the results returned by the comparer function (CompareTwoClass_ReturnDifferences in this case).
var results = CompareSequences(list1, list2, CompareTwoClass_ReturnDifferences);
int index;
foreach(var element in results)
{
Console.WriteLine("{0:#000} {1}", index++, element.ToString());
}
This is what I went through on Amazon/AWS EMR v5. (Adapted from the previous answers), to have Maven and Java8.
sudo wget https://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo
sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo
sudo yum install -y apache-maven
sudo alternatives --config java
pick Java8
sudo alternatives --config javac
pick Java8
Now, if you run:
mvn -version
You should get:
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T07:58:13Z)
Maven home: /usr/share/apache-maven
Java version: 1.8.0_171, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.38.amzn1.x86_64/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.14.47-56.37.amzn1.x86_64", arch: "amd64", family: “unix"
the problem is blade, try this
<i class="fa" v-bind:class="['{{content['cravings']}}' ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline']"></i>
A bug or security vulnerability in the server (either Apache or the PHP engine), or your own PHP code, might allow an attacker to obtain access to your code.
For instance if you have a PHP script to allow people to download files, and an attacker can trick this script into download some of your PHP files, then your code can be leaked.
Since it's impossible to eliminate all bugs from the software you're using, if someone really wants to steal your code, and they have enough resources, there's a reasonable chance they'll be able to.
However, as long as you keep your server up-to-date, someone with casual interest is not able to see the PHP source unless there are some obvious security vulnerabilities in your code.
Read the Security section of the PHP manual as a starting point to keeping your code safe.
Hash functions for algorithmic use have usually 2 goals, first they have to be fast, second they have to evenly distibute the values across the possible numbers. The hash function also required to give the all same number for the same input value.
if your values are strings, here are some examples for bad hash functions:
string[0]
- the ASCII characters a-Z are way more often then othersstring.lengh()
- the most probable value is 1Good hash functions tries to use every bit of the input while keeping the calculation time minimal. If you only need some hash code, try to multiply the bytes with prime numbers, and sum them.
If kill -9
isn't working, then neither will killall
(or even killall -9
which would be more "intense"). Apparently the chromium process is stuck in a non-interruptible system call (i.e., in the kernel, not in userland) -- didn't think MacOSX had any of those left, but I guess there's always one more:-(. If that process has a controlling terminal you can probably background it and kill it while backgrounded; otherwise (or if the intense killing doesn't work even once the process is bakcgrounded) I'm out of ideas and I'm thinking you might have to reboot:-(.
Just check the bootstrap. CSS and search for the class panel-heading and copy the default code.
Copy the default CSS to your personal CSS but vive it a diference classname like my-panel-header for example.
Edit the css Code from the new clones class created.
I don't see anyone mentioning that if you don't provide a message it will open nano for you (at least in Linux) where you can write multiple lines...
Only this is needed:
git commit
You're looking for implode()
$string = implode(",", $array);
You cannot resize an array in java.
Once the size of array is declared, it remains fixed.
Instead you can use ArrayList
that has dynamic size, meaning you don't need to worry about its size. If your array list is not big enough to accommodate new values then it will be resized automatically.
ArrayList<String> ar = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
String s3 ="Test3";
ar.add(s1);
ar.add(s2);
ar.add(s3);
String s4 ="Test4";
ar.add(s4);
Did You use Zend Framework? I have the same problem too.
I solved it by commenting out this the following line in config/application.ini
:
;includePaths.library = APPLICATION_PATH "/../library"
I hope this will help you.
I do it as below
$("a[rel=popover]").click(function(event){
if(event.which == 1)
{
$thisPopOver = $(this);
$thisPopOver.popover('toggle');
$thisPopOver.parent("li").click(function(event){
event.stopPropagation();
$("html").click(function(){
$thisPopOver.popover('hide');
});
});
}
});
Hope this helps!
Below are two functions: dbo.HexToInt and dbo.IntToHex, I use them for such conversion:
if OBJECT_ID('dbo.HexToInt') is not null
drop function dbo.HexToInt
GO
create function dbo.HexToInt (@chars varchar(max))
returns int
begin
declare @char varchar(1), @len int, @i int, @r int, @tmp int, @pow int
set @chars = RTRIM(LTRIM(@chars))
set @len = LEN(@chars)
set @i = 1
set @r = 0
while @i <= @len
begin
set @pow = @len - @i
set @char = SUBSTRING(@chars, @i, 1)
if @char = '0'
set @tmp = 0
else if @char = '1'
set @tmp = 1
else if @char = '2'
set @tmp = 2
else if @char = '3'
set @tmp = 3
else if @char = '4'
set @tmp = 4
else if @char = '5'
set @tmp = 5
else if @char = '6'
set @tmp = 6
else if @char = '7'
set @tmp = 7
else if @char = '8'
set @tmp = 8
else if @char = '9'
set @tmp = 9
else if @char = 'A'
set @tmp = 10
else if @char = 'B'
set @tmp = 11
else if @char = 'C'
set @tmp = 12
else if @char = 'D'
set @tmp = 13
else if @char = 'E'
set @tmp = 14
else if @char = 'F'
set @tmp = 15
set @r = @r + @tmp * POWER(16,@pow)
set @i = @i + 1
end
return @r
end
And the second one:
if OBJECT_ID('dbo.IntToHex') is not null
drop function dbo.IntToHex
GO
create function dbo.IntToHex (@val int)
returns varchar(max)
begin
declare @r varchar(max), @tmp int, @v1 int, @v2 int, @char varchar(1)
set @tmp = @val
set @r = ''
while 1=1
begin
set @v1 = @tmp / 16
set @v2 = @tmp % 16
if @v2 = 0
set @char = '0'
else if @v2 = 1
set @char = '1'
else if @v2 = 2
set @char = '2'
else if @v2 = 3
set @char = '3'
else if @v2 = 4
set @char = '4'
else if @v2 = 5
set @char = '5'
else if @v2 = 6
set @char = '6'
else if @v2 = 7
set @char = '7'
else if @v2 = 8
set @char = '8'
else if @v2 = 9
set @char = '9'
else if @v2 = 10
set @char = 'A'
else if @v2 = 11
set @char = 'B'
else if @v2 = 12
set @char = 'C'
else if @v2 = 13
set @char = 'D'
else if @v2 = 14
set @char = 'E'
else if @v2 = 15
set @char = 'F'
set @tmp = @v1
set @r = @char + @r
if @tmp = 0
break
end
return @r
end
Try doing SHIFT + G
and you will be at the end of the page, but you can't edit yet. Go to the top by doing G + G
<script>
$('#btn_hide').click( function () {
$('#btn_hide').hide();
});
</script>
<input type="button" id="btn_hide"/>
this will be enough
For session cookies it doesn't seem to be supported in Tomcat yet. See the bug report Need to add support for HTTPOnly session cookie parameter. A somewhat involved work-around for now can be found here, which basically boils down to manually patching Tomcat. Can't really find an easy way to do it at this moment at this point I'm affraid.
To summarize the work-around, it involves downloading the 5.5 source, and then change the source in the following places:
org.apache.catalina.connector.Request.java
//this is what needs to be changed
//response.addCookieInternal(cookie);
//this is whats new
response.addCookieInternal(cookie, true);
}
org.apache.catalina.connectorResponse.addCookieInternal
public void addCookieInternal(final Cookie cookie) {
addCookieInternal(cookie, false);
}
public void addCookieInternal(final Cookie cookie, boolean HTTPOnly) {
if (isCommitted())
return;
final StringBuffer sb = new StringBuffer();
//web application code can receive a IllegalArgumentException
//from the appendCookieValue invokation
if (SecurityUtil.isPackageProtectionEnabled()) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run(){
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(),
cookie.getValue(), cookie.getPath(),
cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
return null;
}
});
} else {
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(),
cookie.getPath(), cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
}
//of course, we really need to modify ServerCookie
//but this is the general idea
if (HTTPOnly) {
sb.append("; HttpOnly");
}
//if we reached here, no exception, cookie is valid
// the header name is Set-Cookie for both "old" and v.1 ( RFC2109 )
// RFC2965 is not supported by browsers and the Servlet spec
// asks for 2109.
addHeader("Set-Cookie", sb.toString());
cookies.add(cookie);
}
Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security
. Your JAVA_HOME should always be ../JAVA/JDK
.
The inclusion of your comparison class (or more specifically the AsEnumerable
call you needed to use to get it to work) meant that the sorting logic went from being based on the database server to being on the database client (your application). This meant that your client now needs to retrieve and then process a larger number of records, which will always be less efficient that performing the lookup on the database where the approprate indexes can be used.
You should try to develop a where clause that satisfies your requirements instead, see Using an IEqualityComparer with a LINQ to Entities Except clause for more details.
I wrote a directive which lets you limit the areas where a click has effect. It could be used for certain scenarios like this one, so instead of having to deal with the click on a case by case basis you can just say "clicks won't come out of this element".
You would use it like this:
<table>
<tr ng-repeat="user in users" ng-click="showUser(user)">
<td>{{user.firstname}}</td>
<td>{{user.lastname}}</td>
<td isolate-click>
<button class="btn" ng-click="deleteUser(user.id, $index);">
Delete
</button>
</td>
</tr>
</table>
Keep in mind that this would prevent all clicks on the last cell, not just the button. If that's not what you want you may want to wrap the button like this:
<span isolate-click>
<button class="btn" ng-click="deleteUser(user.id, $index);">
Delete
</button>
</span>
Here is the directive's code:
angular.module('awesome', []).directive('isolateClick', function() {
return {
link: function(scope, elem) {
elem.on('click', function(e){
e.stopPropagation();
});
}
};
});
To remove the special characters, try
var name = name.replace(/[!@#$%^&*]/g, "");
INPUT
STRMIDDLENAME
--------------
Aravind Chaterjee
Shivakumar
Robin Van Parsee
SELECT STRMIDDLENAME,
CASE WHEN INSTR(STRMIDDLENAME,' ',1,2) != 0 THEN SUBSTR(STRMIDDLENAME,1,1) || SUBSTR(STRMIDDLENAME,INSTR(STRMIDDLENAME,' ',1,1)+1,1)||
SUBSTR(STRMIDDLENAME,INSTR(STRMIDDLENAME,' ',1,2)+1,1)
WHEN INSTR(STRMIDDLENAME,' ',1,1) != 0 THEN SUBSTR(STRMIDDLENAME,1,1) || SUBSTR(STRMIDDLENAME,INSTR(STRMIDDLENAME,' ',1,1)+1,1)
ELSE SUBSTR(STRMIDDLENAME,1,1)
END AS FIRSTLETTERS
FROM Dual;
OUTPUT
STRMIDDLENAME FIRSTLETTERS
--------- -----------------
Aravind Chaterjee AC
Shivakumar S
Robin Van Parsee RVP
You must have to define no-args or default constructor if you are creating your own constructor.
You can read why default or no argument constructor is required.
"mysql" may be found even if mysql and mariadb is uninstalled, but not "mysqld".
Faster than rpm -qa | grep mysqld is:
which mysqld
Just add 0 before the permission number:
For example - we want to give all permissions - 777
Syntax: os.chmod("file_name" , permission)
import os
os.chmod("file_name" , 0777)
Python version 3.7 does not support this syntax. It requires '0o' prefix for octal literals - this is the comment I have got in PyCharm
So for python 3.7, it will be
import os
os.chmod("file_name" , 0o777)
you should use tagName
property and attr('type')
for inputs
Smallest solution:
var regExp=/\s+/g, newString=oldString.replace(regExp,' ');
I think that the solution of @Azimuts (https://stackoverflow.com/a/33375677/6503697) is for HTTP only connection. For FTPS connection you can use Bouncy Castle with org.apache.commons.net.ftp.FTPSClient without the need for rewrite FTPS protocol.
I have a program running on JRE 1.6.0_04 and I can not update the JRE.
The program has to connect to an FTPS server that work only with TLS 1.2 (IIS server).
I struggled for days and finally I have understood that there are few versions of bouncy castle library right in my use case: bctls-jdk15on-1.60.jar and bcprov-jdk15on-1.60.jar are ok, but 1.64 versions are not.
The version of apache commons-net is 3.1 .
Following is a small snippet of code that should work:
import java.io.ByteArrayOutputStream;
import java.security.SecureRandom;
import java.security.Security;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSClient;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jsse.provider.BouncyCastleJsseProvider;
import org.junit.Test;
public class FtpsTest {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
} };
@Test public void test() throws Exception {
Security.insertProviderAt(new BouncyCastleProvider(), 1);
Security.addProvider(new BouncyCastleJsseProvider());
SSLContext sslContext = SSLContext.getInstance("TLS", new BouncyCastleJsseProvider());
sslContext.init(null, trustAllCerts, new SecureRandom());
org.apache.commons.net.ftp.FTPSClient ftpClient = new FTPSClient(sslContext);
ByteArrayOutputStream out = null;
try {
ftpClient.connect("hostaname", 21);
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
String msg = "Il server ftp ha rifiutato la connessione.";
throw new Exception(msg);
}
if (!ftpClient.login("username", "pwd")) {
String msg = "Il server ftp ha rifiutato il login con username: username e pwd: password .";
ftpClient.disconnect();
throw new Exception(msg);
}
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setDataTimeout(60000);
ftpClient.execPBSZ(0); // Set protection buffer size
ftpClient.execPROT("P"); // Set data channel protection to private
int bufSize = 1024 * 1024; // 1MB
ftpClient.setBufferSize(bufSize);
out = new ByteArrayOutputStream(bufSize);
ftpClient.retrieveFile("remoteFileName", out);
out.toByteArray();
}
finally {
if (out != null) {
out.close();
}
ftpClient.disconnect();
}
}
}
This is the VB.net version which works fine for me ported from the C code in BlaM's post.
There's a C implementation here:
http://www.cs.rit.edu/~ncs/color/t_convert.html
Should be very straightforward to convert to C#, as almost no functions are called - just > calculations.
Public Sub HSVtoRGB(ByRef r As Double, ByRef g As Double, ByRef b As Double, ByVal h As Double, ByVal s As Double, ByVal v As Double)
Dim i As Integer
Dim f, p, q, t As Double
If (s = 0) Then
' achromatic (grey)
r = v
g = v
b = v
Exit Sub
End If
h /= 60 'sector 0 to 5
i = Math.Floor(h)
f = h - i 'factorial part of h
p = v * (1 - s)
q = v * (1 - s * f)
t = v * (1 - s * (1 - f))
Select Case (i)
Case 0
r = v
g = t
b = p
Exit Select
Case 1
r = q
g = v
b = p
Exit Select
Case 2
r = p
g = v
b = t
Exit Select
Case 3
r = p
g = q
b = v
Exit Select
Case 4
r = t
g = p
b = v
Exit Select
Case Else 'case 5:
r = v
g = p
b = q
Exit Select
End Select
End Sub
Simpler and shorter working code:
We are using HTTPClient 4.3.5 and we tried almost all solutions exist on the stackoverflow but nothing, After thinking and figuring out the problem, we come to the following code which works perfectly, just add it before creating HttpClient instance.
some method which you use to make post request...
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(),
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslSF).build();
HttpPost postRequest = new HttpPost(url);
continue calling and using HttpPost instance in the normal form
add <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
in head
reference: http://thehackernews.com/2015/04/disable-mixed-content-warning.html
browser compatibility: http://caniuse.com/#feat=upgradeinsecurerequests
On Windows, if you're running PuTTY/Pageant, the fingerprint is listed when you load your PuTTY (.ppk) key into Pageant. It is pretty useful in case you forget which one you're using.
Try to save the .config file as utf-8 if you have some "special" characters in there. That was the issue in my case of a console application.
The inherit
value, when used, means that the value of the property is set to the value of the same property of the parent element. For the root element (in HTML documents, for the html
element) there is no parent element; by definition, the value used is the initial value of the property. The initial value is defined for each property in CSS specifications.
The font-family
property is special in the sense that the initial value is not fixed in the specification but defined to be browser-dependent. This means that the browser’s default font family is used. This value can be set by the user.
If there is a continuous chain of elements (in the sense of parent-child relationships) from the root element to the current element, all with font-family
set to inherit
or not set at all in any style sheet (which also causes inheritance), then the font is the browser default.
This is rather uninteresting, though. If you don’t set fonts at all, browsers defaults will be used. Your real problem might be different – you seem to be looking at the part of style sheets that constitute a browser style sheet. There are probably other, more interesting style sheets that affect the situation.
It may be easier. Try to think like this:
:
// 'www.dev.yyy.com'
// 'xxx.foo.pl'
var url = "xxx.foo.pl";
switch (url.match(/\..*.\./)[0]){
case ".dev.yyy." :
console.log("xxx.dev.yyy.com");break;
case ".some.":
console.log("xxx.foo.pl");break;
} //end switch
In httpd.conf, search for "ServerName". It's usually commented out by default on Mac. Just uncomment it and fill it in. Make sure you also have the name/ip combo set in /etc/hosts.
I found the solution of this problem and i should work i'm sure about this because i also face the same problem
here is my solution----->
var request = require('request');
//set url
var url = 'http://localhost:8088/example';
//set header
var headers = {
'Authorization': 'Your authorization'
};
//set form data
var form = {first_name: first_name, last_name: last_name};
//set request parameter
request.post({headers: headers, url: url, form: form, method: 'POST'}, function (e, r, body) {
var bodyValues = JSON.parse(body);
res.send(bodyValues);
});
To be even more pedantic, the most python doc consistent answer would be:
mypath = os.path.join('c:', os.sep, 'sourcedir')
Since you also need os.sep for the posix root path:
mypath = os.path.join(os.sep, 'usr', 'lib')
USE style="max-width:90%;"
<select name=countries style="max-width:90%;">
<option value=af>Afghanistan</option>
<option value=ax>Åland Islands</option>
...
<option value=gs>South Georgia and the South Sandwich Islands</option>
...
</select>
If you faced this probem in React, you need [email protected] and higher. Also for other environment variables than NODE_ENV
to work in React, they need to be prefixed with REACT_APP_
.
I think what you want requires an extra wrapper div.
#map {_x000D_
float: left; _x000D_
width: 700px; _x000D_
height: 500px;_x000D_
}_x000D_
#wrapper {_x000D_
float: left;_x000D_
width: 200px;_x000D_
}_x000D_
#list {_x000D_
background: #eee;_x000D_
list-style: none; _x000D_
padding: 0; _x000D_
}_x000D_
#similar {_x000D_
background: #000; _x000D_
}
_x000D_
<div id="map">Lorem Ipsum</div> _x000D_
<div id="wrapper">_x000D_
<ul id="list"><li>Dolor</li><li>Sit</li><li>Amet</li></ul>_x000D_
<div id ="similar">_x000D_
this text should be below, not next to ul._x000D_
</div>_x000D_
</div>
_x000D_
This could be unrelated to this specific problem, but I ran into a similar issue where I used NumPy indexing on a Python list and got the same exact error message:
# incorrect
weights = list(range(1, 129)) + list(range(128, 0, -1))
mapped_image = weights[image[:, :, band]] # image.shape = [800, 600, 3]
# TypeError: only integer scalar arrays can be converted to a scalar index
It turns out I needed to turn weights
, a 1D Python list, into a NumPy array before I could apply multi-dimensional NumPy indexing. The code below works:
# correct
weights = np.array(list(range(1, 129)) + list(range(128, 0, -1)))
mapped_image = weights[image[:, :, band]] # image.shape = [800, 600, 3]
Another option is to use summary function. It gives a summary of the Ts, Fs and NAs.
> summary(hival)
Mode FALSE TRUE NA's
logical 4367 53 2076
>
I know the question is about getting the day of week as string (e.g. the short name), but for anybody who is looking for the numeric day of week (as I was), you can use the new "u" format string, supported since Java 7. For example:
new SimpleDateFormat("u").format(new Date());
returns today's day-of-week index, namely: 1 = Monday, 2 = Tuesday, ..., 7 = Sunday.
If you are in a dev environment on OS X, connected via Wifi:
echo exec("/sbin/ifconfig en1 | grep 'inet ' | cut -d ' ' -f2");
For more conda list usage details:
usage: conda-script.py list [-h][-n ENVIRONMENT | -p PATH][--json] [-v] [-q]
[--show-channel-urls] [-c] [-f] [--explicit][--md5] [-e] [-r] [--no-pip][regex]
Unfortunately, it seems that proxy information must be set on each call to http.request
. Node does not include a mechanism for global proxy settings.
The global-tunnel-ng
module on NPM appears to handle this, however:
var globalTunnel = require('global-tunnel-ng');
globalTunnel.initialize({
host: '10.0.0.10',
port: 8080,
proxyAuth: 'userId:password', // optional authentication
sockets: 50 // optional pool size for each http and https
});
After the global settings are establish with a call to initialize
, both http.request
and the request
library will use the proxy information.
The module can also use the http_proxy
environment variable:
process.env.http_proxy = 'http://proxy.example.com:3129';
globalTunnel.initialize();
you need to use jboss-client.jar in your client project and you need to use jnp-client jar in your ejb project
If you must have a UITextField with 2 lines of text, one option is to add a UILabel as a subview of the UITextField for the second line of text. I have a UITextField in my app that users often do not realize is editable by tapping, and I wanted to add some small subtitle text that says "Tap to Edit" to the UITextField.
CGFloat tapLlblHeight = 10;
UILabel *tapEditLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, textField.frame.size.height - tapLlblHeight - 2, 70, tapLlblHeight)];
tapEditLbl.backgroundColor = [UIColor clearColor];
tapEditLbl.textColor = [UIColor whiteColor];
tapEditLbl.text = @"Tap to Edit";
[textField addSubview:tapEditLbl];
This is what I ended up going with:
>>>from time import strftime
>>>strftime("%m/%d/%Y %H:%M")
01/09/2015 13:11
Also, this table is a necessary reference for choosing the appropriate format codes to get the date formatted just the way you want it (from Python "datetime" documentation here).
Might I suggest you take a look at WMI (Windows Management Instrumentation). If you add the System.Management reference to your C# project, you'll gain access to the class `ManagementObjectSearcher', which you will probably find useful.
There are various WMI Classes for Installed Applications, but if it was installed with Windows Installer, then the Win32_Product class is probably best suited to you.
ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT * FROM Win32_Product");
New syntax (either):
test = df.sort_values(['one'], ascending=[False])
test = df.sort_values(['one'], ascending=[0])
What sort of things can cause these errors?
Doing naughty things with memory, e.g. writing after the end of a buffer, or writing to a buffer after it's been freed back to the heap.
How do I debug them?
Use an instrument which adds automated bounds-checking to your executable: i.e. valgrind on Unix, or a tool like BoundsChecker (Wikipedia suggests also Purify and Insure++) on Windows.
Beware that these will slow your application, so they may be unusable if yours is a soft-real-time application.
Another possible debugging aid/tool might be MicroQuill's HeapAgent.
This is actually on the main page of nltk.org:
>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']
<button class="btn" onClick="openDialog('New Type','Sample.html')">Middle</button>
<script type="text/javascript">
function openDialog(title,url) {
$('.opened-dialogs').dialog("close");
$('<div class="opened-dialogs">').html('loading...').dialog({
position: ['center',20],
open: function () {
$(this).load(url);
},
close: function(event, ui) {
$(this).remove();
},
title: title,
minWidth: 600
});
return false;
}
</script>
Click on settings in top tool bar;
Click on debugger;
In tree, highlight "gdb/cdb debugger" by clicking it
Click "create configuration"
Add "gdb.exe" (no quotes) as a configuration
Delete default configuration
Click on gdb.exe
that you created in the tree (it should be the only one) and a dialogue will appear to the right for "executable path" with a button to the right.
Click on that button and it will bring up the file that codeblocks is installed in. Just keep clicking until you create the path to the gdb.exe
(it sort of finds itself).
Based on the answers by Ben Carp and Wallace Sidhrée:
This is what I use to copy my entire build folder to my wamp public folder.
package.json
{
"name": "[your project name]",
"homepage": "http://localhost/[your project name]/",
"version": "0.0.1",
[...]
"scripts": {
"build": "react-scripts build",
"postbuild": "@powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./post_build.ps1",
[...]
},
}
post_build.ps1
Copy-Item "./build/*" -Destination "C:/wamp64/www/[your project name]" -Recurse -force
The homepage line is only needed if you are deploying to a subfolder on your server (See This answer from another question).
Here is the detailed explanation of why "Random.nextInt(n)
is both more efficient and less biased than Math.random() * n
" from the Sun forums post that Gili linked to:
Math.random() uses Random.nextDouble() internally.
Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53).
Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.
Prior to scaling by 6, the output of Math.random() is one of 2^53 possible values drawn from a uniform distribution.
Scaling by 6 doesn't alter the number of possible values, and casting to an int then forces these values into one of six 'buckets' (0, 1, 2, 3, 4, 5), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^53). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets.
You will be waiting a very long time rolling dice for this effect to show up.
Math.random() also requires about twice the processing and is subject to synchronization.
The Facebook API watches for the FB._apiKey so you can watch for this before calling your own application of the API with something like:
window.fbAsyncInit = function() {
FB.init({
//...your init object
});
function myUseOfFB(){
//...your FB API calls
};
function FBreadyState(){
if(FB._apiKey) return myUseOfFB();
setTimeout(FBreadyState, 100); // adjust time as-desired
};
FBreadyState();
};
Not sure this makes a difference but in my case--because I wanted to be sure the UI was ready--I've wrapped the initialization with jQuery's document ready (last bit above):
$(document).ready(FBreadyState);
Note too that I'm NOT using async = true to load Facebook's all.js, which in my case seems to be helping with signing into the UI and driving features more reliably.
You have to use the didSelectRow
delegate method, because a UIPickerView
can have an arbitrary number of components. There is no "objectValue" or anything like that, because that's entirely up to you.
It happened to me that the file .git/index was in use by another process (my local development web server). I shut down the process and then it worked.
Use setImmediate
if you want to queue the function behind whatever I/O event callbacks that are already in the event queue. Use process.nextTick
to effectively queue the function at the head of the event queue so that it executes immediately after the current function completes.
So in a case where you're trying to break up a long running, CPU-bound job using recursion, you would now want to use setImmediate
rather than process.nextTick
to queue the next iteration as otherwise any I/O event callbacks wouldn't get the chance to run between iterations.
The missing piece here is Data Conversion
object. It should be in between OLE DB Source and Destination object.
There are two ways to approach this problem: numerically and symbolically.
To solve it numerically, you have to first encode it as a "runnable" function - stick a value in, get a value out. For example,
def my_function(x):
return 2*x + 6
It is quite possible to parse a string to automatically create such a function; say you parse 2x + 6
into a list, [6, 2]
(where the list index corresponds to the power of x - so 6*x^0 + 2*x^1). Then:
def makePoly(arr):
def fn(x):
return sum(c*x**p for p,c in enumerate(arr))
return fn
my_func = makePoly([6, 2])
my_func(3) # returns 12
You then need another function which repeatedly plugs an x-value into your function, looks at the difference between the result and what it wants to find, and tweaks its x-value to (hopefully) minimize the difference.
def dx(fn, x, delta=0.001):
return (fn(x+delta) - fn(x))/delta
def solve(fn, value, x=0.5, maxtries=1000, maxerr=0.00001):
for tries in xrange(maxtries):
err = fn(x) - value
if abs(err) < maxerr:
return x
slope = dx(fn, x)
x -= err/slope
raise ValueError('no solution found')
There are lots of potential problems here - finding a good starting x-value, assuming that the function actually has a solution (ie there are no real-valued answers to x^2 + 2 = 0), hitting the limits of computational accuracy, etc. But in this case, the error minimization function is suitable and we get a good result:
solve(my_func, 16) # returns (x =) 5.000000000000496
Note that this solution is not absolutely, exactly correct. If you need it to be perfect, or if you want to try solving families of equations analytically, you have to turn to a more complicated beast: a symbolic solver.
A symbolic solver, like Mathematica or Maple, is an expert system with a lot of built-in rules ("knowledge") about algebra, calculus, etc; it "knows" that the derivative of sin is cos, that the derivative of kx^p is kpx^(p-1), and so on. When you give it an equation, it tries to find a path, a set of rule-applications, from where it is (the equation) to where you want to be (the simplest possible form of the equation, which is hopefully the solution).
Your example equation is quite simple; a symbolic solution might look like:
=> LHS([6, 2]) RHS([16])
# rule: pull all coefficients into LHS
LHS, RHS = [lh-rh for lh,rh in izip_longest(LHS, RHS, 0)], [0]
=> LHS([-10,2]) RHS([0])
# rule: solve first-degree poly
if RHS==[0] and len(LHS)==2:
LHS, RHS = [0,1], [-LHS[0]/LHS[1]]
=> LHS([0,1]) RHS([5])
and there is your solution: x = 5.
I hope this gives the flavor of the idea; the details of implementation (finding a good, complete set of rules and deciding when each rule should be applied) can easily consume many man-years of effort.
I have a simple solution is following the HTML basic.
<input
type="select"
defaultValue=""
>
<option value="" disabled className="text-hide">Please select</option>
<option>value1</option>
<option>value1</option>
</input>
.text-hide
is a bootstrap's class, if you not using bootstrap, here you are:
.text-hide {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
I copied a master.mdf und mastlog.ldf from another Computer (luckily, we have a lot of Clients with the same configuration, otherwise template data would be perhaps necessary). I backed up the damaged master.mdf and mastlog.mdf. After that I replaced the bad ones with the ones from another Computer. And it worked. I needed to start the MSSQLSERVER Service of course. But, after that I had Problem that the user was already existing but orphaned (error code 15023), I executed the query
USE Database_name EXEC sp_change_users_login 'Auto_Fix', 'username'
after that, everything was working smoothly. Hope this helps you and many thanks for this thread, saved me :)
I did a pull on my git repo:
git pull --rebase <repo> <branch>
Allowing git to pull in all the code for the branch and then I went to do a reset over to the commit that interested me.
git reset --hard <commit-hash>
Hope this helps.
Thanks, that helped me. I made some improvements and wrapped that in a helper script "finalurl":
#!/bin/bash
curl $1 -s -L -I -o /dev/null -w '%{url_effective}'
-o
output to /dev/null
-I
don't actually download, just discover the final URL-s
silent mode, no progressbarsThis made it possible to call the command from other scripts like this:
echo `finalurl http://someurl/`
Also for openCV in python you can do:
img = cv2.imread('myImage.jpg')
height, width, channels = img.shape
*first html page*
<form action="display.jsp" >
<input type="text" name="serialNumber" />
<input type="submit" value="Submit" />
</form>
*Second html page*
<body>
<p>The serial number is:<%=request.getParameter("serialNumber") %></p>
</body>
you will get the value of the textbox on another page.
The following lines are used to control the listen-port of a server, both are necessary:
<listen-port>7002</listen-port>
<listen-port-enabled>true</listen-port-enabled>
The call to InitializeComponent()
(which is usually called in the default constructor of at least Window
and UserControl
) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).
This method locates a URI to the XAML for the Window
/UserControl
that is loading, and passes it to the System.Windows.Application.LoadComponent()
static method. LoadComponent()
loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.
In more detail, LoadComponent
creates an instance of the XamlParser
, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode()
. This gets passed to the BamlRecordWriter
class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.
Note: Interestingly, the InitializeComponent
is a method on the System.Windows.Markup.IComponentConnector
interface, of which Window
/UserControl
implement in the partial generated class.
Hope this helps!
Use expandRows()
from the splitstackshape
package:
library(splitstackshape)
expandRows(df, "freq")
Simple syntax, very fast, works on data.frame
or data.table
.
Result:
var1 var2
1 a d
2 b e
2.1 b e
3 c f
3.1 c f
3.2 c f
Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript.
The CSS:
.carousel .item {-webkit-transition: opacity 3s; -moz-transition: opacity 3s; -ms-transition: opacity 3s; -o-transition: opacity 3s; transition: opacity 3s;}
.carousel .active.left {left:0;opacity:0;z-index:2;}
.carousel .next {left:0;opacity:1;z-index:1;}
I noticed however that the transition end event was firing prematurely with the default interval of 5s and a fade transition of 3s. Bumping the carousel interval to 8s provides a nice effect.
Very smooth.
You can solve your problem using JAIL plugin that also allows you to lazy load images (improving the page performance) and passing the callback as parameter
$('img').asynchImageLoader({callback : function(){...}});
The HTML should look like
<img name="/global/images/sample1.jpg" src="/global/images/blank.gif" width="width" height="height" />
I ran into a similar issue today - my ruby version didn't match my rvm installs.
> ruby -v
ruby 2.0.0p481
> rvm list
rvm rubies
ruby-2.1.2 [ x86_64 ]
=* ruby-2.2.1 [ x86_64 ]
ruby-2.2.3 [ x86_64 ]
Also, rvm current
failed.
> rvm current
Warning! PATH is not properly set up, '/Users/randallreed/.rvm/gems/ruby-2.2.1/bin' is not at first place...
The error message recommended this useful command, which resolved the issue for me:
> rvm get stable --auto-dotfiles
This is one "trick" you can do since your out of an async function so can't use await keywork
Do what you want to do with vm.feed inside a setTimeout
vm.feed = getFeed().then(function(data) {return data;});
setTimeout(() => {
// do you stuf here
// after the time you promise will be revolved or rejected
// if you need some of the values in here immediately out of settimeout
// might occur an error if promise wore not yet resolved or rejected
console.log("vm.feed",vm.feed);
}, 100);
Found this while digging for an answer:
SELECT REPLACE(
REPLACE(
REPLACE(
LTRIM(RTRIM('1 2 3 4 5 6'))
,' ',' '+CHAR(7))
,CHAR(7)+' ','')
,CHAR(7),'') AS CleanString
where charindex(' ', '1 2 3 4 5 6') > 0
The full answer (with explanation) was pulled from: http://techtipsbysatish.blogspot.com/2010/08/sql-server-replace-multiple-spaces-with.html
On second look, seems to be just a slightly different version of the selected answer.
The native dashed border property value does not offer control over the dashes themselves... so bring on the border-image
property!
border-image
Compatibility: It offers great browser support (IE 11 and all modern browsers). A normal border can be set as a fallback for older browsers.
These borders will display exactly the same cross-browser!
This example is 15 pixels wide by 15 pixels high and the gaps are currently 5px wide. It is a .png with transparency.
This is what it looks like in photoshop when zoomed in:
This is what it looks like to scale:
To create wider / shorter gaps or strokes, widen / shorten the gaps or strokes in the image.
Here is an image with wider 10px gaps:
correctly scaled =
Define the border-image-source:
border-image-source:url("http://i.stack.imgur.com/wLdVc.png");
Optional - Define the border-image-width:
border-image-width: 1;
The default value is 1. It can also be set with a pixel value, percentage value, or as another multiple (1x, 2x, 3x etc). This overrides any border-width
set.
Define the border-image-slice:
In this example, the thickness of the images top, right, bottom and left borders is 2px, and there is no gap outside of them, so our slice value is 2:
border-image-slice: 2;
The slices look like this, 2 pixels from the top, right, bottom and left:
Define the border-image-repeat:
In this example, we want the pattern to repeat itself evenly around our div. So we choose:
border-image-repeat: round;
Writing shorthand
The properties above can be set individually, or in shorthand using border-image:
border-image: url("http://i.stack.imgur.com/wLdVc.png") 2 round;
Note the border: dashed 4px #000
fallback. Non-supporting browsers will receive this border.
.bordered {_x000D_
display: inline-block;_x000D_
padding: 20px;_x000D_
/* Fallback dashed border_x000D_
- the 4px width here is overwritten with the border-image-width (if set)_x000D_
- the border-image-width can be omitted below if it is the same as the 4px here_x000D_
*/_x000D_
border: dashed 4px #000;_x000D_
_x000D_
/* Individual border image properties */_x000D_
border-image-source: url("http://i.stack.imgur.com/wLdVc.png");_x000D_
border-image-slice: 2;_x000D_
border-image-repeat: round; _x000D_
_x000D_
/* or use the shorthand border-image */_x000D_
border-image: url("http://i.stack.imgur.com/wLdVc.png") 2 round;_x000D_
}_x000D_
_x000D_
_x000D_
/*The border image of this one creates wider gaps*/_x000D_
.largeGaps {_x000D_
border-image-source: url("http://i.stack.imgur.com/LKclP.png");_x000D_
margin: 0 20px;_x000D_
}
_x000D_
<div class="bordered">This is bordered!</div>_x000D_
_x000D_
<div class="bordered largeGaps">This is bordered and has larger gaps!</div>
_x000D_
Solutions above didn't work. It simply displayed the last key/value pairs, but this did:
http://localhost/?key[]=1&key[]=2
Returns:
Array
(
[key] => Array
(
[0] => 1
[1] => 2
)
try:
gsub('\\$', '', '$5.00$')
Use Getdate()
select sum(transaction_amount) from TransactionMaster
where Card_No=' 123' and transaction_date =convert(varchar(10), getdate(), 102)
NP stands for Non-deterministic Polynomial time.
This means that the problem can be solved in Polynomial time using a Non-deterministic Turing machine (like a regular Turing machine but also including a non-deterministic "choice" function). Basically, a solution has to be testable in poly time. If that's the case, and a known NP problem can be solved using the given problem with modified input (an NP problem can be reduced to the given problem) then the problem is NP complete.
The main thing to take away from an NP-complete problem is that it cannot be solved in polynomial time in any known way. NP-Hard/NP-Complete is a way of showing that certain classes of problems are not solvable in realistic time.
Edit: As others have noted, there are often approximate solutions for NP-Complete problems. In this case, the approximate solution usually gives an approximation bound using special notation which tells us how close the approximation is.
For interpolated strings:
$"Int value: {someInt:D4} or {someInt:0000}. Float: {someFloat: 00.00}"
There is also BatteryTech which we've been using for the past 18 months and have released several games off of it. http://www.batterypoweredgames.com/batterytech
All C++, Android and iOS support, all users get full source. The new v2 includes lua bindings.
For Swift 3.0:
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
where "boldSystemFont" and "16" can be replaced with your custom font and size.
UPDATE ( SELECT t1.value, t2.CODE
FROM table1 t1
INNER JOIN table2 t2 ON t1.Value = t2.DESC
WHERE t1.UPDATETYPE='blah')
SET t1.Value= t2.CODE
Entirely from javacoffeebreak.com/faq/faq0012.html
A low priority thread takes care of garbage collection automatically for the user. During idle time, the thread may be called upon, and it can begin to free memory previously allocated to an object in Java. But don't worry - it won't delete your objects on you!
When there are no references to an object, it becomes fair game for the garbage collector. Rather than calling some routine (like free in C++), you simply assign all references to the object to null, or assign a new class to the reference.
Example :
public static void main(String args[]) { // Instantiate a large memory using class MyLargeMemoryUsingClass myClass = new MyLargeMemoryUsingClass(8192); // Do some work for ( .............. ) { // Do some processing on myClass } // Clear reference to myClass myClass = null; // Continue processing, safe in the knowledge // that the garbage collector will reclaim myClass }
If your code is about to request a large amount of memory, you may want to request the garbage collector begin reclaiming space, rather than allowing it to do so as a low-priority thread. To do this, add the following to your code
System.gc();
The garbage collector will attempt to reclaim free space, and your application can continue executing, with as much memory reclaimed as possible (memory fragmentation issues may apply on certain platforms).
void func (vector v)
Pass variables by value when the function needs complete isolation from the environment i.e. to prevent the function from modifying the original variable as well as to prevent other threads from modifying its value while the function is being executed.
The downside is the CPU cycles and extra memory spent to copy the object.
void func (const vector& v);
This form emulates pass-by-value behavior while removing the copying overhead. The function gets read access to the original object, but cannot modify its value.
The downside is thread safety: any change made to the original object by another thread will show up inside the function while it's still executing.
void func (vector& v)
Use this when the function has to write back some value to the variable, which will ultimately get used by the caller.
Just like the const reference case, this is not thread-safe.
void func (const vector* vp);
Functionally same as pass by const-reference except for the different syntax, plus the fact that the calling function can pass NULL pointer to indicate it has no valid data to pass.
Not thread-safe.
void func (vector* vp);
Similar to non-const reference. The caller typically sets the variable to NULL when the function is not supposed to write back a value. This convention is seen in many glibc APIs. Example:
void func (string* str, /* ... */) {
if (str != NULL) {
*str = some_value; // assign to *str only if it's non-null
}
}
Just like all pass by reference/pointer, not thread-safe.
For the Android platform, you can try ShowJava, available on the Play Store.
You can consult the generated code through the app interface and the generated java files and folders structure are stored in ShowJava
folder in /sdcard
, alongside the resulting .jar
file from the conversion.
The app is free with an ad banner at the bottom of the main view, but there is an in-app purchase option (3,99$) to remove it. In-app purchase does not add any functionality beside removing the ad banner.
Disclosure : I'm not the developer of the app neither I'm affiliated with him in any way.
To clear only certain parameters, you can use:
[:param1, :param2, :param3].each { |k| session.delete(k) }
If you want to show error messages on form submission, you can use condition form.$submitted
to check if an attempt was made to submit the form. Check following example.
<form name="myForm" novalidate ng-submit="myForm.$valid && createUser()">
<input type="text" name="name" ng-model="user.name" placeholder="Enter name of user" required>
<div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
<div ng-message="required">Please enter user name.</div>
</div>
<input type="text" name="address" ng-model="user.address" placeholder="Enter Address" required ng-maxlength="30">
<div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
<div ng-message="required">Please enter user address.</div>
<div ng-message="maxlength">Should be less than 30 chars</div>
</div>
<button type="submit">
Create user
</button>
</form>
The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.
<p align="center">
<img alt="img-name" src="/path/image-name.png" width="300">
<br>
<em>caption</em>
</p>
That is the basic caption use. Not necessary to use an extra plugin.
For me, it wasn't just getting the javadoc window to open, but also getting the complete javadoc to present. You may still get a sparse javadoc that is based solely on the method signature if you are importing libraries from a Maven repository and do not tell Idea to include the javadocs in the download. Be sure to tick the "JavaDocs" option in the "Download Library From Maven Repository" dialog, which can be found under Project Structure -> Projtect Settings -> Libraries.
Nick Craver's solution gave me what I needed but to make it explicit for those using CSS-in-JS:
const styles = {
yourClass: {
/* Styles for all elements with this class */
'&:not(:last-child)': {
/* Styles for all EXCEPT the last element with this class */
},
},
};
in windows by xampp i just changed:
;memory_limit=512M
in php.ini to:
memory_limit =-1
then restart the Apache by xampp
this is the result:
; Maximum amount of memory a script may consume
; http://php.net/memory-limit
memory_limit =-1
;memory_limit=512M
dirname(__FILE__)
will give the absolute route of the current file from which you are demanding the route, the route of your server directory.
example files :
www/http/html/index.php ; if you place this code inside your index.php it will return:
<?php
echo dirname(__FILE__); // this will return: www/http/html/
www/http/html/class/myclass.php ; if you place this code inside your myclass.php it will return:
<?php
echo dirname(__FILE__); // this will return: www/http/html/class/
If I understood your question, try something like this
declare @dd varchar(50)='Jan 30 2013 12:00:00:000AM'
Select convert(varchar,(CONVERT(date,@dd,103)),103)
Update
SELECT
PREFIX_TableName.ColumnName1 AS Name,
PREFIX_TableName.ColumnName2 AS E-Mail,
convert(varchar,(CONVERT(date,PREFIX_TableName.ColumnName3,103)),103) AS TransactionDate,
PREFIX_TableName.ColumnName4 AS OrderNumber
Ok, instead of identifying players by name track with sockets through which they have connected. You can have a implementation like
var allClients = [];
io.sockets.on('connection', function(socket) {
allClients.push(socket);
socket.on('disconnect', function() {
console.log('Got disconnect!');
var i = allClients.indexOf(socket);
allClients.splice(i, 1);
});
});
Hope this will help you to think in another way
function setToggleInputsinPnl(pnlName) {
var domCount = pnlName.length;
for (var i = 0; i < domCount; i++) {
if (pnlName[i].type == 'text') {
pnlName[i].value = '';
} else if (pnlName[i].type == 'select-one') {
pnlName[i].value = '';
}
}
}
$().ready(function(){_x000D_
_x000D_
$('div.alert').delay(1500);_x000D_
$('div.alert').hide(1000);_x000D_
});
_x000D_
div.alert{_x000D_
color: green;_x000D_
background-color: rgb(50,200,50, .5);_x000D_
padding: 10px;_x000D_
text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="alert"><p>Inserted Successfully . . .</p></div>
_x000D_
If you have new project on GitHub which has .travis.yml, but was never tested, you can run tests without commit this way:
Refer to MySQL 8.0 Reference Manual -- 6.1.6 Security Issues with LOAD DATA LOCAL
On the server side, run
mysql.server start --local-infile
On the client side, run
mysql --local-infile database_name -u username -p
There are a few yet to be mentioned techniques available for you. Start with setting the contentType property in your ajax params.
Building on pradeek's example:
$('form').submit(function (e) {
var data;
data = new FormData();
data.append('file', $('#file')[0].files[0]);
$.ajax({
url: 'http://hacheck.tel.fer.hr/xml.pl',
data: data,
processData: false,
type: 'POST',
// This will override the content type header,
// regardless of whether content is actually sent.
// Defaults to 'application/x-www-form-urlencoded'
contentType: 'multipart/form-data',
//Before 1.5.1 you had to do this:
beforeSend: function (x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("multipart/form-data");
}
},
// Now you should be able to do this:
mimeType: 'multipart/form-data', //Property added in 1.5.1
success: function (data) {
alert(data);
}
});
e.preventDefault();
});
In some cases when forcing jQuery ajax to do non-expected things, the beforeSend
event is a great place to do it. For a while people were using beforeSend
to override the mimeType before that was added into jQuery in 1.5.1. You should be able to modify just about anything on the jqXHR object in the before send event.
Simply call InetAddress.getByName(String host)
passing in your textual IP address.
From the javadoc: The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address.
You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
And then you can use returned string with Google Gson to map JSON to object of specified class, like this:
String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);
There is a sample of AuthMsg class:
public class AuthMsg {
private int code;
private String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
JSON returned by http://localhost/authmanager.php must look like this:
{"code":1,"message":"Logged in"}
Regards
Have you taken a look at this Java Tutorial?
Further, I'd advise you to stay the heck away from playing with this kind of stuff in real software. It's good to play with it so you know what it is, but concurrency has pitfalls all over the place. It's better to use higher level abstractions and synchronized collections or JMS queues if you are building software for other people.
That is at least what I do. I'm not a concurrency expert so I stay away from handling threads by hand wherever possible.
You are using <input name='C[]'
in your HTML. This creates an array in PHP when the form is sent.
You are using echo $_POST['C'];
to echo that array - this will not work, but instead emit that notice and the word "Array".
Depending on what you did with the rest of the code, you should probably use echo $_POST['C'][0];
in python intended block mean there is every thing must be written in manner in my case I written it this way
def btnClick(numbers):
global operator
operator = operator + str(numbers)
text_input.set(operator)
Note.its give me error,until I written it in this way such that "giving spaces " then its giving me a block as I am trying to show you in function below code
def btnClick(numbers):
___________________________
|global operator
|operator = operator + str(numbers)
|text_input.set(operator)
Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.
This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.
The HttpSession#setMaxInactiveInterval()
doesn't change much here by the way. It does exactly the same as <session-timeout>
in web.xml
, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static
method).
To play around and experience this yourself, try to set <session-timeout>
to 1 minute and create a HttpSessionListener
like follows:
@WebListener
public class HttpSessionChecker implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
}
public void sessionDestroyed(HttpSessionEvent event) {
System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
}
}
(if you're not on Servlet 3.0 yet and thus can't use @WebListener
, then register in web.xml
as follows):
<listener>
<listener-class>com.example.HttpSessionChecker</listener-class>
</listener>
Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed
line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.
I recently made an Mediaplayer application and I used API-calls to make sure the taskbar was hidden when the program was running fullscreen and then restored the taskbar when the program was not in fullscreen or not had focus or was exited.
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Integer, ByVal hWnd2 As Integer, ByVal lpsz1 As String, ByVal lpsz2 As String) As Integer
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Integer, ByVal nCmdShow As Integer) As Integer
Sub HideTrayBar()
Try
Dim tWnd As Integer = 0
Dim bWnd As Integer = 0
tWnd = FindWindow("Shell_TrayWnd", vbNullString)
bWnd = FindWindowEx(tWnd, bWnd, "BUTTON", vbNullString)
ShowWindow(tWnd, 0)
ShowWindow(bWnd, 0)
Catch ex As Exception
'Error hiding the taskbar, do what you want here..
End Try
End Sub
Sub ShowTraybar()
Try
Dim tWnd As Integer = 0
Dim bWnd As Integer = 0
tWnd = FindWindow("Shell_TrayWnd", vbNullString)
bWnd = FindWindowEx(tWnd, bWnd, "BUTTON", vbNullString)
ShowWindow(bWnd, 1)
ShowWindow(tWnd, 1)
Catch ex As Exception
'Error showing the taskbar, do what you want here..
End Try
End Sub
Check host file which like this
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
# extract numbers from garbage string:
s = '12//n,_@#$%3.14kjlw0xdadfackvj1.6e-19&*ghn334'
newstr = ''.join((ch if ch in '0123456789.-e' else ' ') for ch in s)
listOfNumbers = [float(i) for i in newstr.split()]
print(listOfNumbers)
[12.0, 3.14, 0.0, 1.6e-19, 334.0]
I followed the shaobin0604's answer and I finally managed to lock the HOME button, by adding:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
to AndroidManifest.xml
All you have to do is to copy HomeKeyLocker.java
from shaobin's lib to your project and implement it like in shaobin's example. BTW: My AVD's Android version is Android 4.0.3.
Rollback... will prompt you to select a folder to rollback, ie, it will work on specific folders, and you can rollback to labels or changlists or dates. Back out works on the files in specific changelists.
Bitmap bmp = new Bitmap("filename.bmp");
RectangleF rectf = new RectangleF(70, 90, 90, 50);
Graphics g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf);
g.Flush();
image.Image=bmp;
Uncheck Always Show Toolbar in Full Screen
in View
menu:
and go to fullscreen then:
Alt+Cmd+F - on Mac
F11 - on Windows
import UIKit
class TabbarViewController: UITabBarController,UITabBarControllerDelegate {
//MARK:- View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//Tabbar delegate method
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
let yourView = self.viewControllers![self.selectedIndex] as! UINavigationController
yourView.popToRootViewController(animated:false)
}
}
I was having a similar issue with my button. I included line-height: 0;
and it appears to have worked. Also mentioned by @anddero.
button[type=submit] {
background-color: #4056A1;
border-radius: 12px;
border: 1px solid #4056A1;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 2px 1px;
cursor: pointer;
display: inline-block;
font-size: 16px;
height: 20px;
line-height: 0;
}
--simple codes--
#region odd / even numbers order by desc
//declaration of integer
int TotalCount = 50;
int loop;
Console.WriteLine("\n---------Odd Numbers -------\n");
for (loop = TotalCount; loop >= 0; loop--)
{
if (loop % 2 == 0)
{
Console.WriteLine("Even numbers : #{0}", loop);
}
}
Console.WriteLine("\n---------Even Numbers -------\n");
for (loop = TotalCount; loop >= 0; loop--)
{
if (loop % 2 != 0)
{
Console.WriteLine("odd numbers : #{0}", loop);
}
}
Console.ReadLine();
#endregion
The only thing you can do is obfuscate your code to make it more difficult to read. No matter what you do, if you want the javascript to execute in their browser they'll have to have the code.
Best way to find this is: create a php file and add the following code:
<?php phpinfo(); ?>
and open it in browser, it will show the file which is actually being read!
Updates by OP:
<?php echo php_ini_loaded_file(); ?>
mentioned in this answer.Use:
File.open("out.txt", [your-option-string]) {|f| f.write("write your stuff here") }
where your options are:
r
- Read only. The file must exist. w
- Create an empty file for writing. a
- Append to a file.The file is created if it does not exist. r+
- Open a file for update both reading and writing. The file must exist. w+
- Create an empty file for both reading and writing. a+
- Open a file for reading and appending. The file is created if it does not exist. In your case, 'w'
is preferable.
OR you could have:
out_file = File.new("out.txt", "w")
#...
out_file.puts("write your stuff here")
#...
out_file.close
This error usually occurs if you have not included the xmlns:mm
properly, it occurs usually in the first line of code.
for me it was..
xmlns:mm="http://millennialmedia.com/android/schema"
that i missed in first line of the code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mm="http://millennialmedia.com/android/schema"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="50dp"
android:layout_marginBottom="50dp"
android:background="@android:color/transparent" >
if you have two maps lets say map1 and map2 then using java8 Streams,we can compare maps using code below.But it is recommended to use equals rather then != or ==
boolean b = map1.entrySet().stream().filter(value ->
map2.entrySet().stream().anyMatch(value1 ->
(value1.getKey().equals(value.getKey()) &&
value1.getValue().equals(value.getValue())))).findAny().isPresent();
System.out.println("comparison "+b);
Try this
=IIF(IsNothing(Fields!MyField.Value)=TRUE,"NA",Fields!MyFields.Value)
Here is a function that does the conversion of a PDF file with one or multiple pages to a single merged JPEG image.
import os
import tempfile
from pdf2image import convert_from_path
from PIL import Image
def convert_pdf_to_image(file_path, output_path):
# save temp image files in temp dir, delete them after we are finished
with tempfile.TemporaryDirectory() as temp_dir:
# convert pdf to multiple image
images = convert_from_path(file_path, output_folder=temp_dir)
# save images to temporary directory
temp_images = []
for i in range(len(images)):
image_path = f'{temp_dir}/{i}.jpg'
images[i].save(image_path, 'JPEG')
temp_images.append(image_path)
# read images into pillow.Image
imgs = list(map(Image.open, temp_images))
# find minimum width of images
min_img_width = min(i.width for i in imgs)
# find total height of all images
total_height = 0
for i, img in enumerate(imgs):
total_height += imgs[i].height
# create new image object with width and total height
merged_image = Image.new(imgs[0].mode, (min_img_width, total_height))
# paste images together one by one
y = 0
for img in imgs:
merged_image.paste(img, (0, y))
y += img.height
# save merged image
merged_image.save(output_path)
return output_path
Example usage: -
convert_pdf_to_image("path_to_Pdf/1.pdf", "output_path/output.jpeg")
Thanks for all answers above, but for me, I can not find Base64Encoder class, so I sort out my way anyway.
public static void main(String[] args) {
try {
DefaultHttpClient Client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("https://httpbin.org/basic-auth/user/passwd");
String encoding = DatatypeConverter.printBase64Binary("user:passwd".getBytes("UTF-8"));
httpGet.setHeader("Authorization", "Basic " + encoding);
HttpResponse response = Client.execute(httpGet);
System.out.println("response = " + response);
BufferedReader breader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder responseString = new StringBuilder();
String line = "";
while ((line = breader.readLine()) != null) {
responseString.append(line);
}
breader.close();
String repsonseStr = responseString.toString();
System.out.println("repsonseStr = " + repsonseStr);
} catch (IOException e) {
e.printStackTrace();
}
}
One more thing, I also tried
Base64.encodeBase64String("user:passwd".getBytes());
It does NOT work due to it return a string almost same with
DatatypeConverter.printBase64Binary()
but end with "\r\n", then server will return "bad request".
Also following code is working as well, actually I sort out this first, but for some reason, it does NOT work in some cloud environment (sae.sina.com.cn if you want to know, it is a chinese cloud service). so have to use the http header instead of HttpClient credentials.
public static void main(String[] args) {
try {
DefaultHttpClient Client = new DefaultHttpClient();
Client.getCredentialsProvider().setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("user", "passwd")
);
HttpGet httpGet = new HttpGet("https://httpbin.org/basic-auth/user/passwd");
HttpResponse response = Client.execute(httpGet);
System.out.println("response = " + response);
BufferedReader breader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder responseString = new StringBuilder();
String line = "";
while ((line = breader.readLine()) != null) {
responseString.append(line);
}
breader.close();
String responseStr = responseString.toString();
System.out.println("responseStr = " + responseStr);
} catch (IOException e) {
e.printStackTrace();
}
}
I agree that in 95% of cases, all you need is sudo yum update openssl
However, if you need a specific version of openssl or specific functionality, which is not in CentOS repository, you probably need to compile from source. The other answers here were incomplete. Below is what worked (CentOS 6.9), although this may introduce incompatibilities with installed software, and will not auto-update the openssl.
Choose openssl version from https://www.openssl.org/source/
Log-in as root:
cd /usr/local/src/
# OPTIONALLY CHANGE openssl-1.1.0f.tar.gz to the version which you want
wget https://www.openssl.org/source/openssl-1.1.0f.tar.gz
sha256sum openssl-1.1.0f.tar.gz #confirm this matches the published hash
tar -zxf openssl-1.1.0f.tar.gz
cd /usr/local/src/openssl-1.1.0f
./config --prefix=/usr/local --openssldir=/usr/local/openssl
make
make test
make install
export LD_LIBRARY_PATH=/usr/local/lib64
#make export permanent
echo "export LD_LIBRARY_PATH=/usr/local/lib64" > /etc/profile.d/ld_library_path.sh
chmod ugo+x /etc/profile.d/ld_library_path.sh
openssl version #confirm it works
#recommended reboot here
openssl version #confirm it works after reboot
The echo -e
must have been failing for you because of wrong escaping.
The following code works fine for me on a similar output from your_program with arguments
:
echo -e $(your_program with arguments | sed -e 's/0x\(..\)\.\?/\\x\1/g')
Please note however that your original hexstring consists of non-printable characters.
if you're using jQuery you would have:
$('#elementId').change(function() { alert('Do Stuff'); });
or MS AJAX:
$addHandler($get('elementId'), 'change', function(){ alert('Do Stuff'); });
Or in the raw HTML of the element:
<input type="text" onchange="alert('Do Stuff');" id="myElement" />
After re-reading the question I think I miss-read what was to be done. I've never found a way to update a DOM element in a manner which will force a change event, what you're best doing is having a separate event handler method, like this:
$addHandler($get('elementId'), 'change', elementChanged);
function elementChanged(){
alert('Do Stuff!');
}
function editElement(){
var el = $get('elementId');
el.value = 'something new';
elementChanged();
}
Since you're already writing a JavaScript method which will do the changing it's only 1 additional line to call.
Or, if you are using the Microsoft AJAX framework you can access all the event handlers via:
$get('elementId')._events
It'd allow you to do some reflection-style workings to find the right event handler(s) to fire.
When I try to set Base Memory around 4000MB (my pc have 8GB) I get the same error 'VT-x is disabled in the BIOS'. But when I reduce Base Memory to 2500MB it works and error is solved.
From http://php.quicoto.com/inline-ifelse-statement-ngclick-angularjs/, this is how you do it, if you really have to:
ng-click="variable = (condition=='X' ? 'Y' : 'X')"
I had this same issue but found the following that works great:
The key to creating a responsive YouTube embed is with padding and a container element, which allows you to give it a fixed aspect ratio. You can also use this technique with most other iframe-based embeds, such as slideshows.
Here is what a typical YouTube embed code looks like, with fixed width and height:
<iframe width="560" height="315" src="//www.youtube.com/embed/yCOY82UdFrw"
frameborder="0" allowfullscreen></iframe>
It would be nice if we could just give it a 100% width, but it won't work as the height remains fixed. What you need to do is wrap it in a container like so (note the class names and removal of the width and height):
<div class="container">
<iframe src="//www.youtube.com/embed/yCOY82UdFrw"
frameborder="0" allowfullscreen class="video"></iframe>
</div>
And use the following CSS:
.container {
position: relative;
width: 100%;
height: 0;
padding-bottom: 56.25%;
}
.video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
Here is the page I found the solution on:
https://www.h3xed.com/web-development/how-to-make-a-responsive-100-width-youtube-iframe-embed
Depending on your aspect ratio, you will probably need to adjust the padding-bottom: 56.25%;
to get the height right.
After doing the steps which were mentioned by @Ravindra Bagale,
Try this step.
Server name: localhost\{Instance name you were gave}
select <column list> into <table name> from <source> where <whereclause>
because of your a and b variable is not have been initialized. You must initialized this variables for excample if you declare this variable like this int a=0; int b=0; than your code run without error.
var div = document.createElement("div");_x000D_
div.style.width = "100px";_x000D_
div.style.height = "100px";_x000D_
div.style.background = "red";_x000D_
div.style.color = "white";_x000D_
div.innerHTML = "Hello";_x000D_
_x000D_
document.getElementById("main").appendChild(div);
_x000D_
<body>_x000D_
<div id="main"></div>_x000D_
</body>
_x000D_
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello";
document.getElementById("main").appendChild(div);
OR
document.body.appendChild(div);
Use parent reference instead of document.body
.
The Android SDK doesn't come with any easy way to draw text on OpenGL views. Leaving you with the following options.
You can use another overload of the DropDownList
method. Pick the one you need and pass in
a object with your html attributes.
@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })
I didnt try Sumama Waheed's answer but what worked for me was replacing the bin/catalina.jar with a working jar (I disposed of an older tomcat) and after adding in NetBeans, I put the original catalina.jar again.
Add a background-attachment
line:
#background {
background-attachment:fixed;
width: 100%;
height: 100%;
position: absolute;
margin-left: 0px;
margin-top: 0px;
z-index: 0;
}
.stretch {
width:100%;
height:auto;
}
This is equivalent to the path of the script:
%~dp0
This uses the batch parameter extension syntax. Parameter 0 is always the script itself.
If your script is stored at C:\example\script.bat
, then %~dp0
evaluates to C:\example\
.
ss64.com has more information about the parameter extension syntax. Here is the relevant excerpt:
You can get the value of any parameter using a % followed by it's numerical position on the command line.
[...]
When a parameter is used to supply a filename then the following extended syntax can be applied:
[...]
%~d1 Expand %1 to a Drive letter only - C:
[...]
%~p1 Expand %1 to a Path only e.g. \utils\ this includes a trailing \ which may be interpreted as an escape character by some commands.
[...]
The modifiers above can be combined:
%~dp1 Expand %1 to a drive letter and path only
[...]
You can get the pathname of the batch script itself with %0, parameter extensions can be applied to this so %~dp0 will return the Drive and Path to the batch script e.g. W:\scripts\
Simple Solution, This works with All Browsers,
var StringDate = "24-11-2017"
var DateVar = StringDate.split("-");
var DateVal = new Date(DateVar[1] + "/" + DateVar[0] + "/" + DateVar[2]);
alert(DateVal);
For iOS 8 we can just use this [UIScreen mainScreen].nativeBounds
, like that:
- (NSInteger)resolutionX
{
return CGRectGetWidth([UIScreen mainScreen].nativeBounds);
}
- (NSInteger)resolutionY
{
return CGRectGetHeight([UIScreen mainScreen].nativeBounds);
}
package com.test;
import java.util.ArrayList;
import java.util.List;
public class TEst {
public static void main(String[] args) {
List<Integer> ls=new ArrayList<>();
ls.add(1);
ls.add(2);
List<Integer> ls1=new ArrayList<>();
ls1.add(3);
ls1.add(4);
List<List<Integer>> ls2=new ArrayList<>();
ls2.add(ls);
ls2.add(ls1);
List<List<List<Integer>>> ls3=new ArrayList<>();
ls3.add(ls2);
m1(ls3);
}
private static void m1(List ls3) {
for(Object ls4:ls3)
{
if(ls4 instanceof List)
{
m1((List)ls4);
}else {
System.out.print(ls4);
}
}
}
}
It can be done with simple commands in the following snippet.
Copies the whole file of any size. No size constraint!
Just use this. Tested And Working!!
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream infile;
infile.open("source.pdf",ios::binary|ios::in);
ofstream outfile;
outfile.open("temppdf.pdf",ios::binary|ios::out);
int buffer[2];
while(infile.read((char *)&buffer,sizeof(buffer)))
{
outfile.write((char *)&buffer,sizeof(buffer));
}
infile.close();
outfile.close();
return 0;
}
Having a smaller buffer size would be helpful in copying tiny files. Even "char buffer[2]" would do the job.
all the above @Uday's code is perfect but only one thing is missing(default config in build.gradle)
public void setLocale(String lang) {
Locale myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(this, AndroidLocalize.class);
finish();
startActivity(refresh);
}
Mine was not working just because the languages were not mentioned in the config file(build.gradle)
defaultConfig {
resConfigs "en", "hi", "kn"
}
after that, all languages started running
anhdevit's suggestion in https://github.com/facebook/react-native/issues/24363#issuecomment-488547280 worked for me:
In your terminal, run:
defaults delete com.apple.dt.Xcode
Can you post a link to the HTML in question?
Ultimately you should be able to do:
div {
margin:0;
padding: 0;
}
to remove the spacing. Is this just in one particular browser or all of them?
Using only "native" Windows utilities, try the following, where "516" is the process ID that you want the image name for:
for /f "delims=," %a in ( 'tasklist /fi "PID eq 516" /nh /fo:csv' ) do ( echo %~a )
for /f %a in ( 'tasklist /fi "PID eq 516" ^| findstr "516"' ) do ( echo %a )
Or you could use wmic (the Windows Management Instrumentation Command-line tool) and get the full path to the executable:
wmic process where processId=516 get name
wmic process where processId=516 get ExecutablePath
Or you could download Microsoft PsTools, or specifically download just the pslist utility, and use PsList:
for /f %a in ( 'pslist 516 ^| findstr "516"' ) do ( echo %a )
When you use recv
in connection with select
if the socket is ready to be read from but there is no data to read that means the client has closed the connection.
Here is some code that handles this, also note the exception that is thrown when recv
is called a second time in the while loop. If there is nothing left to read this exception will be thrown it doesn't mean the client has closed the connection :
def listenToSockets(self):
while True:
changed_sockets = self.currentSockets
ready_to_read, ready_to_write, in_error = select.select(changed_sockets, [], [], 0.1)
for s in ready_to_read:
if s == self.serverSocket:
self.acceptNewConnection(s)
else:
self.readDataFromSocket(s)
And the function that receives the data :
def readDataFromSocket(self, socket):
data = ''
buffer = ''
try:
while True:
data = socket.recv(4096)
if not data:
break
buffer += data
except error, (errorCode,message):
# error 10035 is no data available, it is non-fatal
if errorCode != 10035:
print 'socket.error - ('+str(errorCode)+') ' + message
if data:
print 'received '+ buffer
else:
print 'disconnected'
You can use mosquitto_sub
(which is part of the mosquitto-clients
package) and subscribe to the wildcard topic #
:
mosquitto_sub -v -h broker_ip -p 1883 -t '#'
This may be a somewhat limited solution, but does the job using the system's diff
command without external tools:
diff -y <(git show from-rev:the/file/path) <(git show to-rev:the/file/path)
--suppress-common-lines
(if your diff
supports the option).diff
markers--width=term-width
; in Bash can get the width as $COLUMNS
or tput cols
.This can be wrapped into a helper git-script too for more convenience, for example, usage like this:
git diffy the/file/path --from rev1 --to rev2
As wikipedia states algorithm for the leap year should be
(((year%4 == 0) && (year%100 !=0)) || (year%400==0))
Here is a sample program how to check for leap year.
Use the .Clear
method.
Sheets("Test").Range("A1:C3").Clear
With a simple for
loop:
for _, v := range myconfig {
if v.Key == "key1" {
// Found!
}
}
Note that since element type of the slice is a struct
(not a pointer), this may be inefficient if the struct type is "big" as the loop will copy each visited element into the loop variable.
It would be faster to use a range
loop just on the index, this avoids copying the elements:
for i := range myconfig {
if myconfig[i].Key == "key1" {
// Found!
}
}
Notes:
It depends on your case whether multiple configs may exist with the same key
, but if not, you should break
out of the loop if a match is found (to avoid searching for others).
for i := range myconfig {
if myconfig[i].Key == "key1" {
// Found!
break
}
}
Also if this is a frequent operation, you should consider building a map
from it which you can simply index, e.g.
// Build a config map:
confMap := map[string]string{}
for _, v := range myconfig {
confMap[v.Key] = v.Value
}
// And then to find values by key:
if v, ok := confMap["key1"]; ok {
// Found
}
iOs 10+ allow video autoplay inline. but you have to turn off "Low power mode" on your iPhone.
Without VBA...
If you can use a helper column, you can use the MATCH
function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match
To simply identify duplicates, use a helper column
Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:
=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")
Drag/copy this forumla down, and it should identify the duplicates.
To highlight cells, use conditional formatting:
With some tinkering, you can use this MATCH
function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.
Something like:
=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))
For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:
=B1="Duplicate"
This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.
When I tried to create something simillar to inbox floating action button i thought about creating own custom component.
It would be simple frame layout with fixed height (to contain expanded menu) containing FAB button and 3 more placed under the FAB. when you click on FAB you just simply animate other buttons to translate up from under the FAB.
There are some libraries which do that (for example https://github.com/futuresimple/android-floating-action-button), but it's always more fun if you create it by yourself :)
INSERT INTO LOCATION VALUES(PQ95VM,'HAPPY_STREET','FRANCE');
the above mentioned code is not correct because your first parameter POSTCODE is of type VARCHAR(10)
. you should have used ' '
.
try INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');
You could use a bit of jQuery:
$('input:radio').click(function(){
$('label#' + $(this).attr('id')).toggleClass('checkedClass'); // checkedClass is defined in your CSS
});
You'd need to make sure your checked radio buttons have the correct class on page load as well.
I am working on an angular js app, andhavecome across a similar issue. What i did was display the image from the db, then created a button to remove or keep the current image. If the user decided to keep the current image, i changed the ng-submit attribute to another function whihc doesnt require image validation, and updated the record in the db without touching the original image path name. The remove image function also changed the ng-submit attribute value back to a function that submits the form and includes image validation and upload. Also a bit of javascript to slide the into view to upload a new image.
The title
attribute displays a tooltip when the mouse is hovering the element. While this is a great addition, it doesn't help people who cannot use the mouse (due to mobility disabilities) or people who can't see this tooltip (e.g.: people with visual disabilities or people who use a screen reader).
As such, the mindful approach here would be to serve all users. I would add both title
and aria-label
attributes (serving different types of users and different types of usage of the web).
Here's a good article that explains aria-label
in depth
So, after I created my question, I got this related list on the right with a similar issue: Organize routes in Node.js.
The answer in that post linked to the Express repo on GitHub and suggests to look at the 'route-separation' example.
This helped me change my code, and I now have it working. - Thanks for your comments.
My implementation ended up looking like this;
I require my routes in the app.js:
var express = require('express')
, site = require('./site')
, wiki = require('./wiki');
And I add my routes like this:
app.get('/', site.index);
app.get('/wiki/:id', wiki.show);
app.get('/wiki/:id/edit', wiki.edit);
I have two files called wiki.js and site.js in the root of my app, containing this:
exports.edit = function(req, res) {
var wiki_entry = req.params.id;
res.render('wiki/edit', {
title: 'Editing Wiki',
wiki: wiki_entry
})
}
Your best bet is KissFFT - as its name implies it's simple, but it's still quite respectably fast, and a lot more lightweight than FFTW. It's also free, wheras FFTW requires a hefty licence fee if you want to include it in a commercial product.
Here's in javascript: (For example, the future date is New Year's Day)
DEMO (updates every second)
var dateFuture = new Date(new Date().getFullYear() +1, 0, 1);
var dateNow = new Date();
var seconds = Math.floor((dateFuture - (dateNow))/1000);
var minutes = Math.floor(seconds/60);
var hours = Math.floor(minutes/60);
var days = Math.floor(hours/24);
hours = hours-(days*24);
minutes = minutes-(days*24*60)-(hours*60);
seconds = seconds-(days*24*60*60)-(hours*60*60)-(minutes*60);
Based on information found at http://www.windows-tech.info/3/53ee08e46d9cb138.php, I was able to achieve a translucent panel control using the following code.
public class TransparentPanel : Panel
{
protected override CreateParams CreateParams
{
get
{
var cp = base.CreateParams;
cp.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT
return cp;
}
}
protected override void OnPaint(PaintEventArgs e) =>
e.Graphics.FillRectangle(new SolidBrush(this.BackColor), this.ClientRectangle);
}
The caveat is that any controls that are added to the panel have an opaque background. Nonetheless, the translucent panel was useful for me to block off parts of my WinForms application so that users focus was shifted to the appropriate area of the application.
Here is PostgreSQL example without trigger if someone need it on PostgreSQL:
CREATE SEQUENCE messages_seq;
CREATE TABLE IF NOT EXISTS messages (
id CHAR(20) NOT NULL DEFAULT ('message_' || nextval('messages_seq')),
name CHAR(30) NOT NULL,
);
ALTER SEQUENCE messages_seq OWNED BY messages.id;
An update in case what you really need can be covered by having the file included in a checkout of another folder.
Since SVN 1.6 you can make file externals, a kind of svn links. It means that you can have another versioned folder that includes a single file. Committing changes to the file in a checkout of this folder is also possible.
It's very simple, checkout the folder you want to include the file, and simply add a property to the folder
svn propedit svn:externals .
with content like this:
file.txt /repos/path/to/file.txt
After you commit this, the file will appear in future checkouts of the folder. Basically it works, but there are some limitations as described in the documentation linked above.
Phoronix did some benchmarks about this, but it is about a snapshot version of Clang/LLVM from a few months back. The results being that things were more-or-less a push; neither GCC nor Clang is definitively better in all cases.
Since you'd use the latest Clang, it's maybe a little less relevant. Then again, GCC 4.6 is slated to have some major optimizations for Core 2 and i7, apparently.
I figure Clang's faster compilation speed will be nicer for original developers, and then when you push the code out into the world, Linux distro/BSD/etc. end-users will use GCC for the faster binaries.
// Timestamp after converting to milliseconds.
NSString * timeInMS = [NSString stringWithFormat:@"%lld", [@(floor([date timeIntervalSince1970] * 1000)) longLongValue]];
For simple IE detection I tend to use:
(/msie|trident/i).test(navigator.userAgent)
Visit the Microsoft Developer Network to learn about the IE useragent: http://msdn.microsoft.com/library/ms537503.aspx
Facebook's new "Page Plugin" width ranges from 180px
to 500px
as per the documentation.
180px
it would enforce a minimum width of 180px
500px
it would enforce a maximum width of 500px
With Adaptive Width checked, ex:
Unlike like-box, this plugin enforces its limits by sticking to the boundary values if mis-configured.
For small screens / Responsive behaviors
When rendering on smaller screens, enforce desiered width
on the plugin container and plugin would try to fit in.
The plugin renders at a smaller width (to fit in smaller screens) automatically, if the container is of slimmer than the configured width
.
You can scale down the container on mobile and the plugin will fit in as long as it gets the minimum of 180px
to fit in.
Without Adaptive Width
It seems to my case that Excel 2011 for Mac OS is not using Encoding.GetEncoding("10000") as i thought and wasted 2 days with but the same iso as on Microsoft OS. The best proof for this is to make a file in Excel 2011 for MAC with special chars, save it as CSV and then open it in MAC text editor and the chars are scrambled.
For me this approach worked - meaning that csv export on Excel 2011 on MAC OS has special western europeean chars inside:
Encoding isoMacOS = Encoding.GetEncoding("iso-8859-1");
Encoding defaultEncoding = Encoding.Default;
// Convert the string into a byte array.
byte[] defaultEncodingBytes = defaultEncoding.GetBytes(exportText);
// Perform the conversion from one encoding to the other.
byte[] ansiBytes = Encoding.Convert(defaultEncoding, isoMacOS, defaultEncodingBytes);
decodedString = isoMacOS.GetString(ansiBytes);
The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print
statement you can see that each file is found:
import os
rootdir = 'C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print os.path.join(subdir, file)
If you still get errors when running the above, please provide the error message.
Updated for Python3
import os
rootdir = 'C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print(os.path.join(subdir, file))
You can set shadow to your view from storyboard also
There are cross browser issues here.
A typical non-jQuery event handler would be something like this :
function doSomething(evt) {
evt = evt || window.event;
var target = evt.target || evt.srcElement;
if (target.nodeType == 3) // defeat Safari bug
target = target.parentNode;
//do stuff here
}
jQuery normalises evt
and makes the target available as this
in event handlers, so a typical jQuery event handler would be something like this :
function doSomething(evt) {
var $target = $(this);
//do stuff here
}
A hybrid event handler which uses jQuery's normalised evt
and a POJS target would be something like this :
function doSomething(evt) {
var target = evt.target || evt.srcElement;
if (target.nodeType == 3) // defeat Safari bug
target = target.parentNode;
//do stuff here
}
You can learn something called "mocking". You can use this, for example, to check if: - a function was called - a function was called x times - a function was called at least x times - a function was called with a specific set of parameters. In your case, for example, you can use mocking to check that method3 was called once with whatever you pass as arg1 and arg2.
Have a look at these: https://code.google.com/p/mockito/ https://code.google.com/p/powermock/
There's a oneliner for this one.
You can simply run,
docker run -v /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat
This will copy the war file to webapps directory and get your app running in no time.
You can find the source images by extracting them from Other.artwork in UIKit ${SDKROOT}/System/Library/Frameworks/UIKit.framework/Other.artwork. The modding community has some tools for extracting them, here. Once you extract the image you can write some code to recolor it as necessary and set it as the button image. Whether or not you can actually ship such a thing (since you are embedding derived artwork) might be a little dicey, so maybe you want to talk to a lawyer.
The disabled
attribute is not global and is only allowed on form controls. What you could do is set a custom data attribute (perhaps data-disabled
) and check for that attribute when you handle the click event.
str.join()
works fine in Python 3, you just need to get the order of the arguments correct
>>> str.join('.', ('a', 'b', 'c'))
'a.b.c'
I wonder why no one does this:
Calendar time = Calendar.getInstance();
time.add(Calendar.MILLISECOND, -time.getTimeZone().getOffset(time.getTimeInMillis()));
Date date = time.getTime();
Update: Since Java 8,9,10 and more, there should be better alternatives supported by Java. Thanks for your comment @humanity
Just spent a hour or so doing this and with the help of Brad's advice and a few additional changes it all worked.
I've done this using the following: 10.7.3, Xcode 4.3.2, iOS 5.1 btw.
1) Right click on your myapp.xcodeproj
and select package contents
2) open project.pbxproj
with a text editor (don't recommend textedit as it may screw up the formatting)
3) Scroll all the way down until you find /* Begin XCBuildConfiguration section */
4) Notice that you have a debug and release sections
5) In the release section take a look at CODE_SIGN_IDENTITY
& "CODE_SIGN_IDENTITY[sdk=iphoneos*]"
it should look something like this:
CODE_SIGN_IDENTITY = "iPhone Distribution: MyCompany LLC";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution: MyCompany LLC";
6) Take a look at PROVISIONING_PROFILE
and "PROVISIONING_PROFILE[sdk=iphoneos*]"
they should look like this:
PROVISIONING_PROFILE = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
"PROVISIONING_PROFILE[sdk=iphoneos*]" = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
This should match your provisioning profile in Xcode. To see if they match open Xcode > Window > Organizer > Devices > Provisioning Profiles > Right click on the profile > Reveal in Finder > The filename of the .mobileprovision is your profile id.
7) Scroll down in the project.pbxproj
and find a second instance of the release section. The second instance of the release section should end with a comment saying /* End XCBuildConfiguration section */
8) make sure that the second section matches the first section so that CODE_SIGN_IDENTITY, "CODE_SIGN_IDENTITY[sdk=iphoneos*]
, and PROVISIONING_PROFILE
are all filled in.
jQuery's one() will fire the attached event handler once for each element bound, and then remove the event handler.
If for some reason that doesn't fulfill the requirements, one could also disable the button entirely after it has been clicked.
$(document).ready(function () {
$("#submit").one('click', function (event) {
event.preventDefault();
//do something
$(this).prop('disabled', true);
});
});
It should be noted that using the ID submit
can cause issues, as it overwrites the form.submit
function with a reference to that element.
The same way Boston came up with its street plan. They followed the cow paths already there, and built houses where the streets weren't, and after a while it was too much trouble to change.
This took me a while to figure out, as the conventional window['someFunctionName']()
did not work for me at first. The names of my functions were being pulled as an AJAX response from a database. Also, for whatever reason, my functions were declared outside of the scope of the window, so in order to fix this I had to rewrite the functions I was calling from
function someFunctionName() {}
to
window.someFunctionName = function() {}
and from there I could call window['someFunctionName']()
with ease. I hope this helps someone!
I think the answer is incorrectly chosen, that method gives seconds, not milliseconds.
t = Time.now.to_f
=> 1382471965.146
Here I suppose the floating value are the milliseconds
Set max-width:80%;
as an inline stylesheet
<div class="modal-dialog modal-lg" role="document" style="max-width: 80%;">
Here's what I use. If you just subtract the dates, it won't work across the Daylight Savings Time Boundary (eg April 1 to April 30 or Oct 1 to Oct 31). This drops all the hours to make sure you get a day and eliminates any DST problem by using UTC.
var nDays = ( Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate()) -
Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate())) / 86400000;
as a function:
function DaysBetween(StartDate, EndDate) {
// The number of milliseconds in all UTC days (no DST)
const oneDay = 1000 * 60 * 60 * 24;
// A day in UTC always lasts 24 hours (unlike in other time formats)
const start = Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate());
const end = Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate());
// so it's safe to divide by 24 hours
return (start - end) / oneDay;
}
If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.
As a one-liner function:
def is_leap_year(year):
"""Determine whether a year is a leap year."""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
It's similar to the Mark's answer, but short circuits at the first test (note the parenthesis).
Alternatively, you can use the standard library's calendar.isleap
, which has exactly the same implementation:
from calendar import isleap
print(isleap(1900))
Same problem.
Cause : My root wasn't specified in open_basedir.
Fix : Adding my site root directory in :
/etc/php5/fpm/pool.d/mysite.conf<br>
by adding this directive :
php_value[open_basedir] = /my/root/site/dir:/other/directory/allowed
This will clear 25 new lines:
def clear():
print(' \n' * 25)
clear()
I use eclipse with pydev. I like the newline solution better than the for num in range . The for loop throws warnings, while the print newline doesn't. If you want to specify the number of newlines in the clear statement try this variation.
def clear(j):
print(' \n' * j)
clear(25)
You can use .empty()
, like this:
$("#foo").empty();
Remove all child nodes of the set of matched elements from the DOM.