It is quite evident that there is only a single id
corresponding to a single username
because username
is unique.
But the actual problem lies in the query itself-
$sql = "SELECT 'id' FROM Users WHERE username='$name'";
+----+
| id |
+----+
| id |
+----+
i.e. 'id'
actually is treated as a string not as the id
attribute.
$sql = "SELECT `id` FROM Users WHERE username='$name'";
i.e. use grave accent(`) instead of single quote(').
or
$sql = "SELECT id FROM Users WHERE username='$name'";
session_start();
$name = $_GET["username"];
$sql = "SELECT `id` FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$row=mysql_fetch_array($result)
$value = $row[0];
$_SESSION['myid'] = $value;
Thanks @Clint for the great answer:
Just wanted to highlight how easy it was to solve this using the Expando Object:
var dynamicObject = new ExpandoObject() as IDictionary<string, Object>;
foreach (var property in properties) {
dynamicObject.Add(property.Key,property.Value);
}
edited @Asraful Haque answer with a bit of js to show and hide the box
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login Page</title>
<style>
/* Basics */
html, body {
width: 100%;
height: 100%;
font-family: "Helvetica Neue", Helvetica, sans-serif;
color: #444;
-webkit-font-smoothing: antialiased;
background: #f0f0f0;
}
#container {
position: fixed;
width: 340px;
height: 280px;
top: 50%;
left: 50%;
margin-top: -140px;
margin-left: -170px;
background: #fff;
border-radius: 3px;
border: 1px solid #ccc;
box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
display: none;
}
form {
margin: 0 auto;
margin-top: 20px;
}
label {
color: #555;
display: inline-block;
margin-left: 18px;
padding-top: 10px;
font-size: 14px;
}
p a {
font-size: 11px;
color: #aaa;
float: right;
margin-top: -13px;
margin-right: 20px;
-webkit-transition: all .4s ease;
-moz-transition: all .4s ease;
transition: all .4s ease;
}
p a:hover {
color: #555;
}
input {
font-family: "Helvetica Neue", Helvetica, sans-serif;
font-size: 12px;
outline: none;
}
input[type=text],
input[type=password] ,input[type=time]{
color: #777;
padding-left: 10px;
margin: 10px;
margin-top: 12px;
margin-left: 18px;
width: 290px;
height: 35px;
border: 1px solid #c7d0d2;
border-radius: 2px;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #f5f7f8;
-webkit-transition: all .4s ease;
-moz-transition: all .4s ease;
transition: all .4s ease;
}
input[type=text]:hover,
input[type=password]:hover,input[type=time]:hover {
border: 1px solid #b6bfc0;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .7), 0 0 0 5px #f5f7f8;
}
input[type=text]:focus,
input[type=password]:focus,input[type=time]:focus {
border: 1px solid #a8c9e4;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #e6f2f9;
}
#lower {
background: #ecf2f5;
width: 100%;
height: 69px;
margin-top: 20px;
box-shadow: inset 0 1px 1px #fff;
border-top: 1px solid #ccc;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
input[type=checkbox] {
margin-left: 20px;
margin-top: 30px;
}
.check {
margin-left: 3px;
font-size: 11px;
color: #444;
text-shadow: 0 1px 0 #fff;
}
input[type=submit] {
float: right;
margin-right: 20px;
margin-top: 20px;
width: 80px;
height: 30px;
font-size: 14px;
font-weight: bold;
color: #fff;
background-color: #acd6ef; /*IE fallback*/
background-image: -webkit-gradient(linear, left top, left bottom, from(#acd6ef), to(#6ec2e8));
background-image: -moz-linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
background-image: linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
border-radius: 30px;
border: 1px solid #66add6;
box-shadow: 0 1px 2px rgba(0, 0, 0, .3), inset 0 1px 0 rgba(255, 255, 255, .5);
cursor: pointer;
}
input[type=submit]:hover {
background-image: -webkit-gradient(linear, left top, left bottom, from(#b6e2ff), to(#6ec2e8));
background-image: -moz-linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
background-image: linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
}
input[type=submit]:active {
background-image: -webkit-gradient(linear, left top, left bottom, from(#6ec2e8), to(#b6e2ff));
background-image: -moz-linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
background-image: linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
}
</style>
<script>
function clicker () {
var login = document.getElementById("container");
login.style.display="block";
}
</script>
</head>
<body>
<a href="#" id="link" onClick="clicker();">login</a>
<!-- Begin Page Content -->
<div id="container">
<form action="login_process.php" method="post">
<label for="loginmsg" style="color:hsla(0,100%,50%,0.5); font-family:"Helvetica Neue",Helvetica,sans-serif;"><?php echo @$_GET['msg'];?></label>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
<input type="submit" value="Login">
</div><!--/ lower-->
</form>
</div><!--/ container-->
<!-- End Page Content -->
</body>
</html>
Use the modern version of the Fisher–Yates shuffle algorithm:
/**
* Shuffles array in place.
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
/**
* Shuffles array in place. ES6 version
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.
var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);
Using Object.defineProperty
(method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr)
. The following will allow you to call arr.shuffle()
to shuffle the array arr
:
Object.defineProperty(Array.prototype, 'shuffle', {
value: function() {
for (let i = this.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this[i], this[j]] = [this[j], this[i]];
}
return this;
}
});
Using GitPython will give you a good python interface to Git.
For example, after installing it (pip install gitpython
), for cloning a new repository you can use clone_from function:
from git import Repo
Repo.clone_from(git_url, repo_dir)
See the GitPython Tutorial for examples on using the Repo object.
Note: GitPython requires git being installed on the system, and accessible via system's PATH.
If you want to remove the zero digits just before to display on the page or template.
You can use the sprintf() function
sprintf('%g','125.00');
//125
??sprintf('%g','966.70');
//966.7
????sprintf('%g',844.011);
//844.011
You could use CSS to attain this. By specifying the list in the color and style of your choice, you can then also specify the text as a different color.
Follow the example at http://www.echoecho.com/csslists.htm.
I slightly modified Garnaph's great solution above. It seemed like his solution modified the iframe size based upon the size right before the event. For my situation (email submission via an iframe) I needed the iframe height to change right after submission. For example show validation errors or "thank you" message after submission.
I just eliminated the nested click() function and put it into my iframe html:
<script type="text/javascript">
jQuery(document).ready(function () {
var frame = $('#IDofiframeInMainWindow', window.parent.document);
var height = jQuery("#IDofContainerInsideiFrame").height();
frame.height(height + 15);
});
</script>
Worked for me, but not sure about cross browser functionality.
It seems a little tricky since it really had bothered me for a long time.
You just need to open the table (right click the "Select Rows- Limit 10000") and you will open a new window. In this new window, you will find "import icon".
As of 2.6, set.intersection
takes arbitrarily many iterables.
>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s3 = set([2, 4, 6])
>>> s1 & s2 & s3
set([2])
>>> s1.intersection(s2, s3)
set([2])
>>> sets = [s1, s2, s3]
>>> set.intersection(*sets)
set([2])
In my case I had a pem file which contained two certificates and an encrypted private key to be used in mutual SSL authentication. So my pem file looked like this:
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,C8BF220FC76AA5F9
...
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
Split the file into three separate files, so that each one contains just one entry,
starting with ---BEGIN..
and ending with ---END..
lines. Lets assume we now have three files: cert1.pem
, cert2.pem
, and pkey.pem
.
Convert pkey.pem
into DER format using openssl and the following syntax:
openssl pkcs8 -topk8 -nocrypt -in pkey.pem -inform PEM -out pkey.der -outform DER
Note, that if the private key is encrypted you need to supply a password( obtain it from the supplier of the original pem file ) to convert to DER format,
openssl
will ask you for the password like this: "enter a passphrase for pkey.pem
: ".
If conversion is successful, you will get a new file called pkey.der
.
Create a new java keystore and import the private key and the certificates:
String keypass = "password"; // this is a new password, you need to come up with to protect your java key store file
String defaultalias = "importkey";
KeyStore ks = KeyStore.getInstance("JKS", "SUN");
// this section does not make much sense to me,
// but I will leave it intact as this is how it was in the original example I found on internet:
ks.load( null, keypass.toCharArray());
ks.store( new FileOutputStream ( "mykeystore" ), keypass.toCharArray());
ks.load( new FileInputStream ( "mykeystore" ), keypass.toCharArray());
// end of section..
// read the key file from disk and create a PrivateKey
FileInputStream fis = new FileInputStream("pkey.der");
DataInputStream dis = new DataInputStream(fis);
byte[] bytes = new byte[dis.available()];
dis.readFully(bytes);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
byte[] key = new byte[bais.available()];
KeyFactory kf = KeyFactory.getInstance("RSA");
bais.read(key, 0, bais.available());
bais.close();
PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec ( key );
PrivateKey ff = kf.generatePrivate (keysp);
// read the certificates from the files and load them into the key store:
Collection col_crt1 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert1.pem"));
Collection col_crt2 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert2.pem"));
Certificate crt1 = (Certificate) col_crt1.iterator().next();
Certificate crt2 = (Certificate) col_crt2.iterator().next();
Certificate[] chain = new Certificate[] { crt1, crt2 };
String alias1 = ((X509Certificate) crt1).getSubjectX500Principal().getName();
String alias2 = ((X509Certificate) crt2).getSubjectX500Principal().getName();
ks.setCertificateEntry(alias1, crt1);
ks.setCertificateEntry(alias2, crt2);
// store the private key
ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), chain );
// save the key store to a file
ks.store(new FileOutputStream ( "mykeystore" ),keypass.toCharArray());
(optional) Verify the content of your new key store:
$ keytool -list -keystore mykeystore -storepass password
Keystore type: JKS Keystore provider: SUN
Your keystore contains 3 entries:
cn=...,ou=...,o=.., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 2C:B8: ...
importkey, Sep 2, 2014, PrivateKeyEntry, Certificate fingerprint (SHA1): 9C:B0: ...
cn=...,o=...., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 83:63: ...
(optional) Test your certificates and private key from your new key store against your SSL server: ( You may want to enable debugging as an VM option: -Djavax.net.debug=all )
char[] passw = "password".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS", "SUN");
ks.load(new FileInputStream ( "mykeystore" ), passw );
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passw);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
TrustManager[] tm = tmf.getTrustManagers();
SSLContext sclx = SSLContext.getInstance("TLS");
sclx.init( kmf.getKeyManagers(), tm, null);
SSLSocketFactory factory = sclx.getSocketFactory();
SSLSocket socket = (SSLSocket) factory.createSocket( "192.168.1.111", 443 );
socket.startHandshake();
//if no exceptions are thrown in the startHandshake method, then everything is fine..
Finally register your certificates with HttpsURLConnection if plan to use it:
char[] passw = "password".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS", "SUN");
ks.load(new FileInputStream ( "mykeystore" ), passw );
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passw);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
TrustManager[] tm = tmf.getTrustManagers();
SSLContext sclx = SSLContext.getInstance("TLS");
sclx.init( kmf.getKeyManagers(), tm, null);
HostnameVerifier hv = new HostnameVerifier()
{
public boolean verify(String urlHostName, SSLSession session)
{
if (!urlHostName.equalsIgnoreCase(session.getPeerHost()))
{
System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
}
return true;
}
};
HttpsURLConnection.setDefaultSSLSocketFactory( sclx.getSocketFactory() );
HttpsURLConnection.setDefaultHostnameVerifier(hv);
Try this:
MessageBox.Show("Some text", "Some title",
MessageBoxButtons.OK, MessageBoxIcon.Error);
I have seen solutions for aligning drawable at start/left but nothing for drawable end/right, so I came up with this solution. It uses dynamically calculated paddings for aligning drawable and text on both left and right side.
class IconButton @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = R.attr.buttonStyle
) : AppCompatButton(context, attrs, defStyle) {
init {
maxLines = 1
}
override fun onDraw(canvas: Canvas) {
val buttonContentWidth = (width - paddingLeft - paddingRight).toFloat()
val textWidth = paint.measureText(text.toString())
val drawable = compoundDrawables[0] ?: compoundDrawables[2]
val drawableWidth = drawable?.intrinsicWidth ?: 0
val drawablePadding = if (textWidth > 0 && drawable != null) compoundDrawablePadding else 0
val bodyWidth = textWidth + drawableWidth.toFloat() + drawablePadding.toFloat()
canvas.save()
val padding = (buttonContentWidth - bodyWidth).toInt() / 2
val leftOrRight = if (compoundDrawables[0] != null) 1 else -1
setPadding(leftOrRight * padding, 0, -leftOrRight * padding, 0)
super.onDraw(canvas)
canvas.restore()
}
}
It is important to set gravity in your layout to either "center_vertical|start" or "center_vertical|end" depending on where do you set the icon. For example:
<com.stackoverflow.util.IconButton
android:id="@+id/cancel_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawableStart="@drawable/cancel"
android:drawablePadding="@dimen/padding_small"
android:gravity="center_vertical|start"
android:text="Cancel" />
Only problem with this implementation is that button can only have single line of text, otherwise the area of the text fills the button and paddings will be 0.
I have tried this and it worked:
define PROPp_START_DT = TO_DATE('01-SEP-1999')
select * from proposal where prop_start_dt = &PROPp_START_DT
In Chromium 81+, I have found the answer to be: go to chrome://extensions/, click to enable Developer Mode on the top right corner, then drag and drop your .user.js script.
I have the same problem and it annoys me tremendously!!
I have always thought I was surposed to do as answer 2. That used to work in Intellij 9 (now using 10).
However I figured out that by adding these line to my maven pom file helps:
<build>
...
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
...
</build>
Use the collapse
argument to paste
:
paste(a,collapse=" ")
[1] "aa bb cc"
possibly if you want to just transfer data to be used by JavaScript then you can use Hash Tags like this
http://localhost/project/index.html#exist
so once when you are done retriving the data show the message and change the
window.location.hash to a suitable value.. now whenever you ll refresh the page the hashtag
wont be present
NOTE: when you will use this instead ot query strings the data being sent cannot be retrived/read by the server
Here's how we were able to validate the RECAPTCHA using .NET:
FRONT-END
<div id="rcaptcha" class="g-recaptcha" data-sitekey="[YOUR-KEY-GOES-HERE]" data-callback="onFepCaptchaSubmit"></div>
BACK-END:
public static bool IsCaptchaValid(HttpRequestBase requestBase)
{
var recaptchaResponse = requestBase.Form["g-recaptcha-response"];
if (string.IsNullOrEmpty(recaptchaResponse))
{
return false;
}
string postData = string.Format("secret={0}&response={1}&remoteip={2}", "[YOUR-KEY-GOES-HERE]", recaptchaResponse, requestBase.UserHostAddress);
byte[] data = System.Text.Encoding.ASCII.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com/recaptcha/api/siteverify");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = "";
using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
{
responseString = sr.ReadToEnd();
}
return System.Text.RegularExpressions.Regex.IsMatch(responseString, "\"success\"(\\s*?):(\\s*?)true", System.Text.RegularExpressions.RegexOptions.Compiled);
}
Call the above method within your Controller's POST action.
I own a mac too! here is the code that will work:
myButton.setBackground(Color.RED);
myButton.setOpaque(true); //Sets Button Opaque so it works
before doing anything or adding any components set the look and feel so it looks better:
try{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
}catch(Exception e){
e.printStackTrace();
}
That is Supposed to change the look and feel to the cross platform look and feel, hope i helped! :)
As an alternative to using a trigger, you might like to consider creating a stored procedure to handle the INSERT
s that takes most of the columns as arguments and gets the CURRENT_TIMESTAMP
which it includes in the final INSERT
to the database. You could do the same for the CREATE
. You may also be able to set things up so that users cannot execute INSERT
and CREATE
statements other than via the stored procedures.
I have to admit that I haven't actually done this myself so I'm not at all sure of the details.
A singleton service
is a service for which only one instance exists in an app.
There are (2) ways to provide a singleton service for your application.
use the providedIn
property, or
provide the module directly in the AppModule
of the application
Using providedIn
Beginning with Angular 6.0, the preferred way to create a singleton service is to set providedIn
to root on the service's @Injectable()
decorator. This tells Angular to provide the service in the application root.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class UserService {
}
NgModule providers array
In apps built with Angular versions prior to 6.0, services are registered NgModule providers arrays as follows:
@NgModule({
...
providers: [UserService],
...
})
If this NgModule
were the root AppModule
, the UserService would be a singleton and available throughout the app. Though you may see it coded this way, using the providedIn
property of the @Injectable()
decorator on the service itself is preferable as of Angular 6.0 as it makes your services tree-shakable.
here's an example with the accepted answer:
a = [{name:"alex"},{name:"clex"},{name:"blex"}];
For Ascending :
a.sort((a,b)=> (a.name > b.name ? 1 : -1))
output : [{name: "alex"}, {name: "blex"},{name: "clex"} ]
For Decending :
a.sort((a,b)=> (a.name < b.name ? 1 : -1))
output : [{name: "clex"}, {name: "blex"}, {name: "alex"}]
By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.
In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.
The client code must set the withCredentials
property on the XMLHttpRequest
to true
in order to give permission.
However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials
header. Responding with this header to true
means that the server allows cookies (or other user credentials) to be included on cross-origin requests.
You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.
Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).
SELECT FROM_UNIXTIME(mycolumn)
FROM mytable
Installing gem or updating RubyGems fails with permissions error Then Type This Command
sudo gem install cocoapods
0 */2 * * *
The answer is from https://crontab.guru/every-2-hours. It is interesting.
To read a particular date from range EJ_PAYDATES_2021 (index is next to the last "1")
=INDEX(PayDates.xlsx!EJ_PAYDATES_2021,1,1) // Jan
=INDEX(PayDates.xlsx!EJ_PAYDATES_2021,2,1) // Feb
=INDEX(PayDates.xlsx!EJ_PAYDATES_2021,3,1) // Mar
This allows reading a particular element of a range [0] etc from another spreadsheet file. Target file need not be open. Range in the above example is named EJ_PAYDATES_2021, with one element for each month contained within that range.
Took me a while to parse this out, but it works, and is the answer to the question asked above.
Sometimes you are required to indicate where @ComponentScan should scan for components. You can do so by passing the packages as parameter of this annotation, e.g:
@ComponentScan(basePackages={"path.to.my.components","path.to.my.othercomponents"})
However, as already mentioned, @SpringBootApplication annotation replaces @ComponentScan, hence in such cases you must do the same:
@SpringBootApplication(scanBasePackages={"path.to.my.components","path.to.my.othercomponents"})
At least in my case, Intellij stopped complaining.
Actionbarsherlock has the support library in it. This probably causes a conflict if the support library is also in your main project.
Remove android-support-v4.jar
from your project's libs directory.
Also Remove android-support-v4.jar
from your second library and then try again.
Jar Mismatch Found 2 versions of android-support-v4.jar in the dependency list
How about this?
=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))
The "3" at the end means for column C.
This is an extension of Rian Schmits' answer above. In my case, I had HTML code embedded in my JavaScript code and I couldn't see anything other than the HTML code. Maybe Chrome Debugging has changed over the years but right-clicking the Sources/Sources tab presented me with Add folder to workspace. I was able to add my entire project, which gave me access to all of my JavaScripts. You can find more detail in this link. I hope this helps somebody.
In the KeyDown Event:
If e.KeyCode = Keys.Enter Then
Messagebox.Show("Enter key pressed")
end if
HTML event handler code behaves like the body of a JavaScript function. Many languages such as C or Perl implicitly return the value of the last expression evaluated in the function body. JavaScript doesn't, it discards it and returns undefined unless you write an explicit return
EXPR.
The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:
$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
--forward-agent \
--disable-known-hosts deploy:$target; then
echo failed
else
echo succeeded
fi
$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed
Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.
[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr
option that you can set to make it carriage-return-tolerant.
By looking at www.npmjs.com/install.sh I found there is a way to install a specific version by setting an environment-variable
export npm_install="2.14.14"
Then run the download-script as described at npmjs.com:
curl -L https://www.npmjs.com/install.sh | sh
If you omit setting the npm_install variable, then it will install the the version they have marked as latest
Grokking lookaround rapidly.
How to distinguish lookahead and lookbehind?
Take 2 minutes tour with me:
(?=) - positive lookahead
(?<=) - positive lookbehind
Suppose
A B C #in a line
Now, we ask B, Where are you?
B has two solutions to declare it location:
One, B has A ahead and has C bebind
Two, B is ahead(lookahead) of C and behind (lookhehind) A.
As we can see, the behind and ahead are opposite in the two solutions.
Regex is solution Two.
This simple code worked for me
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<input list="brow">_x000D_
<datalist id="brow">_x000D_
<option value="Internet Explorer">_x000D_
<option value="Firefox">_x000D_
<option value="Chrome">_x000D_
<option value="Opera">_x000D_
<option value="Safari">_x000D_
</datalist> _x000D_
</body>_x000D_
</html>
_x000D_
Incase you need to use only select tag use Selectize Js. It has all options we require .Please Try It Demo using Selectize Js
Try setting path to /var/lib/mysql-files/filename.csv
(MySQL 8). Determine what files directory is yours by typping SHOW VARIABLES LIKE "secure_file_priv";
in mysql client command line.
See answer about here: (...) --secure-file-priv in MySQL answered in 2015 by vhu user
In java8, I would use the Instant
class which is already in UTC and is convenient to work with.
import java.time.Instant;
Instant ins = Instant.now();
long ts = ins.toEpochMilli();
Instant ins2 = Instant.ofEpochMilli(ts)
Alternatively, you can use the following:
import java.time.*;
Instant ins = Instant.now();
OffsetDateTime odt = ins.atOffset(ZoneOffset.UTC);
ZonedDateTime zdt = ins.atZone(ZoneId.of("UTC"));
Back to Instant
Instant ins4 = Instant.from(odt);
The correct way in .NET 4.0 is:
if (String.IsNullOrWhiteSpace(strSearch))
The String.IsNullOrWhiteSpace
method used above is equivalent to:
if (strSearch == null || strSearch == String.Empty || strSearch.Trim().Length == 0)
// String.Empty is the same as ""
Reference for IsNullOrWhiteSpace method
http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx
Indicates whether a specified string is Nothing, empty, or consists only of white-space characters.
In earlier versions, you could do something like this:
if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)
The String.IsNullOrEmpty
method used above is equivalent to:
if (strSearch == null || strSearch == String.Empty)
Which means you still need to check for your "IsWhiteSpace" case with the .Trim().Length == 0
as per the example.
Reference for IsNullOrEmpty method
http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx
Indicates whether the specified string is Nothing or an Empty string.
Explanation:
You need to ensure strSearch
(or any variable for that matter) is not null
before you dereference it using the dot character (.
) - i.e. before you do strSearch.SomeMethod()
or strSearch.SomeProperty
you need to check that strSearch != null
.
In your example you want to make sure your string has a value, which means you want to ensure the string:
String.Empty
/ ""
)In the cases above, you must put the "Is it null?" case first, so it doesn't go on to check the other cases (and error) when the string is null
.
I think the cleanest way to do this is with Mockito.spy(). It's a bit more lightweight than creating a separate class to mock and pass around.
Move your environment variable fetching to another method:
@VisibleForTesting
String getEnvironmentVariable(String envVar) {
return System.getenv(envVar);
}
Now in your unit test do this:
@Test
public void test() {
ClassToTest classToTest = new ClassToTest();
ClassToTest classToTestSpy = Mockito.spy(classToTest);
Mockito.when(classToTestSpy.getEnvironmentVariable("key")).thenReturn("value");
// Now test the method that uses getEnvironmentVariable
assertEquals("changedvalue", classToTestSpy.methodToTest());
}
I prefer fork + execlp for "more fine-grade" control as doron mentioned. Example code shown below.
Store you command in a char array parameters, and malloc space for the result.
int fd[2];
pipe(fd);
if ( (childpid = fork() ) == -1){
fprintf(stderr, "FORK failed");
return 1;
} else if( childpid == 0) {
close(1);
dup2(fd[1], 1);
close(fd[0]);
execlp("/bin/sh","/bin/sh","-c",parameters,NULL);
}
wait(NULL);
read(fd[0], result, RESULT_SIZE);
printf("%s\n",result);
Working with dplyr
library(dplyr)
df <- data.frame(A = factor(LETTERS[1:5]),
B = 1:5, C = as.logical(c(1, 1, 0, 0, 1)),
D = letters[1:5],
E = paste(LETTERS[1:5], letters[1:5]),
stringsAsFactors = FALSE)
str(df)
we get:
'data.frame': 5 obs. of 5 variables:
$ A: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
$ B: int 1 2 3 4 5
$ C: logi TRUE TRUE FALSE FALSE TRUE
$ D: chr "a" "b" "c" "d" ...
$ E: chr "A a" "B b" "C c" "D d" ...
Now, we can convert all chr
to factors
:
df <- df%>%mutate_if(is.character, as.factor)
str(df)
And we get:
'data.frame': 5 obs. of 5 variables:
$ A: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
$ B: int 1 2 3 4 5
$ C: logi TRUE TRUE FALSE FALSE TRUE
$ D: chr "a" "b" "c" "d" ...
$ E: chr "A a" "B b" "C c" "D d" ...
Let's provide also other solutions:
With base package:
df[sapply(df, is.character)] <- lapply(df[sapply(df, is.character)],
as.factor)
With dplyr
1.0.0
df <- df%>%mutate(across(where(is.factor), as.character))
With purrr
package:
library(purrr)
df <- df%>% modify_if(is.factor, as.character)
var date = new Date("enter your date");//2018-01-17 14:58:29.013
Just one line is enough no need to do any kind of split
, join
, etc.:
$scope.ssdate=date.toLocaleDateString();// mm/dd/yyyy format
window.clipboardData.getData('Text')
will work in some browsers. However, many browsers where it does work will prompt the user as to whether or not they wish the web page to have access to the clipboard.
You can use something like this:
RewriteEngine on
RewriteRule ^.+$ /index.php [L]
This will redirect every query to the root directory's index.php. Note that it will also redirect queries for files that exist, such as images, javascript files or style sheets.
Use the strong element, that is it's purpose:
<div id="content">
<p><strong>First Word</strong> rest of paragraph.</p>
</div>
Then create a style for it in your style sheet.
#content p strong
{
font-size: 14pt;
}
Python Implementation for @dhanushka's solution:
def process_rgb(rgb):
hasText = False
gray = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)
morphKernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
grad = cv2.morphologyEx(gray, cv2.MORPH_GRADIENT, morphKernel)
# binarize
_, bw = cv2.threshold(grad, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
# connect horizontally oriented regions
morphKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1))
connected = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, morphKernel)
# find contours
mask = np.zeros(bw.shape[:2], dtype="uint8")
_,contours, hierarchy = cv2.findContours(connected, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
# filter contours
idx = 0
while idx >= 0:
x,y,w,h = cv2.boundingRect(contours[idx])
# fill the contour
cv2.drawContours(mask, contours, idx, (255, 255, 255), cv2.FILLED)
# ratio of non-zero pixels in the filled region
r = cv2.contourArea(contours[idx])/(w*h)
if(r > 0.45 and h > 5 and w > 5 and w > h):
cv2.rectangle(rgb, (x,y), (x+w,y+h), (0, 255, 0), 2)
hasText = True
idx = hierarchy[0][idx][0]
return hasText, rgb
You might need a ~/.ssh/config
:
Host gitlab.YOURDOMAIN.DOMAIN
Port 1111
IdentityFile ~/.ssh/id_rsa
and then you can use git clone git@DOMAINandREPOSITORY
. This means you always use the user git
.
Maybe this is helpfull to someone after few years.
New way, on Androidx, of getting SharedPreferences()
inside fragment is to implement into gradle dependencies
implementation "androidx.preference:preference:1.1.1"
and then, inside fragment call
SharedPreferences preferences;
preferences = androidx.preference.PreferenceManager.getDefaultSharedPreferences(getActivity());
You can use CSS to hide the close button instead of JavaScript:
.ui-dialog-titlebar-close{
display: none;
}
If you don't want to affect all the modals, you could use a rule like
.hide-close-btn .ui-dialog-titlebar-close{
display: none;
}
And apply .hide-close-btn
to the top node of the dialog
If the lines are all of a fixed length you can use the Seek method of a stream to move to the correct starting positiion.
If the lines are of a variable length your options are more limited.
If this is a file you will be only using once and then discarding, then you are best off reading it in and working with it in memeory.
If this is a file you will keeping and will be reading from more than writing to, you can create a custom index file that contains the starting positions of each line. Then use that index to get your Seek position. The process of creating the index file is resource intensive. Everytime you add a new line to the file you will need to update the index, so maintenance becomes a non-trivial issue.
It's sort of arbitrary which of the terms to use. It could have been either way. Perhaps the language designers thought of "extends" as the most fundamental term, and "implements" as the special case for interfaces.
But I think implements
would make slightly more sense. I think that communicates more that the parameter types don't have to be in an inheritance relationship, they can be in any kind of subtype relationship.
The Java Glossary expresses a similar view.
This worked for me where I delay the search logic operation and make a check if the value is same as entered in text field. If value is same then I go ahead and perform the operation for the data related to search value.
$('#searchText').on('keyup',function () {
var searchValue = $(this).val();
setTimeout(function(){
if(searchValue == $('#searchText').val() && searchValue != null && searchValue != "") {
// logic to fetch data based on searchValue
}
else if(searchValue == ''){
// logic to load all the data
}
},300);
});
This answer is in three parts, see below for the official release (v3 and v4)
I couldn't even find the col-lg-push-x or pull classes in the original files for RC1 i downloaded, so check your bootstrap.css file. hopefully this is something they will sort out in RC2.
anyways, the col-push-* and pull classes did exist and this will suit your needs. Here is a demo
<div class="row">
<div class="col-sm-5 col-push-5">
Content B
</div>
<div class="col-sm-5 col-pull-5">
Content A
</div>
<div class="col-sm-2">
Content C
</div>
</div>
Also see This blog post on the subject
col-vp-push-x
= push the column to the right by x number of columns, starting from where the column would normally render -> position: relative
, on a vp or larger view-port.
col-vp-pull-x
= pull the column to the left by x number of columns, starting from where the column would normally render -> position: relative
, on a vp or larger view-port.
vp = xs, sm, md, or lg
x = 1 thru 12
I think what messes most people up, is that you need to change the order of the columns in your HTML markup (in the example below, B comes before A), and that it only does the pushing or pulling on view-ports that are greater than or equal to what was specified. i.e. col-sm-push-5
will only push 5 columns on sm
view-ports or greater. This is because Bootstrap is a "mobile first" framework, so your HTML should reflect the mobile version of your site. The Pushing and Pulling are then done on the larger screens.
<div class="row">
<div class="col-sm-5 col-sm-push-5">
Content B
</div>
<div class="col-sm-5 col-sm-pull-5">
Content A
</div>
<div class="col-sm-2">
Content C
</div>
</div>
View-port >= sm
|A|B|C|
View-port < sm
|B|
|A|
|C|
With v4 comes flexbox and other changes to the grid system and the push\pull classes have been removed in favor of using flexbox ordering.
.order-*
classes to control visual order (where * = 1 thru 12).order-md-*
.order-first
(-1) and .order-last
(13) avalable<div class="row">_x000D_
<div class="col order-2">1st yet 2nd</div>_x000D_
<div class="col order-1">2nd yet 1st</div>_x000D_
</div>
_x000D_
This should work, but there is a little trick. After you enter the formula, you need to hold down Ctrl+Shift while you press Enter. When you do, you'll see that the formula bar has curly-braces around your formula. This is called an array formula.
For example, if the Months are in cells A2:A100
and the amounts are in cells B2:B100
, your formula would look like {=SUM(If(A2:A100="January",B2:B100))}
. You don't actually type the curly-braces though.
You could also do something like =SUM((A2:A100="January")*B2:B100)
. You'd still need to use the trick to get it to work correctly.
Here is a variation of @SiegeX's answer which works with traditional Bourne shell (which has no support for +=
assignments).
password=''
while IFS= read -r -s -n1 pass; do
if [ -z "$pass" ]; then
echo
break
else
printf '*'
password="$password$pass"
fi
done
Short answer
Why? Because there is still whitespace (carriage returns, tabs, spaces, newline) left in the input stream.
When? When you are using some function which does not on their own ignores the leading whitespaces. Cin by default ignores and removes the leading whitespace but getline does not ignore the leading whitespace on its own.
Now a detailed answer.
Everything you input in the console is read from the standard stream stdin. When you enter something, let's say 256 in your case and press enter, the contents of the stream become 256\n
. Now cin picks up 256 and removes it from the stream and \n
still remaining in the stream.
Now next when you enter your name, let's say Raddicus
, the new contents of the stream is \nRaddicus
.
Now here comes the catch.
When you try to read a line using getline, if not provided any delimiter as the third argument, getline by default reads till the newline character and removes the newline character from the stream.
So on calling new line, getline reads and discards \n
from the stream and resulting in an empty string read in mystr which appears like getline is skipped (but it's not) because there was already an newline in the stream, getline will not prompt for input as it has already read what it was supposed to read.
Now, how does cin.ignore help here?
According to the ignore documentation extract from cplusplus.com-
istream& ignore (streamsize n = 1, int delim = EOF);
Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.
The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before either extracting n characters or finding delim), the function sets the eofbit flag.
So, cin.ignore(256, '\n');
, ignores first 256 characters or all the character untill it encounters delimeter (here \n in your case), whichever comes first (here \n is the first character, so it ignores until \n is encountered).
Just for your reference, If you don't exactly know how many characters to skip and your sole purpose is to clear the stream to prepare for reading a string using getline or cin you should use cin.ignore(numeric_limits<streamsize>::max(),'\n')
.
Quick explanation: It ignores the characters equal to maximum size of stream or until a '\n' is encountered, whichever case happens first.
enum
s are fine. IIRC, one item in effective Java (2nd Ed) has enum
constants enumerating standard options implementing a [Java keyword] interface
for any value.
My preference is to use a [Java keyword] interface
over a final class
for constants. You implicitly get the public static final
. Some people will argue that an interface
allows bad programmers to implement it, but bad programmers are going to write code that sucks no matter what you do.
Which looks better?
public final class SomeStuff {
private SomeStuff() {
throw new Error();
}
public static final String SOME_CONST = "Some value or another, I don't know.";
}
Or:
public interface SomeStuff {
String SOME_CONST = "Some value or another, I don't know.";
}
You will need to drop and re-create the primary key like this:
alter table my_table drop constraint my_pk;
alter table my_table add constraint my_pk primary key (city_id, buildtime, time);
However, if there are other tables with foreign keys that reference this primary key, then you will need to drop those first, do the above, and then re-create the foreign keys with the new column list.
An alternative syntax to drop the existing primary key (e.g. if you don't know the constraint name):
alter table my_table drop primary key;
The upside-down A symbol is the universal quantifier from predicate logic. (Also see the more complete discussion of the first-order predicate calculus.) As others noted, it means that the stated assertions holds "for all instances" of the given variable (here, s). You'll soon run into its sibling, the backwards capital E, which is the existential quantifier, meaning "there exists at least one" of the given variable conforming to the related assertion.
If you're interested in logic, you might enjoy the book Logic and Databases: The Roots of Relational Theory by C.J. Date. There are several chapters covering these quantifiers and their logical implications. You don't have to be working with databases to benefit from this book's coverage of logic.
On Windows add following lines to _vimrc
" store backup, undo, and swap files in temp directory
set directory=$HOME/temp//
set backupdir=$HOME/temp//
set undodir=$HOME/temp//
Do this to distinguish that.
If for example your number is 3.1214 and stored in num but you don't know kind of num:
num = 3.1214
// cast num to int
int x = (int)num;
if(x == num)
{
// num is a integer
}
else
// num is float
}
In this example we see that num is not integer.
I personally do not see any reason why one would like to use char* or char[] except for compatibility with old code. std::string's no slower than using a c-string, except that it will handle re-allocation for you. You can set it's size when you create it, and thus avoid re-allocation if you want. It's indexing operator ([]) provides constant time access (and is in every sense of the word the exact same thing as using a c-string indexer). Using the at method gives you bounds checked safety as well, something you don't get with c-strings, unless you write it. Your compiler will most often optimize out the indexer use in release mode. It is easy to mess around with c-strings; things such as delete vs delete[], exception safety, even how to reallocate a c-string.
And when you have to deal with advanced concepts like having COW strings, and non-COW for MT etc, you will need std::string.
If you are worried about copies, as long as you use references, and const references wherever you can, you will not have any overhead due to copies, and it's the same thing as you would be doing with the c-string.
First off, this has nothing to do with php. This is a unix permission issue. You need to login as a superuser ( sudo/su ) and type your password, then try that command.
$ su
(type password )
\# your command
$ sudo command
$ (type password)
It might also help if you actually specified the operating system you use.
The reason it is showing this message because it is unable to find Linux containers as running. So, make sure you switch from windows to linux containers before running it.
Let me know if this works. Way to detect an Apple device (Mac computers, iPhones, etc.) with help from StackOverflow.com:
What is the list of possible values for navigator.platform as of today?
var deviceDetect = navigator.platform;
var appleDevicesArr = ['MacIntel', 'MacPPC', 'Mac68K', 'Macintosh', 'iPhone',
'iPod', 'iPad', 'iPhone Simulator', 'iPod Simulator', 'iPad Simulator', 'Pike
v7.6 release 92', 'Pike v7.8 release 517'];
// If on Apple device
if(appleDevicesArr.includes(deviceDetect)) {
// Execute code
}
// If NOT on Apple device
else {
// Execute code
}
this code works great for me :
echo str_replace(array_keys($data), array_values($data), $query->queryString);
Don't forget to replace $data and $query by your names
I think it is called next.
Type _type = myclass.GetType();
PropertyInfo[] _propertyInfos = _type.GetProperties();
Boolean _test = _propertyInfos[0].PropertyType.GetGenericTypeDefinition()
== typeof(List<>);
Try like this
Pass Camera Intent like below
Intent intent = new Intent(this);
startActivityForResult(intent, REQ_CAMERA_IMAGE);
And after capturing image Write an OnActivityResult
as below
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(tempUri));
System.out.println(mImageCaptureUri);
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
String path = "";
if (getContentResolver() != null) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cursor.getString(idx);
cursor.close();
}
}
return path;
}
And check log
Edit:
Lots of people are asking how to not get a thumbnail. You need to add this code instead for the getImageUri
method:
public Uri getImageUri(Context inContext, Bitmap inImage) {
Bitmap OutImage = Bitmap.createScaledBitmap(inImage, 1000, 1000,true);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), OutImage, "Title", null);
return Uri.parse(path);
}
The other method Compresses the file. You can adjust the size by changing the number 1000,1000
If you are using the fluent API, you need to set it up via the Executor
:
Executor.unregisterScheme("https");
SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext,
SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Executor.registerScheme(new Scheme("https", 443, sslSocketFactory));
... where sslContext
is the SSLContext created as shown in the ZZ Coder's answer.
After that, you can do your http requests as:
String responseAsString = Request.Get("https://192.168.1.0/whatever.json")
.execute().getContent().asString();
Note: tested with HttpClient 4.2
you could use class for all your checkboxes, and do:
$(".check_class").click(function() {
$(".check_class").attr("checked", false); //uncheck all checkboxes
$(this).attr("checked", true); //check the clicked one
});
in summary: remove those two lines of code above and your insert statement will work fine. You can the modify the code it later to suit your specific needs. And by the way, some times, you have to enclose dates in pounds signs like #
Problem: (Sql server 2014) This issue happens when assembly Microsoft.SqlServer.management.sdk.sfc version 12.0.0.0
not found by visual studio.
Solution: just go to http://www.microsoft.com/en-us/download/details.aspx?id=42295 and download:
ENU\x64\SharedManagementObjects.msi
for X64 OS orENU\x86\SharedManagementObjects.msi
for X86 OS, then install it, and restart visual studio.
PS: You may need install DB2OLEDBV5_x64.msi
or DB2OLEDBV5_x86.msi
too.
Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0
not found by visual studio.
Solution: just go to http://www.microsoft.com/en-us/download/details.aspx?id=35580 and download:
ENU\x64\SharedManagementObjects.msi
for X64 OS orENU\x86\SharedManagementObjects.msi
for X86 OS, then install it, and restart visual studio.
Microsoft.SqlServer.management.sdk.sfc version 10.0.0.0
not found by visual studio.
Solution: just go to http://www.microsoft.com/en-us/download/details.aspx?id=26728 and download:
1033\x64\SharedManagementObjects.msi
for X64 OS or1033\x86\SharedManagementObjects.msi
for X86 OS, (In most cases downloading this is better http://go.microsoft.com/fwlink/?LinkId=123708&clcid=0x409)
then install it, and restart visual studio.
Microsoft.SqlServer.ConnectionInfo, Version=12.0.0.0
not found by visual studio. The problem was Visual C++ Redistributable Packages for Visual Studio was not installed yet.
Solution: for Visual Studio 2013 just go to http://www.microsoft.com/en-us/download/details.aspx?id=40784 and download:
vcredist_x64.exe
for X64 OS orvcredist_x86.exe
for X86 OS, then install it, and restart visual studio.
PS: You can find Visual C++ Redistributable Packages for Visual Studio 20XX for other versions of Visual Studio easily by googling it.
In C, declaring your enum the first way allows you to use it like so:
TokenType my_type;
If you use the second style, you'll be forced to declare your variable like this:
enum TokenType my_type;
As mentioned by others, this doesn't make a difference in C++. My guess is that either the person who wrote this is a C programmer at heart, or you're compiling C code as C++. Either way, it won't affect the behaviour of your code.
The accepted answer gave two locations:
here
C:\Documents and Settings\Administrator\Local Settings\Temp\VWDWebCache
and possibly here
C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\WebsiteCache
Did you try those?
Edited to add
On my Windows Vista machine, it's located in
%Temp%\VWDWebCache
and in
%LocalAppData%\Microsoft\WebsiteCache
From your additional information (regarding team edition) this comes from Clear Client TFS Cache:
Clear Client TFS Cache
Visual Studio and Team Explorer provide a caching mechanism which can get out of sync. If I have multiple instances of a single TFS which can be connected to from a single Visual Studio client, that client can become confused.
To solve it..
For Windows Vista delete contents of this folder
%LocalAppData%\Microsoft\Team Foundation\1.0\Cache
The best (and only) method is to set correct HTTP headers, specifically these ones: "Expires", "Last-Modified", and "Cache-Control". How to do it depends on the server software you use.
In Improving performance… look for "Optimization on server side" for general considerations and relevant links and for "Client-side cache" for the Apache-specific advice.
If you are a fan of nginx (or nginx in plain English) like I am, you can easily configure it too:
location /images {
...
expires 4h;
}
In the example above any file from /images/ will be cached on the client for 4 hours.
Now when you know right words to look for (HTTP headers "Expires", "Last-Modified", and "Cache-Control"), just peruse the documentation of the web server you use.
Create a new Application Pool
Go to the Advanced Settings of this application pool
Set the Enable 32-Bit Application to True
Point your web application to use this new Pool
If it's a server socket, you should call listen()
on your socket, and then getsockname()
to find the port number on which it is listening:
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
perror("getsockname");
else
printf("port number %d\n", ntohs(sin.sin_port));
As for the IP address, if you use INADDR_ANY
then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname()
on the socket for a specific connection (which you get from accept()
) in order to find out which local IP address is being used on that connection.
If you are looking for a Ruby class/method I used this, and I have also included the tests:
class Binary
def self.binary_to_decimal(binary)
binary_array = binary.to_s.chars.map(&:to_i)
total = 0
binary_array.each_with_index do |n, i|
total += 2 ** (binary_array.length-i-1) * n
end
total
end
end
class BinaryTest < Test::Unit::TestCase
def test_1
test1 = Binary.binary_to_decimal(0001)
assert_equal 1, test1
end
def test_8
test8 = Binary.binary_to_decimal(1000)
assert_equal 8, test8
end
def test_15
test15 = Binary.binary_to_decimal(1111)
assert_equal 15, test15
end
def test_12341
test12341 = Binary.binary_to_decimal(11000000110101)
assert_equal 12341, test12341
end
end
If you are on Ubuntu you don't need to write any other code except your Python file's code , Here are the Steps :-
Remove leading + trailing '0':
list = [i.strip('0') for i in listOfNum ]
Remove leading '0':
list = [ i.lstrip('0') for i in listOfNum ]
Remove trailing '0':
list = [ i.rstrip('0') for i in listOfNum ]
something like this ? :
DataTable dt = ...
DataView dv = new DataView(dt);
dv.RowFilter = "(EmpName != 'abc' or EmpName != 'xyz') and (EmpID = 5)"
Is it what you are searching for?
this code will return duplicate value in same array
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
foreach($arr as $key=>$item){
if(array_count_values($arr)[$item] > 1){
echo "Found Matched value : ".$item." <br />";
}
}
a proper solution with streams and error handling is below:
const fs = require('fs')
const stream = require('stream')
app.get('/report/:chart_id/:user_id',(req, res) => {
const r = fs.createReadStream('path to file') // or any other way to get a readable stream
const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
stream.pipeline(
r,
ps, // <---- this makes a trick with stream error handling
(err) => {
if (err) {
console.log(err) // No such file or any other kind of error
return res.sendStatus(400);
}
})
ps.pipe(res) // <---- this makes a trick with stream error handling
})
with Node older then 10 you will need to use pump instead of pipeline.
How about this?
(A=1 OR B=1 OR C=1)
AND NOT (A=1 AND B=1 AND C=1)
And if A, B and C can have null values you would need the following:
(A=1 OR B=1 OR C=1)
AND NOT ( (A=1 AND A is not null) AND (B=1 AND B is not null) AND (C=1 AND C is not null) )
This is scalable to larger number of fields and hence more applicable.
StackOverflow will not allow me to comment on hesselbom's answer (not enough reputation), so I'm adding my own...
$array = preg_split('/\s*\R\s*/', trim($text), NULL, PREG_SPLIT_NO_EMPTY);
This worked best for me because it also eliminates leading (second \s*) and trailing (first \s*) whitespace automatically and also skips blank lines (the PREG_SPLIT_NO_EMPTY flag).
-= OPTIONS =-
If you want to keep leading whitespace, simply get rid of the second \s* and make it an rtrim() instead...
$array = preg_split('/\s*\R/', rtrim($text), NULL, PREG_SPLIT_NO_EMPTY);
If you need to keep empty lines, get rid of the NULL (it is only a placeholder) and PREG_SPLIT_NO_EMPTY flag, like so...
$array = preg_split('/\s*\R\s*/', trim($text));
Or keeping both leading whitespace and empty lines...
$array = preg_split('/\s*\R/', rtrim($text));
I don't see any reason why you'd ever want to keep trailing whitespace, so I suggest leaving the first \s* in there. But, if all you want is to split by new line (as the title suggests), it is THIS simple (as mentioned by Jan Goyvaerts)...
$array = preg_split('/\R/', $text);
You should be able to rely on os.name.
import os
if os.name == 'nt':
# ...
edit: Now I'd say the clearest way to do this is via the platform module, as per the other answer.
application/force-download
is not a standard MIME type. It's a hack supported by some browsers, added fairly recently.
Your question doesn't really make any sense. It's like asking why Internet Explorer 4 doesn't support the latest CSS 3 functionality.
try putting a delay on the last color fade.
$("p#44.test").delay(3000).css("background-color","red");
What are valid values for the id attribute in HTML?
ID's cannot start with digits!!!
As stated in a similar question, try removing instances of the input-group
class and see if that helps.
refering to bootstrap:
Individual form controls automatically receive some global styling. All textual , , and elements with .form-control are set to width: 100%; by default. Wrap labels and controls in .form-group for optimum spacing.
add attribute type="button" to the button on who's click you see the error, it worked for me.
you forgot an "r" at the end of divider in your divider xml layout
you call the layout @drawable/list_divider but your divider xml is named "list_divide"
in my case this fixed the problem:
sudo apt-get install libssl-dev libcurl4-openssl-dev python-dev
as explained here
Wrap in a div styled with "text-center" class.
For z-index:1000
to have an effect you need a non-static positioning scheme.
Add position:relative;
to a rule selecting the element you want to be on top
For merging first branch to second one:
on first branch: git merge secondBranch
on second branch: Move to first branch-> git checkout firstBranch-> git merge secondBranch
If you want to redirect for pages which reside within your website, then then here's my method - I've added the attribute href to the button, and onclick assigned this.getAttribute('href') to document.location.href
** It won't work if you reference for urls outsite of your domain because of 'X-Frame-Options' to 'sameorigin'.
Sample code:
<button onclick="document.location.href=this.getAttribute('href');" href="/">Home</button>
Try use this:
apt-get install r-base-dev
It will be help. After then I could makeinstall.packages('//package_name')
Coordinate[] coordinates = new Coordinate[3];
coordinates[0] = new Coordinate(102, 26);
coordinates[1] = new Coordinate(103, 25.12);
coordinates[2] = new Coordinate(104, 16.11);
CoordinateSequence coordinateSequence = new CoordinateArraySequence(coordinates);
Geometry geo = new LineString(coordinateSequence, geometryFactory);
CoordinateReferenceSystem wgs84 = DefaultGeographicCRS.WGS84;
CoordinateReferenceSystem cartesinaCrs = DefaultGeocentricCRS.CARTESIAN;
MathTransform mathTransform = CRS.findMathTransform(wgs84, cartesinaCrs, true);
Geometry geo1 = JTS.transform(geo, mathTransform);
As suggested by @The Berga You can add android:layoutDirection="rtl"
but it's only available with API 17.
for dynamic implementation, here it goes
chkBox.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
Run
docker images
to see a list of the images on the host. Let's say you have an image called awesomesauce. In your terminal, cd
to the directory where you want to export the image to. Now run:
docker save awesomesauce:latest > awesomesauce.tar
Copy the tar file to a thumb drive or whatever, and then copy it to the new host computer.
Now from the new host do:
docker load < awesomesauce.tar
Now go have a coffee and read Hacker News...
Based on http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html
What about:
Create Table New_Users Select * from Old_Users Where 1=2;
and if that doesn't work, just select a row and truncate after creation:
Create table New_Users select * from Old_Users Limit 1;
Truncate Table New_Users;
EDIT:
I noticed your comment below about needing indexes, etc. Try:
show create table old_users;
#copy the output ddl statement into a text editor and change the table name to new_users
#run the new query
insert into new_users(id,name...) select id,name,... form old_users group by id;
That should do it. It appears that you are doing this to get rid of duplicates? In which case you may want to put a unique index on id. if it's a primary key, this should already be in place. You can either:
#make primary key
alter table new_users add primary key (id);
#make unique
create unique index idx_new_users_id_uniq on new_users (id);
The instance of the inner class is created when instance of the outer class is created. Therefore the members and methods of the inner class have access to the members and methods of the instance (object) of the outer class. When the instance of the outer class goes out of scope, also the inner class instances cease to exist.
The static nested class doesn't have a concrete instance. It's just loaded when it's used for the first time (just like the static methods). It's a completely independent entity, whose methods and variables doesn't have any access to the instances of the outer class.
The static nested classes are not coupled with the outer object, they are faster, and they don't take heap/stack memory, because its not necessary to create instance of such class. Therefore the rule of thumb is to try to define static nested class, with as limited scope as possible (private >= class >= protected >= public), and then convert it to inner class (by removing "static" identifier) and loosen the scope, if it's really necessary.
here an extended version of the Stefan Farestam's answer:
function parse_yaml {
local prefix=$2
local s='[[:space:]]*' w='[a-zA-Z0-9_]*' fs=$(echo @|tr @ '\034')
sed -ne "s|,$s\]$s\$|]|" \
-e ":1;s|^\($s\)\($w\)$s:$s\[$s\(.*\)$s,$s\(.*\)$s\]|\1\2: [\3]\n\1 - \4|;t1" \
-e "s|^\($s\)\($w\)$s:$s\[$s\(.*\)$s\]|\1\2:\n\1 - \3|;p" $1 | \
sed -ne "s|,$s}$s\$|}|" \
-e ":1;s|^\($s\)-$s{$s\(.*\)$s,$s\($w\)$s:$s\(.*\)$s}|\1- {\2}\n\1 \3: \4|;t1" \
-e "s|^\($s\)-$s{$s\(.*\)$s}|\1-\n\1 \2|;p" | \
sed -ne "s|^\($s\):|\1|" \
-e "s|^\($s\)-$s[\"']\(.*\)[\"']$s\$|\1$fs$fs\2|p" \
-e "s|^\($s\)-$s\(.*\)$s\$|\1$fs$fs\2|p" \
-e "s|^\($s\)\($w\)$s:$s[\"']\(.*\)[\"']$s\$|\1$fs\2$fs\3|p" \
-e "s|^\($s\)\($w\)$s:$s\(.*\)$s\$|\1$fs\2$fs\3|p" | \
awk -F$fs '{
indent = length($1)/2;
vname[indent] = $2;
for (i in vname) {if (i > indent) {delete vname[i]; idx[i]=0}}
if(length($2)== 0){ vname[indent]= ++idx[indent] };
if (length($3) > 0) {
vn=""; for (i=0; i<indent; i++) { vn=(vn)(vname[i])("_")}
printf("%s%s%s=\"%s\"\n", "'$prefix'",vn, vname[indent], $3);
}
}'
}
This version supports the -
notation and the short notation for dictionaries and lists. The following input:
global:
input:
- "main.c"
- "main.h"
flags: [ "-O3", "-fpic" ]
sample_input:
- { property1: value, property2: "value2" }
- { property1: "value3", property2: 'value 4' }
produces this output:
global_input_1="main.c"
global_input_2="main.h"
global_flags_1="-O3"
global_flags_2="-fpic"
global_sample_input_1_property1="value"
global_sample_input_1_property2="value2"
global_sample_input_2_property1="value3"
global_sample_input_2_property2="value 4"
as you can see the -
items automatically get numbered in order to obtain different variable names for each item. In bash
there are no multidimensional arrays, so this is one way to work around. Multiple levels are supported.
To work around the problem with trailing white spaces mentioned by @briceburg one should enclose the values in single or double quotes. However, there are still some limitations: Expansion of the dictionaries and lists can produce wrong results when values contain commas. Also, more complex structures like values spanning multiple lines (like ssh-keys) are not (yet) supported.
A few words about the code: The first sed
command expands the short form of dictionaries { key: value, ...}
to regular and converts them to more simple yaml style. The second sed
call does the same for the short notation of lists and converts [ entry, ... ]
to an itemized list with the -
notation. The third sed
call is the original one that handled normal dictionaries, now with the addition to handle lists with -
and indentations. The awk
part introduces an index for each indentation level and increases it when the variable name is empty (i.e. when processing a list). The current value of the counters are used instead of the empty vname. When going up one level, the counters are zeroed.
Edit: I have created a github repository for this.
As noted, numpy.random.seed(0) sets the random seed to 0, so the pseudo random numbers you get from random will start from the same point. This can be good for debuging in some cases. HOWEVER, after some reading, this seems to be the wrong way to go at it, if you have threads because it is not thread safe.
from differences-between-numpy-random-and-random-random-in-python:
For numpy.random.seed(), the main difficulty is that it is not thread-safe - that is, it's not safe to use if you have many different threads of execution, because it's not guaranteed to work if two different threads are executing the function at the same time. If you're not using threads, and if you can reasonably expect that you won't need to rewrite your program this way in the future, numpy.random.seed() should be fine for testing purposes. If there's any reason to suspect that you may need threads in the future, it's much safer in the long run to do as suggested, and to make a local instance of the numpy.random.Random class. As far as I can tell, random.random.seed() is thread-safe (or at least, I haven't found any evidence to the contrary).
example of how to go about this:
from numpy.random import RandomState
prng = RandomState()
print prng.permutation(10)
prng = RandomState()
print prng.permutation(10)
prng = RandomState(42)
print prng.permutation(10)
prng = RandomState(42)
print prng.permutation(10)
may give:
[3 0 4 6 8 2 1 9 7 5]
[1 6 9 0 2 7 8 3 5 4]
[8 1 5 0 7 2 9 4 3 6]
[8 1 5 0 7 2 9 4 3 6]
Lastly, note that there might be cases where initializing to 0 (as opposed to a seed that has not all bits 0) may result to non-uniform distributions for some few first iterations because of the way xor works, but this depends on the algorithm, and is beyond my current worries and the scope of this question.
You should investigate why VBA can't find queryname.
I have a saved query named qryAddLoginfoRow. It inserts a row with the current time into my loginfo table. That query runs successfully when called by name by CurrentDb.Execute
.
CurrentDb.Execute "qryAddLoginfoRow"
My guess is that either queryname is a variable holding the name of a query which doesn't exist in the current database's QueryDefs collection, or queryname is the literal name of an existing query but you didn't enclose it in quotes.
Edit:
You need to find a way to accept that queryname does not exist in the current db's QueryDefs collection. Add these 2 lines to your VBA code just before the CurrentDb.Execute
line.
Debug.Print "queryname = '" & queryname & "'"
Debug.Print CurrentDb.QueryDefs(queryname).Name
The second of those 2 lines will trigger run-time error 3265, "Item not found in this collection." Then go to the Immediate window to verify the name of the query you're asking CurrentDb
to Execute
.
Try adding this:
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
By looking at your debug logs, you can notice that the failing PhpMailer log shows this:
(..snip..)
SMTP -> ERROR: AUTH not accepted from server: 250 orion.bommtempo.net.br Hello admin-teste.bommtempo.com.br [200.155.129.6]
(..snip..)
503 AUTH command used when not advertised
(..snip..)
While your successful PEAR log shows this:
DEBUG: Send: STARTTLS
DEBUG: Recv: 220 TLS go ahead
My guess is that explicitly asking PHPMailer to use TLS will put it on the right track.
Also, make sure you're using the latest versin of PHPMailer.
Use callbacks. Something like this should work based on your sample code.
function someFunc() {
callAjaxfunc(function() {
console.log('Pass2');
});
}
function callAjaxfunc(callback) {
//All ajax calls called here
onAjaxSuccess: function() {
callback();
};
console.log('Pass1');
}
This will print Pass1
immediately (assuming ajax request takes atleast a few microseconds), then print Pass2
when the onAjaxSuccess
is executed.
valign="top"
should do the work.
<tr>_x000D_
<td valign="top">Description</td>_x000D_
</tr>
_x000D_
Here is a solution I use in one of my project.
network_utils.telnet
import socket
from timeit import default_timer as timer
def telnet(hostname, port=23, timeout=1):
start = timer()
connection = socket.socket()
connection.settimeout(timeout)
try:
connection.connect((hostname, port))
end = timer()
delta = end - start
except (socket.timeout, socket.gaierror) as error:
logger.debug('telnet error: ', error)
delta = None
finally:
connection.close()
return {
hostname: delta
}
def test_telnet_is_null_when_host_unreachable(self):
hostname = 'unreachable'
response = network_utils.telnet(hostname)
self.assertDictEqual(response, {'unreachable': None})
def test_telnet_give_time_when_reachable(self):
hostname = '127.0.0.1'
response = network_utils.telnet(hostname, port=22)
self.assertGreater(response[hostname], 0)
I had the same error. But command "FLUSH PRIVILEGES;" didn't help. I did like that:
CREATE USER 'jimmy'@'localhost' IDENTIFIED BY 'test123';
UPDATE mysql.user SET USER='jack' WHERE USER='jimmy';
It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/
is the same as /../
, and that will get normalized away.
(This is a combination of an answer by bobince and a comment by slowpoison.)
The easiest way is
https://graph.facebook.com/me?fields=id&access_token="xxxxx"
then you will get json response which contains only userid.
The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.
Step 1:
Step 2:
I just had that problem (Java 1.8 vs. Java 9 on Windows 7) and my findings are:
short version
default seems to be (because of Path entry)
c:\ProgramData\Oracle\Java\javapath\java -version
select the version you want (test, use tab completing in cmd, not sure what those numbers represent), I had 2 options, see longer version for details
c:\ProgramData\Oracle\Java\javapath_target_[tab]
remove junction/link and link to your version (the one ending with 181743567 in my case for Java 8)
rmdir javapath
mklink /D javapath javapath_target_181743567
longer version:
Reinstall Java 1.8 after Java 9 didn't work. The sequence of installations was jdk1.8.0_74, jdk-9.0.4 and attempt to make Java 8 default with jdk1.8.0_162...
After jdk1.8.0_162 installation I still have
java -version
java version "9.0.4"
Java(TM) SE Runtime Environment (build 9.0.4+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode)
What I see in path is
Path=...;C:\ProgramData\Oracle\Java\javapath;...
So I checked what is that and I found it is a junction (link)
c:\ProgramData\Oracle\Java>dir
Volume in drive C is OSDisk
Volume Serial Number is DA2F-C2CC
Directory of c:\ProgramData\Oracle\Java
2018-02-07 17:06 <DIR> .
2018-02-07 17:06 <DIR> ..
2018-02-08 17:08 <DIR> .oracle_jre_usage
2017-08-22 11:04 <DIR> installcache
2018-02-08 17:08 <DIR> installcache_x64
2018-02-07 17:06 <JUNCTION> javapath [C:\ProgramData\Oracle\Java\javapath_target_185258831]
2018-02-07 17:06 <DIR> javapath_target_181743567
2018-02-07 17:06 <DIR> javapath_target_185258831
Those hashes doesn't ring a bell, but when I checked
c:\ProgramData\Oracle\Java\javapath_target_181743567>.\java -version
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)
c:\ProgramData\Oracle\Java\javapath_target_185258831>.\java -version
java version "9.0.4"
Java(TM) SE Runtime Environment (build 9.0.4+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode)
so to make Java 8 default again I had to delete the link as described here
rmdir javapath
and recreate with Java I wanted
mklink /D javapath javapath_target_181743567
tested:
c:\ProgramData\Oracle\Java>java -version
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)
** update (Java 10) **
With Java 10 it is similar, only javapath is in c:\Program Files (x86)\Common Files\Oracle\Java\ which is strange as I installed 64-bit IMHO
.\java -version
java version "10.0.2" 2018-07-17
Java(TM) SE Runtime Environment 18.3 (build 10.0.2+13)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.2+13, mixed mode)
In the Project Tool Window
, right-click a project or directory, where Python compiled files should be deleted from.
On the context menu, choose Clean Python compiled files
.
The .pyc
files residing in the selected directory are silently deleted.
In case you have composite primary key, do like this- ALTER TABLE table_name DROP PRIMARY KEY,ADD PRIMARY KEY (col_name1, col_name2);
In python 3
k = None
for name_of_the_group, group in dict(df_group):
if(k != name_of_the_group):
print ('\n', name_of_the_group)
print('..........','\n')
print (group)
k = name_of_the_group
In more interactive way
You can do it using only the shell, no need for tr
or sed
$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test
I have been developing and designing iOS apps for a while and This is the best iOS design cheat sheet out there!
have fun :)!
Update: For iOS 8+, and the new devices (iPhone 6, 6 Plus, iPad Air) see this updated link.
Meta update: Iphone 6s/6s Plus have the same resolutions as iPhone 6/6 Plus respectively
This is an image from the new version of the article:
Where possible, I prefer to call the function rather than dispatch an event. This works well if you have control over the code you want to run, but see below for cases where you don't own the code.
window.onresize = doALoadOfStuff;
function doALoadOfStuff() {
//do a load of stuff
}
In this example, you can call the doALoadOfStuff
function without dispatching an event.
In your modern browsers, you can trigger the event using:
window.dispatchEvent(new Event('resize'));
This doesn't work in Internet Explorer, where you'll have to do the longhand:
var resizeEvent = window.document.createEvent('UIEvents');
resizeEvent.initUIEvent('resize', true, false, window, 0);
window.dispatchEvent(resizeEvent);
jQuery has the trigger
method, which works like this:
$(window).trigger('resize');
And has the caveat:
Although
.trigger()
simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.
You can also simulate events on a specific element...
function simulateClick(id) {
var event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
var elem = document.getElementById(id);
return elem.dispatchEvent(event);
}
Hey guys a combination of 2 awnsers solved my problem. It was port related.
adb reverse tcp:8088 tcp:8088
react-native run-android --port=8088
By doing this, the app loaded fine of my phone connected by USB. I think my AV or Vagrant or something elses in my PC was using that port.
You can change 8088 to something else if needed.
Enjoy!
My experience with trying to use CSS to modify the scroll bars is don't. Only IE will let you do this.
For OS X make sure you have coreutils
$ brew install coreutils
$ bundle
Abstraction- Abstraction in simple words can be said as a way out in which the user is kept away from the complex details or detailed working of some system. You can also assume it as a simple way to solve any problem at the design and interface level.
You can say the only purpose of abstraction is to hide the details that can confuse a user. So for simplification purposes, we can use abstraction. Abstraction is also a concept of object-oriented programming. It hides the actual data and only shows the necessary information. For example, in an ATM machine, you are not aware that how it works internally. Only you are concerned to use the ATM interface. So that can be considered as a type of abstraction process.
Encapsulation- Encapsulation is also part of object-oriented programming. In this, all you have to do is to wrap up the data and code together so that they can work as a single unit. it works at the implementation level. it also improves the application Maintainance.
Encapsulation focuses on the process which will save information. Here you have to protect your data from external use.
The answer comes from the javadoc of ZoneId
(emphasis mine) ...
A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:
- Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
- Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply
Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.
... and from the javadoc of ZoneId#of
(emphasis mine):
This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.
The argument id is specified as "UTC"
, therefore it will return a ZoneId
with an offset, which also presented in the string form:
System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));
Outputs:
2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]
As you use the equals
method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false
.
When the normalized()
method is used as proposed in the documentation, the comparison using equals
will return true
, as normalized()
will return the corresponding ZoneOffset
:
Normalizes the time-zone ID, returning a ZoneOffset where possible.
now.withZoneSameInstant(ZoneOffset.UTC)
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true
As the documentation states, if you use "Z"
or "+0"
as input id, of
will return the ZoneOffset
directly and there is no need to call normalized()
:
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true
To check if they store the same date time, you can use the isEqual
method instead:
now.withZoneSameInstant(ZoneOffset.UTC)
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true
Sample
System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));
Output:
equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true
In answer to OP's three specific questions.
"What I don't understand is why the values in the before and after are the same?"
The first question and sample code shows that time()
has a resolution of 1 second, so the answer has to be that the two functions execute in less than 1 second. But occasionally it will (apparently illogically) inform 1 second if the two timer marks straddle a one second boundary.
The next example uses gettimeofday()
which fills this struct
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
and the second question asks: "How do I read a result of **time taken = 0 26339
? Does that mean 26,339 nanoseconds = 26.3 msec?"
My second answer is the time taken is 0 seconds and 26339 microseconds, that is 0.026339 seconds, which bears out the first example executing in less than 1 second.
The third question asks: "What about **time taken = 4 45025
, does that mean 4 seconds and 25 msec?"
My third answer is the time taken is 4 seconds and 45025 microseconds, that is 4.045025 seconds, which shows that OP has altered the tasks performed by the two functions which he previously timed.
Formatted :
$("input:checkbox[name=type]:checked").each(function(){
yourArray.push($(this).val());
});
Hopefully, it will work.
This issue is indeed usually caused by setting a parameter value to null as HLGEM mentioned above. I thought i would elaborate on some solutions to this problem that i have found useful for the benefit of people new to this problem.
The solution that i prefer is to default the stored procedure parameters to NULL (or whatever value you want), which was mentioned by sangram above, but may be missed because the answer is very verbose. Something along the lines of:
CREATE PROCEDURE GetEmployeeDetails
@DateOfBirth DATETIME = NULL,
@Surname VARCHAR(20),
@GenderCode INT = NULL,
AS
This means that if the parameter ends up being set in code to null under some conditions, .NET will not set the parameter and the stored procedure will then use the default value it has defined. Another solution, if you really want to solve the problem in code, would be to use an extension method that handles the problem for you, something like:
public static SqlParameter AddParameter<T>(this SqlParameterCollection parameters, string parameterName, T value) where T : class
{
return value == null ? parameters.AddWithValue(parameterName, DBNull.Value) : parameters.AddWithValue(parameterName, value);
}
Matt Hamilton has a good post here that lists some more great extension methods when dealing with this area.
I solved this problem by using the following,
@await Html.PartialAsync("_ValidationScriptsPartial")
You can certainly #define a macro as shown below. The compiler will replace "IMAGE_SEGMENT" with its value before compilation. While you will achieve defining a global lookup for your array, it is not the same as a global variable. When the macro is expanded, it works just like inline code and so a new image is created each time. So if you are careful in where you use the macro, then you would have effectively achieved creating a global variable.
#define IMAGE_SEGMENT [[NSImage alloc] initWithContentsOfFile:@"/User/asd.jpg"];
Then use it where you need it as shown below. Each time the below code is executed, a new object is created with a new memory pointer.
imageSegment = IMAGE_SEGMENT
Open ThisWorkbook.Path & "\template.txt" For Output As #1
Print #1, strContent
Close #1
Open
statement Print #
statementClose
statementPrint
StatementWorkbook.Path
propertyHere is a way to count occurrences inside an array of objects. It also places the first array's contents inside a new array to sort the values so that the order in the original array is not disrupted. Then a recursive function is used to go through each element and count the quantity property of each object inside the array.
var big_array = [
{ name: "Pineapples", quantity: 3 },
{ name: "Pineapples", quantity: 1 },
{ name: "Bananas", quantity: 1 },
{ name: "Limes", quantity: 1 },
{ name: "Bananas", quantity: 1 },
{ name: "Pineapples", quantity: 2 },
{ name: "Pineapples", quantity: 1 },
{ name: "Bananas", quantity: 1 },
{ name: "Bananas", quantity: 1 },
{ name: "Bananas", quantity: 5 },
{ name: "Coconuts", quantity: 1 },
{ name: "Lemons", quantity: 2 },
{ name: "Oranges", quantity: 1 },
{ name: "Lemons", quantity: 1 },
{ name: "Limes", quantity: 1 },
{ name: "Grapefruit", quantity: 1 },
{ name: "Coconuts", quantity: 5 },
{ name: "Oranges", quantity: 6 }
];
function countThem() {
var names_array = [];
for (var i = 0; i < big_array.length; i++) {
names_array.push( Object.assign({}, big_array[i]) );
}
function outerHolder(item_array) {
if (item_array.length > 0) {
var occurrences = [];
var counter = 0;
var bgarlen = item_array.length;
item_array.sort(function(a, b) { return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0); });
function recursiveCounter() {
occurrences.push(item_array[0]);
item_array.splice(0, 1);
var last_occurrence_element = occurrences.length - 1;
var last_occurrence_entry = occurrences[last_occurrence_element].name;
var occur_counter = 0;
var quantity_counter = 0;
for (var i = 0; i < occurrences.length; i++) {
if (occurrences[i].name === last_occurrence_entry) {
occur_counter = occur_counter + 1;
if (occur_counter === 1) {
quantity_counter = occurrences[i].quantity;
} else {
quantity_counter = quantity_counter + occurrences[i].quantity;
}
}
}
if (occur_counter > 1) {
var current_match = occurrences.length - 2;
occurrences[current_match].quantity = quantity_counter;
occurrences.splice(last_occurrence_element, 1);
}
counter = counter + 1;
if (counter < bgarlen) {
recursiveCounter();
}
}
recursiveCounter();
return occurrences;
}
}
alert(JSON.stringify(outerHolder(names_array)));
}
npm ls
npm list
is just an alias for npm ls
For the extended info use
npm la
npm ll
You can always set --depth=0
at the end to get the first level deep.
npm ls --depth=0
You can check development and production packages.
npm ls --only=dev
npm ls --only=prod
To show the info in json
format
npm ls --json=true
The default is false
npm ls --json=false
You can insist on long format to show extended information.
npm ls --long=true
You can show parseable output instead of tree view.
npm ls --parseable=true
You can list packages in the global install prefix instead of in the current project.
npm ls --global=true
npm ls -g // shorthand
Full documentation you can find here.
I get enum values in this way:
SELECT COLUMN_TYPE
FROM information_schema.`COLUMNS`
WHERE TABLE_NAME = 'tableName'
AND COLUMN_NAME = 'columnName';
Running this sql I have get : enum('BDBL','AB Bank')
then I have filtered just value using following code :
preg_match("/^enum\(\'(.*)\'\)$/", $type, $matches);
$enum = explode("','", $matches[1]);
var_dump($enum) ;
Out put :
array(2) { [0]=> string(4) "BDBL" [1]=> string(7) "AB Bank" }
After long search and hours of trying this is the simplest code i could make:
ShapeDrawable border = new ShapeDrawable(new RectShape());
border.getPaint().setStyle(Style.STROKE);
border.getPaint().setColor(Color.BLACK);
tv.setBackground(border);
content.addView(tv);
tv is a TextView with a simple text and content is my container (LinearLayout in this Case). That's a little easier.
Use .on()
you need event delegation as these classes are not present on DOM when DOM is ready.
$(document).on("click", ".clickable", function () {
$(this).addClass("grown");
$(this).removeClass("spot");
});
$(document).on("click", ".close_button", function () {
$("#spot1").removeClass("grown");
$("#spot1").addClass("spot");
});
Your code is fine. Only the super was missing in the method :
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO add your menu :
inflater.inflate(R.menu.my_menu, menu);
//TODO call super
super.onCreateOptionsMenu(menu, inflater);
}
I was having the same issue and this works excellently.
Private Sub DataGridView17_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView17.CellFormatting
'Display complete contents in tooltip even though column display cuts off part of it.
DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).ToolTipText = DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
End Sub
I had hit this when I was trying to initiate a SOAP request from Java code. What worked for me was:
Get the Server certificate by hitting the URL in browser: http://docs.bvstools.com/home/ssl-documentation/exporting-certificate-authorities-cas-from-a-website This link has all the steps to get the server certificate
Once you have the server certificate with you follow http://java.globinch.com/enterprise-java/security/pkix-path-building-failed-validation-sun-security-validatorexception/#Valid-Certification-Path-to-Requested-Target .
Copying the text from the link, in case this link dies:
All you need to do to fix this error is to add the server certificate to your trusted Java key store. First You need to download the document from the server.
Once you have the certificate in your hard drive you can import it to the Java trust store. To import the certificate to the trusted Java key store, you can use the java ‘keytool‘ tool. On command prompt navigate to JRE bin folder, in my case the path is : C:\Program Files\Java\jdk1.7.0_75\jre\bin . Then use keytool command as follows to import the certificate to JRE.
keytool -import -alias _alias_name_ -keystore ..\lib\security\cacerts -file _path_to_cer_file
It will ask for a password. By default the password is “changeit”. If the password is different you may not be able to import the certificate.
You can set triangle with position see this code for reference
.top-left-corner {
width: 0px;
height: 0px;
border-top: 0px solid transparent;
border-bottom: 55px solid transparent;
border-left: 55px solid #289006;
position: absolute;
left: 0px;
top: 0px;
}
For boot2docker on Windows, after seeing:
FATA[0000] Get http:///var/run/docker.sock/v1.18/version:
dial unix /var/run/docker.sock: no such file or directory.
Are you trying to connect to a TLS-enabled daemon without TLS?
All I did was:
boot2docker start
boot2docker shellinit
That generated:
export DOCKER_CERT_PATH=C:\Users\vonc\.boot2docker\certs\boot2docker-vm
export DOCKER_TLS_VERIFY=1
export DOCKER_HOST=tcp://192.168.59.103:2376
Finally:
boot2docker ssh
And docker works again
Modify your HTML like this:
<table border="0" cellpadding="0" cellspacing="0">
<thead>
<tr><td>1</td><td>2</td><td>3</td></tr>
</thead>
<tbody>
<tr><td>a</td><td>b></td><td>c</td></tr>
<tr class='odd'><td>x</td><td>y</td><td>z</td></tr>
</tbody>
</table>
(I added border="0" cellpadding="0" cellspacing="0"
)
In CSS, you could do the following:
table {
border-collapse: collapse;
}
Using the most modern syntax available at the moment, it can be done very cleanly like this:
for (const a of document.querySelectorAll("a")) {
if (a.textContent.includes("your search term")) {
console.log(a.textContent)
}
}
Or with a separate filter:
[...document.querySelectorAll("a")]
.filter(a => a.textContent.includes("your search term"))
.forEach(a => console.log(a.textContent))
Naturally, legacy browsers won't handle this, but you can use a transpiler if legacy support is needed.
A jquery solution has been implemented, and source code is available in github at: https://github.com/jackmoore/autosize .
enumerate()
makes this prettier:
for index, value in enumerate(S):
print index, value
See here for more.
We can't define enumeration as string type. The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
If you need more details on enumeration please follow below link,that link will help you to understand enumeration. Enumeration
@narendras1414
methods in blow for your goal
public static String removeNonAscii(String str)
{
return str.replaceAll("[^\\x00-\\x7F]", "");
}
public static String removeNonPrintable(String str) // All Control Char
{
return str.replaceAll("[\\p{C}]", "");
}
public static String removeSomeControlChar(String str) // Some Control Char
{
return str.replaceAll("[\\p{Cntrl}\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]", "");
}
public static String removeFullControlChar(String str)
{
return removeNonPrintable(str).replaceAll("[\\r\\n\\t]", "");
}
You are correct that storing the password in a plain-text field is a horrible idea. However, as far as location goes, for most of the cases you're going to encounter (and I honestly can't think of any counter-examples) storing the representation of a password in the database is the proper thing to do. By representation I mean that you want to hash the password using a salt (which should be different for every user) and a secure 1-way algorithm and store that, throwing away the original password. Then, when you want to verify a password, you hash the value (using the same hashing algorithm and salt) and compare it to the hashed value in the database.
So, while it is a good thing you are thinking about this and it is a good question, this is actually a duplicate of these questions (at least):
To clarify a bit further on the salting bit, the danger with simply hashing a password and storing that is that if a trespasser gets a hold of your database, they can still use what are known as rainbow tables to be able to "decrypt" the password (at least those that show up in the rainbow table). To get around this, developers add a salt to passwords which, when properly done, makes rainbow attacks simply infeasible to do. Do note that a common misconception is to simply add the same unique and long string to all passwords; while this is not horrible, it is best to add unique salts to every password. Read this for more.
This answer is for "One Man" Team to solve this problem quickly without reading through too many information about "Team"
Step 1) Go to web browser, open your developer account. Go to Certificates, Identifiers & Profiles. Select Certificates / Production. You will see the certificate that was missing private key listed there. Click Revoke. And follow the instructions to remove this certificate. Step 2) That's it! go back to Xcode to Validate you app. It will now ask you to generate a new certificate. Now you happily uploading your apps.
You can add a new module to any application as Blundell says on his answer and then reference it from any other application.
If you want to move the module to any place on your computer just move the module folder (modules are completely independent), then you will have to reference the module.
To reference this module you should:
On build.gradle file of your app add:
dependencies {
...
compile project(':myandroidlib')
}
On settings.gradle file add the following:
include ':app', ':myandroidlib'
project(':myandroidlib').projectDir = new File(PATH_TO_YOUR_MODULE)
you can do it in tomcat instance level config file (web.xml) need to add the 'filter' and filter-mapping' in web.xml config file. this will add the [X-frame-options = DENY] in all the page as it is a global setting.
<filter>
<filter-name>httpHeaderSecurity</filter-name>
<filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>antiClickJackingEnabled</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>antiClickJackingOption</param-name>
<param-value>DENY</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>httpHeaderSecurity</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
There's also AppGyver Steroids that unites PhoneGap and Native UI nicely.
With Steroids you can add things like native tabs, native navigation bar, native animations and transitions, native modal windows, native drawer/panel (facebooks side menu) etc. to your PhoneGap app.
Here's a demo: http://youtu.be/oXWwDMdoTCk?t=20m17s
That's compiled code, you'll need to use a decompiler like JAD: http://www.kpdus.com/jad.html
Microsoft Core Library, ie they are at the heart of everything.
There is a more "massaged" explanation you may prefer:
"When Microsoft first started working on the .NET Framework, MSCorLib.dll was an acronym for Microsoft Common Object Runtime Library. Once ECMA started to standardize the CLR and parts of the FCL, MSCorLib.dll officially became the acronym for Multilanguage Standard Common Object Runtime Library."
From http://weblogs.asp.net/mreynolds/archive/2004/01/31/65551.aspx
Around 1999, to my personal memory, .Net was known as "COOL", so I am a little suspicious of this derivation. I never heard it called "COR", which is a silly-sounding name to a native English speaker.
Add "ref" to h1 tag :
<h1 ref="source">Hey there.</h1>
and
const { source } = this.props;
change to const { source } = this.refs;
Both Stubs and Mocks override external dependencies but the difference is
Stubs -> To Test Data
Mocks -> To Test Behavior
Fake/Dummy -> Test nothing (just override functionality with empty methods, eg replace Logger
to avoid any logging noise while testing)
It's because size_t can be anything other than an int (maybe a struct). The idea is that it decouples it's job from the underlying type.
This error usually appears when you're missing a file from the jQuery UI set.
Double-check that you have all the files, the jQuery UI files as well as the CSS and images, and that they're in the correctly linked file/directory location on your server.
From the documentation on http://curl.haxx.se/docs/httpscripting.html :
HTTP Authentication
curl --user name:password http://www.example.com
Put a file to a HTTP server with curl:
curl --upload-file uploadfile http://www.example.com/receive.cgi
Send post data with curl:
curl --data "birthyear=1905&press=%20OK%20" http://www.example.com/when.cgi
double m[][]
declares an array of arrays, so called multidimensional array.
m[0]
points to an array in the size of four, containing 0*0,1*0,2*0,3*0.
Simple math shows the values are actually 0,0,0,0.
Second line is also array in the size of four, containing 0,1,2,3.
And so on...
I guess this mutiple format in you book was to show that 0*0 is row 0 column 0, 0*1 is row 0 column 1, and so on.
You shall pass a this
pointer to tell the function which object to work on because it relies on that as opposed to a static
member function.
If you use the track by
option, the value
attribute is correctly written, e.g.:
<div ng-init="a = [{label: 'one', value: 15}, {label: 'two', value: 20}]">
<select ng-model="foo" ng-options="x for x in a track by x.value"/>
</div>
produces:
<select>
<option value="" selected="selected"></option>
<option value="15">one</option>
<option value="20">two</option>
</select>
I think you mean to update it back to the OLD
password, when the NEW one is not supplied.
DROP TRIGGER IF EXISTS upd_user;
DELIMITER $$
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
IF (NEW.password IS NULL OR NEW.password = '') THEN
SET NEW.password = OLD.password;
ELSE
SET NEW.password = Password(NEW.Password);
END IF;
END$$
DELIMITER ;
However, this means a user can never blank out a password.
DELIMITER $$
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN
SET NEW.password = OLD.password;
ELSE
SET NEW.password = Password(NEW.Password);
END IF;
END$$
DELIMITER ;
This was good enough for me
sudo /etc/init.d/mysql restart
It's enough,if you put in list_row_layout.xml
:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:background="@drawable/listitem_background">... </LinearLayout>
listitem_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/dark" android:state_pressed="true" />
<item android:drawable="@color/dark" android:state_focused="true" />
<item android:drawable="@android:color/white" />
</selector>
Split-Path -Path (Get-Location).Path -Parent
This is how I did it with Kotlin to show progress with percentage.
My fragment layout.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ProgressBar
android:layout_marginLeft="32dp"
android:layout_marginRight="32dp"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/progressBar"/>
</FrameLayout>
My kotlin fragment in onViewCreated
progressBar.max = 100;
webView.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
progressBar.progress = newProgress;
}
}
webView!!.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
progressBar.visibility = View.VISIBLE
progressBar.progress = 0;
super.onPageStarted(view, url, favicon)
}
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
view?.loadUrl(url)
return true
}
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view?.loadUrl(request?.url.toString())
}
return true
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
progressBar.visibility = View.GONE
}
}
webView.loadUrl(url)
Yes, you have a }
too many. Anyway, compressing yourself tends to result in errors.
function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
} // <-- end function?
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}
Use Closure Compiler instead.
I used base64 for the overcoming the same problem, i.e. people can see my password over my shoulder.
Here is what I did - I created a new "db_auth.cfg" file and created parameters with one being my db password. I set the permission as 750 for the file.
DB_PASSWORD=Z29vZ2xl
In my shell script I used the "source" command to get the file and then decode it back to use in my script.
source path_to_the_file/db_auth.cfg
DB_PASSWORD=$(eval echo ${DB_PASSWORD} | base64 --decode)
I hope this helps.
There are already many nice answer about functional differences - so here I want to focus on performance. Today (2020.06.25) I perform tests for Chrome 83.0, Safari 13.1 and Firefox 77.0 for solutions mention in question and additionally from chosen answers
splice
(B) solution is fast for small and big arraysdelete
(A) solution is fastest for big and medium fast for small arraysfilter
(E) solution is fastest on Chrome and Firefox for small arrays (but slowest on Safari, and slow for big arrays)function C(arr, idx) {
var rest = arr.slice(idx + 1 || arr.length);
arr.length = idx < 0 ? arr.length + idx : idx;
arr.push.apply(arr, rest);
return arr;
}
// Crash test
let arr = [...'abcdefghij'.repeat(100000)]; // 1M elements
try {
C(arr,1)
} catch(e) {console.error(e.message)}
_x000D_
I perform following tests for solutions A B C D E (my)
function A(arr, idx) {
delete arr[idx];
return arr;
}
function B(arr, idx) {
arr.splice(idx,1);
return arr;
}
function C(arr, idx) {
var rest = arr.slice(idx + 1 || arr.length);
arr.length = idx < 0 ? arr.length + idx : idx;
arr.push.apply(arr, rest);
return arr;
}
function D(arr,idx){
return arr.slice(0,idx).concat(arr.slice(idx + 1));
}
function E(arr,idx) {
return arr.filter((a,i) => i !== idx);
}
myArray = ['a', 'b', 'c', 'd'];
[A,B,C,D,E].map(f => console.log(`${f.name} ${JSON.stringify(f([...myArray],1))}`));
_x000D_
This snippet only presents used solutions
_x000D_
Example results for Chrome
Modifying, or more correctly, adding additional HTTP headers is a great code debugging tool if nothing else.
When a URL request returns a redirect or an image there is no html "page" to temporarily write the results of debug code to - at least not one that is visible in a browser.
One approach is to write the data to a local log file and view that file later. Another is to temporarily add HTTP headers reflecting the data and variables being debugged.
I regularly add extra HTTP headers like X-fubar-somevar: or X-testing-someresult: to test things out - and have found a lot of bugs that would have otherwise been very difficult to trace.
You must get it via compatible way, others are deprecated:
Drawable drawable = ResourcesCompat.getDrawable(context.getResources(), R.drawable.my_drawable, null);
Multi joins in SQL work by progressively creating derived tables one after the other. See this link explaining the process:
https://www.interfacett.com/blogs/multiple-joins-work-just-like-single-joins/
We solved this problem with deleting .vs folder on project folder and deleting temporary ASP.NET files.
1. Close the Visual Studio.
2. Delete .vs folder on project folder that includes applicationhost.config file.
3. Delete temporary ASP.NET Files located: C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root
Updated! 3/24/2015 (scroll below hr)
lonesomeday's answer is absolutely correct, I just thought I would add this tidbit. I had made a method a while back for getting browser in Vanilla JS and eventually curved it to replace jQuery.browser
in later versions of jQuery. It does not interfere with any part of the new jQuery lib, but provides the same functionality of the traditional jQuery.browser
object, as well as some other little features.
New Extended Version!
Is much more thorough for newer browser. Also, 90+% accuracy on mobile testing! I won't say 100%, as I haven't tested on every mobile browser, but new feature adds $.browser.mobile
boolean/string. It's false if not mobile, else it will be a String name for the mobile device or browser (Best Guesss like: Android, RIM Tablet, iPod, etc...).
One possible caveat, may not work with some older (unsupported) browsers as it is completely reliant on userAgent
string.
/* quick & easy cut & paste */
;;(function($){if(!$.browser&&1.9<=parseFloat($.fn.jquery)){var a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].replace(/[^0-9\.]/g,""))):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,"")))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].replace(/[^0-9\.]/g,""))):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].replace(/[^0-9\.]/g,""))):/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].replace(/[^0-9\.]/g,""))));if(a.browser)for(var b in a.browserArray)a[a.browserArray[b].toLowerCase()]=a.browser==a.browserArray[b];$.extend(!0,$.browser={},a)}})(jQuery);
/* quick & easy cut & paste */
jsFiddle "jQuery Plugin: Get Browser (Extended Alt Edition)"
/** jQuery.browser_x000D_
* @author J.D. McKinstry (2014)_x000D_
* @description Made to replicate older jQuery.browser command in jQuery versions 1.9+_x000D_
* @see http://jsfiddle.net/SpYk3/wsqfbe4s/_x000D_
*_x000D_
* @extends jQuery_x000D_
* @namespace jQuery.browser_x000D_
* @example jQuery.browser.browser == 'browserNameInLowerCase'_x000D_
* @example jQuery.browser.version_x000D_
* @example jQuery.browser.mobile @returns BOOLEAN_x000D_
* @example jQuery.browser['browserNameInLowerCase']_x000D_
* @example jQuery.browser.chrome @returns BOOLEAN_x000D_
* @example jQuery.browser.safari @returns BOOLEAN_x000D_
* @example jQuery.browser.opera @returns BOOLEAN_x000D_
* @example jQuery.browser.msie @returns BOOLEAN_x000D_
* @example jQuery.browser.mozilla @returns BOOLEAN_x000D_
* @example jQuery.browser.webkit @returns BOOLEAN_x000D_
* @example jQuery.browser.ua @returns navigator.userAgent String_x000D_
*/_x000D_
;;(function($){if(!$.browser&&1.9<=parseFloat($.fn.jquery)){var a={browser:void 0,version:void 0,mobile:!1};navigator&&navigator.userAgent&&(a.ua=navigator.userAgent,a.webkit=/WebKit/i.test(a.ua),a.browserArray="MSIE Chrome Opera Kindle Silk BlackBerry PlayBook Android Safari Mozilla Nokia".split(" "),/Sony[^ ]*/i.test(a.ua)?a.mobile="Sony":/RIM Tablet/i.test(a.ua)?a.mobile="RIM Tablet":/BlackBerry/i.test(a.ua)?a.mobile="BlackBerry":/iPhone/i.test(a.ua)?a.mobile="iPhone":/iPad/i.test(a.ua)?a.mobile="iPad":/iPod/i.test(a.ua)?a.mobile="iPod":/Opera Mini/i.test(a.ua)?a.mobile="Opera Mini":/IEMobile/i.test(a.ua)?a.mobile="IEMobile":/BB[0-9]{1,}; Touch/i.test(a.ua)?a.mobile="BlackBerry":/Nokia/i.test(a.ua)?a.mobile="Nokia":/Android/i.test(a.ua)&&(a.mobile="Android"),/MSIE|Trident/i.test(a.ua)?(a.browser="MSIE",a.version=/MSIE/i.test(navigator.userAgent)&&0<parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(a.ua.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge",/Trident/i.test(a.ua)&&/rv:([0-9]{1,}[\.0-9]{0,})/.test(a.ua)&&(a.version=parseFloat(a.ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")))):/Chrome/.test(a.ua)?(a.browser="Chrome",a.version=parseFloat(a.ua.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Opera/.test(a.ua)?(a.browser="Opera",a.version=parseFloat(a.ua.split("Version/")[1].replace(/[^0-9\.]/g,""))):/Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(a.ua)?(a.mobile="Kindle",/Silk/i.test(a.ua)?(a.browser="Silk",a.version=parseFloat(a.ua.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Kindle/i.test(a.ua)&&/Version/i.test(a.ua)&&(a.browser="Kindle",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,"")))):/BlackBerry/.test(a.ua)?(a.browser="BlackBerry",a.version=parseFloat(a.ua.split("/")[1].replace(/[^0-9\.]/g,""))):/PlayBook/.test(a.ua)?(a.browser="PlayBook",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/BB[0-9]{1,}; Touch/.test(a.ua)?(a.browser="Blackberry",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Android/.test(a.ua)?(a.browser="Android",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Safari/.test(a.ua)?(a.browser="Safari",a.version=parseFloat(a.ua.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""))):/Firefox/.test(a.ua)?(a.browser="Mozilla",a.version=parseFloat(a.ua.split("Firefox/")[1].replace(/[^0-9\.]/g,""))):/Nokia/.test(a.ua)&&(a.browser="Nokia",a.version=parseFloat(a.ua.split("Browser")[1].replace(/[^0-9\.]/g,""))));if(a.browser)for(var b in a.browserArray)a[a.browserArray[b].toLowerCase()]=a.browser==a.browserArray[b];$.extend(!0,$.browser={},a)}})(jQuery);_x000D_
/* - - - - - - - - - - - - - - - - - - - */_x000D_
_x000D_
var b = $.browser;_x000D_
console.log($.browser); // see console, working example of jQuery Plugin_x000D_
console.log($.browser.chrome);_x000D_
_x000D_
for (var x in b) {_x000D_
if (x != 'init')_x000D_
$('<tr />').append(_x000D_
$('<th />', { text: x }),_x000D_
$('<td />', { text: b[x] })_x000D_
).appendTo($('table'));_x000D_
}
_x000D_
table { border-collapse: collapse; }_x000D_
th, td { border: 1px solid; padding: .25em .5em; vertical-align: top; }_x000D_
th { text-align: right; }_x000D_
_x000D_
textarea { height: 500px; width: 100%; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<table></table>
_x000D_
You should also take a look at the at
command in Windows. It will launch a program at a certain time in the background which works in this case.
Another option is to use the nssm
service manager software. This will wrap whatever command you are running as a windows service.
UPDATE:
nssm
isn't very good. You should instead look at WinSW project. https://github.com/kohsuke/winsw
Hi this class can do speed and up test for your web page with this class:
from urllib.request import urlopen
from socket import socket
import time
def tcp_test(server_info):
cpos = server_info.find(':')
try:
sock = socket()
sock.connect((server_info[:cpos], int(server_info[cpos+1:])))
sock.close
return True
except Exception as e:
return False
def http_test(server_info):
try:
# TODO : we can use this data after to find sub urls up or down results
startTime = time.time()
data = urlopen(server_info).read()
endTime = time.time()
speed = endTime - startTime
return {'status' : 'up', 'speed' : str(speed)}
except Exception as e:
return {'status' : 'down', 'speed' : str(-1)}
def server_test(test_type, server_info):
if test_type.lower() == 'tcp':
return tcp_test(server_info)
elif test_type.lower() == 'http':
return http_test(server_info)
based on this
I modified the original to this:
^(?:(?:(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec))(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:(?:0?2|(?:Feb))(\/|-|\.)(?:29)\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
There are methods to scroll element directly into the view, but if you want to scroll to a point relative from an element, you have to do it manually:
Inside the click handler, get the position of the element relative to the document, subtract 20
and use window.scrollTo
:
var pos = $(this).offset();
var top = pos.top - 20;
var left = pos.left - 20;
window.scrollTo((left < 0 ? 0 : left), (top < 0 ? 0 : top));
I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:
SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;
Thanks for answering, it helped my train of thought.
You can access the fields by indexing the object array:
foreach (object[] item in selectedValues)
{
idTextBox.Text = item[0];
titleTextBox.Text = item[1];
contentTextBox.Text = item[2];
}
That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:
public class MyObject
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
Then you can do:
foreach (MyObject item in selectedValues)
{
idTextBox.Text = item.Id;
titleTextBox.Text = item.Title;
contentTextBox.Text = item.Content;
}
Improvement to @madprops answer - solution as a django management command:
import MySQLdb
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
host = settings.DATABASES['default']['HOST']
password = settings.DATABASES['default']['PASSWORD']
user = settings.DATABASES['default']['USER']
dbname = settings.DATABASES['default']['NAME']
db = MySQLdb.connect(host=host, user=user, passwd=password, db=dbname)
cursor = db.cursor()
cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)
sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print(f'Changing table "{row[0]}"...')
sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
cursor.execute(sql)
db.close()
Hope this helps anybody but me :)
Why javascript when you can use just css?
a[aria-expanded="true"]{_x000D_
background-color: #42DCA3;_x000D_
}
_x000D_
<li class="active">_x000D_
<a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true"> _x000D_
<span class="network-name">Google+</span>_x000D_
</a>_x000D_
</li>_x000D_
<li class="active">_x000D_
<a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false"> _x000D_
<span class="network-name">Google+</span>_x000D_
</a>_x000D_
</li>
_x000D_
For any CSS3-enabled browser you can use an adjacent sibling selector for styling your labels
input:checked + label {
color: white;
}
MDN's browser compatibility table says essentially all of the current, popular browsers (Chrome, IE, Firefox, Safari), on both desktop and mobile, are compatible.
You can use an extension method.
static class Extensions
{
public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable
{
return listToClone.Select(item => (T)item.Clone()).ToList();
}
}
When you zip()
together three lists containing 20 elements each, the result has twenty elements. Each element is a three-tuple.
See for yourself:
In [1]: a = b = c = range(20)
In [2]: zip(a, b, c)
Out[2]:
[(0, 0, 0),
(1, 1, 1),
...
(17, 17, 17),
(18, 18, 18),
(19, 19, 19)]
To find out how many elements each tuple contains, you could examine the length of the first element:
In [3]: result = zip(a, b, c)
In [4]: len(result[0])
Out[4]: 3
Of course, this won't work if the lists were empty to start with.
Add the UIScrollViewDelegate
and adding the following code to the viewDidAppear
method fixed it for me.
@interface testScrollViewController () <UIScrollViewDelegate>
-(void)viewDidAppear:(BOOL)animated {
self.scrollView.delegate = self;
self.scrollView.scrollEnabled = YES;
self.scrollView.contentSize = CGSizeMake(375, 800);
}
After thorough research I found the solution
Encoding
let plainData = (plainString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let base64String =plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
println(base64String) // bXkgcGxhbmkgdGV4dA==
Decoding
let decodedData = NSData(base64EncodedString: base64String, options:NSDataBase64DecodingOptions.fromRaw(0)!)
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
println(decodedString) // my plain data
More on this http://creativecoefficient.net/swift/encoding-and-decoding-base64/
My personal opinion is that it is a waste of time. I believe that the visual clutter and added verbosity is not worth it.
I have never been in a situation where I have reassigned (remember, this does not make objects immutable, all it means is that you can't reassign another reference to a variable) a variable in error.
But, of course, it's all personal preference ;-)
ping -n 11 -w 1000 127.0.0.1 > nul
Update
Beginner's mistake. Ping doesn't wait 1000 ms before or after an request, but inbetween requests. So to wait 10 seconds, you'll have to do 11 pings to have 10 'gaps' of a second inbetween.
Try: $(date +%F)
In my case I was using more than two variables, and this worked for me better:
cor(x = as.matrix(tbl), method = "pearson", use = "pairwise.complete.obs")
However:
If use has the value "pairwise.complete.obs" then the correlation or covariance between each pair of variables is computed using all complete pairs of observations on those variables. This can result in covariance or correlation matrices which are not positive semi-definite, as well as NA entries if there are no complete pairs for that pair of variables.