The Extended WPF Toolkit has one: NumericUpDown
Using the "Replace all" functionality, you can delete a line directly by ending your pattern with:
$\n?
$(\r\n)?
For instance, in your case :
.*#RedirectMatch Permanent.*$\n?
As its name is "numbers" it is clear it is a list of number... So an array of number... no need of the attribute type... Although I like the principle of specifying the type of field in a type attribute...
In SQL Server 2008 and above just do this:
SELECT DATEADD(day, 1, Getdate()) AS DateAdd;
I got this example from the *JavaScript Patterns Build Better Applications with Coding and Design Patterns book (by Stoyan Stefanov). In case you need some simple implementation class like a singleton object, you can use an immediate function as in the following:
var ClassName;
(function() {
var instance;
ClassName = function ClassName() {
// If the private instance variable is already initialized, return a reference
if(instance) {
return instance;
}
// If the instance is not created, save a pointer of the original reference
// to the private instance variable.
instance = this;
// All constructor initialization will be here
// i.e.:
this.someProperty = 0;
this.someMethod = function() {
// Some action here
};
};
}());
And you can check this example by following test case:
// Extending defined class like singleton object using the new prototype property
ClassName.prototype.nothing = true;
var obj_1 = new ClassName();
// Extending the defined class like a singleton object using the new prototype property
ClassName.prototype.everything = true;
var obj_2 = new ClassName();
// Testing makes these two objects point to the same instance
console.log(obj_1 === obj_2); // Result is true, and it points to the same instance object
// All prototype properties work
// no matter when they were defined
console.log(obj_1.nothing && obj_1.everything
&& obj_2.nothing && obj_2.everything); // Result true
// Values of properties which are defined inside of the constructor
console.log(obj_1.someProperty); // Outputs 0
console.log(obj_2.someProperty); // Outputs 0
// Changing property value
obj_1.someProperty = 1;
console.log(obj_1.someProperty); // Output 1
console.log(obj_2.someProperty); // Output 1
console.log(obj_1.constructor === ClassName); // Output true
This approach passes all test cases while a private static implementation will fail when a prototype extension is used (it can be fixed, but it will not be simple) and a public static implementation less advisable due to an instance is exposed to the public.
The poster didn't ask about looking up values if exact=FALSE
, but I'm adding this as an answer for my own reference and possibly others.
If you're looking up categorical values, use the other answers.
Excel's vlookup
also allows you to match match approximately for numeric values with the 4th argument(1) match=TRUE
. I think of match=TRUE
like looking up values on a thermometer. The default value is FALSE, which is perfect for categorical values.
If you want to match approximately (perform a lookup), R has a function called findInterval
, which (as the name implies) will find the interval / bin that contains your continuous numeric value.
However, let's say that you want to findInterval
for several values. You could write a loop or use an apply function. However, I've found it more efficient to take a DIY vectorized approach.
Let's say that you have a grid of values indexed by x and y:
grid <- list(x = c(-87.727, -87.723, -87.719, -87.715, -87.711),
y = c(41.836, 41.839, 41.843, 41.847, 41.851),
z = (matrix(data = c(-3.428, -3.722, -3.061, -2.554, -2.362,
-3.034, -3.925, -3.639, -3.357, -3.283,
-0.152, -1.688, -2.765, -3.084, -2.742,
1.973, 1.193, -0.354, -1.682, -1.803,
0.998, 2.863, 3.224, 1.541, -0.044),
nrow = 5, ncol = 5)))
and you have some values you want to look up by x and y:
df <- data.frame(x = c(-87.723, -87.712, -87.726, -87.719, -87.722, -87.722),
y = c(41.84, 41.842, 41.844, 41.849, 41.838, 41.842),
id = c("a", "b", "c", "d", "e", "f")
Here is the example visualized:
contour(grid)
points(df$x, df$y, pch=df$id, col="blue", cex=1.2)
You can find the x intervals and y intervals with this type of formula:
xrng <- range(grid$x)
xbins <- length(grid$x) -1
yrng <- range(grid$y)
ybins <- length(grid$y) -1
df$ix <- trunc( (df$x - min(xrng)) / diff(xrng) * (xbins)) + 1
df$iy <- trunc( (df$y - min(yrng)) / diff(yrng) * (ybins)) + 1
You could take it one step further and perform a (simplistic) interpolation on the z values in grid
like this:
df$z <- with(df, (grid$z[cbind(ix, iy)] +
grid$z[cbind(ix + 1, iy)] +
grid$z[cbind(ix, iy + 1)] +
grid$z[cbind(ix + 1, iy + 1)]) / 4)
Which gives you these values:
contour(grid, xlim = range(c(grid$x, df$x)), ylim = range(c(grid$y, df$y)))
points(df$x, df$y, pch=df$id, col="blue", cex=1.2)
text(df$x + .001, df$y, lab=round(df$z, 2), col="blue", cex=1)
df
# x y id ix iy z
# 1 -87.723 41.840 a 2 2 -3.00425
# 2 -87.712 41.842 b 4 2 -3.11650
# 3 -87.726 41.844 c 1 3 0.33150
# 4 -87.719 41.849 d 3 4 0.68225
# 6 -87.722 41.838 e 2 1 -3.58675
# 7 -87.722 41.842 f 2 2 -3.00425
Note that ix, and iy could have also been found with a loop using findInterval
, e.g. here's one example for the second row
findInterval(df$x[2], grid$x)
# 4
findInterval(df$y[2], grid$y)
# 2
Which matches ix
and iy
in df[2]
Footnote: (1) The fourth argument of vlookup was previously called "match", but after they introduced the ribbon it was renamed to "[range_lookup]".
CTRL+SHIFT+ENTER, ARRAY FORMULA EXCEL 2016 MAC. So I arrive late into the game, but maybe someone else will. This almost drove me nuts. No matter what I searched for in Google I came up empty. Whatever I tried, no solution seemed to be in sight. Switched to Excel 2016 quite some time ago and today I needed to do some array formulas. Also sitting on a MacBook Pro 15 Touch Bar 2016. Not that it really matters, but still, since the solution was published on Youtube in 2013. The reason why, for me anyway, nothing worked, is in the Mac OS, the control key by default, for me anyway, is set to manage Mission control, which, at least for me, disabled the control button in Excel. In order to enable the key to actually control functions in Excel, you need to go to System preferences > Mission Control, and disable shortcuts for Mission control. So, let's see how long this solution will last. Probably be back to square one after the coffee break. Have a good one!
The answers above are incorrect, they will all run weather or not the submission is successful... You need to write an error component that will receive any errors then check if there are errors in state, if there are not then clear the form....
use .then()
example:
const onSubmit = e => {
e.preventDefault();
const fd = new FormData();
fd.append("ticketType", ticketType);
fd.append("ticketSubject", ticketSubject);
fd.append("ticketDescription", ticketDescription);
fd.append("itHelpType", itHelpType);
fd.append("ticketPriority", ticketPriority);
fd.append("ticketAttachments", ticketAttachments);
newTicketITTicket(fd).then(()=>{
setTicketData({
ticketType: "IT",
ticketSubject: "",
ticketDescription: "",
itHelpType: "",
ticketPriority: ""
})
})
};
You can also just access $s1 like an array, if you only need to access it:
$s1 = "hello world";
echo $s1[0]; // -> h
a version similar to C. Dragon's, but for if you only need a single replacement:
int n = myText.IndexOf(oldValue, System.StringComparison.InvariantCultureIgnoreCase);
if (n >= 0)
{
myText = myText.Substring(0, n)
+ newValue
+ myText.Substring(n + oldValue.Length);
}
Character arrays (char[]
) can be cleared after use by setting each character to zero and Strings not. If someone can somehow see the memory image, they can see a password in plain text if Strings are used, but if char[]
is used, after purging data with 0's, the password is secure.
This Problem is because of Path so you need to build the path using following Steps
Goto project ----->Right Click on Project Name ---->properties ---->click on Than Java Build Path option than ---> click Android 4.2.2---->Ok
ul > li > a
selects only the direct children. In this case only the first level <a>
of the first level <li>
inside the <ul>
will be selected.
ul li a
on the other hand will select ALL <a>
-s in ALL <li>
-s in the unordered list
Example of ul > li
ul > li.bg {_x000D_
background: red;_x000D_
}
_x000D_
<ul>_x000D_
<li class="bg">affected</li>_x000D_
<li class="bg">affected</li> _x000D_
<li>_x000D_
<ol>_x000D_
<li class="bg">NOT affected</li>_x000D_
<li class="bg">NOT affected</li>_x000D_
</ol>_x000D_
</li>_x000D_
</ul>
_x000D_
if you'd be using ul li
- ALL of the li
-s would be affected
UPDATE The order of more to less efficient CSS selectors goes thus:
#header
.promo
div
h2 + p
li > ul
ul a
*
[type="text"]
a:hover
So your better bet is to use the children
selector instead of just descendant
. However the difference on a regular page (without tens of thousands elements to go through) might be absolutely negligible.
Here is how I solved the same problem using the Oracle.DataAccess.Client
Namespace.
using Oracle.DataAccess.Client;
string strConnection = ConfigurationManager.ConnectionStrings["oConnection"].ConnectionString;
dataConnection = new OracleConnectionStringBuilder(strConnection);
OracleConnection oConnection = new OracleConnection(dataConnection.ToString());
oConnection.Open();
OracleCommand tmpCommand = oConnection.CreateCommand();
tmpCommand.Parameters.Add("user", OracleDbType.Varchar2, txtUser.Text, ParameterDirection.Input);
tmpCommand.CommandText = "SELECT USER, PASS FROM TB_USERS WHERE USER = :1";
try
{
OracleDataReader tmpReader = tmpCommand.ExecuteReader(CommandBehavior.SingleRow);
if (tmpReader.HasRows)
{
// PT: IMPLEMENTE SEU CÓDIGO
// ES: IMPLEMENTAR EL CÓDIGO
// EN: IMPLEMENT YOUR CODE
}
}
catch(Exception e)
{
// PT: IMPLEMENTE SEU CÓDIGO
// ES: IMPLEMENTAR EL CÓDIGO
// EN: IMPLEMENT YOUR CODE
}
Currently i am using since this is trustable for getting location and calculating distance for my application...... i am using this for my taxi application.
use the fusion API that google developer have developed with fusion of GPS Sensor,Magnetometer,Accelerometer also using Wifi or cell location to calculate or estimate the location. It is also able to give location updates also inside the building accurately. for detail get to link https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class MainActivity extends Activity implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final long ONE_MIN = 500;
private static final long TWO_MIN = 500;
private static final long FIVE_MIN = 500;
private static final long POLLING_FREQ = 1000 * 20;
private static final long FASTEST_UPDATE_FREQ = 1000 * 5;
private static final float MIN_ACCURACY = 1.0f;
private static final float MIN_LAST_READ_ACCURACY = 1;
private LocationRequest mLocationRequest;
private Location mBestReading;
TextView tv;
private GoogleApiClient mGoogleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!servicesAvailable()) {
finish();
}
setContentView(R.layout.activity_main);
tv= (TextView) findViewById(R.id.tv1);
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(POLLING_FREQ);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_FREQ);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
protected void onPause() {d
super.onPause();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
tv.setText(location + "");
// Determine whether new location is better than current best
// estimate
if (null == mBestReading || location.getAccuracy() < mBestReading.getAccuracy()) {
mBestReading = location;
if (mBestReading.getAccuracy() < MIN_ACCURACY) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
}
@Override
public void onConnected(Bundle dataBundle) {
// Get first reading. Get additional location updates if necessary
if (servicesAvailable()) {
// Get best last location measurement meeting criteria
mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
if (null == mBestReading
|| mBestReading.getAccuracy() > MIN_LAST_READ_ACCURACY
|| mBestReading.getTime() < System.currentTimeMillis() - TWO_MIN) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
//Schedule a runnable to unregister location listeners
@Override
public void run() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, MainActivity.this);
}
}, ONE_MIN, TimeUnit.MILLISECONDS);
}
}
}
@Override
public void onConnectionSuspended(int i) {
}
private Location bestLastKnownLocation(float minAccuracy, long minTime) {
Location bestResult = null;
float bestAccuracy = Float.MAX_VALUE;
long bestTime = Long.MIN_VALUE;
// Get the best most recent location currently available
Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
//tv.setText(mCurrentLocation+"");
if (mCurrentLocation != null) {
float accuracy = mCurrentLocation.getAccuracy();
long time = mCurrentLocation.getTime();
if (accuracy < bestAccuracy) {
bestResult = mCurrentLocation;
bestAccuracy = accuracy;
bestTime = time;
}
}
// Return best reading or null
if (bestAccuracy > minAccuracy || bestTime < minTime) {
return null;
}
else {
return bestResult;
}
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
private boolean servicesAvailable() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == resultCode) {
return true;
}
else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, 0).show();
return false;
}
}
}
you can add some javascript to surpress those obnoxious validation bubbles and add your own validators.
document.addEventListener('invalid', (function(){
return function(e) {
//prevent the browser from showing default error bubble / hint
e.preventDefault();
// optionally fire off some custom validation handler
// myValidation();
};
})(), true);
If you want to allow every bot to crawl everything, this is the best way to specify it in your robots.txt:
User-agent: *
Disallow:
Note that the Disallow
field has an empty value, which means according to the specification:
Any empty value, indicates that all URLs can be retrieved.
Your way (with Allow: /
instead of Disallow:
) works, too, but Allow
is not part of the original robots.txt specification, so it’s not supported by all bots (many popular ones support it, though, like the Googlebot). That said, unrecognized fields have to be ignored, and for bots that don’t recognize Allow
, the result would be the same in this case anyway: if nothing is forbidden to be crawled (with Disallow
), everything is allowed to be crawled.
However, formally (per the original spec) it’s an invalid record, because at least one Disallow
field is required:
At least one Disallow field needs to be present in a record.
You need to use <> operator:
while (<>) {
print $_; # or simply "print;"
}
Which can be compacted to:
print while (<>);
Arbitrary file:
open F, "<file.txt" or die $!;
while (<F>) {
print $_;
}
close F;
The broken pipe error usually occurs if your request is blocked or takes too long and after request-side timeout, it'll close the connection and then, when the respond-side (server) tries to write to the socket, it will throw a pipe broken error.
public class CryptographyProcessor
{
public string CreateSalt(int size)
{
//Generate a cryptographic random number.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
rng.GetBytes(buff);
return Convert.ToBase64String(buff);
}
public string GenerateHash(string input, string salt)
{
byte[] bytes = Encoding.UTF8.GetBytes(input + salt);
SHA256Managed sHA256ManagedString = new SHA256Managed();
byte[] hash = sHA256ManagedString.ComputeHash(bytes);
return Convert.ToBase64String(hash);
}
public bool AreEqual(string plainTextInput, string hashedInput, string salt)
{
string newHashedPin = GenerateHash(plainTextInput, salt);
return newHashedPin.Equals(hashedInput);
}
}
In my Reactive form, I needed to mark a field as invalid if another field was checked. In ng version 7 I did the following:
const checkboxField = this.form.get('<name of field>');
const dropDownField = this.form.get('<name of field>');
this.checkboxField$ = checkboxField.valueChanges
.subscribe((checked: boolean) => {
if(checked) {
dropDownField.setValidators(Validators.required);
dropDownField.setErrors({ required: true });
dropDownField.markAsDirty();
} else {
dropDownField.clearValidators();
dropDownField.markAsPristine();
}
});
So above, when I check the box it sets the dropdown as required and marks it as dirty. If you don't mark as such it then it won't be invalid (in error) until you try to submit the form or interact with it.
If the checkbox is set to false (unchecked) then we clear the required validator on the dropdown and reset it to a pristine state.
Also - remember to unsubscribe from monitoring field changes!
Taken from jQuery docs:
var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };
jQuery.each(arr, function() {
$("#" + this).text("My id is " + this + ".");
return (this != "four"); // will stop running to skip "five"
});
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
BufferedReader br = null;
try {
String fpath = Environment.getExternalStorageDirectory() + <your file name>;
try {
br = new BufferedReader(new FileReader(fpath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = "";
while ((line = br.readLine()) != null) {
//Do something here
}
EDIT: A simple possibility to eliminate before getting into more complicated solutions: have you tried setting the character set to utf8 in the text editor in which you're reading the file? This could just be a case of somebody sending you a utf8 file that you're reading in an editor set to say cp1252.
Just taking the two examples, this is a case of utf8 being read through the lens of a single-byte encoding, likely one of iso-8859-1, iso-8859-15, or cp1252. If you can post examples of other problem characters, it should be possible to narrow that down more.
As visual inspection of the characters can be misleading, you'll also need to look at the underlying bytes: the § you see on screen might be either 0xa7 or 0xc2a7, and that will determine the kind of character set conversion you have to do.
Can you assume that all of your data has been distorted in exactly the same way - that it's come from the same source and gone through the same sequence of transformations, so that for example there isn't a single é in your text, it's always ç? If so, the problem can be solved with a sequence of character set conversions. If you can be more specific about the environment you're in and the database you're using, somebody here can probably tell you how to perform the appropriate conversion.
Otherwise, if the problem characters are only occurring in some places in your data, you'll have to take it instance by instance, based on assumptions along the lines of "no author intended to put ç in their text, so whenever you see it, replace by ç". The latter option is more risky, firstly because those assumptions about the intentions of the authors might be wrong, secondly because you'll have to spot every problem character yourself, which might be impossible if there's too much text to visually inspect or if it's written in a language or writing system that's foreign to you.
For those who decided to use a structural directive as a replacement of *ngIf
, keep in mind that the directive context isn't type checked by default. To create a type safe directive ngTemplateContextGuard
property should be added, see Typing the directive's context. For example:
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
// don't use 'ng' prefix since it's reserved for Angular
selector: '[appVar]',
})
export class VarDirective<T = unknown> {
// https://angular.io/guide/structural-directives#typing-the-directives-context
static ngTemplateContextGuard<T>(dir: VarDirective<T>, ctx: any): ctx is Context<T> {
return true;
}
private context?: Context<T>;
constructor(
private vcRef: ViewContainerRef,
private templateRef: TemplateRef<Context<T>>
) {}
@Input()
set appVar(value: T) {
if (this.context) {
this.context.appVar = value;
} else {
this.context = { appVar: value };
this.vcRef.createEmbeddedView(this.templateRef, this.context);
}
}
}
interface Context<T> {
appVar: T;
}
The directive can be used just like *ngIf
, except that it can store false values:
<ng-container *appVar="false as value">{{value}}</ng-container>
<!-- error: User doesn't have `nam` property-->
<ng-container *appVar="user as user">{{user.nam}}</ng-container>
<ng-container *appVar="user$ | async as user">{{user.name}}</ng-container>
The only drawback compared to *ngIf
is that Angular Language Service cannot figure out the variable type so there is no code completion in templates. I hope it will be fixed soon.
You need run visudo
and in the editor that it opens write:
igor ALL=(ALL) ALL
That line grants all permissions to user igor
.
If you want permit to run only some commands, you need to list them in the line:
igor ALL=(ALL) /bin/kill, /bin/ps
Below are the steps to do revoke your JWT access token:
Please let me know if you need more details, I can share the code (Java + Spring boot) as well.
For your questions:
Q1: It's another JWT with fewer claims put in with long expiry time.
Q2: It won't be in a database. The backend will not store anywhere. They will just decrypt the token with private/public key and validate it with its expiry time also.
Q3: Yes, Correct
I'd like to provide an abstract, high-level perspective.
I/O operations interact with the environment. The environment is not part of your program, and not under your control. The environment truly exists "concurrently" with your program. As with all things concurrent, questions about the "current state" don't make sense: There is no concept of "simultaneity" across concurrent events. Many properties of state simply don't exist concurrently.
Let me make this more precise: Suppose you want to ask, "do you have more data". You could ask this of a concurrent container, or of your I/O system. But the answer is generally unactionable, and thus meaningless. So what if the container says "yes" – by the time you try reading, it may no longer have data. Similarly, if the answer is "no", by the time you try reading, data may have arrived. The conclusion is that there simply is no property like "I have data", since you cannot act meaningfully in response to any possible answer. (The situation is slightly better with buffered input, where you might conceivably get a "yes, I have data" that constitutes some kind of guarantee, but you would still have to be able to deal with the opposite case. And with output the situation is certainly just as bad as I described: you never know if that disk or that network buffer is full.)
So we conclude that it is impossible, and in fact unreasonable, to ask an I/O system whether it will be able to perform an I/O operation. The only possible way we can interact with it (just as with a concurrent container) is to attempt the operation and check whether it succeeded or failed. At that moment where you interact with the environment, then and only then can you know whether the interaction was actually possible, and at that point you must commit to performing the interaction. (This is a "synchronisation point", if you will.)
Now we get to EOF. EOF is the response you get from an attempted I/O operation. It means that you were trying to read or write something, but when doing so you failed to read or write any data, and instead the end of the input or output was encountered. This is true for essentially all the I/O APIs, whether it be the C standard library, C++ iostreams, or other libraries. As long as the I/O operations succeed, you simply cannot know whether further, future operations will succeed. You must always first try the operation and then respond to success or failure.
In each of the examples, note carefully that we first attempt the I/O operation and then consume the result if it is valid. Note further that we always must use the result of the I/O operation, though the result takes different shapes and forms in each example.
C stdio, read from a file:
for (;;) {
size_t n = fread(buf, 1, bufsize, infile);
consume(buf, n);
if (n == 0) { break; }
}
The result we must use is n
, the number of elements that were read (which may be as little as zero).
C stdio, scanf
:
for (int a, b, c; scanf("%d %d %d", &a, &b, &c) == 3; ) {
consume(a, b, c);
}
The result we must use is the return value of scanf
, the number of elements converted.
C++, iostreams formatted extraction:
for (int n; std::cin >> n; ) {
consume(n);
}
The result we must use is std::cin
itself, which can be evaluated in a boolean context and tells us whether the stream is still in the good()
state.
C++, iostreams getline:
for (std::string line; std::getline(std::cin, line); ) {
consume(line);
}
The result we must use is again std::cin
, just as before.
POSIX, write(2)
to flush a buffer:
char const * p = buf;
ssize_t n = bufsize;
for (ssize_t k = bufsize; (k = write(fd, p, n)) > 0; p += k, n -= k) {}
if (n != 0) { /* error, failed to write complete buffer */ }
The result we use here is k
, the number of bytes written. The point here is that we can only know how many bytes were written after the write operation.
POSIX getline()
char *buffer = NULL;
size_t bufsiz = 0;
ssize_t nbytes;
while ((nbytes = getline(&buffer, &bufsiz, fp)) != -1)
{
/* Use nbytes of data in buffer */
}
free(buffer);
The result we must use is nbytes
, the number of bytes up to and including the newline (or EOF if the file did not end with a newline).
Note that the function explicitly returns -1
(and not EOF!) when an error occurs or it reaches EOF.
You may notice that we very rarely spell out the actual word "EOF". We usually detect the error condition in some other way that is more immediately interesting to us (e.g. failure to perform as much I/O as we had desired). In every example there is some API feature that could tell us explicitly that the EOF state has been encountered, but this is in fact not a terribly useful piece of information. It is much more of a detail than we often care about. What matters is whether the I/O succeeded, more-so than how it failed.
A final example that actually queries the EOF state: Suppose you have a string and want to test that it represents an integer in its entirety, with no extra bits at the end except whitespace. Using C++ iostreams, it goes like this:
std::string input = " 123 "; // example
std::istringstream iss(input);
int value;
if (iss >> value >> std::ws && iss.get() == EOF) {
consume(value);
} else {
// error, "input" is not parsable as an integer
}
We use two results here. The first is iss
, the stream object itself, to check that the formatted extraction to value
succeeded. But then, after also consuming whitespace, we perform another I/O/ operation, iss.get()
, and expect it to fail as EOF, which is the case if the entire string has already been consumed by the formatted extraction.
In the C standard library you can achieve something similar with the strto*l
functions by checking that the end pointer has reached the end of the input string.
while(!feof)
is wrong because it tests for something that is irrelevant and fails to test for something that you need to know. The result is that you are erroneously executing code that assumes that it is accessing data that was read successfully, when in fact this never happened.
One of the most important steps is to sanitize any user input before it is processed and/or rendered back to the browser. PHP has some "filter" functions that can be used.
The form that XSS attacks usually have is to insert a link to some off-site javascript that contains malicious intent for the user. Read more about it here.
You'll also want to test your site - I can recommend the Firefox add-on XSS Me.
EDIT: updated code in order to reflect changes made to the way pipes work in more recent versions of RXJS. All operators (take in my example) are now wrapped into the pipe() operator.
I realize that this Question was quite a while ago and you surely have a proper solution by now, but for anyone looking for this I would suggest solving it with a Promise to keep the async pattern.
A more verbose version would be creating a new Promise:
function getValueFromObservable() {
return new Promise(resolve=>{
this.store.pipe(
take(1) //useful if you need the data once and don't want to manually cancel the subscription again
)
.subscribe(
(data:any) => {
console.log(data);
resolve(data);
})
})
}
On the receiving end you will then have "wait" for the promise to resolve with something like this:
getValueFromObservable()
.then((data:any)=>{
//... continue with anything depending on "data" after the Promise has resolved
})
A slimmer solution would be using RxJS' .toPromise() instead:
function getValueFromObservable() {
return this.store.pipe(take(1))
.toPromise()
}
The receiving side stays the same as above of course.
The CSS property display: inline-block
was designed to address this need. You can read a bit about it here: http://robertnyman.com/2010/02/24/css-display-inline-block-why-it-rocks-and-why-it-sucks/
Below is an example of its use. The key elements are that the row
element has white-space: nowrap
and the cell
elements have display: inline-block
. This example should work on most major browsers; a compatibility table is available here: http://caniuse.com/#feat=inline-block
<html>
<body>
<style>
.row {
float:left;
border: 1px solid yellow;
width: 100%;
overflow: auto;
white-space: nowrap;
}
.cell {
display: inline-block;
border: 1px solid red;
width: 200px;
height: 100px;
}
</style>
<div class="row">
<div class="cell">a</div>
<div class="cell">b</div>
<div class="cell">c</div>
</div>
</body>
</html>
Here's a cross-browser CSS-only solution. Hope it helps!
.progress .progress-bar {_x000D_
-moz-animation-name: animateBar;_x000D_
-moz-animation-iteration-count: 1;_x000D_
-moz-animation-timing-function: ease-in;_x000D_
-moz-animation-duration: .4s;_x000D_
_x000D_
-webkit-animation-name: animateBar;_x000D_
-webkit-animation-iteration-count: 1;_x000D_
-webkit-animation-timing-function: ease-in;_x000D_
-webkit-animation-duration: .4s;_x000D_
_x000D_
animation-name: animateBar;_x000D_
animation-iteration-count: 1;_x000D_
animation-timing-function: ease-in;_x000D_
animation-duration: .4s;_x000D_
}_x000D_
_x000D_
@-moz-keyframes animateBar {_x000D_
0% {-moz-transform: translateX(-100%);}_x000D_
100% {-moz-transform: translateX(0);}_x000D_
}_x000D_
@-webkit-keyframes animateBar {_x000D_
0% {-webkit-transform: translateX(-100%);}_x000D_
100% {-webkit-transform: translateX(0);}_x000D_
}_x000D_
@keyframes animateBar {_x000D_
0% {transform: translateX(-100%);}_x000D_
100% {transform: translateX(0);}_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
<h3>Progress bar animation on load</h3>_x000D_
_x000D_
<div class="progress">_x000D_
<div class="progress-bar progress-bar-success" style="width: 75%;"></div>_x000D_
</div>_x000D_
</div>
_x000D_
Here is another way to pad to the right:
// put the number of spaces, or any character you like, in your paddedString
String paddedString = "--------------------";
String myStringToBePadded = "I like donuts";
myStringToBePadded = myStringToBePadded + paddedString.substring(myStringToBePadded.length());
//result:
myStringToBePadded = "I like donuts-------";
The Date type is just an alias of the DateTime type used by VB.NET (like int becomes Integer). Both of these types have a Date property that returns you the object with the time part set to 00:00:00.
I've tested this for my project, it finds the max/min in O(n) time:
from django.db.models import Max
# Find the maximum value of the rating and then get the record with that rating.
# Notice the double underscores in rating__max
max_rating = App.objects.aggregate(Max('rating'))['rating__max']
return App.objects.get(rating=max_rating)
This is guaranteed to get you one of the maximum elements efficiently, rather than sorting the whole table and getting the top (around O(n*logn)).
In case if you want the desktop icon
In desktop, create a new shortcut, in Location paste this
%comspec% /k spyder3
then type the name Spyder,
Now you may have Desktop Icon for opening Spyder
You can quickly review the changes made to a file using the diff command:
git diff <commit hash> <filename>
Then to revert a specific file to that commit use the reset command:
git reset <commit hash> <filename>
You may need to use the --hard
option if you have local modifications.
A good workflow for managaging waypoints is to use tags to cleanly mark points in your timeline. I can't quite understand your last sentence but what you may want is diverge a branch from a previous point in time. To do this, use the handy checkout command:
git checkout <commit hash>
git checkout -b <new branch name>
You can then rebase that against your mainline when you are ready to merge those changes:
git checkout <my branch>
git rebase master
git checkout master
git merge <my branch>
before you send the email you can press <ESC> f
(Escape followed by f) to change the From:
Address.
Constraint: This only works if you use mutt in curses mode and do not wan't to script it or if you want to change the address permanent. Then the other solutions are way better!
Yet another way: if you are working with a C string, e.g. const char *, C native atoi()
is more convenient.
the
:checked
pseudo-class initially applies to such elements that have the HTML4selected
andchecked
attributes
Source: w3.org
So, this CSS works, although styling the color
is not possible in every browser:
option:checked { color: red; }
An example of this in action, hiding the currently selected item from the drop down list.
option:checked { display:none; }
_x000D_
<select>_x000D_
<option>A</option>_x000D_
<option>B</option>_x000D_
<option>C</option>_x000D_
</select>
_x000D_
To style the currently selected option in the closed dropdown as well, you could try reversing the logic:
select { color: red; }
option:not(:checked) { color: black; } /* or whatever your default style is */
Simply do this in angular2+ by adding (onkeypress)
<input type="number"
maxlength="3"
min="0"
max="100"
required
mdInput
placeholder="Charge"
[(ngModel)]="rateInput"
(onkeypress)="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57"
name="rateInput">
Tested on Angular 7
Simply type in the console :
$ git reset HEAD~
This command discards all local commits ahead of the remote HEAD
I am sure you would've already found your answer... here is the solution I derived at.
That's my CSS.
.field, .actions {
margin-bottom: 15px;
}
.field label {
float: left;
width: 30%;
text-align: right;
padding-right: 10px;
margin: 5px 0px 5px 0px;
}
.field input {
width: 70%;
margin: 0px;
}
And my HTML...
<h1>New customer</h1>
<div class="container form-center">
<form accept-charset="UTF-8" action="/customers" class="new_customer" id="new_customer" method="post">
<div style="margin:0;padding:0;display:inline"></div>
<div class="field">
<label for="customer_first_name">First name</label>
<input class="form-control" id="customer_first_name" name="customer[first_name]" type="text" />
</div>
<div class="field">
<label for="customer_last_name">Last name</label>
<input class="form-control" id="customer_last_name" name="customer[last_name]" type="text" />
</div>
<div class="field">
<label for="customer_addr1">Addr1</label>
<input class="form-control" id="customer_addr1" name="customer[addr1]" type="text" />
</div>
<div class="field">
<label for="customer_addr2">Addr2</label>
<input class="form-control" id="customer_addr2" name="customer[addr2]" type="text" />
</div>
<div class="field">
<label for="customer_city">City</label>
<input class="form-control" id="customer_city" name="customer[city]" type="text" />
</div>
<div class="field">
<label for="customer_pincode">Pincode</label>
<input class="form-control" id="customer_pincode" name="customer[pincode]" type="text" />
</div>
<div class="field">
<label for="customer_homephone">Homephone</label>
<input class="form-control" id="customer_homephone" name="customer[homephone]" type="text" />
</div>
<div class="field">
<label for="customer_mobile">Mobile</label>
<input class="form-control" id="customer_mobile" name="customer[mobile]" type="text" />
</div>
<div class="actions">
<input class="btn btn-primary btn-large btn-block" name="commit" type="submit" value="Create Customer" />
</div>
</form>
</div>
You can see the working example here... http://jsfiddle.net/s6Ujm/
PS: I am a beginner too, pro designers... feel free share your reviews.
If all else fails you can also use
"My text needs a line break here" + System.Environment.NewLine + " This should be a new line"
If you are using Json.Net attribute [JsonIgnore]
will simply ignore the field/property while serializing or deserialising.
public class Car
{
// included in JSON
public string Model { get; set; }
public DateTime Year { get; set; }
public List<string> Features { get; set; }
// ignored
[JsonIgnore]
public DateTime LastModified { get; set; }
}
Or you can use DataContract and DataMember attribute to selectively serialize/deserialize properties/fields.
[DataContract]
public class Computer
{
// included in JSON
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal SalePrice { get; set; }
// ignored
public string Manufacture { get; set; }
public int StockCount { get; set; }
public decimal WholeSalePrice { get; set; }
public DateTime NextShipmentDate { get; set; }
}
Refer http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size for more details
If you want TextView in the center of parent..
Your main layout is Constraint Layout
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/logout"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:gravity="center">
</androidx.appcompat.widget.AppCompatTextView>
You can do this with the win32 class in the Microsoft namespace
using Microsoft.Win32;
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.SetValue("aldwin", "\"" + Application.ExecutablePath + "\"");
}
You can create a big subplot that covers the two subplots and then set the common labels.
import random
import matplotlib.pyplot as plt
x = range(1, 101)
y1 = [random.randint(1, 100) for _ in range(len(x))]
y2 = [random.randint(1, 100) for _ in range(len(x))]
fig = plt.figure()
ax = fig.add_subplot(111) # The big subplot
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
# Turn off axis lines and ticks of the big subplot
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
ax.tick_params(labelcolor='w', top=False, bottom=False, left=False, right=False)
ax1.loglog(x, y1)
ax2.loglog(x, y2)
# Set common labels
ax.set_xlabel('common xlabel')
ax.set_ylabel('common ylabel')
ax1.set_title('ax1 title')
ax2.set_title('ax2 title')
plt.savefig('common_labels.png', dpi=300)
Another way is using fig.text() to set the locations of the common labels directly.
import random
import matplotlib.pyplot as plt
x = range(1, 101)
y1 = [random.randint(1, 100) for _ in range(len(x))]
y2 = [random.randint(1, 100) for _ in range(len(x))]
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.loglog(x, y1)
ax2.loglog(x, y2)
# Set common labels
fig.text(0.5, 0.04, 'common xlabel', ha='center', va='center')
fig.text(0.06, 0.5, 'common ylabel', ha='center', va='center', rotation='vertical')
ax1.set_title('ax1 title')
ax2.set_title('ax2 title')
plt.savefig('common_labels_text.png', dpi=300)
I think this will work even though this was forever ago.
SELECT employee_number, Row_Number()
OVER (PARTITION BY course_code ORDER BY course_completion_date DESC ) as rownum
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
AND rownum = 1
If you want to get the last Id if the date is the same then you can use this assuming your primary key is Id.
SELECT employee_number, Row_Number()
OVER (PARTITION BY course_code ORDER BY course_completion_date DESC, Id Desc) as rownum FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
AND rownum = 1
You could get the full path as a string then split it into a list using your operating system's separator character. Then you get the program name, folder name etc by accessing the elements from the end of the list using negative indices.
Like this:
import os
strPath = os.path.realpath(__file__)
print( f"Full Path :{strPath}" )
nmFolders = strPath.split( os.path.sep )
print( "List of Folders:", nmFolders )
print( f"Program Name :{nmFolders[-1]}" )
print( f"Folder Name :{nmFolders[-2]}" )
print( f"Folder Parent:{nmFolders[-3]}" )
The output of the above was this:
Full Path :C:\Users\terry\Documents\apps\environments\dev\app_02\app_02.py
List of Folders: ['C:', 'Users', 'terry', 'Documents', 'apps', 'environments', 'dev', 'app_02', 'app_02.py']
Program Name :app_02.py
Folder Name :app_02
Folder Parent:dev
<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
<tr bgcolor="#CCC">
<td width="100">xxxxx</td>
<td width="700">xxxxxx</td>
<td width="170">xxxxxx</td>
<td width="30">xxxxxx</td>
</tr>
<tr bgcolor="#FFFFFF">
<td><?php
$date = date_create($row_Recordset3['fecha']);
echo date_format($date, 'd-m-Y');
?></td>
<td><?php echo $row_Recordset3['descripcion']; ?></td>
<td><?php echo $row_Recordset3['producto']; ?></td>
<td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
</tr>
</table>
<input type="hidden" id="datatodisplay" name="datatodisplay">
<input type="submit" value="Export to Excel">
exporttable.php
<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>
If you just need to output the date in ISO8601 format including the trailing Z and you are on at least SQL Server 2012, then you may use FORMAT
:
SELECT FORMAT(GetUtcDate(),'yyyy-MM-ddTHH:mm:ssZ')
This will give you something like:
2016-02-18T21:34:14Z
Just as @Pxtl points out in a comment FORMAT may have performance implications, a cost that has to be considered compared to any flexibility it brings.
i tried putting distinct on both, count(distinct ord.ord_id) as num_order, count(distinct items.item_id) as num items
its working :)
SELECT
people.pe_name,
COUNT(distinct orders.ord_id) AS num_orders,
COUNT(distinct items.item_id) AS num_items
FROM
people
INNER JOIN orders ON (orders.pe_id = people.pe_id)
INNER JOIN items ON items.pe_id = people.pe_id
GROUP BY
people.pe_id;
Thanks for the Thread it helps :)
For people who are not able to find the coverage view , follow these steps :
Go to Windows Menu bar > Show View > Other > Type coverage and open it.
Click on Coverage.
To clear highlightings, click on X or XX icon as per convenience.
I am just using the java.net
package.
Here you can do the following:
...
import java.net.URI;
...
String myUrl = "http://stackoverflow.com";
URI myURI = new URI(myUrl);
There is no API to post photo to instagram using API , But there is a simple way is that install google extension " User Agent " it will covert your browser to android mobile chrome version . Here is the extension link https://chrome.google.com/webstore/detail/user-agent-switcher/clddifkhlkcojbojppdojfeeikdkgiae?utm_source=chrome-ntp-icon
just click on extension icon and choose chrome for android and open Instagram.com
A public item is one that is accessible from any other class. You just have to know what object it is and you can use a dot operator to access it. Protected means that a class and its subclasses have access to the variable, but not any other classes, they need to use a getter/setter to do anything with the variable. A private means that only that class has direct access to the variable, everything else needs a method/function to access or change that data. Hope this helps.
You can't but you could avoid CORS using JSONP.
If you don't want to use the PRI* macros, another approach for printing ANY integer type is to cast to intmax_t
or uintmax_t
and use "%jd"
or %ju
, respectively. This is especially useful for POSIX (or other OS) types that don't have PRI* macros defined, for instance off_t
.
To use the default android drawable resource, no need copy anything.. you can just import it first with..
import android.R;
but i will make your own resources will have an error if you want to use it. The error will be something like:
R. cannot be resolved
So, I prefer not to import android.R
but import *my.own.package*.R;
then when I can normally use my own resource with R.drawable.*something*
without error,
and put android.R.*something_default*
to use the default android resources.
I use Butterknife with switch-case to handle this kind of cases:
@OnClick({R.id.button_bireysel, R.id.button_kurumsal})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.button_bireysel:
//Do something
break;
case R.id.button_kurumsal:
//Do something
break;
}
}
But the thing is there is no default case and switch statement falls through
You're getting that because VARCHAR
is not a valid type to cast into. According to the MySQL docs (http://dev.mysql.com/doc/refman/5.5/en/cast-functions.html#function_cast) you can only cast to:
I think your best-bet is to use CHAR
.
Works for every browser.
<button type="button" onClick="Refresh()">Close</button>
<script>
function Refresh() {
window.parent.location = window.parent.location.href;
}
</script>
Below code worked for me:
<input #fileInput type="file" id="avatar" accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" />
application/pdf means .pdf
application/msword means .doc
application/vnd.openxmlformats-officedocument.wordprocessingml.document means .docx
While I believe SJoshi (oracle guy) has the most complete answer, the SWIG project is a special case, interesting and useful one, at that, but not generalized for the majority of projects that have done well with the standard SDK ant based projects + NDK. We all would like to be using Android studio now most likely, or want a more CI friendly build toolchain for mobile, which gradle theoretically offers.
I've posted my approach, borrowed from somewhere (I found this on SO, but posted a gist for the app build.gradle: https://gist.github.com/truedat101/c45ff2b69e91d5c8e9c7962d4b96e841 ). In a nutshell, I recommend the following:
Gradle for Android has been a mess in my opinion, much as I like the maven concepts borrowed and the opinionated structure of directories for a project. This NDK feature has been "coming soon" for almost 3+ years.
I had the very same problem today. Here is a simple solution we found to solve this issue (thanks to Anghiara):
Instead of loading your new code to the Arduino using the "upload button" (the circle with the green arrow) in your screen, use your mouse to click "Sketch" and then "Upload".
Please remember to add a delay() line to your code when working with Serial.println() and loops. I learned my lesson the hard way.
I got the same problem and have solved it at the moment.
"Google" told me that I need to install "Microsoft Visual C++ Compiler for Python 2.7". I install not only the tool, but also Visual C++ 2008 Reditributable, but it didn't help. I then tried to install Visual C++ 2008 Express Edition. And the problem has gone!
Just try to install Visual C++ 2008 Express Edition!
This is my experience for this problem maybe it could help you :
I copied all folders and files inside the /data
folder to have a backup from my db
.
When I switched to another Computer's Xampp
and I started copying all folders and files copied before from previous phpmyadmin /data
folder.
So when I was done this problem happened for me .
To solve this issue :
1 - I made a backup from /data
folder of phpmyadmin
by copying only only folders have same name with tables I want to make backup .
2 - Uninstall Xampp.
3 - Reinstall Xampp .
4 - Copy all folders Kept in step 1 inside mysql/data
folder . this folders are only database tables and be careful don't touch another file and folder or replace anything when copying.
I just give other option for this question - you need to use '.dt' in your code:
import pandas as pd_x000D_
_x000D_
df.index = pd.to_datetime(df.index)_x000D_
_x000D_
#for get year_x000D_
df.index.dt.year_x000D_
_x000D_
#for get month_x000D_
df.index.dt.month_x000D_
_x000D_
#for get day_x000D_
df.index.dt.day_x000D_
_x000D_
#for get hour_x000D_
df.index.dt.hour_x000D_
_x000D_
#for get minute_x000D_
df.index.dt.minute
_x000D_
Create your file then return a reference to it with the correct header to trigger the Save As - edit the following as needed. Put your CSV data into $csvdata.
$fname = 'myCSV.csv';
$fp = fopen($fname,'wb');
fwrite($fp,$csvdata);
fclose($fp);
header('Content-type: application/csv');
header("Content-Disposition: inline; filename=".$fname);
readfile($fname);
data.rename(columns={'gdp':'log(gdp)'}, inplace=True)
The rename
show that it accepts a dict as a param for columns
so you just pass a dict with a single entry.
Also see related
This was a real issue for me, and quite a sneaky problem to try and remedy...
The problem I had was that a module that was installed on my WiFi adapter was conflicting with the Microsoft Virtual Adapter (or whatever it's actually called).
To fix it:
R
ncpa.cpl
in to the box, and hit OK
.Properties
.The connection uses the following items:
. Look down the list for anything that seems out of the ordinary, and uncheck it. Hit OK
.netsh wlan start hostednetwork
command again.In my case my adapter was running a module called SoftEther Lightweight Network Protocol
, which I believe is used to help connect to VPN Gate VPN servers via the SoftEther software.
If literally nothing else works, then I'd suspect something similar to the problem I encountered, namely that a module on your network adapter is interfering with the hostednetwork aspect of your driver.
Could you try something like this for example I think what you are wanting to utilize is the port.ReadExisting() Method
using System;
using System.IO.Ports;
class SerialPortProgram
{
// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM1",
9600, Parity.None, 8, StopBits.One);
[STAThread]
static void Main(string[] args)
{
// Instatiate this
SerialPortProgram();
}
private static void SerialPortProgram()
{
Console.WriteLine("Incoming Data:");
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
// Enter an application loop to keep this thread alive
Console.ReadLine();
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
Console.WriteLine(port.ReadExisting());
}
}
Or is you want to do it based on what you were trying to do , you can try this
public class MySerialReader : IDisposable
{
private SerialPort serialPort;
private Queue<byte> recievedData = new Queue<byte>();
public MySerialReader()
{
serialPort = new SerialPort();
serialPort.Open();
serialPort.DataReceived += serialPort_DataReceived;
}
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[serialPort.BytesToRead];
serialPort.Read(data, 0, data.Length);
data.ToList().ForEach(b => recievedData.Enqueue(b));
processData();
}
void processData()
{
// Determine if we have a "packet" in the queue
if (recievedData.Count > 50)
{
var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());
}
}
public void Dispose()
{
if (serialPort != null)
{
serialPort.Dispose();
}
}
There are 10 events in ASP.NET page life cycle, and the sequence is:
Below is a pictorial view of ASP.NET Page life cycle with what kind of code is expected in that event. I suggest you read this article I wrote on the ASP.NET Page life cycle, which explains each of the 10 events in detail and when to use them.
Image source: my own article at https://www.c-sharpcorner.com/uploadfile/shivprasadk/Asp-Net-application-and-page-life-cycle/ from 19 April 2010
A common trick is to check like this:
trim(TextBox1.Value & vbnullstring) = vbnullstring
this will work for spaces, empty strings, and genuine null values
it is not working in the Powershell and should use CMD in my case
for this scenario run npm install express command using your cmd prompt for the respective folder where you want to run the program. Example I want to run the express module program server.js in F:\nodeSample. So run "npm install express" in that particular folder then run server.js
If you are on windows.
Open pg_hba.conf
file and change from md5
to peer
Open cmd, type psql postgres postgres
Then type \password
to be prompted for a new password.
Refer to this medium post for further information & granular steps.
The BufferedWriter class offers a newLine()
method. Using this will ensure platform independence.
Are there other ways?
Negative margins were also used for horizontal (and vertical!) centering but there are quite a few drawbacks when you resize the window browser: no window slider; the content can't be seen anymore if the size of the window browser is too small.
No surprise as it uses absolute positioning, a beast never completely tamed!
Example: http://bluerobot.com/web/css/center2.html
So that was only FYI as you asked for it, margin: 0 auto;
is a better solution.
I think the only way will be to stop the process which has opened the port.
To remove it from all inputs
input {
outline:none;
}
This question already has a good answer, but I want to supplement it with some more pictures. My full answer is here.
To help me remember frame, I think of a picture frame on a wall. Just like a picture can be moved anywhere on the wall, the coordinate system of a view's frame is the superview. (wall=superview, frame=view)
To help me remember bounds, I think of the bounds of a basketball court. The basketball is somewhere within the court just like the coordinate system of the view's bounds is within the view itself. (court=view, basketball/players=content inside the view)
Like the frame, view.center is also in the coordinates of the superview.
The yellow rectangle represents the view's frame. The green rectangle represents the view's bounds. The red dot in both images represents the origin of the frame or bounds within their coordinate systems.
Frame
origin = (0, 0)
width = 80
height = 130
Bounds
origin = (0, 0)
width = 80
height = 130
Frame
origin = (40, 60) // That is, x=40 and y=60
width = 80
height = 130
Bounds
origin = (0, 0)
width = 80
height = 130
Frame
origin = (20, 52) // These are just rough estimates.
width = 118
height = 187
Bounds
origin = (0, 0)
width = 80
height = 130
This is the same as example 2, except this time the whole content of the view is shown as it would look like if it weren't clipped to the bounds of the view.
Frame
origin = (40, 60)
width = 80
height = 130
Bounds
origin = (0, 0)
width = 80
height = 130
Frame
origin = (40, 60)
width = 80
height = 130
Bounds
origin = (280, 70)
width = 80
height = 130
Again, see here for my answer with more details.
Cast/Convert the values to a Date
type for your group by.
GROUP BY CAST(myDateTime AS DATE)
chartr
is also convenient for these types of substitutions:
chartr("_", "-", data1$c)
# [1] "A-B" "A-B" "A-B" "A-B" "A-C" "A-C" "A-C" "A-C" "A-C" "A-C"
Thus, you can just do:
data1$c <- chartr("_", "-", data1$c)
I needed column names as a flat array, while the other answers returned associative arrays, so I used:
$con = mysqli_connect('localhost',$db_user,$db_pw,$db_name);
$table = 'people';
/**
* Get the column names for a mysql table
**/
function get_column_names($con, $table) {
$sql = 'DESCRIBE '.$table;
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row['Field'];
}
return $rows;
}
$col_names = function get_column_names($con, $table);
$col_names now equals:
(
[0] => name
[1] => parent
[2] => number
[3] => chart_id
[4] => type
[5] => id
)
Try to declare it in menifest file
<activity android:name=".HomeActivity"
android:label="@string/app_name"
android:windowSoftInputMode="stateAlwaysHidden"
>
I scripted this for my Dropbox file list.
sed
is used for removing full paths of symlinked file/folder path coming after ->
Unfortunately, tabs are lost. Using zsh
I am able to preserve tabs.
!/usr/bin/env bash
#!/usr/bin/env zsh
F1='index-2.md' #With hyperlinks
F2='index.md'
if [ -e $F1 ];then
rm $F1
fi
if [ -e $F2 ];then
rm $F2
fi
DATA=`tree --dirsfirst -t -Rl --noreport | \
sed 's/->.*$//g'` # Remove symlink adress and ->
echo -e '```\n' ${DATA} '\n```' > $F1 # Markdown needs triple back ticks for <pre>
# With the power of piping, creating HTML tree than pipe it
# to html2markdown program, creates cool markdown file with hyperlinks.
DATA=`tree --dirsfirst -t -Rl --noreport -H http://guneysu.pancakeapps.com`
echo $DATA | \
sed 's/\r\r/\n/g' | \
html2markdown | \
sed '/^\s*$/d' | \
sed 's/\# Directory Tree//g' | \
> $F2
The outputs like this:
```
.
+-- 2013
¦ +-- index.markdown
+-- 2014
¦ +-- index.markdown
+-- 2015
¦ +-- index.markdown
+-- _posts
¦ +-- 2014-12-27-2014-yili-degerlendirmesi.markdown
+-- _stash
+-- update.sh
```
[BASE_URL/](BASE_URL/)
+-- [2013](BASE_URL/2013/)
¦ +-- [index.markdown](BASE_URL/2013/index.markdown)
+-- [2014](BASE_URL/2014/)
¦ +-- [index.markdown](BASE_URL/2014/index.markdown)
+-- [2015](BASE_URL/2015/)
¦ +-- [index.markdown](BASE_URL/2015/index.markdown)
+-- [_posts](BASE_URL/_posts/)
¦ +-- [2014-12-27-2014-yili-degerlendirmesi.markdown](_posts/2014-12-27-2014-yili-degerlendirmesi.markdown)
+-- [_stash](BASE_URL/_stash/)
+-- [index-2.md](BASE_URL/index-2.md)
+-- [update.sh](BASE_URL/update.sh)
* * *
tree v1.6.0 © 1996 - 2011 by Steve Baker and Thomas Moore
HTML output hacked and copyleft © 1998 by Francesc Rocher
Charsets / OS/2 support © 2001 by Kyosuke Tokoro
In my case, I had to load the Map on my Wordpress website and the problem was that the Google's api script was loading before the initMap(). Therefore, I solved the problem with a delay:
<script>
function initMap() {
// Your Javascript Codes for the map
...
}
<?php
// Delay for 5 seconds
sleep(5);
?>
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEYWY&callback=initMap"></script>
I am trying to explain by putting problem statement and solution to it. I hope it will help
Problem Statement:
Find all the published products, whose name like ABC Product or PQR Product, and price should be less than 15/-
Solution:
Below are the conditions that need to be taken care of
Below is the statement that applies above criterion to create query and fetch data.
$elements = $collection->find(
Array(
[price] => Array( [$lt] => 15 ),
[$or] => Array(
[0]=>Array(
[product_name]=>Array(
[$in]=>Array(
[0] => ABC Product,
[1]=> PQR Product
)
)
)
),
[state]=>Published
)
);
About the nested properties discussion, you can avoid all the reflection stuff if you use the DataBinder.Eval Method (Object, String)
as below:
var value = DataBinder.Eval(DateTime.Now, "TimeOfDay.Hours");
Of course, you'll need to add a reference to the System.Web
assembly, but this probably isn't a big deal.
If you don't have the source code and API documentation, the machine code is all there is, you need to disassemble the dll library using something like IDA Pro , another option is use the trial version of PE Explorer.
PE Explorer provides a Disassembler. There is only one way to figure out the parameters: run the disassembler and read the disassembly output. Unfortunately, this task of reverse engineering the interface cannot be automated.
PE Explorer comes bundled with descriptions for 39 various libraries, including the core Windows® operating system libraries (eg. KERNEL32, GDI32, USER32, SHELL32, WSOCK32), key graphics libraries (DDRAW, OPENGL32) and more.
(source: heaventools.com)
SELECT * FROM mysql.user;
It's a big table so you might want to be more selective on what fields you choose.
If you are wanting to remove spaces from the front (and back) but not the middle, you should use stringByTrimmingCharactersInSet
let dirtyString = " First Word "
let cleanString = dirtyString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
If you want to remove spaces from anywhere in the string, then you might want to look at stringByReplacing...
The best solution is not to use the same element for column and panel:
<div class="row">
<div class="col-md-3">
<div class="panel" id="gameplay-away-team">Away Team</div>
</div>
<div class="col-md-6">
<div class="panel" id="gameplay-baseball-field">Baseball Field</div>
</div>
<div class="col-md-3">
<div class="panel" id="gameplay-home-team">Home Team</div>
</div>
</div>
and some more styles:
#gameplay-baseball-field {
padding-right: 10px;
padding-left: 10px;
}
COALESCE(field, 'default')
For example:
SELECT
t.id,
COALESCE(d.field, 'default')
FROM
test t
LEFT JOIN
detail d ON t.id = d.item
Also, you can use multiple columns to check their NULL
by COALESCE function.
For example:
mysql> SELECT COALESCE(NULL, 1, NULL);
-> 1
mysql> SELECT COALESCE(0, 1, NULL);
-> 0
mysql> SELECT COALESCE(NULL, NULL, NULL);
-> NULL
And if you want these translation units to share this variable, define int k;
in A.cpp and put extern int k;
in B.cpp.
In Python 3.5 you can overload @
as an operator. It is named as __matmul__
, because it is designed to do matrix multiplication, but it can be anything you want. See PEP465 for details.
This is a simple implementation of matrix multiplication.
class Mat(list):
def __matmul__(self, B):
A = self
return Mat([[sum(A[i][k]*B[k][j] for k in range(len(B)))
for j in range(len(B[0])) ] for i in range(len(A))])
A = Mat([[1,3],[7,5]])
B = Mat([[6,8],[4,2]])
print(A @ B)
This code yields:
[[18, 14], [62, 66]]
See this thread concerning uninitialized bools, but it should answer your question.
Local variables are not initialized unless you call their constructors (new) or assign them a value.
As per PHP Documentation,
Thread Safety means that binary can work in a multithreaded webserver context, such as Apache 2 on Windows. Thread Safety works by creating a local storage copy in each thread, so that the data won't collide with another thread.
So what do I choose? If you choose to run PHP as a CGI binary, then you won't need thread safety, because the binary is invoked at each request. For multithreaded webservers, such as IIS5 and IIS6, you should use the threaded version of PHP.
Following Libraries are not thread safe. They are not recommended for use in a multi-threaded environment.
xcopy "%userprofile%\Desktop\?????????" "D:\Backup\" /s/h/e/k/f/c
should work, assuming that your language setting allows Cyrillic (or you use Unicode fonts in the console).
For reference about the arguments: http://ss64.com/nt/xcopy.html
Might wanna check this, got everything you need for your app icons
http://developer.android.com/guide/practices/ui_guidelines/icon_design.html
update
I think by default it uses your launcher icon... Your best bet is to create a separate image... Designed for the action bar and using that. For that check: http://developer.android.com/guide/topics/ui/actionbar.html#ActionItems
I hope help you.
/// <summary>
/// Get the integer part of any decimal number passed trough a string
/// </summary>
/// <param name="decimalNumber">String passed</param>
/// <returns>teh integer part , 0 in case of error</returns>
private int GetIntPart(String decimalNumber)
{
if(!Decimal.TryParse(decimalNumber, NumberStyles.Any , new CultureInfo("en-US"), out decimal dn))
{
MessageBox.Show("String " + decimalNumber + " is not in corret format", "GetIntPart", MessageBoxButtons.OK, MessageBoxIcon.Error);
return default(int);
}
return Convert.ToInt32(Decimal.Truncate(dn));
}
I dont know whether you can change the default height/width of AlertDialog but if you wanted to do this, I think you can do it by creating your own custom dialog. You just have to give android:theme="@android:style/Theme.Dialog"
in the android manifest.xml for your activity and can write the whole layout as per your requirement. you can set the height and width of your custom dialog from the Android Resource XML.
this works too, ...if you have multiple column joins
from p in context.Periods
join f in context.Facts
on new {
id = p.periodid,
p.otherid
} equals new {
f.id,
f.otherid
} into fg
from fgi in fg.DefaultIfEmpty()
where p.companyid == 100
select f.value
Today I have bumped into this problem and solved it in the following way. I pressed "Reset defaults" button everywhere I could find it in Eclipse settings (for example, Preferences/C++/Build/Settings/Discovery). After that the error disappeared and the code compiled successfully.
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
Replace
registerReceiver(new YourReceiver(),new IntentFilter("YourAction"));
With
localBroadcastManager.registerReceiver(new YourReceiver(),new IntentFilter("YourAction"));
Replace
sendBroadcast(intent);
With
localBroadcastManager.sendBroadcast(intent);
Replace
unregisterReceiver(mybroadcast);
With
localBroadcastManager.unregisterReceiver(mybroadcast);
A .jar file usually only contains the .class files, not the .java files they were compiled from. That's why eclipse is telling you it doesn't know the source code of that class.
"Attaching" the source to a JAR means telling eclipse where the source code can be found. Of course, if you don't know yourself, that feature is of little help. Of course, you could try googling for the source code (or check wherever you got the JAR file from).
That said, you don't necessarily need the source to debug.
Bootstrap.yml is used to fetch config from the server. It can be for a Spring cloud application or for others. Typically it looks like:
spring:
application:
name: "app-name"
cloud:
config:
uri: ${config.server:http://some-server-where-config-resides}
When we start the application it tries to connect to the given server and read the configuration based on spring profile mentioned in run/debug configuration.
If the server is unreachable application might even be unable to proceed further. However, if configurations matching the profile are present locally the server configs get overridden.
Good approach:
Maintain a separate profile for local and run the app using different profiles.
Here's another way of doing it, remember to use free() on the result.
char* wchar_to_char(const wchar_t* pwchar)
{
// get the number of characters in the string.
int currentCharIndex = 0;
char currentChar = pwchar[currentCharIndex];
while (currentChar != '\0')
{
currentCharIndex++;
currentChar = pwchar[currentCharIndex];
}
const int charCount = currentCharIndex + 1;
// allocate a new block of memory size char (1 byte) instead of wide char (2 bytes)
char* filePathC = (char*)malloc(sizeof(char) * charCount);
for (int i = 0; i < charCount; i++)
{
// convert to char (1 byte)
char character = pwchar[i];
*filePathC = character;
filePathC += sizeof(char);
}
filePathC += '\0';
filePathC -= (sizeof(char) * charCount);
return filePathC;
}
str.contains
In recent versions of pandas, you can use string methods on the index and columns. Here, str.startswith
seems like a good fit.
To remove all columns starting with a given substring:
df.columns.str.startswith('Test')
# array([ True, False, False, False])
df.loc[:,~df.columns.str.startswith('Test')]
toto test2 riri
0 x x x
1 x x x
For case-insensitive matching, you can use regex-based matching with str.contains
with an SOL anchor:
df.columns.str.contains('^test', case=False)
# array([ True, False, True, False])
df.loc[:,~df.columns.str.contains('^test', case=False)]
toto riri
0 x x
1 x x
if mixed-types is a possibility, specify na=False
as well.
Well, you can use default
branch to detect it, for a closed channel will be selected, for example: the following code will select default
, channel
, channel
, the first select is not blocked.
func main() {
ch := make(chan int)
go func() {
select {
case <-ch:
log.Printf("1.channel")
default:
log.Printf("1.default")
}
select {
case <-ch:
log.Printf("2.channel")
}
close(ch)
select {
case <-ch:
log.Printf("3.channel")
default:
log.Printf("3.default")
}
}()
time.Sleep(time.Second)
ch <- 1
time.Sleep(time.Second)
}
Prints
2018/05/24 08:00:00 1.default
2018/05/24 08:00:01 2.channel
2018/05/24 08:00:01 3.channel
Just want to share my button style from my ResourceDictionary that i've been using. You can freely change the onHover background at the style triggers. "ColorAnimation To = *your desired BG(i.e #FFCEF7A0)". The button BG will also automatically revert to its original BG after the mouseOver state.You can even set how fast the transition.
Resource Dictionary
<Style x:Key="Flat_Button" TargetType="{x:Type Button}">
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="50"/>
<Setter Property="Margin" Value="2"/>
<Setter Property="FontFamily" Value="Arial Narrow"/>
<Setter Property="FontSize" Value="12px"/>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Opacity="1" Color="White"/>
</Setter.Value>
</Setter>
<Setter Property="Background" >
<Setter.Value>
<SolidColorBrush Opacity="1" Color="#28C2FF" />
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border"
SnapsToDevicePixels="True"
BorderThickness="1"
Padding="4,2"
BorderBrush="Gray"
CornerRadius="3"
Background="{TemplateBinding Background}">
<Grid>
<ContentPresenter
Margin="2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
RecognizesAccessKey="True" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation To="#D2F898"
Storyboard.TargetProperty="(Control.Background).(SolidColorBrush.Color)"
FillBehavior="HoldEnd" Duration="0:0:0.25" AutoReverse="False" RepeatBehavior="1x"/>
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation
Storyboard.TargetProperty="(Control.Background).(SolidColorBrush.Color)"
FillBehavior="HoldEnd" Duration="0:0:0.25" AutoReverse="False" RepeatBehavior="1x"/>
</Storyboard>
</BeginStoryboard>
</Trigger.ExitActions>
</Trigger>
</Style.Triggers>
</Style>
all you have to do is call the style.
Example Implementation
<Button Style="{StaticResource Flat_Button}" Height="Auto"Width="Auto">
<StackPanel>
<TextBlock Text="SAVE" FontFamily="Arial" FontSize="10.667"/>
</StackPanel>
</Button>
I had the similar issue, but, using SSH keys. From Tupy's answer, above, I figured out that the issue is with known_hosts file not being present or github.com not being present in the list of known hosts. Here are the steps I followed to resolve it -
mkdir -p ~/.ssh
ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts
ssh-keygen -t rsa -C "user.email"
$ cat ~/.ssh/id_rsa.pub
and copy it. Extending la_f0ka's comment, esp. if you also need the index position in your code, you should be able to do
s = 'ABCDEFG'
for pos in 0...s.length
puts s[pos].chr
end
The .chr
is important as Ruby < 1.9 returns the code of the character at that position instead of a substring of one character at that position.
You would need a mapping provider for MySQL. That is an extra thing the Entity Framework needs to make the magic happen. This blog talks about other mapping providers besides the one Microsoft is supplying. I haven't found any mentionings of MySQL.
I did like this
var datetoEnter= DateTime.ParseExact(createdDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);
return false;
You can return false at the end of the function or after the function call.
Just as long as it's the last thing that happens, the form will not submit.
There is a solution starting with KitKat (4.4.2), called Immersive Mode: https://developer.android.com/training/system-ui/immersive.html
Basically, you should add this code to your onResume() method:
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
callback from adapter to activity can be done using registering listener in form of interface: Make an interface:
public MyInterface{
public void yourmethod(//incase needs parameters );
}
In Adapter Let's Say MyAdapter:
public MyAdapter extends BaseAdapter{
private MyInterface listener;
MyAdapter(Context context){
try {
this. listener = (( MyInterface ) context);
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement MyInterface");
}
//do this where u need to fire listener l
try {
listener . yourmethod ();
} catch (ClassCastException exception) {
// do something
}
In Activity Implement your method:
MyActivity extends AppCompatActivity implements MyInterface{
yourmethod(){
//do whatever you want
}
}
If you're calling native apps, you need to worry about [Environment]::CurrentDirectory
not about PowerShell's $PWD
current directory. For various reasons, PowerShell does not set the process' current working directory when you Set-Location or Push-Location, so you need to make sure you do so if you're running applications (or cmdlets) that expect it to be set.
In a script, you can do this:
$CWD = [Environment]::CurrentDirectory
Push-Location $MyInvocation.MyCommand.Path
[Environment]::CurrentDirectory = $PWD
## Your script code calling a native executable
Pop-Location
# Consider whether you really want to set it back:
# What if another runspace has set it in-between calls?
[Environment]::CurrentDirectory = $CWD
There's no foolproof alternative to this. Many of us put a line in our prompt function to set [Environment]::CurrentDirectory ... but that doesn't help you when you're changing the location within a script.
Two notes about the reason why this is not set by PowerShell automatically:
$PWD
present working directory, but there's only one process, and only one Environment.$PWD
isn't always a legal CurrentDirectory (you might CD into the registry provider for instance).If you want to put it into your prompt (which would only run in the main runspace, single-threaded), you need to use:
[Environment]::CurrentDirectory = Get-Location -PSProvider FileSystem
Sample here:
<Style TargetType="Window" x:Key="DialogWindow">
<Setter Property="AllowsTransparency" Value="True"/>
<Setter Property="WindowStyle" Value="None"/>
<Setter Property="ResizeMode" Value="CanResizeWithGrip"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<Border BorderBrush="Black" BorderThickness="3" CornerRadius="10" Height="{TemplateBinding Height}"
Width="{TemplateBinding Width}" Background="Gray">
<DockPanel>
<Grid DockPanel.Dock="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
<Label Height="35" Grid.ColumnSpan="2"
x:Name="PART_WindowHeader"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"/>
<Button Width="15" Height="15" Content="x" Grid.Column="1" x:Name="PART_CloseButton"/>
</Grid>
<Border HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Background="LightBlue" CornerRadius="0,0,10,10"
Grid.ColumnSpan="2"
Grid.RowSpan="2">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="20"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="20"></RowDefinition>
</Grid.RowDefinitions>
<ResizeGrip Width="10" Height="10" Grid.Column="1" VerticalAlignment="Bottom" Grid.Row="1"/>
</Grid>
</Border>
</DockPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
There are two ways to tackle this based on what you want:
Solution 1: Remove purple commits, preserving history (incase you want to roll back)
git revert -m 1 <SHA of merge>
-m 1
specifies which parent line to choose
Purple commits will still be there in history but since you have reverted, you will not see code from those commits.
Solution 2: Completely remove purple commits (disruptive change if repo is shared)
git rebase -i <SHA before branching out>
and delete (remove lines) corresponding to purple commits.
This would be less tricky if commits were not made after merge. Additional commits increase the chance of conflicts during revert/rebase
.
The characters '<', and '>', are to indicate a place-holder, you should remove them to read:
php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME
Another way (Using Formulas in VBA). I guess this is the shortest VBA code as well?
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("B1:B" & lRow).Formula = "=If(A1<>"""",""My Text"","""")"
.Range("B1:B" & lRow).Value = .Range("B1:B" & lRow).Value
End With
End Sub
Small tip for you. Microsoft frequently has 'launch parties' or 'launch events' in which they frequently distribute licensed, not for resale copies, of that product. I've gotten the last two versions of VS (2005 and 2008) by attending my local .NET user group chapter during those days.
I prefer using the value returned by System.currentTimeMillis()
for all kinds of calculations and only use Calendar
or Date
if I need to really display a value that is read by humans. This will also prevent 99% of your daylight-saving-time bugs. :)
memset(msg, 0, 65546)
I have noticed that when using type="image/vnd.microsoft.icon"
, the favicon fails to appear when the browser is not connected to the internet.
But type="image/x-icon"
works whether the browser can connect to the internet, or not.
When developing, at times I am not connected to the internet.
Please note that MVC 3 onwards the persistence behavior of TempData has changed, now the value in TempData is persisted until it is read, and not just for the next request.
The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request. https://msdn.microsoft.com/en-in/library/dd394711%28v=vs.100%29.aspx
The solution given didn't work for me on the desktop, it just showed both divs, although the mobile only showed the mobile div. So I did a little search and found the min-width option. I updated my code to the following and it works fine now :)
CSS:
@media all and (min-width: 480px) {
.deskContent {display:block;}
.phoneContent {display:none;}
}
@media all and (max-width: 479px) {
.deskContent {display:none;}
.phoneContent {display:block;}
}
HTML:
<div class="deskContent">Content for desktop</div>
<div class="phoneContent">Content for mobile</div>
Another useful tool, and as a MySQL front-end replacement, is Toad for MySQL. Sadly, no longer supported by Quest, but a brilliant IDE for MySQL, with IMPORT and EXPORT wizards, catering for most file types.
A slight modification to solution provided by lebreeze:
function daysInMonth(iMonth, iYear)
{
return new Date(iYear, iMonth, 0).getDate();
}
Here is my recursive approach:
function visit(object) {
if (isIterable(object)) {
forEachIn(object, function (accessor, child) {
visit(child);
});
}
else {
var value = object;
console.log(value);
}
}
function forEachIn(iterable, functionRef) {
for (var accessor in iterable) {
functionRef(accessor, iterable[accessor]);
}
}
function isIterable(element) {
return isArray(element) || isObject(element);
}
function isArray(element) {
return element.constructor == Array;
}
function isObject(element) {
return element.constructor == Object;
}
To add to tacaswell's answer, the colorbar()
function has an optional cax
input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')
cax.set_xlabel('data label') # cax == cb.ax
Yeah, or just:
var arr = [1, 2, 5];
arr.reverse()[0]
if you want the value, and not a new list.
Try with below code sample.it is working for me
var date_input_field = $('input[name="date"]');
date_input_field .datepicker({
dateFormat: '/dd/mm/yyyy',
container: container,
todayHighlight: true,
autoclose: true,
}).on('change', function(selected){
alert("startDate..."+selected.timeStamp);
});
Setting the HOME environment variable to an appropriate value fix this issue for me.
Select Tools > Preferences > Database / Advanced
There is an input field for Sql Array Fetch Size but it only allows setting a max of 500 rows.
I had the same problem, and found the answer. If you use node.js with express, you need to give it its own function in order for the js file to be reached. For example:
const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))
var objResponse1 =
JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
worked!
How about plain JavaScript? More about Array.prototype.filter()
.
var myArray = [{'id': '73', 'name': 'john'}, {'id': '45', 'name': 'Jass'}]_x000D_
_x000D_
var item73 = myArray.filter(function(item) {_x000D_
return item.id === '73';_x000D_
})[0];_x000D_
_x000D_
// even nicer with ES6 arrow functions:_x000D_
// var item73 = myArray.filter(i => i.id === '73')[0];_x000D_
_x000D_
console.log(item73); // {"id": "73", "name": "john"}
_x000D_
In my case ( XCode 7 and iOS 9 ), I use UINavigationController
"hidden", so Ihave to add UINavigationControllerDelegate
to present camera or roll and it work like it is supposed to! And pickerControllerDelegate.self
doesn't display error either!
For .NET Core projects, run dotnet restore
or dotnet build
command in NuGet Package Manager Console
(which automatically runs restore)
You can run console from
Tools > NuGet Package Manager > Package Manager Console
I agree that this var formattedString = string.replace(/'/g, "\\'");
works very well, but since I used this part of code in PHP with the framework Prado (you can register the js script in a PHP class) I needed this sample working inside double quotes.
The solution that worked for me is that you need to put three \
and escape the double quotes.
"var string = \"l'avancement\";
var formattedString = string.replace(/'/g, \"\\\'\");"
I answer that question since I had trouble finding that three \
was the work around.
Date.now() returns a unix timestamp in milliseconds.
const now = Date.now(); // Unix timestamp in milliseconds_x000D_
console.log( now );
_x000D_
Prior to ECMAScript5 (I.E. Internet Explorer 8 and older) you needed to construct a Date object, from which there are several ways to get a unix timestamp in milliseconds:
console.log( +new Date );_x000D_
console.log( (new Date).getTime() );_x000D_
console.log( (new Date).valueOf() );
_x000D_
The difference between the two is best brought in what seems a necessary and sufficient definition of the dependencyManagement element available in Maven website docs:
dependencyManagement
"Default dependency information for projects that inherit from this one. The dependencies in this section are not immediately resolved. Instead, when a POM derived from this one declares a dependency described by a matching groupId and artifactId, the version and other values from this section are used for that dependency if they were not already specified." [ https://maven.apache.org/ref/3.6.1/maven-model/maven.html ]
It should be read along with some more information available on a different page:
“..the minimal set of information for matching a dependency reference against a dependencyManagement section is actually {groupId, artifactId, type, classifier}. In many cases, these dependencies will refer to jar artifacts with no classifier. This allows us to shorthand the identity set to {groupId, artifactId}, since the default for the type field is jar, and the default classifier is null.” [https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html ]
Thus, all the sub-elements (scope, exclusions etc.,) of a dependency element--other than groupId, artifactId, type, classifier, not just version--are available for lockdown/default at the point (and thus inherited from there onward) you specify the dependency within a dependencyElement. If you’d specified a dependency with the type and classifier sub-elements (see the first-cited webpage to check all sub-elements) as not jar and not null respectively, you’d need {groupId, artifactId, classifier, type} to reference (resolve) that dependency at any point in an inheritance originating from the dependencyManagement element. Else, {groupId, artifactId} would suffice if you do not intend to override the defaults for classifier and type (jar and null respectively). So default is a good keyword in that definition; any sub-element(s) (other than groupId, artifactId, classifier and type, of course) explicitly assigned value(s) at the point you reference a dependency override the defaults in the dependencyManagement element.
So, any dependency element outside of dependencyManagement, whether as a reference to some dependencyManagement element or as a standalone is immediately resolved (i.e. installed to the local repository and available for classpaths).
Start by selecting the sheets you want to combine:
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\tempo.pdf", Quality:= xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
I found the solution to this. There is a temporary tablespace called TEMP which is used internally by database for operations like distinct, joins,etc. Since my query(which has 4 joins) fetches almost 50 million records the TEMP tablespace does not have that much space to occupy all data. Hence the query fails even though my tablespace has free space.So, after increasing the size of TEMP tablespace the issue was resolved. Hope this helps someone with the same issue. Thanks :)
If you or another dev will not work on branchB further, I think it's better to keep commits in order to make reverts without headaches. So ;
git checkout branchA
git pull --rebase branchB
It's important that branchB shouldn't be used anymore.
For more ; https://www.derekgourlay.com/blog/git-when-to-merge-vs-when-to-rebase/
I've had some very good experience with Qt, so I would definitely recommend it.
You should be ware of the licensing model though. If you're developing an open source application, you can use the open-source licensed version free of charge. If you're developing a commercial application, you'll have to pay license fees. And you can't develop in the open source one and then switch the license to commercial before you start selling.
P.S. I just had a quick look at shoes. I really like the declarative definitions of the UI elements, so that's definitely worth investigating...
Include "B.h" in "A.h". That brings in the declaration of 'B' for the compiler while compiling 'A'.
The first bullet holds in the case of OP.
$3.4.1/7 -
"A name used in the definition of a class X outside of a member function body or nested class definition27) shall be declared in one of the following ways:
— before its use in class X or be a member of a base class of X (10.2), or
— if X is a nested class of class Y (9.7), before the definition of X in Y, or shall be a member of a base class of Y (this lookup applies in turn to Y’s enclosing classes, starting with the innermost enclosing class),28) or
— if X is a local class (9.8) or is a nested class of a local class, before the definition of class X in a block enclosing the definition of class X, or
— if X is a member of namespace N, or is a nested class of a class that is a member of N, or is a local class or a nested class within a local class of a function that is a member of N, before the definition of class X in namespace N or in one of N’s enclosing namespaces."
It's not a problem. When you first design your application, you can use the test codes provided by AdMob. These codes work great on your emulators and on real devices. But as soon as you publish your application on Google Play, these codes stop working immediately. You need to make your test devices. https://developers.google.com/admob/android/test-ads
But you can use a life hack to continue using test codes for an already published application. Change the application ID in the build.gradle(android) file to a different name and everything will work. Do not forget to return the old name before publishing the application to the Market.
I dug deeper into this and found the best solutions are here.
http://blog.notdot.net/2010/07/Getting-unicode-right-in-Python
In my case I solved "UnicodeEncodeError: 'charmap' codec can't encode character "
original code:
print("Process lines, file_name command_line %s\n"% command_line))
New code:
print("Process lines, file_name command_line %s\n"% command_line.encode('utf-8'))
gb = df.groupby(['A'])
gb_groups = grouped_df.groups
If you are looking for selective groupby objects then, do: gb_groups.keys(), and input desired key into the following key_list..
gb_groups.keys()
key_list = [key1, key2, key3 and so on...]
for key, values in gb_groups.iteritems():
if key in key_list:
print df.ix[values], "\n"
If you're on a Mac do brew install geckodriver
and off you go!
This algorithm is simple but not efficient, O(N2). All the "order by" algorithms are typically O(N log N). It probably doesn't make a difference below hundreds of thousands of elements but it would for large lists.
var stringlist = ... // add your values to stringlist
var r = new Random();
var res = new List<string>(stringlist.Count);
while (stringlist.Count >0)
{
var i = r.Next(stringlist.Count);
res.Add(stringlist[i]);
stringlist.RemoveAt(i);
}
The reason why it's O(N2) is subtle: List.RemoveAt() is a O(N) operation unless you remove in order from the end.
It will be approximately 37% larger:
Very roughly, the final size of Base64-encoded binary data is equal to 1.37 times the original data size
If you don't want to group, then use the following method:
db.collection.aggregate( [
{ $match : { score : { $gt : 70, $lte : 90 } } },
{ $count: 'count' }
] );
This can be achieved with the writing-mode
property. If you set an element's writing-mode
to a vertical writing mode, such as vertical-lr
, its descendants' percentage values for padding and margin, in both dimensions, become relative to height instead of width.
From the spec:
. . . percentages on the margin and padding properties, which are always calculated with respect to the containing block width in CSS2.1, are calculated with respect to the inline size of the containing block in CSS3.
The definition of inline size:
A measurement in the inline dimension: refers to the physical width (horizontal dimension) in horizontal writing modes, and to the physical height (vertical dimension) in vertical writing modes.
Example, with a resizable element, where horizontal margins are relative to width and vertical margins are relative to height.
.resize {_x000D_
width: 400px;_x000D_
height: 200px;_x000D_
resize: both;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
.outer {_x000D_
height: 100%;_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.middle {_x000D_
writing-mode: vertical-lr;_x000D_
margin: 0 10%;_x000D_
width: 80%;_x000D_
height: 100%;_x000D_
background-color: yellow;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
writing-mode: horizontal-tb;_x000D_
margin: 10% 0;_x000D_
width: 100%;_x000D_
height: 80%;_x000D_
background-color: blue;_x000D_
}
_x000D_
<div class="resize">_x000D_
<div class="outer">_x000D_
<div class="middle">_x000D_
<div class="inner"></div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Using a vertical writing mode can be particularly useful in circumstances where you want the aspect ratio of an element to remain constant, but want its size to scale in correlation to its height instead of width.
find the position of the nth occurrence of str2 in str1(same order of parameters as Oracle SQL INSTR), returns 0 if not found
instr <- function(str1,str2,startpos=1,n=1){
aa=unlist(strsplit(substring(str1,startpos),str2))
if(length(aa) < n+1 ) return(0);
return(sum(nchar(aa[1:n])) + startpos+(n-1)*nchar(str2) )
}
instr('xxabcdefabdddfabx','ab')
[1] 3
instr('xxabcdefabdddfabx','ab',1,3)
[1] 15
instr('xxabcdefabdddfabx','xx',2,1)
[1] 0
Another way to do it on Ubuntu 18.0.4
sudo /usr/share/kibana/bin/kibana --version
Here is how to integrate CSS star rating into an HTML form without using javascript (only html and css):
CSS:
.txt-center {
text-align: center;
}
.hide {
display: none;
}
.clear {
float: none;
clear: both;
}
.rating {
width: 90px;
unicode-bidi: bidi-override;
direction: rtl;
text-align: center;
position: relative;
}
.rating > label {
float: right;
display: inline;
padding: 0;
margin: 0;
position: relative;
width: 1.1em;
cursor: pointer;
color: #000;
}
.rating > label:hover,
.rating > label:hover ~ label,
.rating > input.radio-btn:checked ~ label {
color: transparent;
}
.rating > label:hover:before,
.rating > label:hover ~ label:before,
.rating > input.radio-btn:checked ~ label:before,
.rating > input.radio-btn:checked ~ label:before {
content: "\2605";
position: absolute;
left: 0;
color: #FFD700;
}
HTML:
<div class="txt-center">
<form>
<div class="rating">
<input id="star5" name="star" type="radio" value="5" class="radio-btn hide" />
<label for="star5">?</label>
<input id="star4" name="star" type="radio" value="4" class="radio-btn hide" />
<label for="star4">?</label>
<input id="star3" name="star" type="radio" value="3" class="radio-btn hide" />
<label for="star3">?</label>
<input id="star2" name="star" type="radio" value="2" class="radio-btn hide" />
<label for="star2">?</label>
<input id="star1" name="star" type="radio" value="1" class="radio-btn hide" />
<label for="star1">?</label>
<div class="clear"></div>
</div>
</form>
</div>
Please check the demo
I prefer another approach if you are using mongo
shell:
First as the another answers: use my_database_name
then:
db.getCollectionNames().map( (name) => ({[name]: db[name].find().toArray().length}) )
This query will show you something like this:
[
{
"agreements" : 60
},
{
"libraries" : 45
},
{
"templates" : 9
},
{
"users" : 19
}
]
You can use similar approach with db.getCollectionInfos()
it is pretty useful if you have so much data & helpful as well.
With this step set permission to gradlew
steps {
echo 'Compile project'
sh "chmod +x gradlew"
sh "./gradlew clean build --no-daemon"
}
S3DirectoryInfo has a MoveTo method that will move one directory into another directory, such that the moved directory will become a subdirectory of the other directory with the same name as it originally had.
The extension method below will move one directory to another directory, i.e. the moved directory will become the other directory. What it actually does is create the new directory, move all the contents of the old directory into it, and then delete the old one.
public static class S3DirectoryInfoExtensions
{
public static S3DirectoryInfo Move(this S3DirectoryInfo fromDir, S3DirectoryInfo toDir)
{
if (toDir.Exists)
throw new ArgumentException("Destination for Rename operation already exists", "toDir");
toDir.Create();
foreach (var d in fromDir.EnumerateDirectories())
d.MoveTo(toDir);
foreach (var f in fromDir.EnumerateFiles())
f.MoveTo(toDir);
fromDir.Delete();
return toDir;
}
}
The base difference that which already everyone mentioned is that one is heavy weight and other is light weight. Let me explain, basically what the term heavy weight means is that when you're using the awt components the native code used for getting the view component is generated by the Operating System, thats why it the look and feel changes from OS to OS. Where as in swing components its the responsibility of JVM to generate the view for the components. Another statement which i saw is that swing is MVC based and awt is not.
Accepted answer fails to mention how to delete the .swp file.
Hit "D" when the prompt comes up and it will remove it.
In my case, after I hit D it left the latest saved version intact and deleted the .swp which got created because I exited VIM incorrectly
One advantage is for binding scenarios. Data grids and property grids will pick up the dynamic properties via the TypeDescriptor system. In addition, WPF data binding will understand dynamic properties, so WPF controls can bind to an ExpandoObject more readily than a dictionary.
Interoperability with dynamic languages, which will be expecting DLR properties rather than dictionary entries, may also be a consideration in some scenarios.
You're declaring (some of) your event handlers incorrectly:
$('.menuOption').click(function( event ){ // <---- "event" parameter here
event.preventDefault();
var categories = $(this).attr('rel');
$('.pages').hide();
$(categories).fadeIn();
});
You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.
edit — to clarify: you have to provide some parameter name; using event
makes it clear what you intend, but you can call it e
or cupcake
or anything else.
Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.
You can try it this way:
/* Get the data into a temp table */
SELECT * INTO #TempTable
FROM YourTable
/* Drop the columns that are not needed */
ALTER TABLE #TempTable
DROP COLUMN ColumnToDrop
/* Get results and drop temp table */
SELECT * FROM #TempTable
DROP TABLE #TempTable
if [[ $(ls -A | head -c1 | wc -c) -ne 0 ]]; then ...; fi
Thanks to netj
for a suggestion to improve my original:if [[ $(ls -A | wc -c) -ne 0 ]]; then ...; fi
This is an old question but I see at least two things that need some improvement or at least some clarification.
First problem I see is that most of the examples provided here simply don't work. They use the ls -al
and ls -Al
commands - both of which output non-empty strings in empty directories. Those examples always report that there are files even when there are none.
For that reason you should use just ls -A
- Why would anyone want to use the -l
switch which means "use a long listing format" when all you want is test if there is any output or not, anyway?
So most of the answers here are simply incorrect.
The second problem is that while some answers work fine (those that don't use ls -al
or ls -Al
but ls -A
instead) they all do something like this:
What I would suggest doing instead would be:
using head -c1
So for example, instead of:
if [[ $(ls -A) ]]
I would use:
if [[ $(ls -A | wc -c) -ne 0 ]]
# or:
if [[ $(ls -A | head -c1 | wc -c) -ne 0 ]]
Instead of:
if [ -z "$(ls -lA)" ]
I would use:
if [ $(ls -lA | wc -c) -eq 0 ]
# or:
if [ $(ls -lA | head -c1 | wc -c) -eq 0 ]
and so on.
For small outputs it may not be a problem but for larger outputs the difference may be significant:
$ time [ -z "$(seq 1 10000000)" ]
real 0m2.703s
user 0m2.485s
sys 0m0.347s
Compare it with:
$ time [ $(seq 1 10000000 | wc -c) -eq 0 ]
real 0m0.128s
user 0m0.081s
sys 0m0.105s
And even better:
$ time [ $(seq 1 10000000 | head -c1 | wc -c) -eq 0 ]
real 0m0.004s
user 0m0.000s
sys 0m0.007s
Updated example from the answer by Will Vousden:
if [[ $(ls -A | wc -c) -ne 0 ]]; then
echo "there are files"
else
echo "no files found"
fi
Updated again after suggestions by netj:
if [[ $(ls -A | head -c1 | wc -c) -ne 0 ]]; then
echo "there are files"
else
echo "no files found"
fi
Additional update by jakeonfire:
grep
will exit with a failure if there is no match. We can take advantage of this to simplify the syntax slightly:
if ls -A | head -c1 | grep -E '.'; then
echo "there are files"
fi
if ! ls -A | head -c1 | grep -E '.'; then
echo "no files found"
fi
If the command that you're testing could output some whitespace that you want to treat as an empty string, then instead of:
| wc -c
you could use:
| tr -d ' \n\r\t ' | wc -c
or with head -c1
:
| tr -d ' \n\r\t ' | head -c1 | wc -c
or something like that.
First, use a command that works.
Second, avoid unnecessary storing in RAM and processing of potentially huge data.
The answer didn't specify that the output is always small so a possibility of large output needs to be considered as well.
Without knowing all the information... You could bind a reset trigger to your model or controller:
this.bind("reset", this.updateView);
and when you want to reset the views, trigger a reset.
For your callback, do something like:
updateView: function() {
view.remove();
view.render();
};
When you use a function ...
<p onclick="update_url('/en/step2');">Link</p>
<script>
function update_url(url) {
history.pushState(null, null, url);
}
</script>
public class Merge {
// stably merge a[lo .. mid] with a[mid+1 .. hi] using aux[lo .. hi]
public static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {
// precondition: a[lo .. mid] and a[mid+1 .. hi] are sorted subarrays
assert isSorted(a, lo, mid);
assert isSorted(a, mid+1, hi);
// copy to aux[]
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
}
// merge back to a[]
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) a[k] = aux[j++];
else if (j > hi) a[k] = aux[i++];
else if (less(aux[j], aux[i])) a[k] = aux[j++];
else a[k] = aux[i++];
}
// postcondition: a[lo .. hi] is sorted
assert isSorted(a, lo, hi);
}
// mergesort a[lo..hi] using auxiliary array aux[lo..hi]
private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, aux, lo, mid);
sort(a, aux, mid + 1, hi);
merge(a, aux, lo, mid, hi);
}
public static void sort(Comparable[] a) {
Comparable[] aux = new Comparable[a.length];
sort(a, aux, 0, a.length-1);
assert isSorted(a);
}
/***********************************************************************
* Helper sorting functions
***********************************************************************/
// is v < w ?
private static boolean less(Comparable v, Comparable w) {
return (v.compareTo(w) < 0);
}
// exchange a[i] and a[j]
private static void exch(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
/***********************************************************************
* Check if array is sorted - useful for debugging
***********************************************************************/
private static boolean isSorted(Comparable[] a) {
return isSorted(a, 0, a.length - 1);
}
private static boolean isSorted(Comparable[] a, int lo, int hi) {
for (int i = lo + 1; i <= hi; i++)
if (less(a[i], a[i-1])) return false;
return true;
}
/***********************************************************************
* Index mergesort
***********************************************************************/
// stably merge a[lo .. mid] with a[mid+1 .. hi] using aux[lo .. hi]
private static void merge(Comparable[] a, int[] index, int[] aux, int lo, int mid, int hi) {
// copy to aux[]
for (int k = lo; k <= hi; k++) {
aux[k] = index[k];
}
// merge back to a[]
int i = lo, j = mid+1;
for (int k = lo; k <= hi; k++) {
if (i > mid) index[k] = aux[j++];
else if (j > hi) index[k] = aux[i++];
else if (less(a[aux[j]], a[aux[i]])) index[k] = aux[j++];
else index[k] = aux[i++];
}
}
// return a permutation that gives the elements in a[] in ascending order
// do not change the original array a[]
public static int[] indexSort(Comparable[] a) {
int N = a.length;
int[] index = new int[N];
for (int i = 0; i < N; i++)
index[i] = i;
int[] aux = new int[N];
sort(a, index, aux, 0, N-1);
return index;
}
// mergesort a[lo..hi] using auxiliary array aux[lo..hi]
private static void sort(Comparable[] a, int[] index, int[] aux, int lo, int hi) {
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, index, aux, lo, mid);
sort(a, index, aux, mid + 1, hi);
merge(a, index, aux, lo, mid, hi);
}
// print array to standard output
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
StdOut.println(a[i]);
}
}
// Read strings from standard input, sort them, and print.
public static void main(String[] args) {
String[] a = StdIn.readStrings();
Merge.sort(a);
show(a);
}
}
You should use Java's built in serialization mechanism. To use it, you need to do the following:
Declare the Club
class as implementing Serializable
:
public class Club implements Serializable {
...
}
This tells the JVM that the class can be serialized to a stream. You don't have to implement any method, since this is a marker interface.
To write your list to a file do the following:
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(clubs);
oos.close();
To read the list from a file, do the following:
FileInputStream fis = new FileInputStream("t.tmp");
ObjectInputStream ois = new ObjectInputStream(fis);
List<Club> clubs = (List<Club>) ois.readObject();
ois.close();
Simply use the .closest()
method: $(this).closest('.li').remove();
It starts with the current element and then climbs up the chain looking for a matching element and stops as soon as it found one.
.parent()
only accesses the direct parent of the element, i.e. div.msg-modification
which does not match .li
. So it never reaches the element you are looking for.
Another solution besides .closest()
(which checks the current element and then climbs up the chain) would be using .parents()
- however, this would have the caveat that it does not stop as soon as it finds a matching element (and it doesn't check the current element but only parent elements). In your case it doesn't really matter but for what you are trying to do .closest()
is the most appropriate method.
NEVER use the same ID for more than one element. It's not allowed and causes very hard-to-debug problems. Remove the id="191"
from the link and, if you need to access the ID in the click handler, use $(this).closest('.li').attr('id')
. Actually it would be even cleaner if you used data-id="123"
and then .data('id')
instead of .attr('id')
to access it (so your element ID does not need to resemble whatever ID the (database?) row has)
EADDRINUSE
means that the port number which listen()
tries to bind the server to is already in use.
So, in your case, there must be running a server on port 80 already.
If you have another webserver running on this port you have to put node.js behind that server and proxy it through it.
You should check for the listening
event like this, to see if the server is really listening:
var http=require('http');
var server=http.createServer(function(req,res){
res.end('test');
});
server.on('listening',function(){
console.log('ok, server is running');
});
server.listen(80);
You can use PHP to add a stylesheet for IE 10
Like:
if (stripos($_SERVER['HTTP_USER_AGENT'], 'MSIE 10')) {
<link rel="stylesheet" type="text/css" href="../ie10.css" />
}
Here are node and node-sass compatible versions list.
NodeJS Supported node-sass version *
Node 15 5.0+
Node 14 4.14+
Node 13 4.13+, < 5.0
Node 12 4.12+
Node 11 4.10+, < 5.0
Node 10 4.9+
Node 8 4.5.3+, < 5.0
Node < 8 < 5.0 < 57
If issue exists, upgrade or downgrade versions.
JavaScript
<script language="javascript">
var flag=0;
function username()
{
user=loginform.username.value;
if(user=="")
{
document.getElementById("error0").innerHTML="Enter UserID";
flag=1;
}
}
function password()
{
pass=loginform.password.value;
if(pass=="")
{
document.getElementById("error1").innerHTML="Enter password";
flag=1;
}
}
function check(form)
{
flag=0;
username();
password();
if(flag==1)
return false;
else
return true;
}
</script>
HTML
<form name="loginform" action="Login" method="post" class="form-signin" onSubmit="return check(this)">
<div id="error0"></div>
<input type="text" id="inputEmail" name="username" placeholder="UserID" onBlur="username()">
controls">
<div id="error1"></div>
<input type="password" id="inputPassword" name="password" placeholder="Password" onBlur="password()" onclick="make_blank()">
<button type="submit" class="btn">Sign in</button>
</div>
</div>
</form>
As a setter, how about:
// setter
public void beCurrent(boolean X) {
this.isCurrent = X;
}
or
// setter
public void makeCurrent(boolean X) {
this.isCurrent = X;
}
I'm not sure if these naming make sense to native English speakers.
It can easy be done using Object.assign() method -
var object1 = {name: "John"};
var object2 = {location: "San Jose"};
var object3 = Object.assign(object1,object2);
console.log(object3);
now object3 is { name: 'John', location: 'San Jose' }
A function is not even needed. Just put parentheses around the default expression:
create temporary table test(
id int,
ts timestamp without time zone default (now() at time zone 'utc')
);
I got same error in my application.I am loading many controls in single page.In button click event i am clearing the controls.clearing the controls doesnot release the controls from memory.So dispose the controls from memory. I just commented controls.clear() method and include few lines of code to dispose the controls. Something like this
for each ctl as control in controlcollection
ctl.dispose()
Next
I've tried as following and it worked for me:
select {
line-height:normal;
padding:3px;
}
I did it this way,
<audio controls="controls" loop="loop">
<source src="someSound.ogg" type="audio/ogg" />
</audio>
and it looks like this
if a device has an SD card, you use:
Environment.getExternalStorageState()
if you don't have an SD card, you use:
Environment.getDataDirectory()
if there is no SD card, you can create your own directory on the device locally.
//if there is no SD card, create new directory objects to make directory on device
if (Environment.getExternalStorageState() == null) {
//create new file directory object
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}// end of SD card checking
add permissions on your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Happy coding..
USE COUNT_STAR
LOGS= LOAD 'log';
LOGS_GROUP= GROUP LOGS ALL;
LOG_COUNT = FOREACH LOGS_GROUP GENERATE COUNT_STAR(LOGS);
The following method converts all the letters into upper/lower case, depending on their position near a space or other special chars.
public static String capitalizeString(String string) {
char[] chars = string.toLowerCase().toCharArray();
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (!found && Character.isLetter(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here
found = false;
}
}
return String.valueOf(chars);
}
One way would be to just escape the quotes properly:
<input type="button" value="click" id="mybtn"
onclick="myfunction('/myController/myAction',
'myfuncionOnOK(\'/myController2/myAction2\',
\'myParameter2\');',
'myfuncionOnCancel(\'/myController3/myAction3\',
\'myParameter3\');');">
In this case, though, I think a better way to handle this would be to wrap the two handlers in anonymous functions:
<input type="button" value="click" id="mybtn"
onclick="myfunction('/myController/myAction',
function() { myfuncionOnOK('/myController2/myAction2',
'myParameter2'); },
function() { myfuncionOnCancel('/myController3/myAction3',
'myParameter3'); });">
And then, you could call them from within myfunction
like this:
function myfunction(url, onOK, onCancel)
{
// Do whatever myfunction would normally do...
if (okClicked)
{
onOK();
}
if (cancelClicked)
{
onCancel();
}
}
That's probably not what myfunction
would actually look like, but you get the general idea. The point is, if you use anonymous functions, you have a lot more flexibility, and you keep your code a lot cleaner as well.
The System.DateTime
class has a property called Now
, which:
Gets a
DateTime
object that is set to the current date and time on this computer, expressed as the local time.
You can set the Text
property of your label to the current time like this (where myLabel
is the name of your label):
myLabel.Text = DateTime.Now.ToString();
If you can't go over your time limit (it's a hard limit) then a thread is your best bet. You can use a loop to terminate the thread once you get to the time threshold. Whatever is going on in that thread at the time can be interrupted, allowing calculations to stop almost instantly. Here is an example:
Thread t = new Thread(myRunnable); // myRunnable does your calculations
long startTime = System.currentTimeMillis();
long endTime = startTime + 60000L;
t.start(); // Kick off calculations
while (System.currentTimeMillis() < endTime) {
// Still within time theshold, wait a little longer
try {
Thread.sleep(500L); // Sleep 1/2 second
} catch (InterruptedException e) {
// Someone woke us up during sleep, that's OK
}
}
t.interrupt(); // Tell the thread to stop
t.join(); // Wait for the thread to cleanup and finish
That will give you resolution to about 1/2 second. By polling more often in the while loop, you can get that down.
Your runnable's run would look something like this:
public void run() {
while (true) {
try {
// Long running work
calculateMassOfUniverse();
} catch (InterruptedException e) {
// We were signaled, clean things up
cleanupStuff();
break; // Leave the loop, thread will exit
}
}
Update based on Dmitri's answer
Dmitri pointed out TimerTask, which would let you avoid the loop. You could just do the join call and the TimerTask you setup would take care of interrupting the thread. This would let you get more exact resolution without having to poll in a loop.
You wrote the assignment backward: to assign a value (or an expression) to a variable you must have that variable at the left side of the assignment operator ( = in python )
subsequent_amount = invest(initial_amount,top_company(5,year,year+1))
Add a notifier in the viewWillAppear
function
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
}
The orientation change notifies this function
- (void)orientationChanged:(NSNotification *)notification{
[self adjustViewsForOrientation:[[UIApplication sharedApplication] statusBarOrientation]];
}
which in-turn calls this function where the moviePlayerController frame is orientation is handled
- (void) adjustViewsForOrientation:(UIInterfaceOrientation) orientation {
switch (orientation)
{
case UIInterfaceOrientationPortrait:
case UIInterfaceOrientationPortraitUpsideDown:
{
//load the portrait view
}
break;
case UIInterfaceOrientationLandscapeLeft:
case UIInterfaceOrientationLandscapeRight:
{
//load the landscape view
}
break;
case UIInterfaceOrientationUnknown:break;
}
}
in viewDidDisappear
remove the notification
-(void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter]removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
}
I guess this is the fastest u can have changed the view as per orientation
If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:
class YourNonActivityClass{
// variable to hold context
private Context context;
//save the context recievied via constructor in a local variable
public YourNonActivityClass(Context context){
this.context=context;
}
}
You can create instance of this class from the activity as follows:
new YourNonActivityClass(this);
If you look at the code for the component you can see that it uses the className
prop passed to it to combine with the row
class to get the resulting set of classes (<Row className="aaa bbb"...
works).Also, if you provide the id
prop like <Row id="444" ...
it will actually set the id attribute for the element.
First I am afraid your question contains a little mistake. There is not method writeline in class Console. Instead class Console provides method writer() that returns PrintWriter. This print writer has println().
Now what is the difference between
System.console().writer().println("hello from console");
and
System.out.println("hello system out");
If you run your application from command line I think there is no difference. But if console is unavailable System.console() returns null while System.out still exists. This may happen if you invoke your application and perform redirect of STDOUT to file.
Here is an example I have just implemented.
import java.io.Console;
public class TestConsole {
public static void main(String[] args) {
Console console = System.console();
System.out.println("console=" + console);
console.writer().println("hello from console");
}
}
When I ran the application from command prompt I got the following:
$ java TestConsole
console=java.io.Console@93dcd
hello from console
but when I redirected the STDOUT to file...
$ java TestConsole >/tmp/test
Exception in thread "main" java.lang.NullPointerException
at TestConsole.main(TestConsole.java:8)
Line 8 is console.writer().println()
.
Here is the content of /tmp/test
console=null
I hope my explanations help.