Dirk has explained how to plot the density function over the histogram. But sometimes you might want to go with the stronger assumption of a skewed normal distribution and plot that instead of density. You can estimate the parameters of the distribution and plot it using the sn package:
> sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
$call
sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35,
times = 10), rep(45, times = 4)))
$cp
mean s.d. skewness
41.46228 12.47892 0.99527
This probably works better on data that is more skew-normal:
Here you have an example working on py2.6 and py3.2:
from scipy.stats import norm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
# read data from a text file. One number per line
arch = "test/Log(2)_ACRatio.txt"
datos = []
for item in open(arch,'r'):
item = item.strip()
if item != '':
try:
datos.append(float(item))
except ValueError:
pass
# best fit of data
(mu, sigma) = norm.fit(datos)
# the histogram of the data
n, bins, patches = plt.hist(datos, 60, normed=1, facecolor='green', alpha=0.75)
# add a 'best fit' line
y = mlab.normpdf( bins, mu, sigma)
l = plt.plot(bins, y, 'r--', linewidth=2)
#plot
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=%.3f,\ \sigma=%.3f$' %(mu, sigma))
plt.grid(True)
plt.show()
LOESS is a very good approach, as Dirk said.
Another option is using Bezier splines, which may in some cases work better than LOESS if you don't have many data points.
Here you'll find an example: http://rosettacode.org/wiki/Cubic_bezier_curves#R
# x, y: the x and y coordinates of the hull points
# n: the number of points in the curve.
bezierCurve <- function(x, y, n=10)
{
outx <- NULL
outy <- NULL
i <- 1
for (t in seq(0, 1, length.out=n))
{
b <- bez(x, y, t)
outx[i] <- b$x
outy[i] <- b$y
i <- i+1
}
return (list(x=outx, y=outy))
}
bez <- function(x, y, t)
{
outx <- 0
outy <- 0
n <- length(x)-1
for (i in 0:n)
{
outx <- outx + choose(n, i)*((1-t)^(n-i))*t^i*x[i+1]
outy <- outy + choose(n, i)*((1-t)^(n-i))*t^i*y[i+1]
}
return (list(x=outx, y=outy))
}
# Example usage
x <- c(4,6,4,5,6,7)
y <- 1:6
plot(x, y, "o", pch=20)
points(bezierCurve(x,y,20), type="l", col="red")
You'll first need to separate your numpy array into two separate arrays containing x and y values.
x = [1, 2, 3, 9]
y = [1, 4, 1, 3]
curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like
def func(x, a, b):
return a*x + b
scipy.optimize.curve_fit(func, x, y)
will return a numpy array containing two arrays: the first will contain values for a
and b
that best fit your data, and the second will be the covariance of the optimal fit parameters.
Here's an example for a linear fit with the data you provided.
import numpy as np
from scipy.optimize import curve_fit
x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])
def fit_func(x, a, b):
return a*x + b
params = curve_fit(fit_func, x, y)
[a, b] = params[0]
This code will return a = 0.135483870968
and b = 1.74193548387
Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.
A very late reply, but just in case someone needs a ready function for this:
i.e.
slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, y)
as in @Adam Marples's answer.
To get a third order polynomial in x (x^3), you can do
lm(y ~ x + I(x^2) + I(x^3))
or
lm(y ~ poly(x, 3, raw=TRUE))
You could fit a 10th order polynomial and get a near-perfect fit, but should you?
EDIT: poly(x, 3) is probably a better choice (see @hadley below).
For fitting y = A + B log x, just fit y against (log x).
>>> x = numpy.array([1, 7, 20, 50, 79])
>>> y = numpy.array([10, 19, 30, 35, 51])
>>> numpy.polyfit(numpy.log(x), y, 1)
array([ 8.46295607, 6.61867463])
# y ˜ 8.46 log(x) + 6.62
For fitting y = AeBx, take the logarithm of both side gives log y = log A + Bx. So fit (log y) against x.
Note that fitting (log y) as if it is linear will emphasize small values of y, causing large deviation for large y. This is because polyfit
(linear regression) works by minimizing ?i (?Y)2 = ?i (Yi − Yi)2. When Yi = log yi, the residues ?Yi = ?(log yi) ˜ ?yi / |yi|. So even if polyfit
makes a very bad decision for large y, the "divide-by-|y|" factor will compensate for it, causing polyfit
favors small values.
This could be alleviated by giving each entry a "weight" proportional to y. polyfit
supports weighted-least-squares via the w
keyword argument.
>>> x = numpy.array([10, 19, 30, 35, 51])
>>> y = numpy.array([1, 7, 20, 50, 79])
>>> numpy.polyfit(x, numpy.log(y), 1)
array([ 0.10502711, -0.40116352])
# y ˜ exp(-0.401) * exp(0.105 * x) = 0.670 * exp(0.105 * x)
# (^ biased towards small values)
>>> numpy.polyfit(x, numpy.log(y), 1, w=numpy.sqrt(y))
array([ 0.06009446, 1.41648096])
# y ˜ exp(1.42) * exp(0.0601 * x) = 4.12 * exp(0.0601 * x)
# (^ not so biased)
Note that Excel, LibreOffice and most scientific calculators typically use the unweighted (biased) formula for the exponential regression / trend lines. If you want your results to be compatible with these platforms, do not include the weights even if it provides better results.
Now, if you can use scipy, you could use scipy.optimize.curve_fit
to fit any model without transformations.
For y = A + B log x the result is the same as the transformation method:
>>> x = numpy.array([1, 7, 20, 50, 79])
>>> y = numpy.array([10, 19, 30, 35, 51])
>>> scipy.optimize.curve_fit(lambda t,a,b: a+b*numpy.log(t), x, y)
(array([ 6.61867467, 8.46295606]),
array([[ 28.15948002, -7.89609542],
[ -7.89609542, 2.9857172 ]]))
# y ˜ 6.62 + 8.46 log(x)
For y = AeBx, however, we can get a better fit since it computes ?(log y) directly. But we need to provide an initialize guess so curve_fit
can reach the desired local minimum.
>>> x = numpy.array([10, 19, 30, 35, 51])
>>> y = numpy.array([1, 7, 20, 50, 79])
>>> scipy.optimize.curve_fit(lambda t,a,b: a*numpy.exp(b*t), x, y)
(array([ 5.60728326e-21, 9.99993501e-01]),
array([[ 4.14809412e-27, -1.45078961e-08],
[ -1.45078961e-08, 5.07411462e+10]]))
# oops, definitely wrong.
>>> scipy.optimize.curve_fit(lambda t,a,b: a*numpy.exp(b*t), x, y, p0=(4, 0.1))
(array([ 4.88003249, 0.05531256]),
array([[ 1.01261314e+01, -4.31940132e-02],
[ -4.31940132e-02, 1.91188656e-04]]))
# y ˜ 4.88 exp(0.0553 x). much better.
This code:
from scipy.stats import linregress
linregress(x,y) #x and y are arrays or lists.
gives out a list with the following:
slope : float
slope of the regression line
intercept : float
intercept of the regression line
r-value : float
correlation coefficient
p-value : float
two-sided p-value for a hypothesis test whose null hypothesis is that the slope is zero
stderr : float
Standard error of the estimate
Note that you can use the Polynomial class directly to do the fitting and return a Polynomial instance.
from numpy.polynomial import Polynomial
p = Polynomial.fit(x, y, 4)
plt.plot(*p.linspace())
p
uses scaled and shifted x values for numerical stability. If you need the usual form of the coefficients, you will need to follow with
pnormal = p.convert(domain=(-1, 1))
To make sure you get the right version with Environment.OSVersion
you should add an app.manifest
using Visual Studio and uncomment following supportedOS
tags:
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- A list of the Windows versions that this application has been tested on
and is designed to work with. Uncomment the appropriate elements
and Windows will automatically select the most compatible environment. -->
<!-- Windows Vista -->
<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />
<!-- Windows 7 -->
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />
<!-- Windows 8 -->
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />
<!-- Windows 8.1 -->
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>
Then in your code you can use Environment.OSVersion
like this:
var version = System.Environment.OSVersion;
Console.WriteLine(version);
Example
For instance in my machine (Windows 10.0 Build 18362.476
) result would be like this which is incorrect:
Microsoft Windows NT 6.2.9200.0
By adding app.manifest
and uncomment those tags I will get the right version number:
Microsoft Windows NT 10.0.18362.0
If you don't like adding app.manifest
to your project, you can use OSDescription
which is available since .NET Framework 4.7.1 and .NET Core 1.0.
string description = RuntimeInformation.OSDescription;
Note: Don't forget to add following using statement at top of your file.
using System.Runtime.InteropServices;
You can read more about it and supported platforms here.
I can able to get this resolved by resetting the domain (server machine, which is the domain server, but not related to SQL Server except domain managing) followed by the client machines.
Thank you all for your immediate support!
Just in case, I had similar error with bundler 2.1.2 and solved it with:
sudo gem install bundler -v 1.17.3
If you have several bundler versions installed, then you can run specific version of bundle this way: bundle _1.17.3_ exec rspec
Though seems like later bundler versions are pretty buggy (had issues on 3 different projects on 2 operation systems), having one old bundler may work the best, at least this is what I have on my Ubuntu & MacOS
Latest bundler versions may override stable bundler -v 1.17.3. It can be not easy to remove latest bundler from system, here is what helped me:
bundler.rb
and bundler
folder from load paths: ruby -e 'puts $LOAD_PATH'
Pseudo code, something like:
CASE
When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'
This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.
For Ubuntu and running android-studio run to install the packages (these are not installed by default):
android update sdk
Of course, "Fagner Antunes Dornelles" is correct in its answer. But it seems to me that it is worth checking the registry branch itself in addition, or be sure of the part that is exactly there.
For example ("dirty hack"), i need to establish trust in the RMS infrastructure, otherwise when i open Word or Excel documents, i will be prompted for "Active Directory Rights Management Services". Here's how i can add remote trust to me servers in the enterprise infrastructure.
foreach (var strServer in listServer)
{
try
{
RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC\\{strServer}", false);
if (regCurrentUser == null)
throw new ApplicationException("Not found registry SubKey ...");
if (regCurrentUser.GetValueNames().Contains("UserConsent") == false)
throw new ApplicationException("Not found value in SubKey ...");
}
catch (ApplicationException appEx)
{
Console.WriteLine(appEx);
try
{
RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC", true);
RegistryKey newKey = regCurrentUser.CreateSubKey(strServer, true);
newKey.SetValue("UserConsent", 1, RegistryValueKind.DWord);
}
catch(Exception ex)
{
Console.WriteLine($"{ex} Pipec kakoito ...");
}
}
}
Mostly the image is not displayed because you URL contains spaces. In your case you almost did everything correct. Except one thing - you have not added single quotes like you do if you specify background-image in css I.e.
.bg-img { \/ \/
background-image: url('http://...');
}
To do so escape quot character in HTML via \'
\/ \/
<div [ngStyle]="{'background-image': 'url(\''+ item.color.catalogImageLink + '\')'}"></div>
If you have an issue where you only want to remove trailing characters, you can try this:
WHILE EXISTS
(SELECT * FROM @ReportSet WHERE
ASCII(right(addr_3,1)) = 10
OR ASCII(right(addr_3,1)) = 13
OR ASCII(right(addr_3,1)) = 32)
BEGIN
UPDATE @ReportSet
SET addr_3 = LEFT(addr_3,LEN(addr_3)-1)
WHERE
ASCII(right(addr_3,1)) = 10
OR ASCII(right(addr_3,1)) = 13
OR ASCII(right(addr_3,1)) = 32
END
This solved a problem I had with addresses where a procedure created a field with a fixed number of lines, even if those lines were empty. To save space in my SSRS report, I cut them down.
For Mac OS X:
export ANDROID_HOME=/<installation location>/android-sdk-macosx
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
You can even make it fancier with extensions:
namespace Foo
{
public static class Extensions
{
public static byte[] ToByteArray(this Stream stream)
{
using (stream)
{
using (MemoryStream memStream = new MemoryStream())
{
stream.CopyTo(memStream);
return memStream.ToArray();
}
}
}
}
}
And then call it as a regular method:
byte[] arr = someStream.ToByteArray()
You cannot initialize reference types by default other than null. You have to make them readonly. So this could work;
readonly MyStruct[] MyArray = new MyStruct[]{
new MyStruct{ label = "a", id = 1},
new MyStruct{ label = "b", id = 5},
new MyStruct{ label = "c", id = 1}
};
Another problem is that CSS has to be defined outside component scope, breaking component encapsulation
This is not true. With scss (SASS) you can easily style the component (itself;host) as so:
:host {
display: block;
position: absolute;
width: 100%;
height: 100%;
pointer-events: none;
visibility: hidden;
&.someClass {
visibility: visible;
}
}
This way the encapsulation is "unbroken".
Handles either type of line break
str.replace(new RegExp('\r?\n','g'), '<br />');
I believe your 1:m relationships should already implicitly create DISTINCT JOINs.
But, if you're goal is just C's in each A, it might be easier to just use DISTINCT on the outer-most query.
SELECT DISTINCT a.valueA, c.valueC
FROM C
INNER JOIN B ON B.lookupC = C.id
INNER JOIN A ON A.lookupB = B.id
ORDER BY a.valueA, c.valueC
.toString()
is available, or just add ""
to the end of the int
var x = 3,
toString = x.toString(),
toConcat = x + "";
Angular is simply JavaScript at the core.
You can change your target's launch settings in "Manage Scheme" to Wait for <app>.app to be launched manually
, which allows you debug by setting a breakpoint in application: didReceiveRemoteNotification: fetchCompletionHandler:
and sending the push notification to trigger the background launch.
I'm not sure it'll solve the issue, but it may assist you with debugging for now.
Do Following steps:
You can keep the default behaviour (with gutter) and add a class to your CSS stylesheet for tasks like yours:
.no-gutter > [class*='col-'] {
padding-right:0;
padding-left:0;
}
And here’s how you can use it in your HTML:
<div class="row no-gutter">
<div class="col-md-4">
...
</div>
<div class="col-md-4">
...
</div>
<div class="col-md-4">
...
</div>
</div>
I found that this question was still relevant but not clearly answered in my case.
Using SQL Server 2012 with an orphaned SQL_USER this was the fix;
USE databasename -- The database I had recently attached
EXEC sp_change_users_login 'Report' -- Display orphaned users
EXEC sp_change_users_login 'Auto_Fix', 'UserName', NULL, 'Password'
Thanks to CSS3
img
{
object-fit: contain;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
IE and EDGE as always outsiders: http://caniuse.com/#feat=object-fit
Use []
notation for string representations of properties:
console.log(obj[name]);
Otherwise it's looking for the "name" property, rather than the "a" property.
This problem can occur if you have some child projects that refer to a parent pom and you have not installed from the parent pom directory (run mvn install
from the parent directory). One of the child projects may depend on a sibling project and when it goes to read the pom of the sibling, it will fail with the error mentioned in the question unless you have installed from the parent pom directory at least once.
I just ran into this problem when moving a project to a new computer. I was in the habit of running commands from the child project and didn't run install on the parent.
If you are happy with "blah" in somestring
but want it to be a function/method call, you can probably do this
import operator
if not operator.contains(somestring, "blah"):
continue
All operators in Python can be more or less found in the operator module including in
.
Objective-C
Create:
NSDictionary *dictionary = @{@"myKey1": @7, @"myKey2": @5};
Change:
NSMutableDictionary *mutableDictionary = [dictionary mutableCopy]; //Make the dictionary mutable to change/add
mutableDictionary[@"myKey3"] = @3;
The short-hand syntax is called Objective-C Literals
.
Swift
Create:
var dictionary = ["myKey1": 7, "myKey2": 5]
Change:
dictionary["myKey3"] = 3
Executive summary: Don't do that.
j_random_hacker's answer tells you how to do this. However, I would also like to point out that you should not do this. The whole point of templates is that they can accept any compatible type, and Java style type constraints break that.
Java's type constraints are a bug not a feature. They are there because Java does type erasure on generics, so Java can't figure out how to call methods based on the value of type parameters alone.
C++ on the other hand has no such restriction. Template parameter types can be any type compatible with the operations they are used with. There doesn't have to be a common base class. This is similar to Python's "Duck Typing," but done at compile time.
A simple example showing the power of templates:
// Sum a vector of some type.
// Example:
// int total = sum({1,2,3,4,5});
template <typename T>
T sum(const vector<T>& vec) {
T total = T();
for (const T& x : vec) {
total += x;
}
return total;
}
This sum function can sum a vector of any type that support the correct operations. It works with both primitives like int/long/float/double, and user defined numeric types that overload the += operator. Heck, you can even use this function to join strings, since they support +=.
No boxing/unboxing of primitives is necessary.
Note that it also constructs new instances of T using T(). This is trivial in C++ using implicit interfaces, but not really possible in Java with type constraints.
While C++ templates don't have explicit type constraints, they are still type safe, and will not compile with code that does not support the correct operations.
import numpy as np
hist, bin_edges = np.histogram([1, 1, 2, 2, 2, 2, 3], bins = range(5))
Below, hist
indicates that there are 0 items in bin #0, 2 in bin #1, 4 in bin #3, 1 in bin #4.
print(hist)
# array([0, 2, 4, 1])
bin_edges
indicates that bin #0 is the interval [0,1), bin #1 is [1,2), ...,
bin #3 is [3,4).
print (bin_edges)
# array([0, 1, 2, 3, 4]))
Play with the above code, change the input to np.histogram
and see how it works.
But a picture is worth a thousand words:
import matplotlib.pyplot as plt
plt.bar(bin_edges[:-1], hist, width = 1)
plt.xlim(min(bin_edges), max(bin_edges))
plt.show()
Using =
causes the variable to be assigned a value. If the variable already had a value, it is replaced. This value will be expanded when it is used. For example:
HELLO = world
HELLO_WORLD = $(HELLO) world!
# This echoes "world world!"
echo $(HELLO_WORLD)
HELLO = hello
# This echoes "hello world!"
echo $(HELLO_WORLD)
Using :=
is similar to using =
. However, instead of the value being expanded when it is used, it is expanded during the assignment. For example:
HELLO = world
HELLO_WORLD := $(HELLO) world!
# This echoes "world world!"
echo $(HELLO_WORLD)
HELLO = hello
# Still echoes "world world!"
echo $(HELLO_WORLD)
HELLO_WORLD := $(HELLO) world!
# This echoes "hello world!"
echo $(HELLO_WORLD)
Using ?=
assigns the variable a value iff the variable was not previously assigned. If the variable was previously assigned a blank value (VAR=
), it is still considered set I think. Otherwise, functions exactly like =
.
Using +=
is like using =
, but instead of replacing the value, the value is appended to the current one, with a space in between. If the variable was previously set with :=
, it is expanded I think. The resulting value is expanded when it is used I think. For example:
HELLO_WORLD = hello
HELLO_WORLD += world!
# This echoes "hello world!"
echo $(HELLO_WORLD)
If something like HELLO_WORLD = $(HELLO_WORLD) world!
were used, recursion would result, which would most likely end the execution of your Makefile. If A := $(A) $(B)
were used, the result would not be the exact same as using +=
because B
is expanded with :=
whereas +=
would not cause B
to be expanded.
I created this extension for save a screen shot from UIView
extension UIView {
func saveImageFromView(path path:String) {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageJPEGRepresentation(image, 0.4)?.writeToFile(path, atomically: true)
}}
call:
let pathDocuments = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first!
let pathImage = "\(pathDocuments)/\(user!.usuarioID.integerValue).jpg"
reportView.saveImageFromView(path: pathImage)
If you want to create a png must change:
UIImageJPEGRepresentation(image, 0.4)?.writeToFile(path, atomically: true)
by
UIImagePNGRepresentation(image)?.writeToFile(path, atomically: true)
We can make a plugin pretty easily:
$.fn.filterData = function(key, value) {
return this.filter(function() {
return $(this).data(key) == value;
});
};
Usage (checking a radio button):
$('input[name=location_id]').filterData('my-data','data-val').prop('checked',true);
If you see this warning:
warning: receiver 'MyCoolClass' is a forward class and corresponding @interface may not exist
you need to #import
the file, but you can do that in your implementation file (.m), and use the @class
declaration in your header file.
@class
does not (usually) remove the need to #import
files, it just moves the requirement down closer to where the information is useful.
For Example
If you say @class MyCoolClass
, the compiler knows that it may see something like:
MyCoolClass *myObject;
It doesn't have to worry about anything other than MyCoolClass
is a valid class, and it should reserve room for a pointer to it (really, just a pointer). Thus, in your header, @class
suffices 90% of the time.
However, if you ever need to create or access myObject
's members, you'll need to let the compiler know what those methods are. At this point (presumably in your implementation file), you'll need to #import "MyCoolClass.h"
, to tell the compiler additional information beyond just "this is a class".
string valueStr = "title, genre, director, actor";
var vals = valueStr.Split(',')[0];
vals will give you the title
I don't think you should use the synchronous approach, asynchronously writing data to a file is better also stringify the output
if it's an object
.
Note: If output
is a string, then specify the encoding and remember the flag
options as well.:
const fs = require('fs');
const content = JSON.stringify(output);
fs.writeFile('/tmp/phraseFreqs.json', content, 'utf8', function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
Added Synchronous method of writing data to a file, but please consider your use case. Asynchronous vs synchronous execution, what does it really mean?
const fs = require('fs');
const content = JSON.stringify(output);
fs.writeFileSync('/tmp/phraseFreqs.json', content);
Kotlin version:
fun okHttpClientFactory(): OkHttpClient {
return OkHttpClient().newBuilder()
.addInterceptor { chain ->
chain.request().newBuilder()
.addHeader(HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION)
.build()
.let(chain::proceed)
}
.build()
}
For iOS<10
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
//-- Set Notification
if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
{
// iOS 8 Notifications
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[application registerForRemoteNotifications];
}
else
{
// iOS < 8 Notifications
[application registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)];
}
//--- your custom code
return YES;
}
For iOS10
This query helps me every time for problems like this. Replace N with position..
select *
from(
select *
from (select * from TABLE_NAME order by SALARY_COLUMN desc)
where rownum <=N
)
where SALARY_COLUMN <= all(
select SALARY_COLUMN
from (select * from TABLE_NAME order by SALARY_COLUMN desc)
where rownum <=N
);
I found that Apache2 (you might want to also check Apache 1.5) has a way to restrict this before uploading by dropping this in your .htaccess file:
LimitRequestBody 2097152
This restricts it to 2 megabytes (2 * 1024 * 1024) on file upload (if I did my byte math properly).
Note when you do this, the Apache error log will generate this entry when you exceed this limit on a form post or get request:
Requested content-length of 4000107 is larger than the configured limit of 2097152
And it will also display this message back in the web browser:
<h1>Request Entity Too Large</h1>
So, if you're doing AJAX form posts with something like the Malsup jQuery Form Plugin, you could trap for the H1 response like this and show an error result.
By the way, the error number returned is 413. So, you could use a directive in your .htaccess file like...
Redirect 413 413.html
...and provide a more graceful error result back.
-None of the above consistently worked for me. So here is the solution i worked out that works consistently across all browsers as it uses basic functionality. Hope this may help others. Using jQuery 8.2
1) Get the jquery object for "span". 2) Get the DOM object from above. Using jquery .get(0) 3) Using DOM's object's innerText get the text.
Here is a simple example
var curSpan = $(this).parent().children(' span').get(0);
var spansText = curSpan.innerText;
HTML
<div >
<input type='checkbox' /><span >testinput</span>
</div>
Using ASP.NET's visible="false"
property will set the visibility
attribute where as I think when you call show()
in jQuery it modifies the display
attribute of the CSS style.
So doing the latter won't rectify the former.
You need to do this:
$("#test1").attr("visibility", "visible");
To set Compatibility error
use this before using pivot function
ALTER DATABASE [dbname] SET COMPATIBILITY_LEVEL = 100
You should add first jquery.cookie.js
then add your js or jQuery where you are using that function.
When browser loads the webpage first it loads this jquery.cookie.js
and after then you js or jQuery and now that function is available for use
I think the possibilities are less, but FireBug (addon of FireFox) has some network analysis tools, too.
In C++17, use std::to_chars
as:
std::array<char, 10> str;
std::to_chars(str.data(), str.data() + str.size(), 42);
In C++11, use std::to_string
as:
std::string s = std::to_string(number);
char const *pchar = s.c_str(); //use char const* as target type
And in C++03, what you're doing is just fine, except use const
as:
char const* pchar = temp_str.c_str(); //dont use cast
When you declare
public static <T> void foo(List<T>... bar)
the compiler converts it to
public static <T> void foo(List<T>[] bar)
then to
public static void foo(List[] bar)
The danger then arises that you'll mistakenly assign incorrect values into the list and the compiler will not trigger any error. For example, if T
is a String
then the following code will compile without error but will fail at runtime:
// First, strip away the array type (arrays allow this kind of upcasting)
Object[] objectArray = bar;
// Next, insert an element with an incorrect type into the array
objectArray[0] = Arrays.asList(new Integer(42));
// Finally, try accessing the original array. A runtime error will occur
// (ClassCastException due to a casting from Integer to String)
T firstElement = bar[0].get(0);
If you reviewed the method to ensure that it doesn't contain such vulnerabilities then you can annotate it with @SafeVarargs
to suppress the warning. For interfaces, use @SuppressWarnings("unchecked")
.
If you get this error message:
Varargs method could cause heap pollution from non-reifiable varargs parameter
and you are sure that your usage is safe then you should use @SuppressWarnings("varargs")
instead. See Is @SafeVarargs an appropriate annotation for this method? and https://stackoverflow.com/a/14252221/14731 for a nice explanation of this second kind of error.
References:
With Exuberant ctags, you can create tag files with file information:
ctags --extra=+f -R *
Then, open file from VIM with
:tag filename
You can also use <tab>
to autocomplete file name.
java.util.Date date = ...
DateTime dateTime = new DateTime(date);
Make sure date
isn't null
, though, otherwise it acts like new DateTime()
- I really don't like that.
There are 3 problems.
1) Incorrect decimal separator
Different cultures use different decimal separators (namely ,
and .
).
If you replace .
with ,
it should work as expected:
Console.WriteLine(Convert.ToDouble("52,8725945"));
You can parse your doubles using overloaded method which takes culture as a second parameter. In this case you can use InvariantCulture
(What is the invariant culture) e.g. using double.Parse
:
double.Parse("52.8725945", System.Globalization.CultureInfo.InvariantCulture);
You should also take a look at double.TryParse
, you can use it with many options and it is especially useful to check wheter or not your string is a valid double
.
2) You have an incorrect double
One of your values is incorrect, because it contains two dots:
15.5859949000000662452.23862099999999
3) Your array has an empty value at the end, which is an incorrect double
You can use overloaded Split
which removes empty values:
string[] someArray = a.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
The .swapcase method transforms the uppercase latters in a string to lowercase and the lowercase letters to uppercase.
'TESTING'.swapcase #=> testing
'testing'.swapcase #=> TESTING
If none of the other solutions here work for you, and you have created multiple ssh-keys, but still cannot do simple things like
git pull
then assuming you have two ssh key files like
id_rsa
id_rsa_other_key
then inside of the git repo, try:
# Run these commands INSIDE your git directory
eval `ssh-agent -s`
ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_other_key
and also make sure your github default username and userid are correct by:
# Run these commands INSIDE your git directory
git config user.name "Mona Lisa"
git config user.email "[email protected]"
See https://gist.github.com/jexchan/2351996 for more more information.
For large vectors:
y = as.POSIXlt(date1)$year + 1900 # x$year : years since 1900
m = as.POSIXlt(date1)$mon + 1 # x$mon : 0–11
Google, no API needed:
$data = file_get_contents('http://picasaweb.google.com/data/entry/api/user/<USER_ID>?alt=json');
$d = json_decode($data);
$avatar = $d->{'entry'}->{'gphoto$thumbnail'}->{'$t'};
// Outputs example: https://lh3.googleusercontent.com/-2N6fRg5OFbM/AAAAAAAAAAI/AAAAAAAAADE/2-RmpExH6iU/s64-c/photo.jpg
CHANGE: the 64 in "s64" for the size
In my case, I use below command:
git diff <branch name> -- <path + file name>
This command can help you compare same file in two different branches
The above addMethod by Lod Lawson is not completely correct. It's $.validator and not $.validate and the validator method name cb_selectone requires quotes. Here is a corrected version that I tested:
$.validator.addMethod('cb_selectone', function(value,element){
if(element.length>0){
for(var i=0;i<element.length;i++){
if($(element[i]).val('checked')) return true;
}
return false;
}
return false;
}, 'Please select at least one option');
Swift 4* and above you can try this also:
func leftPadding(valueString: String, toLength: Int, withPad: String = " ") -> String {
guard toLength > valueString.count else { return valueString }
let padding = String(repeating: withPad, count: toLength - valueString.count)
return padding + valueString
}
call the function:
leftPadding(valueString: "12", toLength: 5, withPad: "0")
Output: "00012"
I have found that from version 1.8.4 on, the libraries can be found in ~/Arduino/Libraries. Hope this helps anyone else.
I suggest a simple way to testing if a variable is an DOM element
function isDomEntity(entity) {
if(typeof entity === 'object' && entity.nodeType !== undefined){
return true;
}
else{
return false;
}
}
or as HTMLGuy suggested:
const isDomEntity = entity => {
return typeof entity === 'object' && entity.nodeType !== undefined
}
this might be a solution, i have done something similar but this one does not seem to work for example if the necessary function requires administrator privileges it should ask you to restart it as admin.
@echo off
mkdir C:\Users\cmdfolder
if echo=="Access is denied." (goto :1A) else (goto :A4)
:A1
cls
color 0d
echo restart this program as administator
:A4
pause
Very easy:
Here is what you want:
import os.path as path
two_up = path.abspath(path.join(__file__ ,"../.."))
The up-to-date answer (as of PHP 5.4 or newer) for generating 404 pages is to use http_response_code
:
<?php
http_response_code(404);
include('my_404.php'); // provide your own HTML for the error page
die();
die()
is not strictly necessary, but it makes sure that you don't continue the normal execution.
import { FormsModule } from '@angular/forms'; [...] @NgModule({ imports: [ [...] FormsModule ], [...] })
After all these awesome answers, I hope my answer finds someone and helps them out. I wrote a small service to keep track of route history. Here it goes.
import { Injectable } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs/operators';
@Injectable()
export class RouteInterceptorService {
private _previousUrl: string;
private _currentUrl: string;
private _routeHistory: string[];
constructor(router: Router) {
this._routeHistory = [];
router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => {
this._setURLs(event);
});
}
private _setURLs(event: NavigationEnd): void {
const tempUrl = this._currentUrl;
this._previousUrl = tempUrl;
this._currentUrl = event.urlAfterRedirects;
this._routeHistory.push(event.urlAfterRedirects);
}
get previousUrl(): string {
return this._previousUrl;
}
get currentUrl(): string {
return this._currentUrl;
}
get routeHistory(): string[] {
return this._routeHistory;
}
}
Abusive one-liner!
Array.from(fd).reduce((obj, [k, v]) => ({...obj, [k]: v}), {});
Today I learned firefox has object spread support and array destructuring!
CREATE TABLE db1.table1 SELECT * FROM db2.table1
where db1 is the destination and db2 is the source
Agree with Subir Kumar Sao and Faiz.
element_enter.findElement(By.xpath("//html/body/div[1]/div[3]/div[1]/form/div/div/input")).sendKeys(barcode);
A good answer already, but there are a couple of other ways to do this:
unique(c[c%in%a[a%in%b]])
or,
tst <- c(unique(a),unique(b),unique(c))
tst <- tst[duplicated(tst)]
tst[duplicated(tst)]
You can obviously omit the unique
calls if you know that there are no repeated values within a
, b
or c
.
In bootstrap v4.3.1, it’s a column which is 12 / 5 = 2.4 columns wide. let’s call it col-2dot4 (and col-sm-2dot4, col-md-2dot4, …).
And each column should have 20% of the available space.
The SCSS code which comes out as below:
@mixin make-5-grid-column($columns: $grid-columns, $gutter: $grid-gutter-width, $breakpoints: $grid-breakpoints) {
// Common properties for all breakpoints
%grid-column {
position: relative;
width: 100%;
padding-right: $gutter / 2;
padding-left: $gutter / 2;
}
@each $breakpoint in map-keys($breakpoints) {
$infix: breakpoint-infix($breakpoint, $breakpoints);
.col#{$infix}-2dot4 {
@extend %grid-column;
}
.col#{$infix},
.col#{$infix}-auto {
@extend %grid-column;
}
@include media-breakpoint-up($breakpoint, $breakpoints) {
// Provide basic `.col-{bp}` classes for equal-width flexbox columns
.col#{$infix} {
flex-basis: 0;
flex-grow: 1;
max-width: 100%;
}
.col#{$infix}-auto {
flex: 0 0 auto;
width: auto;
max-width: 100%; // Reset earlier grid tiers
}
.col#{$infix}-2dot4 {
@include make-col(1, 5);
}
}
}
}
@if $enable-grid-classes {
@include make-5-grid-column();
}
In my case, I had to deactivate AdBlock and it worked fine.
The most effective solution that I found is to define the parent element with display:flex
and align-items:center
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.myclass{
display:flex;
align-items:center;
background-color:grey;
color:#fff;
height:50px;
}
</style>
</head>
<body>
<div class="myclass">
<input type="checkbox">
<label>do you love Ananas?
</label>
</div>
</body>
</html>
OUTPUT:
Running IIS 7.5, I had luck adding permissions for the local computer user IUSR. The app pool user didn't work.
The reason enums work easily with == is because each defined instance is also a singleton. So identity comparison using == will always work.
But using == because it works with enums means all your code is tightly coupled with usage of that enum.
For example: Enums can implement an interface. Suppose you are currently using an enum which implements Interface1. If later on, someone changes it or introduces a new class Impl1 as an implementation of same interface. Then, if you start using instances of Impl1, you'll have a lot of code to change and test because of previous usage of ==.
Hence, it's best to follow what is deemed a good practice unless there is any justifiable gain.
=IF(ISNA(INDEX(B:B,MATCH(C2,A:A,0))),"",INDEX(B:B,MATCH(C2,A:A,0)))
Will return the answer you want and also remove the #N/A
result that would appear if you couldn't find a result due to it not appearing in your lookup list.
Ross
Sometimes you just don't have a choice about having to store numbers mixed with text. In one of our applications, the web site host we use for our e-commerce site makes filters dynamically out of lists. There is no option to sort by any field but the displayed text. When we wanted filters built off a list that said things like 2" to 8" 9" to 12" 13" to 15" etc, we needed it to sort 2-9-13, not 13-2-9 as it will when reading the numeric values. So I used the SQL Server Replicate function along with the length of the longest number to pad any shorter numbers with a leading space. Now 20 is sorted after 3, and so on.
I was working with a view that gave me the minimum and maximum lengths, widths, etc for the item type and class, and here is an example of how I did the text. (LBnLow and LBnHigh are the Low and High end of the 5 length brackets.)
REPLICATE(' ', LEN(LB5Low) - LEN(LB1High)) + CONVERT(NVARCHAR(4), LB1High) + '" and Under' AS L1Text,
REPLICATE(' ', LEN(LB5Low) - LEN(LB2Low)) + CONVERT(NVARCHAR(4), LB2Low) + '" to ' + CONVERT(NVARCHAR(4), LB2High) + '"' AS L2Text,
REPLICATE(' ', LEN(LB5Low) - LEN(LB3Low)) + CONVERT(NVARCHAR(4), LB3Low) + '" to ' + CONVERT(NVARCHAR(4), LB3High) + '"' AS L3Text,
REPLICATE(' ', LEN(LB5Low) - LEN(LB4Low)) + CONVERT(NVARCHAR(4), LB4Low) + '" to ' + CONVERT(NVARCHAR(4), LB4High) + '"' AS L4Text,
CONVERT(NVARCHAR(4), LB5Low) + '" and Over' AS L5Text
@echo off
::Ask
echo Your Source Path:
set INPUT1=
set /P INPUT1=Type input: %=%
echo Your Destination Path:
set INPUT2=
set /P INPUT2=Type input: %=%
xcopy %INPUT1% %INPUT2% /y /s
The proper way to do it is probably to break down the method by putting the try-catch block in a separate method, and use a return statement:
public void someMethod() {
try {
...
if (condition)
return;
...
} catch (SomeException e) {
...
}
}
If the code involves lots of local variables, you may also consider using a break
from a labeled block, as suggested by Stephen C:
label: try {
...
if (condition)
break label;
...
} catch (SomeException e) {
...
}
I think you are putting one too many curly brackets. Try this
@if($user->status=='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{!! $user->travel_id !!}" data-toggle="modal" data-target="#myModal">Approve/Reject</a> </td>
@else
<td>{!! $user->status !!}</td>
@endif
Why not do it with one method call:
File.AppendAllLines("file.txt", new[] { DateTime.Now.ToString() });
which will do the newline for you, and allow you to insert multiple lines at once if you want.
I come back to this answer fairly often, though none of these are quite right for me. That said, the right answer for me is a mixture of the others.
What I find works is the following:
git config --global core.eol lf
git config --global core.autocrlf input
For repos that were checked out after those global settings were set, everything will be checked out as whatever it is in the repo – hopefully LF
(\n
). Any CRLF
will be converted to just LF
on checkin.
With an existing repo that you have already checked out – that has the correct line endings in the repo but not your working copy – you can run the following commands to fix it:
git rm -rf --cached .
git reset --hard HEAD
This will delete (rm
) recursively (r
) without prompt (-f
), all files except those that you have edited (--cached
), from the current directory (.
). The reset
then returns all of those files to a state where they have their true line endings (matching what's in the repo).
If you need to fix the line endings of files in a repo, I recommend grabbing an editor that will let you do that in bulk like IntelliJ or Sublime Text, but I'm sure any good one will likely support this.
There is a weird case where if the element is set to display: inline
the jQuery check for visibility fails.
Example:
CSS
#myspan {display: inline;}
jQuery
$('#myspan').show(); // Our element is `inline` instead of `block`
$('#myspan').is(":visible"); // This is false
To fix it you can hide the element in jQuery and than show/hide
or toggle()
should work fine.
$('#myspan').hide()
$('#otherElement').on('click', function() {
$('#myspan').toggle();
});
Well, since you can currently only have one ngView directive... I use nested directive controls. This allows you to set up templating and inherit (or isolate) scopes among them. Outside of that I use ng-switch or even just ng-show to choose which controls I'm displaying based on what's coming in from $routeParams.
EDIT Here's some example pseudo-code to give you an idea of what I'm talking about. With a nested sub navigation.
Here's the main app page
<!-- primary nav -->
<a href="#/page/1">Page 1</a>
<a href="#/page/2">Page 2</a>
<a href="#/page/3">Page 3</a>
<!-- display the view -->
<div ng-view>
</div>
Directive for the sub navigation
app.directive('mySubNav', function(){
return {
restrict: 'E',
scope: {
current: '=current'
},
templateUrl: 'mySubNav.html',
controller: function($scope) {
}
};
});
template for the sub navigation
<a href="#/page/1/sub/1">Sub Item 1</a>
<a href="#/page/1/sub/2">Sub Item 2</a>
<a href="#/page/1/sub/3">Sub Item 3</a>
template for a main page (from primary nav)
<my-sub-nav current="sub"></my-sub-nav>
<ng-switch on="sub">
<div ng-switch-when="1">
<my-sub-area1></my-sub-area>
</div>
<div ng-switch-when="2">
<my-sub-area2></my-sub-area>
</div>
<div ng-switch-when="3">
<my-sub-area3></my-sub-area>
</div>
</ng-switch>
Controller for a main page. (from the primary nav)
app.controller('page1Ctrl', function($scope, $routeParams) {
$scope.sub = $routeParams.sub;
});
Directive for a Sub Area
app.directive('mySubArea1', function(){
return {
restrict: 'E',
templateUrl: 'mySubArea1.html',
controller: function($scope) {
//controller for your sub area.
}
};
});
You need to check for DBNull
, not null
. Additionally, two of your three ReplaceNull
methods don't make sense. double
and DateTime
are non-nullable, so checking them for null
will always be false
...
You can try something like:
var str = "a,d,k";
str.replace(/,/g, "");
I have this function in my code base, this should work for you.
public static Document loadXMLFromString(String xml) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
return builder.parse(is);
}
also see this similar question
Just set the header width to be 100vw to make it full screen width and set the header height to be 100vh to make it full screen height
It's very easy for Kotlin!
listToBeSorted.sortBy { it.distance }
Just add to the CommandArgument
parameter and read it out on the Click
handler:
<asp:LinkButton ID="ENameLinkBtn" runat="server"
style="font-weight: 700; font-size: 8pt;" CommandArgument="YourValueHere"
OnClick="ENameLinkBtn_Click" >
Then in your click event:
protected void ENameLinkBtn_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)(sender);
string yourValue = btn.CommandArgument;
// do what you need here
}
Also you can set the CommandArgument
argument when binding if you are using the LinkButton
in any bindable controls by doing:
CommandArgument='<%# Eval("SomeFieldYouNeedArguementFrom") %>'
There can also be a solution by having both float
to left
.
Try this out:
P.S. This is just an improvement of Ankit's Answer
const int n = snprintf(NULL, 0, "%lu", ulong_value);
assert(n > 0);
char buf[n+1];
int c = snprintf(buf, n+1, "%lu", ulong_value);
assert(buf[n] == '\0');
assert(c == n);
pkill -x matches the process name exactly.
pkill -x amarok
pkill -f is similar but allows a regular expression pattern.
Note that pkill with no other parameters (e.g. -x, -f) will allow partial matches on process names. So "pkill amarok" would kill amarok, amarokBanana, bananaamarok, etc.
I wish -x was the default behavior!
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
Just add the class disabled
on your anchor:
<a class="dropdown-toggle disabled" href="{your link}">
Dropdown</a>
And you are free to go.
There is no simple (as in a couple of clicks or a simple command) solution to this issue.
Quoting from some answers in this bug report in Eclipse.org, these are the work-arounds. Pick the one that's the least painful to you:
Update: After July 2014, there is a better way (thanks to @Brad-Mace's answer below:
If you have created your own build file instead of using Project -> Generate Javadocs
, then you can add useexternalfile="yes"
to the Javadoc task, which is designed specifically to solve this problem.
Perhaps your subquery (SELECT ename FROM EMP WHERE empno = mgr)
thinks, give me the employee records that are their own managers! (i.e., where the empno of a row is the same as the mgr of the same row.)
have you considered perhaps rewriting this to use an inner (self) join? (I'm asking, becuase i'm not even sure if the following will work or not.)
SELECT t1.ename, t1.empno, t2.ename as MANAGER, t1.mgr
from emp as t1
inner join emp t2 ON t1.mgr = t2.empno
order by t1.empno;
If you are looking for the simplest "back" button, then you could set up a directive like so:
.directive('back', function factory($window) {
return {
restrict : 'E',
replace : true,
transclude : true,
templateUrl: 'wherever your template is located',
link: function (scope, element, attrs) {
scope.navBack = function() {
$window.history.back();
};
}
};
});
Keep in mind this is a fairly unintelligent "back" button because it is using the browser's history. If you include it on your landing page, it will send a user back to any url they came from prior to landing on yours.
from PIL import Image
image = Image.open('File.jpg')
image.show()
This is called partial functions and there are at least 3 ways to do this. My favorite way is using lambda because it avoids dependency on extra package and is the least verbose. Assume you have a function add(x, y)
and you want to pass add(3, y)
to some other function as parameter such that the other function decides the value for y
.
Use lambda
# generic function takes op and its argument
def runOp(op, val):
return op(val)
# declare full function
def add(x, y):
return x+y
# run example
def main():
f = lambda y: add(3, y)
result = runOp(f, 1) # is 4
Create Your Own Wrapper
Here you need to create a function that returns the partial function. This is obviously lot more verbose.
# generic function takes op and its argument
def runOp(op, val):
return op(val)
# declare full function
def add(x, y):
return x+y
# declare partial function
def addPartial(x):
def _wrapper(y):
return add(x, y)
return _wrapper
# run example
def main():
f = addPartial(3)
result = runOp(f, 1) # is 4
Use partial from functools
This is almost identical to lambda
shown above. Then why do we need this? There are few reasons. In short, partial
might be bit faster in some cases (see its implementation) and that you can use it for early binding vs lambda's late binding.
from functools import partial
# generic function takes op and its argument
def runOp(op, val):
return op(val)
# declare full function
def add(x, y):
return x+y
# run example
def main():
f = partial(add, 3)
result = runOp(f, 1) # is 4
This should work for all elements regardless of when they are generated.
if($('some_element').length == 0) {
}
write your code in the ajax callback functions and it should work fine.
pass by value means how to pass value to a function by making use of arguments. in pass by value we copy the data stored in the variable we specify and it is slower than pass by reference bcse t he data is copied . of we make changes in the copied data the original data is not affected. nd in pass by refernce or pass by address we send direct link to the variable itself . or passing pointer to a variable. it is faster bcse less time is consumed
Yes this post is 8 years old, but incase someone comes on here also looking for an answer: you can now just use semicolons. However, you cannot use if/elif/else staments, for/while loops, and you can't define functions. The main use of this would be when using imported modules where you don't have to define any functions or use any if/elif/else/for/while statements/loops.
Here's an example that takes the artist of a song, the song name, and searches genius for the lyrics:
import bs4, requests; song = input('Input artist then song name\n'); print(bs4.BeautifulSoup(requests.get(f'https://genius.com/{song.replace(" ", "-")}-lyrics').text,'html.parser').select('.lyrics')[0].text.strip())
Here is an example Dockerfile leveraging several clever techniques to all you to run a full conda environment for every RUN
stanza. You can use a similar approach to execute any arbitrary prep in a script file.
Note: there is a lot of nuance when it comes to login/interactive vs nonlogin/noninteractive shells, signals, exec
, the way multiple args are handled, quoting, how CMD and ENTRYPOINT interact, and a million other things, so don't be discouraged if when hacking around with these things, stuff goes sideways. I've spent many frustrating hours digging through all manner of literature and I still don't quite get how it all clicks.
## Conda with custom entrypoint from base ubuntu image
## Build with e.g. `docker build -t monoconda .`
## Run with `docker run --rm -it monoconda bash` to drop right into
## the environment `foo` !
FROM ubuntu:18.04
## Install things we need to install more things
RUN apt-get update -qq &&\
apt-get install -qq curl wget git &&\
apt-get install -qq --no-install-recommends \
libssl-dev \
software-properties-common \
&& rm -rf /var/lib/apt/lists/*
## Install miniconda
RUN wget -nv https://repo.anaconda.com/miniconda/Miniconda3-4.7.12-Linux-x86_64.sh -O ~/miniconda.sh && \
/bin/bash ~/miniconda.sh -b -p /opt/conda && \
rm ~/miniconda.sh && \
/opt/conda/bin/conda clean -tipsy && \
ln -s /opt/conda/etc/profile.d/conda.sh /etc/profile.d/conda.sh
## add conda to the path so we can execute it by name
ENV PATH=/opt/conda/bin:$PATH
## Create /entry.sh which will be our new shell entry point. This performs actions to configure the environment
## before starting a new shell (which inherits the env).
## The exec is important! This allows signals to pass
RUN (echo '#!/bin/bash' \
&& echo '__conda_setup="$(/opt/conda/bin/conda shell.bash hook 2> /dev/null)"' \
&& echo 'eval "$__conda_setup"' \
&& echo 'conda activate "${CONDA_TARGET_ENV:-base}"' \
&& echo '>&2 echo "ENTRYPOINT: CONDA_DEFAULT_ENV=${CONDA_DEFAULT_ENV}"' \
&& echo 'exec "$@"'\
) >> /entry.sh && chmod +x /entry.sh
## Tell the docker build process to use this for RUN.
## The default shell on Linux is ["/bin/sh", "-c"], and on Windows is ["cmd", "/S", "/C"]
SHELL ["/entry.sh", "/bin/bash", "-c"]
## Now, every following invocation of RUN will start with the entry script
RUN conda update conda -y
## Create a dummy env
RUN conda create --name foo
## I added this variable such that I have the entry script activate a specific env
ENV CONDA_TARGET_ENV=foo
## This will get installed in the env foo since it gets activated at the start of the RUN stanza
RUN conda install pip
## Configure .bashrc to drop into a conda env and immediately activate our TARGET env
RUN conda init && echo 'conda activate "${CONDA_TARGET_ENV:-base}"' >> ~/.bashrc
ENTRYPOINT ["/entry.sh"]
You need to enclose your <parent>
elements in a surrounding element as XML Documents can have only one root node:
<parents> <!-- I've added this tag -->
<parent>
<child>
Text
</child>
</parent>
<parent>
<child>
<grandchild>
Text
</grandchild>
<grandchild>
Text
</grandchild>
</child>
<child>
Text
</child>
</parent>
</parents> <!-- I've added this tag -->
As you're receiving this markup from somewhere else, rather than generating it yourself, you may have to do this yourself by treating the response as a string and wrapping it with appropriate tags, prior to attempting to parse it as XML.
So, you've a couple of choices:
<parent>
node) and process each as a distinct XML DocumentThis command works perfectly. I have 8GB ram in my laptop, So I set size=8192. It is all about ram and also you need set file name. I run npm run build command that's why I used build.js.
node --expose-gc --max-old-space-size=8192 node_modules/react-scripts/scripts/build.js
stuck in the same issue, this helps me
URL resource = getClass().getClassLoader().getResource("jsonschema.json");
JsonNode jsonNode = JsonLoader.fromURL(resource);
This is a linker issue. Try:
g++ -o test_1 test_1.cpp `pkg-config opencv --cflags --libs`
This should work to compile the source. However, if you recently compiled OpenCV from source, you will meet linking issue in run-time, the library will not be found. In most cases, after compiling libraries from source, you need to do finally:
sudo ldconfig
Your second delegate is not a rewrite of the first in anonymous delegate (rather than lambda) format. Look at your conditions.
First:
x.ID == packageId || x.Parent.ID == packageId || x.Parent.Parent.ID == packageId
Second:
(x.ID == packageId) || (x.Parent != null && x.Parent.ID == packageId) ||
(x.Parent != null && x.Parent.Parent != null && x.Parent.Parent.ID == packageId)
The call to the lambda would throw an exception for any x
where the ID doesn't match and either the parent is null or doesn't match and the grandparent is null. Copy the null checks into the lambda and it should work correctly.
If your original object is not a List<T>
, then we have no way of knowing what the return type of FindAll()
is, and whether or not this implements the IQueryable
interface. If it does, then that likely explains the discrepancy. Because lambdas can be converted at compile time into an Expression<Func<T>>
but anonymous delegates cannot, then you may be using the implementation of IQueryable
when using the lambda version but LINQ-to-Objects when using the anonymous delegate version.
This would also explain why your lambda is not causing a NullReferenceException
. If you were to pass that lambda expression to something that implements IEnumerable<T>
but not IQueryable<T>
, runtime evaluation of the lambda (which is no different from other methods, anonymous or not) would throw a NullReferenceException
the first time it encountered an object where ID
was not equal to the target and the parent or grandparent was null.
Consider the following simple example:
IQueryable<MyObject> source = ...; // some object that implements IQueryable<MyObject>
var anonymousMethod = source.Where(delegate(MyObject o) { return o.Name == "Adam"; });
var expressionLambda = source.Where(o => o.Name == "Adam");
These two methods produce entirely different results.
The first query is the simple version. The anonymous method results in a delegate that's then passed to the IEnumerable<MyObject>.Where
extension method, where the entire contents of source
will be checked (manually in memory using ordinary compiled code) against your delegate. In other words, if you're familiar with iterator blocks in C#, it's something like doing this:
public IEnumerable<MyObject> MyWhere(IEnumerable<MyObject> dataSource, Func<MyObject, bool> predicate)
{
foreach(MyObject item in dataSource)
{
if(predicate(item)) yield return item;
}
}
The salient point here is that you're actually performing your filtering in memory on the client side. For example, if your source were some SQL ORM, there would be no WHERE
clause in the query; the entire result set would be brought back to the client and filtered there.
The second query, which uses a lambda expression, is converted to an Expression<Func<MyObject, bool>>
and uses the IQueryable<MyObject>.Where()
extension method. This results in an object that is also typed as IQueryable<MyObject>
. All of this works by then passing the expression to the underlying provider. This is why you aren't getting a NullReferenceException
. It's entirely up to the query provider how to translate the expression (which, rather than being an actual compiled function that it can just call, is a representation of the logic of the expression using objects) into something it can use.
An easy way to see the distinction (or, at least, that there is) a distinction, would be to put a call to AsEnumerable()
before your call to Where
in the lambda version. This will force your code to use LINQ-to-Objects (meaning it operates on IEnumerable<T>
like the anonymous delegate version, not IQueryable<T>
like the lambda version currently does), and you'll get the exceptions as expected.
The long and the short of it is that your lambda expression is being translated into some kind of query against your data source, whereas the anonymous method version is evaluating the entire data source in memory. Whatever is doing the translating of your lambda into a query is not representing the logic that you're expecting, which is why it isn't producing the results you're expecting.
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to id.co.bni.switcherservice.model.SwitcherServiceSource
Problem is
(List<SwitcherServiceSource>) LoadSource.list();
This will return a List of Object arrays (Object[]) with scalar values for each column in the SwitcherServiceSource
table. Hibernate will use ResultSetMetadata to deduce the actual order and types of the returned scalar values.
List<Object> result = (List<Object>) LoadSource.list();
Iterator itr = result.iterator();
while(itr.hasNext()){
Object[] obj = (Object[]) itr.next();
//now you have one array of Object for each row
String client = String.valueOf(obj[0]); // don't know the type of column CLIENT assuming String
Integer service = Integer.parseInt(String.valueOf(obj[1])); //SERVICE assumed as int
//same way for all obj[2], obj[3], obj[4]
}
SELECT Col.Column_Name from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
WHERE
Col.Constraint_Name = Tab.Constraint_Name
AND Col.Table_Name = Tab.Table_Name
AND Constraint_Type = 'PRIMARY KEY'
AND Col.Table_Name = '<your table name>'
Necro'ing this Question ;)
You need to change the data being sent as Stringified JSON, that way you can modularize the Ajax call into a single supportable function.
/***
* This helper is used to call WebMethods from the page WebMethods.aspx
*
* @method - String value; the name of the Web Method to execute
* @data - JSON Object; the JSON structure data to pass, it will be Stringified
* before sending
* @beforeSend - Function(xhr, sett)
* @success - Function(data, status, xhr)
* @error - Function(xhr, status, err)
*/
function AddToCartAjax(method, data, beforeSend, success, error) {
$.ajax({
url: 'AddToCart.aspx/', + method,
data: JSON.stringify(data),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: beforeSend,
success: success,
error: error
})
}
[WebMethod]
public static string AddTo_Cart ( object items ) {
var js = new JavaScriptSerializer();
var json = js.ConvertToType<Dictionary<string , int>>( items );
SpiritsShared.ShoppingCart.AddItem(json["itemId"], json["quantity"]);
return "Add";
}
This can be called just about anywhere, JS-file, HTML-file, or Server-side construction.
var items = { "quantity": total_qty, "itemId": itemId };
AddToCartAjax("AddTo_Cart", items,
function (xhr, sett) { // @beforeSend
alert("Start!!!");
}, function (data, status, xhr) { // @success
alert("a");
}, function(xhr, status, err){ // @error
alert("Sorry!!!");
});
I had the same problem with different assemblies referencing different versions of Newtonsoft.json. The solution that worked for me was running update-package from Nuget Package Manager Console.
please check below javaScripts, there you can get only number
var txt = "abc1234char5678#!9";_x000D_
var str = txt.match(/\d+/g, "")+'';_x000D_
var s = str.split(',').join('');_x000D_
alert(Number(s));
_x000D_
output : 1234567789
You can use String.Join for this if you are using .NET framework> 4.0.
var result= String.Join(",", yourList);
yum install php-mbstring (as per http://php.net/manual/en/mbstring.installation.php)
I think you have to install the EPEL repository http://fedoraproject.org/wiki/EPEL
The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[]
with an index read from stream. Try vector::at()
instead of vector::operator[]
. This won't solve your problem, but will show which assignment to the vector causes error.
Use this class to set divider in your RecyclerView
.
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
if (position < spanCount) { // top edge
outRect.top = spacing;
}
outRect.bottom = spacing; // item bottom
} else {
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
There is no tuple type in Go, and you are correct, the multiple values returned by functions do not represent a first-class object.
Nick's answer shows how you can do something similar that handles arbitrary types using interface{}
. (I might have used an array rather than a struct to make it indexable like a tuple, but the key idea is the interface{}
type)
My other answer shows how you can do something similar that avoids creating a type using anonymous structs.
These techniques have some properties of tuples, but no, they are not tuples.
-webkit-overflow-scrolling:touch
as mentioned in the answer is infact the possible solution.
<div style="overflow:scroll !important; -webkit-overflow-scrolling:touch !important;">
<iframe src="YOUR_PAGE_URL" width="600" height="400"></iframe>
</div>
But if you are unable to scroll up and down inside the iframe as shown in image below,
you could try scrolling with 2 fingers diagonally like this,
This actually worked in my case, so just sharing it if you haven't still found a solution for this.
I had this problem when I did a SharePoint 2010 to 2013 migration. I suspected that because the database server is on the other side of a firewall which does not route IP6 that it was trying then to use IP6 and failing when connecting to the database.
I think the issue is now solved. The errors seem to have stopped. What I did was I simply disabled IP6 (by unchecking it) for the network adapter on the SharePoint Servers.
You could use p2pkit, or the free solution it was based on: https://github.com/GitGarage. Doesn't work very well, and its a fixer-upper for sure, but its, well, free. Works for small amounts of data transfer right now.
left = 37,up = 38, right = 39,down = 40
$(document).keydown(function(e) {
switch(e.which) {
case 37:
$( "#prev" ).click();
break;
case 38:
$( "#prev" ).click();
break;
case 39:
$( "#next" ).click();
break;
case 40:
$( "#next" ).click();
break;
default: return;
}
e.preventDefault();
});
For anyone looking to style child elements of a :host
here is an example of how to use ::ng-deep
:host::ng-deep <child element>
e.g :host::ng-deep span { color: red; }
As others said /deep/
is deprecated
You can try calling this method in you program:
static double string_double(string s)
{
double temp = 0;
double dtemp = 0;
int b = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '.')
{
i++;
while (i < s.Length)
{
dtemp = (dtemp * 10) + (int)char.GetNumericValue(s[i]);
i++;
b++;
}
temp = temp + (dtemp * Math.Pow(10, -b));
return temp;
}
else
{
temp = (temp * 10) + (int)char.GetNumericValue(s[i]);
}
}
return -1; //if somehow failed
}
Example:
string s = "12.3";
double d = string_double (s); //d = 12.3
You will need to use the IO.Directory.GetFiles function.
Dim files() As String = IO.Directory.GetFiles("c:\")
For Each file As String In files
' Do work, example
Dim text As String = IO.File.ReadAllText(file)
Next
INSERT
INTO remotedblink.remotedatabase.remoteschema.remotetable
SELECT *
FROM mytable
There is no such thing as "the end of the table" in relational databases.
I'm using this one:
internal static bool IsValidJson(string data)
{
data = data.Trim();
try
{
if (data.StartsWith("{") && data.EndsWith("}"))
{
JToken.Parse(data);
}
else if (data.StartsWith("[") && data.EndsWith("]"))
{
JArray.Parse(data);
}
else
{
return false;
}
return true;
}
catch
{
return false;
}
}
This workaround works most of the time. It uses eclipse's 'smart insert' features instead:
Hope this helps until Shift+TAB is implemented in Eclipse.
via Is there a way to link someone to a YouTube Video in HD 1080p quality?
Yes there is:
https://www.youtube.com/embed/Susj4jVWs0s?version=3&vq=hd720
options are:
default|none: vq=auto;
Code for auto: vq=auto;
Code for 2160p: vq=hd2160;
Code for 1440p: vq=hd1440;
Code for 1080p: vq=hd1080;
Code for 720p: vq=hd720;
Code for 480p: vq=large;
Code for 360p: vq=medium;
Code for 240p: vq=small;
As mentioned, you have to use the /embed/
or /v/
URL.
Note: Some copyrighted content doesn't support be played in this way
Updated answer
Check https://shatter-box.com/knowledgebase/android-apk-signing-tool-apk-signer/
Old answer
check apk-signer a nice way to sign your app
Class is Data Type,You use this type to create object.
Instance is Logical but object is Physical means occupies some memory.
We can create an instance for abstract class as well as for interface, but we cannot create an
object for those.
Object is instance of class and instance means representative of class i.e object.
Instance refers to Reference of an object.
Object is actually pointing to memory address of that instance.
You can’t pass instance over the layers but you can pass the object over the layers
You can’t store an instance but you can store an object
A single object can have more than one instance.
Instance will have the both class definition and the object definition where as in object it will have only the object definition.
Syntax of Object:
Classname var=new Classname();
But for instance creation it returns only a pointer refering to an object, syntax is :
Classname varname;
I just had a similar issue with a field like that which I solved a different way. My use case was needing to take those ids in a comma separated list for use in a join.
I was able to solve it using a like, but it was made easier because in addition to the comma delimiter the ids were also quoted like so:
keys
"1","2","6","12"
Because of that, I was able to do a LIKE
SELECT twwf.id, jtwi.id joined_id
FROM table_with_weird_field twwf
INNER JOIN join_table_with_ids jtwi
ON twwf.delimited_field LIKE CONCAT("%\"", jtwi.id, "\"%")
This basically just looks to see if the id from the table you're trying to join appears in the set and at that point you can join on it easily enough and return your records. You could also just create a view from something like this.
It worked well for my use case where I was dealing with a Wordpress plugin that managed relations in the way described. The quotes really help though because otherwise you run the risk of partial matches (aka - id 1 within 18, etc).
Since you are the only user:
git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}
( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )
Without doing any changes to your local repo, you can also do something like:
git push -f origin <sha_of_previous_commit>:master
Generally, in published repos, it is safer to do git revert
and then git push
The default limit for the length of the request line is 8192 bytes = 8* 1024. It you want to change the limit, you have to add or update in your tomcat server.xml the attribut maxHttpHeaderSize.
as:
<Connector port="8080" maxHttpHeaderSize="65536" protocol="HTTP/1.1" ... />
In this example I set the limite to 65536 bytes= 64*1024.
Hope this will help.
User
.Add a property to the Response class 'user' with the type of the new class for the user values User
.
public class Response {
public string id { get; set; }
public string text { get; set; }
public string url { get; set; }
public string width { get; set; }
public string height { get; set; }
public string size { get; set; }
public string type { get; set; }
public string timestamp { get; set; }
public User user { get; set; }
}
public class User {
public int id { get; set; }
public string screen_name { get; set; }
}
In general you should make sure the property types of the json and your CLR classes match up. It seems that the structure that you're trying to deserialize contains multiple number values (most likely int
). I'm not sure if the JavaScriptSerializer
is able to deserialize numbers into string fields automatically, but you should try to match your CLR type as close to the actual data as possible anyway.
I've seen this error while trying to access a column value after processing the resultset.
if (rs != null) {
while (rs.next()) {
count = rs.getInt(1);
}
count = rs.getInt(1); //this will throw Exhausted resultset
}
Hope this will help you :)
Use nargs='?'
(or nargs='*'
if you need more than one dir)
parser.add_argument('dir', nargs='?', default=os.getcwd())
extended example:
>>> import os, argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-v', action='store_true')
_StoreTrueAction(option_strings=['-v'], dest='v', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('dir', nargs='?', default=os.getcwd())
_StoreAction(option_strings=[], dest='dir', nargs='?', const=None, default='/home/vinay', type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('somedir -v'.split())
Namespace(dir='somedir', v=True)
>>> parser.parse_args('-v'.split())
Namespace(dir='/home/vinay', v=True)
>>> parser.parse_args(''.split())
Namespace(dir='/home/vinay', v=False)
>>> parser.parse_args(['somedir'])
Namespace(dir='somedir', v=False)
>>> parser.parse_args('somedir -h -v'.split())
usage: [-h] [-v] [dir]
positional arguments:
dir
optional arguments:
-h, --help show this help message and exit
-v
For us we used a solution like this:
this.http.get(this.urls.order + '&list', {
headers: {
'Cache-Control': 'no-cache',
}
}).subscribe((response) => { ...
Reference here
You can launch apps using open
:
open -a APP_YOU_WANT
This should open the application that you want.
A great way is to use set_exception_handler
.
Warning!!! with PHP 7, you might get a white screen of death for fatal errors. For example, if you call a method on a non-object you would normally get Fatal error: Call to a member function your_method() on null
and you would expect to see this if error reporting is on.
The above error will NOT be caught with catch(Exception $e)
.
The above error will NOT trigger any custom error handler set by set_error_handler
.
You must use catch(Error $e){ }
to catch errors in PHP7. .
This could help:
class ErrorHandler{
public static function excep_handler($e)
{
print_r($e);
}
}
set_exception_handler(array('ErrorHandler','excep_handler'));
These are really two questions.
The first one is answered here: Calling a Sub in VBA
To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.
If this div is a function I suggest use cursor:pointer in your style like style="cursor:pointer" and can use onclick function.
like this
<div onclick="myfunction()" style="cursor:pointer"></div>
Having my tslint
rules configuration here always replacing the line Object["values"](myObject)
with Object.values(myObject)
.
Two options if you have same issue:
(Object as any).values(myObject)
or
/*tslint:disable:no-string-literal*/
`Object["values"](myObject)`
Just in case you are like me and the Id Field of the User Entity is an Int or something else other than a string,
using Microsoft.AspNet.Identity;
int userId = User.Identity.GetUserId<int>();
will do the trick
I tried this:
"""
Transcript - direct print output to a file, in addition to terminal.
Usage:
import transcript
transcript.start('logfile.log')
print("inside file")
transcript.stop()
print("outside file")
"""
import sys
class Transcript(object):
def __init__(self, filename):
self.terminal = sys.stdout, sys.stderr
self.logfile = open(filename, "a")
def write(self, message):
self.terminal.write(message)
self.logfile.write(message)
def flush(self):
# this flush method is needed for python 3 compatibility.
# this handles the flush command by doing nothing.
# you might want to specify some extra behavior here.
pass
def start(filename):
"""Start transcript, appending print output to given filename"""
sys.stdout = Transcript(filename)
def stop():
"""Stop transcript and return print functionality to normal"""
sys.stdout.logfile.close()
sys.stdout = sys.stdout.terminal
sys.stderr = sys.stderr.terminal
This is very confusing for beginners. The basic difference is map
emits one item for each entry in the list and flatMap
is basically a map
+ flatten
operation. To be more clear, use flatMap when you require more than one value, eg when you are expecting a loop to return arrays, flatMap will be really helpful in this case.
I have written a blog about this, you can check it out here.
Going down your list:
Utf32String
class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)There's more on my Unicode page and tips for debugging Unicode problems.
The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.
When there is more than one input file, the more
command concatenates them and also includes each filename as a header.
To concatenate to a file:
more *.txt > out.txt
To concatenate to the terminal:
more *.txt | cat
Example output:
::::::::::::::
file1.txt
::::::::::::::
This is
my first file.
::::::::::::::
file2.txt
::::::::::::::
And this is my
second file.
In the beautifulsoup source this line allows divs to be nested within divs; so your concern in lukas' comment wouldn't be valid.
NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del']
What I think you need to do is to specify the attrs you want such as
source.find('div', attrs={'id':'articlebody'})
Just encode html using Base64 algorithm before adding html to the JSON and decode html using Base64 when you read.
byte[] utf8 = htmlMessage.getBytes("UTF8");
htmlMessage= new String(new Base64().encode(utf8));
byte[] dec = new Base64().decode(htmlMessage.getBytes());
htmlMessage = new String(dec , "UTF8");
I see 2 possible problems:
Problem 1
Solution: assign a callback function to the objects "onreadystatechange" -event and handle the data in that function
xmlhttp.onreadystatechange = callbackFunctionName;
Once the state has reached DONE (4), the response content is ready to be read.
Problem 2
Solution: Either use a try-catch for creating the correct object for correct browser ( ActiveXObject in IE) or use a framework, for example jQuery ajax-method
Note: if you decide to use jQuery ajax-method, you assign the callback-function with jqXHR.done()
No, you have to use the underscore, but I believe that VB.NET 10 will allow multiple lines w/o the underscore, only requiring if it can't figure out where the end should be.
The behaviour comes from the fact that in Python prior to version 3 bytes
was just an alias for str
. In Python3.x bytes
is an immutable version of bytearray
- completely new type, not backwards compatible.
The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.
The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.
Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.
$date = new DateTime(date("Y-m-d"));
$date->modify('+7 day');
$tomorrowDATE = $date->format('Y-m-d');
None of the above solutions were suitable for my scenario, handling .Navigated and .FileDownload events seemed like a good fit but accessing the WebBrowser.Document property threw an UnauthorizedAccessException which is caused by cross frame scripting security (our web content contains frames - all on the same domain/address but frames have their own security holes that are being blocked).
The solution that worked was to override IOleCommandTarget and to catch the script error commands at that level. Here's the WebBrowser sub-class to achieve this:
/// <summary>
/// Subclassed WebBrowser that suppresses error pop-ups.
///
/// Notes.
/// ScriptErrorsSuppressed property is not used because this actually suppresses *all* pop-ups.
///
/// More info at:
/// http://stackoverflow.com/questions/2476360/disable-javascript-error-in-webbrowser-control
/// </summary>
public class WebBrowserEx : WebBrowser
{
#region Constructor
/// <summary>
/// Default constructor.
/// Initialise browser control and attach customer event handlers.
/// </summary>
public WebBrowserEx()
{
this.ScriptErrorsSuppressed = false;
}
#endregion
#region Overrides
/// <summary>
/// Override to allow custom script error handling.
/// </summary>
/// <returns></returns>
protected override WebBrowserSiteBase CreateWebBrowserSiteBase()
{
return new WebBrowserSiteEx(this);
}
#endregion
#region Inner Class [WebBrowserSiteEx]
/// <summary>
/// Sub-class to allow custom script error handling.
/// </summary>
protected class WebBrowserSiteEx : WebBrowserSite, NativeMethods.IOleCommandTarget
{
/// <summary>
/// Default constructor.
/// </summary>
public WebBrowserSiteEx(WebBrowserEx webBrowser) : base (webBrowser)
{
}
/// <summary>Queries the object for the status of one or more commands generated by user interface events.</summary>
/// <param name="pguidCmdGroup">The GUID of the command group.</param>
/// <param name="cCmds">The number of commands in <paramref name="prgCmds" />.</param>
/// <param name="prgCmds">An array of OLECMD structures that indicate the commands for which the caller needs status information. This method fills the <paramref name="cmdf" /> member of each structure with values taken from the OLECMDF enumeration.</param>
/// <param name="pCmdText">An OLECMDTEXT structure in which to return name and/or status information of a single command. This parameter can be null to indicate that the caller does not need this information.</param>
/// <returns>This method returns S_OK on success. Other possible return values include the following.
/// E_FAIL The operation failed.
/// E_UNEXPECTED An unexpected error has occurred.
/// E_POINTER The <paramref name="prgCmds" /> argument is null.
/// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.</returns>
public int QueryStatus(ref Guid pguidCmdGroup, int cCmds, NativeMethods.OLECMD prgCmds, IntPtr pCmdText)
{
if((int)NativeMethods.OLECMDID.OLECMDID_SHOWSCRIPTERROR == prgCmds.cmdID)
{ // Do nothing (suppress script errors)
return NativeMethods.S_OK;
}
// Indicate that command is unknown. The command will then be handled by another IOleCommandTarget.
return NativeMethods.OLECMDERR_E_UNKNOWNGROUP;
}
/// <summary>Executes the specified command.</summary>
/// <param name="pguidCmdGroup">The GUID of the command group.</param>
/// <param name="nCmdID">The command ID.</param>
/// <param name="nCmdexecopt">Specifies how the object should execute the command. Possible values are taken from the <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDEXECOPT" /> and <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDID_WINDOWSTATE_FLAG" /> enumerations.</param>
/// <param name="pvaIn">The input arguments of the command.</param>
/// <param name="pvaOut">The output arguments of the command.</param>
/// <returns>This method returns S_OK on success. Other possible return values include
/// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.
/// OLECMDERR_E_NOTSUPPORTED The <paramref name="nCmdID" /> parameter is not a valid command in the group identified by <paramref name="pguidCmdGroup" />.
/// OLECMDERR_E_DISABLED The command identified by <paramref name="nCmdID" /> is currently disabled and cannot be executed.
/// OLECMDERR_E_NOHELP The caller has asked for help on the command identified by <paramref name="nCmdID" />, but no help is available.
/// OLECMDERR_E_CANCELED The user canceled the execution of the command.</returns>
public int Exec(ref Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, object[] pvaIn, int pvaOut)
{
if((int)NativeMethods.OLECMDID.OLECMDID_SHOWSCRIPTERROR == nCmdID)
{ // Do nothing (suppress script errors)
return NativeMethods.S_OK;
}
// Indicate that command is unknown. The command will then be handled by another IOleCommandTarget.
return NativeMethods.OLECMDERR_E_UNKNOWNGROUP;
}
}
#endregion
}
~
/// <summary>
/// Native (unmanaged) methods, required for custom command handling for the WebBrowser control.
/// </summary>
public static class NativeMethods
{
/// From docobj.h
public const int OLECMDERR_E_UNKNOWNGROUP = -2147221244;
/// <summary>
/// From Microsoft.VisualStudio.OLE.Interop (Visual Studio 2010 SDK).
/// </summary>
public enum OLECMDID
{
/// <summary />
OLECMDID_OPEN = 1,
/// <summary />
OLECMDID_NEW,
/// <summary />
OLECMDID_SAVE,
/// <summary />
OLECMDID_SAVEAS,
/// <summary />
OLECMDID_SAVECOPYAS,
/// <summary />
OLECMDID_PRINT,
/// <summary />
OLECMDID_PRINTPREVIEW,
/// <summary />
OLECMDID_PAGESETUP,
/// <summary />
OLECMDID_SPELL,
/// <summary />
OLECMDID_PROPERTIES,
/// <summary />
OLECMDID_CUT,
/// <summary />
OLECMDID_COPY,
/// <summary />
OLECMDID_PASTE,
/// <summary />
OLECMDID_PASTESPECIAL,
/// <summary />
OLECMDID_UNDO,
/// <summary />
OLECMDID_REDO,
/// <summary />
OLECMDID_SELECTALL,
/// <summary />
OLECMDID_CLEARSELECTION,
/// <summary />
OLECMDID_ZOOM,
/// <summary />
OLECMDID_GETZOOMRANGE,
/// <summary />
OLECMDID_UPDATECOMMANDS,
/// <summary />
OLECMDID_REFRESH,
/// <summary />
OLECMDID_STOP,
/// <summary />
OLECMDID_HIDETOOLBARS,
/// <summary />
OLECMDID_SETPROGRESSMAX,
/// <summary />
OLECMDID_SETPROGRESSPOS,
/// <summary />
OLECMDID_SETPROGRESSTEXT,
/// <summary />
OLECMDID_SETTITLE,
/// <summary />
OLECMDID_SETDOWNLOADSTATE,
/// <summary />
OLECMDID_STOPDOWNLOAD,
/// <summary />
OLECMDID_ONTOOLBARACTIVATED,
/// <summary />
OLECMDID_FIND,
/// <summary />
OLECMDID_DELETE,
/// <summary />
OLECMDID_HTTPEQUIV,
/// <summary />
OLECMDID_HTTPEQUIV_DONE,
/// <summary />
OLECMDID_ENABLE_INTERACTION,
/// <summary />
OLECMDID_ONUNLOAD,
/// <summary />
OLECMDID_PROPERTYBAG2,
/// <summary />
OLECMDID_PREREFRESH,
/// <summary />
OLECMDID_SHOWSCRIPTERROR,
/// <summary />
OLECMDID_SHOWMESSAGE,
/// <summary />
OLECMDID_SHOWFIND,
/// <summary />
OLECMDID_SHOWPAGESETUP,
/// <summary />
OLECMDID_SHOWPRINT,
/// <summary />
OLECMDID_CLOSE,
/// <summary />
OLECMDID_ALLOWUILESSSAVEAS,
/// <summary />
OLECMDID_DONTDOWNLOADCSS,
/// <summary />
OLECMDID_UPDATEPAGESTATUS,
/// <summary />
OLECMDID_PRINT2,
/// <summary />
OLECMDID_PRINTPREVIEW2,
/// <summary />
OLECMDID_SETPRINTTEMPLATE,
/// <summary />
OLECMDID_GETPRINTTEMPLATE
}
/// <summary>
/// From Microsoft.VisualStudio.Shell (Visual Studio 2010 SDK).
/// </summary>
public const int S_OK = 0;
/// <summary>
/// OLE command structure.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class OLECMD
{
/// <summary>
/// Command ID.
/// </summary>
[MarshalAs(UnmanagedType.U4)]
public int cmdID;
/// <summary>
/// Flags associated with cmdID.
/// </summary>
[MarshalAs(UnmanagedType.U4)]
public int cmdf;
}
/// <summary>
/// Enables the dispatching of commands between objects and containers.
/// </summary>
[ComVisible(true), Guid("B722BCCB-4E68-101B-A2BC-00AA00404770"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface IOleCommandTarget
{
/// <summary>Queries the object for the status of one or more commands generated by user interface events.</summary>
/// <param name="pguidCmdGroup">The GUID of the command group.</param>
/// <param name="cCmds">The number of commands in <paramref name="prgCmds" />.</param>
/// <param name="prgCmds">An array of <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMD" /> structures that indicate the commands for which the caller needs status information.</param>
/// <param name="pCmdText">An <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT" /> structure in which to return name and/or status information of a single command. This parameter can be null to indicate that the caller does not need this information.</param>
/// <returns>This method returns S_OK on success. Other possible return values include the following.
/// E_FAIL The operation failed.
/// E_UNEXPECTED An unexpected error has occurred.
/// E_POINTER The <paramref name="prgCmds" /> argument is null.
/// OLECMDERR_E_UNKNOWNGROUPThe <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.</returns>
[PreserveSig]
[return: MarshalAs(UnmanagedType.I4)]
int QueryStatus(ref Guid pguidCmdGroup, int cCmds, [In] [Out] NativeMethods.OLECMD prgCmds, [In] [Out] IntPtr pCmdText);
/// <summary>Executes the specified command.</summary>
/// <param name="pguidCmdGroup">The GUID of the command group.</param>
/// <param name="nCmdID">The command ID.</param>
/// <param name="nCmdexecopt">Specifies how the object should execute the command. Possible values are taken from the <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDEXECOPT" /> and <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDID_WINDOWSTATE_FLAG" /> enumerations.</param>
/// <param name="pvaIn">The input arguments of the command.</param>
/// <param name="pvaOut">The output arguments of the command.</param>
/// <returns>This method returns S_OK on success. Other possible return values include
/// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.
/// OLECMDERR_E_NOTSUPPORTED The <paramref name="nCmdID" /> parameter is not a valid command in the group identified by <paramref name="pguidCmdGroup" />.
/// OLECMDERR_E_DISABLED The command identified by <paramref name="nCmdID" /> is currently disabled and cannot be executed.
/// OLECMDERR_E_NOHELP The caller has asked for help on the command identified by <paramref name="nCmdID" />, but no help is available.
/// OLECMDERR_E_CANCELED The user canceled the execution of the command.</returns>
[PreserveSig]
[return: MarshalAs(UnmanagedType.I4)]
int Exec(ref Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, [MarshalAs(UnmanagedType.LPArray)] [In] object[] pvaIn, int pvaOut);
}
}
why not printf '%02d' $num
? See help printf
for this internal bash command.
Find the tag as type="file"
. this the main tag which is supported by selenium. If you are able to build your XPath with same when it is recommended.
As below :-
driver.findElement(By.xpath("//input[@id='files']")).sendKeys("D:"+File.separator+"images"+File.separator+"Lighthouse.jpg"");
Thread.sleep(5000);
driver.findElement(By.xpath("//button[@id='Upload']")).click();
For multiple file upload put all files one by one by sendkeys and then click on upload
driver.findElement(By.xpath("//input[@id='files']")).sendKeys("D:"+File.separator+"images"+File.separator+"Lighthouse.jpg"");
driver.findElement(By.xpath("//input[@id='files']")).sendKeys("D:"+File.separator+"images"+File.separator+"home.jpg");
driver.findElement(By.xpath("//input[@id='files']")).sendKeys("D:"+File.separator+"images"+File.separator+"tsquare.jpg");
Thread.sleep(5000);
driver.findElement(By.xpath("//button[@id='Upload']")).click(); // Upload button
The code you've shown will read 8 bytes. You could use
with open(filename, 'rb') as f:
while 1:
byte_s = f.read(1)
if not byte_s:
break
byte = byte_s[0]
...
> SELECT CONVERT(VARCHAR(30), GETDATE(), 100) as date_n_time
> SELECT CONVERT(VARCHAR(20),convert(time,GETDATE()),100) as req_time
> select convert(varchar(20),GETDATE(),103)+' '+convert(varchar(20),convert(time,getdate()),100)
> Result (1):- Jun 9 2018 11:36AM
> result(2):- 11:35AM
> Result (3):- 06/10/2018 11:22AM
In a POST method, you can put an array. However, in a PUT method, you should use http_build_query
to build the params like this:
curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $postArr ) );
You can define foreign key by:
public class Parent
{
public int Id { get; set; }
public virtual ICollection<Child> Childs { get; set; }
}
public class Child
{
public int Id { get; set; }
// This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.
If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation
Data annotation:
// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }
Fluent API:
modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent)
.WithMany(p => p.Childs)
.HasForeignKey(c => c.ParentId);
Other types of constraints can be enforced by data annotations and model validation.
Edit:
You will get an exception if you don't set ParentId
. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
If you need to change the figure size after you have created it, use the methods
fig = plt.figure()
fig.set_figheight(value_height)
fig.set_figwidth(value_width)
where value_height
and value_width
are in inches. For me this is the most practical way.
You can also get an updated version of the Eclipse's ADT plugin (based on an unreleased 24.2.0 version) that I managed to patch and compile at https://github.com/khaledev/ADT.
I think the easy answer is MvcMailer. It s NuGet package that lets you use your favorite view engine to generate emails. See the NuGet package here and the project documentation
Hope it helps!
The simplest non recursive way is:
for d in */; do
echo "$d"
done
The /
at the end tells, use directories only.
There is no need for
Over time, I have found that extracting text from PDFs in a structured format is tough business. However if you are looking for an easy solution, you might want to consider XPDF tool pdftotext
.
Pseudocode to extract the text would include:
SHELL
VBA statement to extract the text from PDF to a temporary file using XPDFSimplified example below:
Sub ReadIntoExcel(PDFName As String)
'Convert PDF to text
Shell "C:\Utils\pdftotext.exe -layout " & PDFName & " tempfile.txt"
'Read in the text file and write to Excel
Dim TextLine as String
Dim RowNumber as Integer
Dim F1 as Integer
RowNumber = 1
F1 = Freefile()
Open "tempfile.txt" for Input as #F1
While Not EOF(#F1)
Line Input #F1, TextLine
ThisWorkbook.WorkSheets(1).Cells(RowNumber, 1).Value = TextLine
RowNumber = RowNumber + 1
Wend
Close #F1
End Sub
You have to close the stream before closing the connection:
tcpClient.GetStream().Close();
tcpClient.Close();
Closing the client does not close the stream.
After spend almost 2 hour I resolve this Issue by just delete a line from .csproj file.
<PlatformTarget>AnyCPU</PlatformTarget>
For me this location worked: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\DevDiv\vc\Servicing\11.0\RuntimeMinimum\Version
Check what version you have after you installed the package and use that as a condition in your installer. (mine is set to 11.0.50727 after installing VCred).
You should always include all relevant code when asking a question. In this case, the print statement that is the center of your question. The print statement is probably the most crucial piece of information. The second most crucial piece of information is the error, which you also did not include. Next time, include both of those.
print $ids
should be a fairly hard statement to mess up, but it is possible. Possible reasons:
$ids
is undefined. Gives the warning undefined value in print
$ids
is out of scope. With use
strict
, gives fatal warning Global
variable $ids needs explicit package
name
, and otherwise the undefined
warning from above.print $ids $nIds
,
in which case perl thinks that $ids
is supposed to be a filehandle, and
you get an error such as print to
unopened filehandle
.Explanations
1: Should not happen. It might happen if you do something like this (assuming you are not using strict
):
my $var;
while (<>) {
$Var .= $_;
}
print $var;
Gives the warning for undefined value, because $Var
and $var
are two different variables.
2: Might happen, if you do something like this:
if ($something) {
my $var = "something happened!";
}
print $var;
my
declares the variable inside the current block. Outside the block, it is out of scope.
3: Simple enough, common mistake, easily fixed. Easier to spot with use warnings
.
4: Also a common mistake. There are a number of ways to correctly print two variables in the same print
statement:
print "$var1 $var2"; # concatenation inside a double quoted string
print $var1 . $var2; # concatenation
print $var1, $var2; # supplying print with a list of args
Lastly, some perl magic tips for you:
use strict;
use warnings;
# open with explicit direction '<', check the return value
# to make sure open succeeded. Using a lexical filehandle.
open my $fh, '<', 'file.txt' or die $!;
# read the whole file into an array and
# chomp all the lines at once
chomp(my @file = <$fh>);
close $fh;
my $ids = join(' ', @file);
my $nIds = scalar @file;
print "Number of lines: $nIds\n";
print "Text:\n$ids\n";
Reading the whole file into an array is suitable for small files only, otherwise it uses a lot of memory. Usually, line-by-line is preferred.
Variations:
print "@file"
is equivalent to
$ids = join(' ',@file); print $ids;
$#file
will return the last index
in @file
. Since arrays usually start at 0,
$#file + 1
is equivalent to scalar @file
. You can also do:
my $ids;
do {
local $/;
$ids = <$fh>;
}
By temporarily "turning off" $/
, the input record separator, i.e. newline, you will make <$fh>
return the entire file. What <$fh>
really does is read until it finds $/
, then return that string. Note that this will preserve the newlines in $ids
.
Line-by-line solution:
open my $fh, '<', 'file.txt' or die $!; # btw, $! contains the most recent error
my $ids;
while (<$fh>) {
chomp;
$ids .= "$_ "; # concatenate with string
}
my $nIds = $.; # $. is Current line number for the last filehandle accessed.
I know this is an old thread, but it exactly matches what recently happened to me and I thought I'd document it here. The setup (in Docker) is as follows:
The symptom was a "502 Gateway Timeout" on the application login prompt. Examination of logs found:
POST
to /login
... and so .../login
request, and eventually reported a timeout.499
response, which of course means "the host died."/login
request did not appear at all(!) in the FPM server's logs!It turned out that the problem was a failure to connect to the database to verify the login. But how to figure that out turned out to be pure guesswork.
The complete absence of application traceback logs ... or even a record that the request had been received by FPM ... was a complete (and, devastating ...) surprise to me. Yes, the application is supposed to log failures, but in this case it looks like the FPM worker process died with a runtime error, leading to the 499
response from nginx. Now, this obviously is a problem in our application ... somewhere. But I wanted to record the particulars of what happened for the benefit of the next folks who face something like this.
Try the following:
JS file
this.options = {
languages: [{language: 'English', lg:'en'}, {language:'German', lg:'de'}]
};
console.log(signinDetails.language);
HTML file
<div class="form-group col-sm-6">
<label>Preferred language</label>
<select class="form-control" name="right" ng-model="signinDetails.language" ng-init="signinDetails.language = options.languages[0]" ng-options="l as l.language for l in options.languages"><option></option>
</select>
</div>
Yeah, it is quite vague.
You should use it whenever for readers of the documentation of your method it may be useful to also look at some other method. If the documentation of your methodA says "Works like methodB but ...", then you surely should put a link.
An alternative to @see
would be the inline {@link ...}
tag:
/**
* ...
* Works like {@link #methodB}, but ...
*/
When the fact that methodA calls methodB is an implementation detail and there is no real relation from the outside, you don't need a link here.
in iterm2
fn + leftArraw or fn + rightArrow
this worked for me
You can simply cast strings to DateTime:
[DateTime]"2020-7-16"
or
[DateTime]"Jul-16"
or
$myDate = [DateTime]"Jul-16";
And you can format the resulting DateTime variable by doing something like this:
'{0:yyyy-MM-dd}' -f [DateTime]'Jul-16'
or
([DateTime]"Jul-16").ToString('yyyy-MM-dd')
or
$myDate = [DateTime]"Jul-16";
'{0:yyyy-MM-dd}' -f $myDate
There are three parts:
You need to add a shebang at the top of your script so the shell knows which interpreter to use when parsing your script. It is generally:
#!path/to/interpretter
To find the path to your python interpretter on your machine you can run the command:
which python
This will search your PATH to find the location of your python executable. It should come back with a absolute path which you can then use to form your shebang. Make sure your shebang is at the top of your python script:
#!/usr/bin/python
You have to mark your script with run permissions so that your shell knows you want to actually execute it when you try to use it as a command. To do this you can run this command:
chmod +x myscript.py
The PATH environment variable is an ordered list of directories that your shell will search when looking for a command you are trying to run. So if you want your python script to be a command you can run from anywhere then it needs to be in your PATH. You can see the contents of your path running the command:
echo $PATH
This will print out a long line of text, where each directory is seperated by a semicolon. Whenever you are wondering where the actual location of an executable that you are running from your PATH, you can find it by running the command:
which <commandname>
Now you have two options: Add your script to a directory already in your PATH, or add a new directory to your PATH. I usually create a directory in my user home directory and then add it the PATH. To add things to your path you can run the command:
export PATH=/my/directory/with/pythonscript:$PATH
Now you should be able to run your python script as a command anywhere. BUT! if you close the shell window and open a new one, the new one won't remember the change you just made to your PATH. So if you want this change to be saved then you need to add that command at the bottom of your .bashrc or .bash_profile
Arrays in C# are immutable, e.g. string[]
, int[]
. That means you can't resize them. You need to create a brand new array.
Here is the code for Array.Resize:
public static void Resize<T>(ref T[] array, int newSize)
{
if (newSize < 0)
{
throw new ArgumentOutOfRangeException("newSize", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
T[] sourceArray = array;
if (sourceArray == null)
{
array = new T[newSize];
}
else if (sourceArray.Length != newSize)
{
T[] destinationArray = new T[newSize];
Copy(sourceArray, 0, destinationArray, 0, (sourceArray.Length > newSize) ? newSize : sourceArray.Length);
array = destinationArray;
}
}
As you can see it creates a new array with the new size, copies the content of the source array and sets the reference to the new array. The hint for this is the ref keyword for the first parameter.
There are lists that can dynamically allocate new slots for new items. This is e.g. List<T>. These contain immutable arrays and resize them when needed (List<T> is not a linked list implementation!). ArrayList is the same thing without Generics (with Object array).
LinkedList<T> is a real linked list implementation. Unfortunately you can add just LinkListNode<T> elements to the list, so you must wrap your own list elements into this node type. I think its use is uncommon.
// sample code for addition using JOptionPane
import javax.swing.JOptionPane;
public class Addition {
public static void main(String[] args) {
String firstNumber = JOptionPane.showInputDialog("Input <First Integer>");
String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>");
int num1 = Integer.parseInt(firstNumber);
int num2 = Integer.parseInt(secondNumber);
int sum = num1 + num2;
JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sum of two Integers", JOptionPane.PLAIN_MESSAGE);
}
}
The preferred way is to use a JavaScript library such as jQuery and set your data option as an object, then let jQuery do the encoding, like this:
$.ajax({
type: "POST",
url: "/link.json",
data: { value: poststr },
error: function(){ alert('some error occured'); }
});
If you can't use jQuery (which is pretty much the standard these days), use encodeURIComponent.
If the process runs for at least a couple seconds, then you can use the following bash script, which will run the given command line then print to stderr the peak RSS (substitute for rss
any other attribute you're interested in). It's somewhat lightweight, and it works for me with the ps
included in Ubuntu 9.04 (which I can't say for time
).
#!/usr/bin/env bash
"$@" & # Run the given command line in the background.
pid=$! peak=0
while true; do
sleep 1
sample="$(ps -o rss= $pid 2> /dev/null)" || break
let peak='sample > peak ? sample : peak'
done
echo "Peak: $peak" 1>&2
Slightly more compact:
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)
Note:
sort
has been deprecated, replaced by sort_index
for this scenarioinplace
as it is usually harder to read and prevents chaining. See explanation in answer here:
Pandas: peculiar performance drop for inplace rename after dropnaError in file(file, "rt") :
I just faced the same error and resolved by removing spacing in address using paste0 instead of paste
filepath=paste0(directory,"/",filename[1],sep="")
Using new ES6 Object.entries()
, it makes for a fun little nested map
/join
:
const encodeGetParams = p => _x000D_
Object.entries(p).map(kv => kv.map(encodeURIComponent).join("=")).join("&");_x000D_
_x000D_
const params = {_x000D_
user: "María Rodríguez",_x000D_
awesome: true,_x000D_
awesomeness: 64,_x000D_
"ZOMG+&=*(": "*^%*GMOZ"_x000D_
};_x000D_
_x000D_
console.log("https://example.com/endpoint?" + encodeGetParams(params))
_x000D_
The second way is a tad more efficient, but a much better way is to execute them in batches:
public void executeBatch(List<Entity> entities) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL);
) {
for (Entity entity : entities) {
statement.setObject(1, entity.getSomeProperty());
// ...
statement.addBatch();
}
statement.executeBatch();
}
}
You're however dependent on the JDBC driver implementation how many batches you could execute at once. You may for example want to execute them every 1000 batches:
public void executeBatch(List<Entity> entities) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL);
) {
int i = 0;
for (Entity entity : entities) {
statement.setObject(1, entity.getSomeProperty());
// ...
statement.addBatch();
i++;
if (i % 1000 == 0 || i == entities.size()) {
statement.executeBatch(); // Execute every 1000 items.
}
}
}
}
As to the multithreaded environments, you don't need to worry about this if you acquire and close the connection and the statement in the shortest possible scope inside the same method block according the normal JDBC idiom using try-with-resources statement as shown in above snippets.
If those batches are transactional, then you'd like to turn off autocommit of the connection and only commit the transaction when all batches are finished. Otherwise it may result in a dirty database when the first bunch of batches succeeded and the later not.
public void executeBatch(List<Entity> entities) throws SQLException {
try (Connection connection = dataSource.getConnection()) {
connection.setAutoCommit(false);
try (PreparedStatement statement = connection.prepareStatement(SQL)) {
// ...
try {
connection.commit();
} catch (SQLException e) {
connection.rollback();
throw e;
}
}
}
}
Double underscore. That mangles the name. The variable can still be accessed, but it's generally a bad idea to do so.
Use single underscores for semi-private (tells python developers "only change this if you absolutely must") and doubles for fully private.
Although this question specifically mentions jQuery-UI autosuggest feature, the question title is more general: does bootstrap 3 work with jQuery UI? I was having trouble with the jQUI datepicker (pop-up calendar) feature. I solved the datepicker problem and hope the solution will help with other jQUI/BS issues.
I had a difficult time today getting the latest jQueryUI (ver 1.12.1) datepicker to work with bootstrap 3.3.7. What was happening is that the calendar would display but it would not close.
Turned out to be a version problem with jQUI and BS. I was using the latest version of Bootstrap, and found that I had to downgrade to these versions of jQUI and jQuery:
jQueryUI - 1.9.2 (tested - works)
jQuery - 1.9.1 or 2.1.4 (tested - both work. Other vers may work, but these work.)
Bootstrap 3.3.7 (tested - works)
Because I wanted to use a custom theme, I also built a custom download of jQUI (removed a few things like all the interactions, dialog, progressbar and a few effects I don't use) -- and made sure to select "Cupertino" at the bottom as my theme.
I installed them thus:
<head>
...etc...
<link rel="stylesheet" href="css/font-awesome.min.css">
<link rel="stylesheet" href="css/cupertino/jquery-ui-1.9.2.custom.min.css">
<link rel="stylesheet" href="css/bootstrap-3.3.7.min.css">
<!-- <script src="js/jquery-1.9.1.min.js"></script> -->
<script src="js/jquery-2.1.4.min.js"></script>
<script src="js/jquery-ui-1.9.2.custom.min.js"></script>
<script src="js/bootstrap-3.3.7.min.js"></script>
...etc...
</head>
For those interested, the CSS folder looks like this:
[css]
- bootstrap-3.3.7.min.css
- font-awesome.min.css
- style.css
- [cupertino]
- jquery-ui-1.9.2.custom.min.css
[images]
- ui-bg_diagonals-thick_90_eeeeee_40x40.png
- ui-bg_glass_100_e4f1fb_1x400.png
- ui-bg_glass_50_3baae3_1x400.png
- ui-bg_glass_80_d7ebf9_1x400.png
- ui-bg_highlight-hard_100_f2f5f7_1x100.png
- etc (8 more files that were in the downloaded jQUI zip file)
Comparable is used to compare instances of your class. We can compare instances from many ways that is why we need to implement a method compareTo
in order to know how (attributes) we want to compare instances.
Dog
class:package test;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Dog d1 = new Dog("brutus");
Dog d2 = new Dog("medor");
Dog d3 = new Dog("ara");
Dog[] dogs = new Dog[3];
dogs[0] = d1;
dogs[1] = d2;
dogs[2] = d3;
for (int i = 0; i < 3; i++) {
System.out.println(dogs[i].getName());
}
/**
* Output:
* brutus
* medor
* ara
*/
Arrays.sort(dogs, Dog.NameComparator);
for (int i = 0; i < 3; i++) {
System.out.println(dogs[i].getName());
}
/**
* Output:
* ara
* medor
* brutus
*/
}
}
Main
class:package test;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Dog d1 = new Dog("brutus");
Dog d2 = new Dog("medor");
Dog d3 = new Dog("ara");
Dog[] dogs = new Dog[3];
dogs[0] = d1;
dogs[1] = d2;
dogs[2] = d3;
for (int i = 0; i < 3; i++) {
System.out.println(dogs[i].getName());
}
/**
* Output:
* brutus
* medor
* ara
*/
Arrays.sort(dogs, Dog.NameComparator);
for (int i = 0; i < 3; i++) {
System.out.println(dogs[i].getName());
}
/**
* Output:
* ara
* medor
* brutus
*/
}
}
Here is a good example how to use comparable in Java:
http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html?page=2
x or "default"
works best — i can even use a function call inline, without executing it twice or using extra variable:
self.lineEdit_path.setText( self.getDir(basepath) or basepath )
I use it when opening Qt's dialog.getExistingDirectory()
and canceling, which returns empty string.
No. You have to make your own like this:
boolean tryParseInt(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
...and you can use it like this:
if (tryParseInt(input)) {
Integer.parseInt(input); // We now know that it's safe to parse
}
EDIT (Based on the comment by @Erk)
Something like follows should be better
public int tryParse(String value, int defaultVal) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
return defaultVal;
}
}
When you overload this with a single string parameter method, it would be even better, which will enable using with the default value being optional.
public int tryParse(String value) {
return tryParse(value, 0)
}
There is an alternative way to change the key of an array element when working with a full array - without changing the order of the array. It's simply to copy the array into a new array.
For instance, I was working with a mixed, multi-dimensional array that contained indexed and associative keys - and I wanted to replace the integer keys with their values, without breaking the order.
I did so by switching key/value for all numeric array entries - here: ['0'=>'foo']. Note that the order is intact.
<?php
$arr = [
'foo',
'bar'=>'alfa',
'baz'=>['a'=>'hello', 'b'=>'world'],
];
foreach($arr as $k=>$v) {
$kk = is_numeric($k) ? $v : $k;
$vv = is_numeric($k) ? null : $v;
$arr2[$kk] = $vv;
}
print_r($arr2);
Output:
Array (
[foo] =>
[bar] => alfa
[baz] => Array (
[a] => hello
[b] => world
)
)
Another way is to use the powers of /usr/bin/env
:
docker run ubuntu env DEBUG=1 path/to/script.sh
Very simply, Maven wants to own the world. It wants to define projects, how they're laid out on the file system, where the jars go in its cutesy local cache, how to fetch things, dependency graphs, build plugins, ide plugins, etc etc etc.
Some people love that kind of thing, admire it. For me, it's all about the quality, I could care less about your boooooring theories. Just execute, do it flawlessly, and then preferably fade into the background until I decide to mess with you again.
My message to Sonatype and Maven adherents/apologists is that you do not yet ooze with quality. pom.xml format is too verbose, academic, and tedious - fix it. Complex, multiproject builds are maddening to setup with Maven - why so hard? Fine tuning when to fetch and when not to fetch underspecified jars would be an interesting thing - until we get that, the maven strategery of fetching whenever we can/think we want to is maddening. SNAPSHOT is always all in caps because it's screaming/laughing at me and driving me mad? The minutae and goofy/unique ways cruddy open source maven plugins plug into poms is maddening. Classpath issues with no good way to resolve them? Oh yeah, and the legacy apache commons-* groupId's polluting my repository root are maddening in a "the cheese triangles don't go that way!!"-rage sort of way. m2eclipse is pure concentrated madness, die monster die, kill it with fire it's the only way we can be sure.
Maven embarrassed me once to a client - it's inexcusable that a tool so got in the way of my being productive! I want my tools (and their makers) to act like the humble servants they are. When I ask Maven who the king is, I expect the answer to be "DAVE" followed by pleasantries and much bowing and lowing! :)
Inertia is the real story with Maven. If you want to play with open source java, you're pretty much going to be pulling from a Maven repository. So, if you want to play nice there, you had better be able to get your dependencies the Maven way and learn to read poms... Thank goodness for Ivy and IvyDE, that I can set my maven dependencies in both Ant and Eclipse and not be stuck with the Maven toolchain.
Maven repository server software I've used like Nexus and Artifactory are neat, futuristic tools. They are glittering jewels compared to the rest of the maven ecosystem.
My Maven experience feels like how Eclipse felt back in the day. Eclipse wanted to own the world too with their dumb ideas, and it took a long time for the platform to mature, years and years, before I really allowed Eclipse to own my world. Perhaps in years and years Maven can reach that level of quality? At this point, I say "never again shall mine eyes witness the horrors", but I was saying that about Eclipse 1.0 too when it came out. :)
If you have jQuery UI this little function allows basic tabbing
handlePseudoTab(direction) {
if (!document.hasFocus() || !document.activeElement) {
return;
}
const focusList = $(":focusable", $yourHTMLElement);
const i = focusList.index(document.activeElement);
if (i < 0) {
focusList[0].focus(); // nothing is focussed so go to list item 0
} else if (direction === 'next' && i + 1 < focusList.length) {
focusList[i + 1].focus(); // advance one
} else if (direction === 'prev' && i - 1 > -1) {
focusList[i - 1].focus(); // go back one
}
}
T-SQL doesn't support arrays that I'm aware of.
What's your table structure? You could probably design a query that does this instead:
select
month,
sum(sales)
from sales_table
group by month
order by month
I use
\pagenumbering{roman}
for everything in the frontmatter and then switch over to
\pagenumbering{arabic}
for the actual content. With pdftex, the page numbers come out right in the PDF file.
This is described here: https://yarnpkg.com/en/docs/cli/add#toc-adding-dependencies
For example:
yarn add https://github.com/novnc/noVNC.git#0613d18
On the other hand, it:
At the cost of:
So really it depends on what you're doing, but I tend to prefer a DataReader until I need something that's only supported by a dataset. SqlDataReader is perfect for the common data access case of binding to a read-only grid.
For more info, see the official Microsoft documentation.
The Cause
Lion comes with a version of postgres already installed and uses those binaries by default. In general you can get around this by using the full path to the homebrew postgres binaries but there may be still issues with other programs.
The Solution
curl http://nextmarvel.net/blog/downloads/fixBrewLionPostgres.sh | sh
Via
http://nextmarvel.net/blog/2011/09/brew-install-postgresql-on-os-x-lion/
You should be able to do this just fine:
$.ajax({
url: 'controller/myaction',
data: JSON.stringify({
myKey: myArray
}),
success: function(data) { /* Whatever */ }
});
Then your action method would be like so:
public ActionResult(List<int> myKey)
{
// Do Stuff
}
For you, it looks like you just need to stringify your values. The JSONValueProvider in MVC will convert that back into an IEnumerable for you.
You can use $.each() to iterate over the array and locate the object you're interested in:
$.each(projects, function() {
if (this.value == "jquery-ui") {
this.desc = "Your new description";
}
});