For those who are wondering about the alignment issue inside bracket, JetBrains has this as in their issue tracking.
Here is the answer:
A few comments:
analog=True
in the call to butter
, and you should use scipy.signal.freqz
(not freqs
) to generate the frequency response.Here's my modified version of your script, followed by the plot that it generates.
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
# Filter requirements.
order = 6
fs = 30.0 # sample rate, Hz
cutoff = 3.667 # desired cutoff frequency of the filter, Hz
# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)
# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()
# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0 # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data. We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)
# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()
plt.subplots_adjust(hspace=0.35)
plt.show()
Not to beat a dead horse, but I was searching for a solution, ended up here, and was myself not satisfied with the options, not least for some reason I wasn't able to get the provided solutions here to work well for me. (Likely due to errors on my part...) But I've been playing with flexbox and here's something I did get to work for myself.
Some of the settings are hard-wired, but only for purposes of demonstration. I'd think this solution ought to work in just about any modern browser. Just remove/adjust the fixed settings for the .flex-parent class, adjust colors/text/stuff and (I hope) you'll be as happy as I am with this approach.
HTML:
.flex-parent {_x000D_
display: flex;_x000D_
width: 300px;_x000D_
height: 20px;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
.flex-child-edge {_x000D_
flex-grow: 2;_x000D_
height: 1px;_x000D_
background-color: #000;_x000D_
border: 1px #000 solid;_x000D_
}_x000D_
.flex-child-text {_x000D_
flex-basis: auto;_x000D_
flex-grow: 0;_x000D_
margin: 0px 5px 0px 5px;_x000D_
text-align: center;_x000D_
}
_x000D_
<div class="flex-parent">_x000D_
<div class="flex-child-edge"></div>_x000D_
<div class="flex-child-text">I found this simpler!</div>_x000D_
<div class="flex-child-edge"></div>_x000D_
</div>
_x000D_
I also saved my solution here: https://jsfiddle.net/Wellspring/wupj1y1a/1/
The query component is indicated by the first ?
in a URI. "Query string" might be a synonym (this term is not used in the URI standard).
Some examples for HTTP URIs with query components:
http://example.com/foo?bar
http://example.com/foo/foo/foo?bar/bar/bar
http://example.com/?bar
http://example.com/?@bar._=???/1:
http://example.com/?bar1=a&bar2=b
(list of allowed characters in the query component)
The "format" of the query component is up to the URI authors. A common convention (but nothing more than a convention, as far as the URI standard is concerned¹) is to use the query component for key-value pairs, aka. parameters, like in the last example above: bar1=a&bar2=b
.
Such parameters could also appear in the other URI components, i.e., the path² and the fragment. As far as the URI standard is concerned, it’s up to you which component and which format to use.
Example URI with parameters in the path, the query, and the fragment:
http://example.com/foo;key1=value1?key2=value2#key3=value3
¹ The URI standard says about the query component:
[…] query components are often used to carry identifying information in the form of "key=value" pairs […]
² The URI standard says about the path component:
[…] the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes.
A = zeros(20, 10, 3); %# Creates a 20x10x3 matrix
B = zeros(4,4);
C = zeros(size(B,1), size(B,2), 4); %# New matrix with B's size, and 3rd dimension of size 4
C(:,:,1) = B; %# Copy the content of B into C's first set of values
zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0
for a 3D matrix. To confirm the size of your matrices you can run: size(A)
which gives 20 10 3
.
There is no explicit bound on the number of dimensions a matrix may have.
If you would like to redirect the user after the alert, do this:
echo ("<script LANGUAGE='JavaScript'>
window.alert('Succesfully Updated');
window.location.href='<URL to redirect to>';
</script>");
An example taken form here:
When an Employee
entity object is removed, the remove operation is cascaded to the referenced Address
entity object. In this regard, orphanRemoval=true
and cascade=CascadeType.REMOVE
are identical, and if orphanRemoval=true
is specified, CascadeType.REMOVE
is redundant.
The difference between the two settings is in the response to disconnecting a relationship. For example, such as when setting the address field to null
or to another Address
object.
If orphanRemoval=true
is specified the disconnected Address
instance
is automatically removed. This is useful for cleaning up dependent
objects (e.g. Address
) that should not exist without a reference from
an owner object (e.g. Employee
).
If only cascade=CascadeType.REMOVE
is specified, no automatic action
is taken since disconnecting a relationship is not a remove
operation.
To avoid dangling references as a result of orphan removal, this feature should only be enabled for fields that hold private non shared dependent objects.
I hope this makes it more clear.
If the command contains some special characters such as pipes and quotes, the command needs to be padded with quotes. For example, to repeat ls -l | grep "txt"
, the watch command should be:
watch -n 5 'ls -l | grep "txt"'
I typically see performance increases when filtering on the join. Especially if you can join on indexed columns for both tables. You should be able to cut down on logical reads with most queries doing this too, which is, in a high volume environment, a much better performance indicator than execution time.
I'm always mildly amused when someone shows their SQL benchmarking and they've executed both versions of a sproc 50,000 times at midnight on the dev server and compare the average times.
To well understand the behaviour, you can run this code:
#include <iostream>
class MyClass
{
public:
MyClass() { std::cout << "run constructor MyClass::MyClass()" << std::endl; }
~MyClass() { std::cout << "run destructor MyClass::~MyClass()" << std::endl; }
MyClass(const MyClass& x) { std::cout << "run copy constructor MyClass::MyClass(const MyClass&)" << std::endl; }
MyClass& operator = (const MyClass& x) { std::cout << "run assignation MyClass::operator=(const MyClass&)" << std::endl; }
};
MyClass my_function()
{
std::cout << "run my_function()" << std::endl;
MyClass a;
std::cout << "my_function is going to return a..." << std::endl;
return a;
}
int main(int argc, char** argv)
{
MyClass b = my_function();
MyClass c;
c = my_function();
return 0;
}
The output is the following:
run my_function()
run constructor MyClass::MyClass()
my_function is going to return a...
run constructor MyClass::MyClass()
run my_function()
run constructor MyClass::MyClass()
my_function is going to return a...
run assignation MyClass::operator=(const MyClass&)
run destructor MyClass::~MyClass()
run destructor MyClass::~MyClass()
run destructor MyClass::~MyClass()
Note that this example was provided in C++03 context, it could be improved for C++ >= 11
Between the deprecation of mutation events and the emergence of MutationObserver
, an efficent way to be notified when a specific element was added to the DOM was to exploit CSS3 animation events.
To quote the blog post:
Setup a CSS keyframe sequence that targets (via your choice of CSS selector) whatever DOM elements you want to receive a DOM node insertion event for.
I used a relatively benign and little used css property, clipI used outline-color in an attempt to avoid messing with intended page styles – the code once targeted the clip property, but it is no longer animatable in IE as of version 11. That said, any property that can be animated will work, choose whichever one you like.Next I added a document-wide animationstart listener that I use as a delegate to process the node insertions. The animation event has a property called animationName on it that tells you which keyframe sequence kicked off the animation. Just make sure the animationName property is the same as the keyframe sequence name you added for node insertions and you’re good to go.
On Unix systems, for several projects, I added these lines into the CMakeLists.txt and it was compiling successfully because base (/usr/include) and local includes (/usr/local/include) go into separated directories:
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I/usr/local/include -L/usr/local/lib")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/usr/local/include")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L/usr/local/lib")
It appends the correct directory, including paths for the C and C++ compiler flags and the correct directory path for the linker flags.
Note: C++ compiler (c++) doesn't support -L, so we have to use CMAKE_EXE_LINKER_FLAGS
Adding allowfullscreen="allowfullscreen"
and altering the type of YouTube embed fixed my issue.
Late answer but this works:
/* applies to GIF and PNG images; avoids blurry edges */
img[src$=".gif"], img[src$=".png"] {
image-rendering: -moz-crisp-edges; /* Firefox */
image-rendering: -o-crisp-edges; /* Opera */
image-rendering: -webkit-optimize-contrast;/* Webkit (non-standard naming) */
image-rendering: crisp-edges;
-ms-interpolation-mode: nearest-neighbor; /* IE (non-standard property) */
}
https://developer.mozilla.org/en/docs/Web/CSS/image-rendering
Here is another link as well which talks about browser support:
https://css-tricks.com/almanac/properties/i/image-rendering/
In C, there's no (real, distinct type of) strings. Every C "string" is an array of chars, zero terminated.
Therefore, to extract a character c at index i from string your_string, just use
char c = your_string[i];
Index is base 0 (first character is your_string[0], second is your_string[1]...).
Use a pattern along these lines:
function getValue(file) {
return lookupValue(file);
}
getValue('myFile.txt').then(function(res) {
// do whatever with res here
});
(although this is a bit redundant, I'm sure your actual code is more complicated)
http://www.w3.org/TR/CSS21/visuren.html#z-index
'z-index'
Value: auto | <integer> | inherit
http://www.w3.org/TR/CSS21/syndata.html#numbers
Some value types may have integer values (denoted by <integer>) or real number values (denoted by <number>). Real numbers and integers are specified in decimal notation only. An <integer> consists of one or more digits "0" to "9". A <number> can either be an <integer>, or it can be zero or more digits followed by a dot (.) followed by one or more digits. Both integers and real numbers may be preceded by a "-" or "+" to indicate the sign. -0 is equivalent to 0 and is not a negative number.
Note that many properties that allow an integer or real number as a value actually restrict the value to some range, often to a non-negative value.
So basically there are no limitations for z-index value in the CSS standard, but I guess most browsers limit it to signed 32-bit values (-2147483648 to +2147483647) in practice (64 would be a little off the top, and it doesn't make sense to use anything less than 32 bits these days)
As Jesse said, use self join:
SELECT
e.emp_id
, e.emp_name
, e.emp_mgr_id
, m.emp_name AS mgr_name
FROM [dbo].[tblEmployeeDetails] e
LEFT JOIN [dbo].[tblEmployeeDetails] m ON e.emp_mgr_id = m.emp_id
for property, value in vars(theObject).items():
print(property, ":", value)
Be aware that in some rare cases there's a __slots__
property, such classes often have no __dict__
.
Use map
with operator.add
:
>>> from operator import add
>>> list( map(add, list1, list2) )
[5, 7, 9]
or zip
with a list comprehension:
>>> [sum(x) for x in zip(list1, list2)]
[5, 7, 9]
>>> list2 = [4, 5, 6]*10**5
>>> list1 = [1, 2, 3]*10**5
>>> %timeit from operator import add;map(add, list1, list2)
10 loops, best of 3: 44.6 ms per loop
>>> %timeit from itertools import izip; [a + b for a, b in izip(list1, list2)]
10 loops, best of 3: 71 ms per loop
>>> %timeit [a + b for a, b in zip(list1, list2)]
10 loops, best of 3: 112 ms per loop
>>> %timeit from itertools import izip;[sum(x) for x in izip(list1, list2)]
1 loops, best of 3: 139 ms per loop
>>> %timeit [sum(x) for x in zip(list1, list2)]
1 loops, best of 3: 177 ms per loop
You can also use NumberUtil.isNumber(String str) from Apache Commons
You can use a script from udhos/update-golang
.
Here is a two-liner as example (run as root
):
bash <(curl -s https://raw.githubusercontent.com/udhos/update-golang/master/update-golang.sh)
ln -vs /usr/local/go/bin/go* /usr/local/bin/
Try this.
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var json = config.Formatters.JsonFormatter;
json.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
config.Formatters.Remove(config.Formatters.XmlFormatter);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional , Action =RouteParameter.Optional }
);
}
}
If you're using jquery:
$(function() {
$("#Box1").focus();
});
or prototype:
Event.observe(window, 'load', function() {
$("Box1").focus();
});
or plain javascript:
window.onload = function() {
document.getElementById("Box1").focus();
};
though keep in mind that this will replace other on load handlers, so look up addLoadEvent() in google for a safe way to append onload handlers rather than replacing.
Threads share everything [1]. There is one address space for the whole process.
Each thread has its own stack and registers, but all threads' stacks are visible in the shared address space.
If one thread allocates some object on its stack, and sends the address to another thread, they'll both have equal access to that object.
Actually, I just noticed a broader issue: I think you're confusing two uses of the word segment.
The file format for an executable (eg, ELF) has distinct sections in it, which may be referred to as segments, containing compiled code (text), initialized data, linker symbols, debug info, etc. There are no heap or stack segments here, since those are runtime-only constructs.
These binary file segments may be mapped into the process address space seperately, with different permissions (eg, read-only executable for code/text, and copy-on-write non-executable for initialized data).
Areas of this address space are used for different purposes, like heap allocation and thread stacks, by convention (enforced by your language runtime libraries). It is all just memory though, and probably not segmented unless you're running in virtual 8086 mode. Each thread's stack is a chunk of memory allocated at thread creation time, with the current stack top address stored in a stack pointer register, and each thread keeps its own stack pointer along with its other registers.
[1] OK, I know: signal masks, TSS/TSD etc. The address space, including all its mapped program segments, are still shared though.
Your original example works just fine for me:
<html>
<head>
</head>
<body>
<script>
var widthRange = new Array();
widthRange[46] = { sel:46, min:0, max:52 };
widthRange[66] = { sel:66, min:52, max:70 };
widthRange[90] = { sel:90, min:70, max:94 };
var i = 1;
for (var key in widthRange)
{
document.write("Key #" + i + " = " + key + "; min/max = " + widthRange[key].min + "/" + widthRange[key].max + "<br />");
i++;
}
</script>
</html>
Results in the browser (Firefox 3.6.2 on Windows XP):
Key #1 = 46; min/max = 0/52
Key #2 = 66; min/max = 52/70
Key #3 = 90; min/max = 70/94
I also had to save Base64 encoded images that are part of data URLs, so I ended up making a small npm module to do it in case I (or someone else) needed to do it again in the future. It's called ba64.
Simply put, it takes a data URL with a Base64 encoded image and saves the image to your file system. It can save synchronously or asynchronously. It also has two helper functions, one to get the file extension of the image, and the other to separate the Base64 encoding from the data:
scheme prefix.
Here's an example:
var ba64 = require("ba64"),
data_url = "data:image/jpeg;base64,[Base64 encoded image goes here]";
// Save the image synchronously.
ba64.writeImageSync("myimage", data_url); // Saves myimage.jpeg.
// Or save the image asynchronously.
ba64.writeImage("myimage", data_url, function(err){
if (err) throw err;
console.log("Image saved successfully");
// do stuff
});
Install it: npm i ba64 -S
. Repo is on GitHub: https://github.com/HarryStevens/ba64.
P.S. It occurred to me later that ba64 is probably a bad name for the module since people may assume it does Base64 encoding and decoding, which it doesn't (there are lots of modules that already do that). Oh well.
To configure your JRE in eclipse:
using unescape(stringValue)
var str = "Passwords%20do%20not%20match%21";
document.write(unescape(str))
_x000D_
//Output
Passwords do not match!
use decodeURI(stringValue)
var str = "Passwords%20do%20not%20match%21";
document.write(decodeURI(str))
_x000D_
Space = %20
? = %3F
! = %21
# = %23
...etc
Sticky session means that when a request comes into a site from a client all further requests go to the same server initial client request accessed. I believe that session affinity is a synonym for sticky session.
From the man page:
-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there
is only one file (or only standard input) to search.
You can't easily do this in a generic way: you can only convert an integer to a specific type of enum. As Nicholas has shown, this is a trivial cast if you only care about one kind of enum, but if you want to write a generic method that can handle different kinds of enums, things get a bit more complicated. You want a method along the lines of:
public static string GetEnumDescription<TEnum>(int value)
{
return GetEnumDescription((Enum)((TEnum)value)); // error!
}
but this results in a compiler error that "int can't be converted to TEnum" (and if you work around this, that "TEnum can't be converted to Enum"). So you need to fool the compiler by inserting casts to object:
public static string GetEnumDescription<TEnum>(int value)
{
return GetEnumDescription((Enum)(object)((TEnum)(object)value)); // ugly, but works
}
You can now call this to get a description for whatever type of enum is at hand:
GetEnumDescription<MyEnum>(1);
GetEnumDescription<YourEnum>(2);
in handlebars first register a function like below
Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
});
you can register more than one function . to add another function just add like below
Handlebars.registerHelper('calculate', function(operand1, operator, operand2) {
let result;
switch (operator) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
result = operand1 / operand2;
break;
}
return Number(result);
});
and in HTML page just include the conditions like
{{#ifEquals day "mon"}}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
//html code goes here
</html>
{{else ifEquals day "sun"}}
<html>
//html code goes here
</html>
{{else}}
//html code goes here
{{/ifEquals}}
I would suggest adding stdout
and stderr
file in systemd service
file itself.
Referring : https://www.freedesktop.org/software/systemd/man/systemd.exec.html#StandardOutput=
As you have configured it should not like:
StandardOutput=/home/user/log1.log
StandardError=/home/user/log2.log
It should be:
StandardOutput=file:/home/user/log1.log
StandardError=file:/home/user/log2.log
This works when you don't want to restart the service again and again.
This will create a new file and does not append to the existing file.
Use Instead:
StandardOutput=append:/home/user/log1.log
StandardError=append:/home/user/log2.log
NOTE: Make sure you create the directory already. I guess it does not support to create a directory.
In my case, the error was valid and it was due to using try with resource
try (ConfigurableApplicationContext cxt = new ClassPathXmlApplicationContext(
"classpath:application-main-config.xml")) {..
}
It auto closes the stream which should not happen if I want to reuse this context in other beans.
It sounds like you're asking about a function
string Left(string s, int left)
that will return the leftmost left
characters of the string s
. In that case you can just use String.Substring
. You can write this as an extension method:
public static class StringExtensions
{
public static string Left(this string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
maxLength = Math.Abs(maxLength);
return ( value.Length <= maxLength
? value
: value.Substring(0, maxLength)
);
}
}
and use it like so:
string left = s.Left(number);
For your specific example:
string s = fac.GetCachedValue("Auto Print Clinical Warnings").ToLower() + " ";
string left = s.Substring(0, 1);
In my experience, the fastest method is
UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE field LIKE '%foo%';
The INSTR()
way is the second-fastest and omitting the WHERE
clause altogether is slowest, even if the column is not indexed.
When you want to edit something in Angular you need to insert an ngModel in your html
try this in your sample:
<input type="text" name="abc" class="color" ng-model="myStyle.color">
You don't need to watch the change at all!
TypeA[] array = (TypeA[]) a.toArray();
In C ++, if a const object is initialized with a constant expression, we can use our const object wherever a constant expression is required.
const int x = 10;
int a[x] = {0};
For example, we can make a case statement in switch.
constexpr can be used with arrays.
constexpr is not a type.
The constexpr keyword can be used in conjunction with the auto keyword.
constexpr auto x = 10;
struct Data { // We can make a bit field element of struct.
int a:x;
};
If we initialize a const object with a constant expression, the expression generated by that const object is now a constant expression as well.
Constant Expression : An expression whose value can be calculated at compile time.
x*5-4 // This is a constant expression. For the compiler, there is no difference between typing this expression and typing 46 directly.
Initialize is mandatory. It can be used for reading purposes only. It cannot be changed. Up to this point, there is no difference between the "const" and "constexpr" keywords.
NOTE: We can use constexpr and const in the same declaration.
constexpr const int* p;
Normally, the return value of a function is obtained at runtime. But calls to constexpr functions will be obtained as a constant in compile time when certain conditions are met.
NOTE : Arguments sent to the parameter variable of the function in function calls or to all parameter variables if there is more than one parameter, if C.E the return value of the function will be calculated in compile time. !!!
constexpr int square (int a){
return a*a;
}
constexpr int a = 3;
constexpr int b = 5;
int arr[square(a*b+20)] = {0}; //This expression is equal to int arr[35] = {0};
In order for a function to be a constexpr function, the return value type of the function and the type of the function's parameters must be in the type category called "literal type".
The constexpr functions are implicitly inline functions.
None of the constexpr functions need to be called with a constant expression.It is not mandatory. If this happens, the computation will not be done at compile time. It will be treated like a normal function call. Therefore, where the constant expression is required, we will no longer be able to use this expression.
1 ) The types used in the parameters of the function and the type of the return value of the function must be literal type.
2 ) A local variable with static life time should not be used inside the function.
3 ) If the function is legal, when we call this function with a constant expression in compile time, the compiler calculates the return value of the function in compile time.
4 ) The compiler needs to see the code of the function, so constexpr functions will almost always be in the header files.
5 ) In order for the function we created to be a constexpr function, the definition of the function must be in the header file.Thus, whichever source file includes that header file will see the function definition.
Normally with Default Member Initialization, static data members with const and integral types can be initialized within the class. However, in order to do this, there must be both "const" and "integral types".
If we use static constexpr then it doesn't have to be an integral type to initialize it inside the class. As long as I initialize it with a constant expression, there is no problem.
class Myclass {
const static int sx = 15; // OK
constexpr static int sy = 15; // OK
const static double sd = 1.5; // ERROR
constexpr static double sd = 1.5; // OK
};
theme root directory path code
<?php $root_path = get_home_path(); ?>
print "Path: ".$root_path;
Return "Path: /var/www/htdocs/" or "Path: /var/www/htdocs/wordpress/" if it is subfolder
Theme Root Path
$theme_root = get_theme_root();
echo $theme_root
Results:- /home/user/public_html/wp-content/themes
This answer is based on Eclipse 3.4, but should work in older versions of Eclipse.
When selecting Run As..., go into the run configurations.
On the Arguments tab of your Java run configuration, configure the variable ${string_prompt} to appear (you can click variables to get it, or copy that to set it directly).
Every time you use that run configuration (name it well so you have it for later), you will be prompted for the command line arguments.
I know this thread is a little old but it came in handy for a specific scenario I had and I thought it worth while to note that there is another reason why System.Threading.Timer
might be a good approach.
When you have to periodically execute a Job that might take a long time and you want to ensure that the entire waiting period is used between jobs or if you don't want the job to run again before the previous job has finished in the case where the job takes longer than the timer period.
You could use the following:
using System;
using System.ServiceProcess;
using System.Threading;
public partial class TimerExampleService : ServiceBase
{
private AutoResetEvent AutoEventInstance { get; set; }
private StatusChecker StatusCheckerInstance { get; set; }
private Timer StateTimer { get; set; }
public int TimerInterval { get; set; }
public CaseIndexingService()
{
InitializeComponent();
TimerInterval = 300000;
}
protected override void OnStart(string[] args)
{
AutoEventInstance = new AutoResetEvent(false);
StatusCheckerInstance = new StatusChecker();
// Create the delegate that invokes methods for the timer.
TimerCallback timerDelegate =
new TimerCallback(StatusCheckerInstance.CheckStatus);
// Create a timer that signals the delegate to invoke
// 1.CheckStatus immediately,
// 2.Wait until the job is finished,
// 3.then wait 5 minutes before executing again.
// 4.Repeat from point 2.
Console.WriteLine("{0} Creating timer.\n",
DateTime.Now.ToString("h:mm:ss.fff"));
//Start Immediately but don't run again.
StateTimer = new Timer(timerDelegate, AutoEventInstance, 0, Timeout.Infinite);
while (StateTimer != null)
{
//Wait until the job is done
AutoEventInstance.WaitOne();
//Wait for 5 minutes before starting the job again.
StateTimer.Change(TimerInterval, Timeout.Infinite);
}
//If the Job somehow takes longer than 5 minutes to complete then it wont matter because we will always wait another 5 minutes before running again.
}
protected override void OnStop()
{
StateTimer.Dispose();
}
}
class StatusChecker
{
public StatusChecker()
{
}
// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Start Checking status.",
DateTime.Now.ToString("h:mm:ss.fff"));
//This job takes time to run. For example purposes, I put a delay in here.
int milliseconds = 5000;
Thread.Sleep(milliseconds);
//Job is now done running and the timer can now be reset to wait for the next interval
Console.WriteLine("{0} Done Checking status.",
DateTime.Now.ToString("h:mm:ss.fff"));
autoEvent.Set();
}
}
the root parent have to be in pixels if you want to work freely with percents,
<body style="margin: 0px; width: 1886px; height: 939px;">
<div id="containerA" class="containerA" style="height:65%;width:100%;">
<div id="containerAinnerDiv" style="position: relative; background-color: aqua;width:70%;height: 80%;left:15%;top:10%;">
<div style="height: 100%;width: 50%;float: left;"></div>
<div style="height: 100%;width: 28%;float:left">
<img src="img/justimage.png" style="max-width:100%;max-height:100%;">
</div>
<div style="height: 100%;width: 22%;float: left;"></div>
</div>
</div>
</body>
Use this:
void double_to_char(double f,char * buffer){
gcvt(f,10,buffer);
}
the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.
try
sudo dnf update
and then
sudo dnf install gcc-c++
I also had the same issue. Tried all ways and it didn't work out until I added the following in app.module.ts
import { Ng4LoadingSpinnerModule } from 'ng4-loading-spinner';
And add the following in your imports in app.module.ts
Ng4LoadingSpinnerModule.forRoot()
This case might be rare but I hope this helps someone out there
I was looking for an example that had default kwargs using type annotation:
def test_var_kwarg(a: str, b: str='B', c: str='', **kwargs) -> str:
return ' '.join([a, b, c, str(kwargs)])
example:
>>> print(test_var_kwarg('A', c='okay'))
A B okay {}
>>> d = {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', c='c', b='b', **d))
a b c {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', 'b', 'c'))
a b c {}
const urlParams = new URLSearchParams(window.location.search);
urlParams.set('order', 'date');
window.location.search = urlParams;
.set first agrument is the key, the second one is the value.
The pythonic way is to use enumerate
:
for idx,item in enumerate(list):
To add the latest solution for 2021...
I found that the project nanoid provides unique string ids that can be used as key while also being fast and very small.
After installing using npm install nanoid
, use as follows:
import { nanoid } from 'nanoid';
// Have the id associated with the data.
const todos = [{id: nanoid(), text: 'first todo'}];
// Then later, it can be rendered using a stable id as the key.
const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
)
Here's the solution I plan to go with. Not only does this work with non-sequential integers, but it should work with any other data type you may want to use as the underlying id for your enum values.
public Enum MyEnum {
THIS(5),
THAT(16),
THE_OTHER(35);
private int id; // Could be other data type besides int
private MyEnum(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public static Map<Integer, MyEnum> buildMap() {
Map<Integer, MyEnum> map = new HashMap<Integer, MyEnum>();
MyEnum[] values = MyEnum.values();
for (MyEnum value : values) {
map.put(value.getId(), value);
}
return map;
}
}
I only need to convert id's to enums at specific times (when loading data from a file), so there's no reason for me to keep the Map in memory at all times. If you do need the map to be accessible at all times, you can always cache it as a static member of your Enum class.
Curl will look for a .curlrc file in your home folder when it starts. You can create (or edit) this file and add this line:
proxy = yourproxy.com:8080
Assign a new Image
object to your PictureBox
's Image
property. To load an Image
from a file, you may use the Image.FromFile
method. In your particular case, assuming the current directory is one under bin
, this should load the image bin/Pics/image1.jpg
, for example:
pictureBox1.Image = Image.FromFile("../Pics/image1.jpg");
Additionally, if these images are static and to be used only as resources in your application, resources would be a much better fit than files.
There's not a way as of 11/2012, HOWEVER
Highlight Text (In visual Studio.net)
ctrl + k + c, ctrl + k + u
Will comment / uncomment, respectively
Here is an alternate css/jQuery solution that I prefer for its terseness and minimized scripting:
css:
a.disabled {
opacity: 0.5;
pointer-events: none;
cursor: default;
}
jQuery:
$('.disableAfterClick').click(function (e) {
$(this).addClass('disabled');
});
That is because you are trying to access the plugin before it's loaded. You should try making a call to it when the DOM is loaded by surrounding it with this:
$(document).ready(function(){
$("#colorpicker").colorpicker();
}
An approximated solution (based on an equirectangular projection), much faster (it requires only 1 trig and 1 square root).
This approximation is relevant if your points are not too far apart. It will always over-estimate compared to the real haversine distance. For example it will add no more than 0.05382 % to the real distance if the delta latitude or longitude between your two points does not exceed 4 decimal degrees.
The standard formula (Haversine) is the exact one (that is, it works for any couple of longitude/latitude on earth) but is much slower as it needs 7 trigonometric and 2 square roots. If your couple of points are not too far apart, and absolute precision is not paramount, you can use this approximate version (Equirectangular), which is much faster as it uses only one trigonometric and one square root.
// Approximate Equirectangular -- works if (lat1,lon1) ~ (lat2,lon2)
int R = 6371; // km
double x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
double y = (lat2 - lat1);
double distance = Math.sqrt(x * x + y * y) * R;
You can optimize this further by either:
For more info see: http://www.movable-type.co.uk/scripts/latlong.html
There is a nice reference implementation of the Haversine formula in several languages at: http://www.codecodex.com/wiki/Calculate_Distance_Between_Two_Points_on_a_Globe
There is a menu shortcut to run all cells under Cell > "Run All". This isn't bound to a keyboard shortcut by default- you'll have to define your own custom binding from within the notebook, as described here.
For example, to add a keyboard binding that lets you run all the cells in a notebook, you can insert this in a cell:
%%javascript
Jupyter.keyboard_manager.command_shortcuts.add_shortcut('r', {
help : 'run all cells',
help_index : 'zz',
handler : function (event) {
IPython.notebook.execute_all_cells();
return false;
}}
);
If you run this code from within iPython notebook, you should find that you now have a keyboard binding to run all cells (in this case, press ctrl-M followed by r)
public class ObjectComparator implements Comparator<Object> {
public int compare(Object obj1, Object obj2) {
return obj1.getName().compareTo(obj2.getName());
}
}
Please replace Object with your class which contains name field
Usage:
ObjectComparator comparator = new ObjectComparator();
Collections.sort(list, comparator);
If you're paranoid like me about using Math.max.apply
(which could cause errors when given large arrays according to MDN), try this:
function arrayMax(array) {
return array.reduce(function(a, b) {
return Math.max(a, b);
});
}
function arrayMin(array) {
return array.reduce(function(a, b) {
return Math.min(a, b);
});
}
Or, in ES6:
function arrayMax(array) {
return array.reduce((a, b) => Math.max(a, b));
}
function arrayMin(array) {
return array.reduce((a, b) => Math.min(a, b));
}
The anonymous functions are unfortunately necessary (instead of using Math.max.bind(Math)
because reduce
doesn't just pass a
and b
to its function, but also i
and a reference to the array itself, so we have to ensure we don't try to call max
on those as well.
It can also be useful to use String.Format
, e.g.
String.Format("{0}\t{1}", FirstName,Count);
If you are using Kotlin and Kotlin android extensions, then there is a beautiful way of doing this.
val uri = myUriString.toUri()
To add Kotlin extensions (KTX) to your project add the following to your app module's build.gradle
repositories {
google()
}
dependencies {
implementation 'androidx.core:core-ktx:1.0.0-rc01'
}
Guys I have a better solution its short and works perfectly to me. I used it to video. And its perfectly emulates the cover option in css.
Javascript
$(window).resize(function(){
//use the aspect ration of your video or image instead 16/9
if($(window).width()/$(window).height()>16/9){
$("video").css("width","100%");
$("video").css("height","auto");
}
else{
$("video").css("width","auto");
$("video").css("height","100%");
}
});
If you flip the if, else you will get contain.
And here is the css. (You don't need to use it if you don't want center positioning, the parent div must be "position:relative")
CSS
video {
position: absolute;
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
top: 50%;
left: 50%;}
If having following JSON from web service, Json Array as a response :
[3]
0: {
id: 2
name: "a561137"
password: "test"
firstName: "abhishek"
lastName: "ringsia"
organization: "bbb"
}-
1: {
id: 3
name: "a561023"
password: "hello"
firstName: "hello"
lastName: "hello"
organization: "hello"
}-
2: {
id: 4
name: "a541234"
password: "hello"
firstName: "hello"
lastName: "hello"
organization: "hello"
}
have To Accept it first as a Json Array ,then while reading its Object have to use Object Mapper.readValue ,because Json Object Still in String .
List<User> list = new ArrayList<User>();
JSONArray jsonArr = new JSONArray(response);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
ObjectMapper mapper = new ObjectMapper();
User usr = mapper.readValue(jsonObj.toString(), User.class);
list.add(usr);
}
mapper.read is correct function ,if u use mapper.convert(param,param) . It will give u error .
$(function(){
$("#my-div").toggle();
$("#my-div").click(function(){$("#my-div").toggle()})
})
// you don't even have to set the #my-div
.hide
nor !important
, just paste/repeat the toggle in the event function.
Answer by Adamski is a good one and describes the steps in an encoding operation when using the general encode method (that takes a byte buffer as one of the inputs)
However, the method in question (in this discussion) is a variant of encode - encode(CharBuffer in). This is a convenience method that implements the entire encoding operation. (Please see java docs reference in P.S.)
As per the docs, This method should therefore not be invoked if an encoding operation is already in progress (which is what is happening in ZenBlender's code -- using static encoder/decoder in a multi threaded environment).
Personally, I like to use convenience methods (over the more general encode/decode methods) as they take away the burden by performing all the steps under the covers.
ZenBlender and Adamski have already suggested multiple ways options to safely do this in their comments. Listing them all here:
P.S.
java docs references:
Another option is to rename using a regular expression:
import pandas as pd
import re
df = pd.DataFrame({'$a':[1,2], '$b':[3,4], '$c':[5,6]})
df = df.rename(columns=lambda x: re.sub('\$','',x))
>>> df
a b c
0 1 3 5
1 2 4 6
This worked for me.
look for this:
DirectoryIndex index.php
replace with this:
DirectoryIndex something.php index.php
Upload and refresh page. You will get a page error.
just change it back to:
DirectoryIndex index.php
reupload and refresh page again.
I checked this on all of my devices and, it worked.
Just add a file .gitkeep
in every folder you want committed.
On windows do so by right clicking when in the folder and select: Git bash from here. Then type: touch .gitkeep
Add android:includeFontPadding="false" to see if it helps.And make text view size same as that of text size rather than "wrap content".It will definitely work.
I think this is simple enough
uint8_t reverse(uint8_t a)
{
unsigned w = ((a << 7) & 0x0880) | ((a << 5) & 0x0440) | ((a << 3) & 0x0220) | ((a << 1) & 0x0110);
return static_cast<uint8_t>(w | (w>>8));
}
or
uint8_t reverse(uint8_t a)
{
unsigned w = ((a & 0x11) << 7) | ((a & 0x22) << 5) | ((a & 0x44) << 3) | ((a & 0x88) << 1);
return static_cast<uint8_t>(w | (w>>8));
}
If you need to pass $_GET
, $_REQUEST
, $_POST
, or anything else you can also use PHP interactive mode:
php -a
Then type:
<?php
$_GET['a']=1;
$_POST['b']=2;
include("/somefolder/some_file_path.php");
This will manually set any variables you want and then run your php file with those variables set.
The only reliable way to open it is Window -> Show View -> Other -> Search "console". There was a handful suggestions in this post and none of them works! Apparently Eclipse likes to change their logic every other second.
Also, resetting the view is the most horrible suggestion, because that way you will lose everything you have ever done to change the layout, so it will probably not work for the most of the readers.
CONNECTION_REFUSED is standard when the port is closed, but it could be rejected because SSL is failing authentication (one of a billion reasons). Did you configure SSL with Ratchet? (Apache is bypassed) Did you try without SSL in JavaScript?
I don't think Ratchet has built-in support for SSL. But even if it does you'll want to try the ws:// protocol first; it's a lot simpler, easier to debug, and closer to telnet. Chrome or the socket service may also be generating the REFUSED error if the service doesn't support SSL (because you explicitly requested SSL).
However the refused message is likely a server side problem, (usually port closed).
I know this is really old and most of the folks have already answered it right. Here are at least two ways you can find out the gradle version (not the gradle plugin version) by selecting one of the following on project tab on left:
I fixed it by changing the quotation mark (") with apostrophe (') inside Values. For instance:
insert into trucks ("id","datetime") VALUES (862,"10-09-2002 09:15:59");
Becomes this:
insert into trucks ("id","datetime") VALUES (862,'10-09-2002 09:15:59');
Assuming datetime
column is VarChar.
The MAC address (the low-level local network interface address) does not survive hops through IP routers. You can't find the client MAC address from a remote server.
In a local subnet, the MAC addresses are mapped to IP addresses through the ARP system. Interfaces on the local net know how to map IP addresses to MAC addresses. However, when your packets have been routed on the local subnet to (and through) the gateway out to the "real" Internet, the originating MAC address is lost. Simplistically, each subnet-to-subnet hop of your packets involve the same sort of IP-to-MAC mapping for local routing in each subnet.
It's also possible to use java Foo | tee -a some.log
. it just prints to stdout as well. Like:
user at Computer in ~
$ echo "hi" | tee -a foo.txt
hi
user at Computer in ~
$ echo "hello" | tee -a foo.txt
hello
user at Computer in ~
$ cat foo.txt
hi
hello
After like three (3) hours of google..ing.This is the solution to the problem: First, I run this command;
$mysqladmin -u root -p[your root password here] version
Which outputs:
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Server version 5.5.49-0ubuntu0.14.04.1
Protocol version 10
Connection Localhost via UNIX socket
UNIX socket /var/run/mysqld/mysqld.sock
Uptime: 1 hour 54 min 3 sec
Finally, I changed the connect_type
parameter from tcp
to socket
and added the parameter socket
in config.inc.php
:
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'socket';
$cfg['Servers'][$i]['socket'] = '/var/run/mysqld/mysqld.sock';
All credit goes to this person: This is the correct solution
This is because ASP.NET it changing the Id of your textbox, if you run your page, and do a view source, you will see the text box id is something like
ctl00_ContentColumn_txt_model_code
There are a few ways round this:
Use the actual control name:
var TestVar = document.getElementById('ctl00_ContentColumn_txt_model_code').value;
use the ClientID property within ASP script tags
document.getElementById('<%= txt_model_code.ClientID %>').value;
Or if you are running .NET 4 you can use the new ClientIdMode property, see this link for more details.
http://weblogs.asp.net/scottgu/archive/2010/03/30/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series.aspx1
To load your data in WebView. Call loadData() method of WebView
webView.loadData(yourData, "text/html; charset=utf-8", "UTF-8");
You can check this example
http://developer.android.com/reference/android/webkit/WebView.html
You do it:
console.log('hi')_x000D_
let start = 1_x000D_
setTimeout(function(){_x000D_
let interval = setInterval(function(){_x000D_
if(start == 10) clearInterval(interval)_x000D_
start++_x000D_
console.log('hello')_x000D_
}, 3000)_x000D_
}, 3000)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
If you are running multiple instances of Tomcat on a single host you should set CATALINA_BASE
to be equal to the .../tomcat_instance1
or .../tomcat_instance2
directory as appropriate for each instance and the CATALINA_HOME
environment variable to the common Tomcat installation whose files will be shared between the two instances.
The CATALINA_BASE
environment is optional if you are running a single Tomcat instance on the host and will default to CATALINA_HOME
in that case. If you are running multiple instances as you are it should be provided.
There is a pretty good description of this setup in the RUNNING.txt
file in the root of the Apache Tomcat distribution under the heading Advanced Configuration - Multiple Tomcat Instances
1.1 ls
It will show you default location.
1.2 CD "C:\Users\user\Desktop\HTML" We need to assign project path
1.3 git init It will initialize the empty git repository in C:\Users\user\Desktop\HTML
1.4 ls It will list all files name
1.5 git remote add origin https://github.com/repository/test.git it is your https://github.com/repository/test.git is your repository path
1.6 git remote -v To check weather we have fetch or push permisson or not
1.7 git add . If you put . then it mean whatever we have in perticular folder publish all.
1.8 git commit -m "First time"
1.9 git push -u origin master
I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..
Opening A Seperate File:
ChDir "[Path here]" 'get into the right folder here
Workbooks.Open Filename:= "[Path here]" 'include the filename in this path
'copy data into current workbook or whatever you want here
ActiveWindow.Close 'closes out the file
Opening A File With Specified Date If It Exists:
I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.
Some common error checking statements:
On Error Resume Next 'if error occurs continues on to the next line (ignores it)
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Or (better option):
if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?
you would most likely want to use the GoTo ErrorHandler
shown below to achieve this
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
ErrorHandler:
'Display error message or any code you want to run on error here
Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm
Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/
Hope this helps!
Example on how to ensure error code doesn't run EVERYtime:
if you debug through the code without the Exit Sub
BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.
Sub Macro
On Error GoTo ErrorHandler:
ChDir "[Path here]"
Workbooks.Open Filename:= "[Path here]" 'try to open file here
Exit Sub 'Code will exit BEFORE ErrorHandler if everything goes smoothly
'Otherwise, on error, ErrorHandler will be run
ErrorHandler:
'Display error message or any code you want to run on error here
End Sub
Also, look at this other question in you need more reference to how this works: goto block not working VBA
If you create a tag by e.g.
git tag v1.0
the tag will refer to the most recent commit of the branch you are currently on. You can change branch and create a tag there.
You can also just refer to the other branch while tagging,
git tag v1.0 name_of_other_branch
which will create the tag to the most recent commit of the other branch.
Or you can just put the tag anywhere, no matter which branch, by directly referencing to the SHA1 of some commit
git tag v1.0 <sha1>
I have used Guava Sets.difference.
The parameters are sets and not general collections, but a handy way to create sets from any collection (with unique items) is Guava ImmutableSet.copyOf(Iterable).
(I first posted this on a related/dupe question, but I'm copying it here too since I feel it is a good option that is so far missing.)
Having read the above answers i found that for my situation the following fixed the issue.
This threw the error
myButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MyDialogue dialog = new MyDialogue(getApplicationContext());
dialog.show();
}
});
Based on the previous answers that suggested the context was the wrong one, i changed the getApplicationContext() to retrieve the context from the View passed in to the buttons onClick method.
myButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MyDialogue dialog = new MyDialogue(v.getContext());
dialog.show();
}
});
I don't fully understand the workings of Java so i could be wrong, but I'm guessing that for my specific situation the cause could have been related to the fact that the above snippet was defined in an Abstract Activity class; inherited and used by many Activities, perhaps that contributed to the fact that getApplicationContext() doesn't return a valid context?? (Just a guess).
I assume you mean that you want the final SQL query, with parameter values interpolated into it. I understand that this would be useful for debugging, but it is not the way prepared statements work. Parameters are not combined with a prepared statement on the client-side, so PDO should never have access to the query string combined with its parameters.
The SQL statement is sent to the database server when you do prepare(), and the parameters are sent separately when you do execute(). MySQL's general query log does show the final SQL with values interpolated after you execute(). Below is an excerpt from my general query log. I ran the queries from the mysql CLI, not from PDO, but the principle is the same.
081016 16:51:28 2 Query prepare s1 from 'select * from foo where i = ?'
2 Prepare [2] select * from foo where i = ?
081016 16:51:39 2 Query set @a =1
081016 16:51:47 2 Query execute s1 using @a
2 Execute [2] select * from foo where i = 1
You can also get what you want if you set the PDO attribute PDO::ATTR_EMULATE_PREPARES. In this mode, PDO interpolate parameters into the SQL query and sends the whole query when you execute(). This is not a true prepared query. You will circumvent the benefits of prepared queries by interpolating variables into the SQL string before execute().
Re comment from @afilina:
No, the textual SQL query is not combined with the parameters during execution. So there's nothing for PDO to show you.
Internally, if you use PDO::ATTR_EMULATE_PREPARES, PDO makes a copy of the SQL query and interpolates parameter values into it before doing the prepare and execute. But PDO does not expose this modified SQL query.
The PDOStatement object has a property $queryString, but this is set only in the constructor for the PDOStatement, and it's not updated when the query is rewritten with parameters.
It would be a reasonable feature request for PDO to ask them to expose the rewritten query. But even that wouldn't give you the "complete" query unless you use PDO::ATTR_EMULATE_PREPARES.
This is why I show the workaround above of using the MySQL server's general query log, because in this case even a prepared query with parameter placeholders is rewritten on the server, with parameter values backfilled into the query string. But this is only done during logging, not during query execution.
This will search for a string over every database:
declare @search_term varchar(max)
set @search_term = 'something'
select @search_term = 'use ? SET QUOTED_IDENTIFIER ON
select
''[''+db_name()+''].[''+c.name+''].[''+b.name+'']'' as [object],
b.type_desc as [type],
d.obj_def.value(''.'',''varchar(max)'') as [definition]
from (
select distinct
a.id
from sys.syscomments a
where a.[text] like ''%'+@search_term+'%''
) a
inner join sys.all_objects b
on b.[object_id] = a.id
inner join sys.schemas c
on c.[schema_id] = b.[schema_id]
cross apply (
select
[text()] = a1.[text]
from sys.syscomments a1
where a1.id = a.id
order by a1.colid
for xml path(''''), type
) d(obj_def)
where c.schema_id not in (3,4) -- avoid searching in sys and INFORMATION_SCHEMA schemas
and db_id() not in (1,2,3,4) -- avoid sys databases'
if object_id('tempdb..#textsearch') is not null drop table #textsearch
create table #textsearch
(
[object] varchar(300),
[type] varchar(300),
[definition] varchar(max)
)
insert #textsearch
exec sp_MSforeachdb @search_term
select *
from #textsearch
order by [object]
UConverter can be used since PHP 5.5. UConverter is better the choice if you use intl extension and don't use mbstring.
function replace_invalid_byte_sequence($str)
{
return UConverter::transcode($str, 'UTF-8', 'UTF-8');
}
function replace_invalid_byte_sequence2($str)
{
return (new UConverter('UTF-8', 'UTF-8'))->convert($str);
}
htmlspecialchars can be used to remove invalid byte sequence since PHP 5.4. Htmlspecialchars is better than preg_match for handling large size of byte and the accuracy. A lot of the wrong implementation by using regular expression can be seen.
function replace_invalid_byte_sequence3($str)
{
return htmlspecialchars_decode(htmlspecialchars($str, ENT_SUBSTITUTE, 'UTF-8'));
}
You don't even need to nest the second relative
layout inside the first one. Simply use the android:layout_alignParentBottom="true"
in the Button and EditText.
It is possible with PowerShell 4.
Get-Service *spool* | select name,starttype | ft -AutoSize
Looking under the hood, the two statements will be transformed into different query representations. Depending on the QueryProvider
of Collection
, this might be optimized away or not.
When this is a linq-to-object call, multiple where clauses will lead to a chain of IEnumerables that read from each other. Using the single-clause form will help performance here.
When the underlying provider translates it into a SQL statement, the chances are good that both variants will create the same statement.
If you are counting letters, the above solution will fail for some unicode symbols. For example for these 5 characters sample.length() will return 6 instead of 5:
String sample = "\u760c\u0444\u03b3\u03b5\ud800\udf45"; // ???e
The codePointCount function was introduced in Java 1.5 and I understand gives better results for glyphs etc
sample.codePointCount(0, sample.length()) // returns 5
http://globalizer.wordpress.com/2007/01/16/utf-8-and-string-length-limitations/
Open the Command Palette
Ctrl + Shift + P
Then type:
Reload Window
I personally prefer the simpler syntax of the ~ operator.
SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' ~ tag_name;
Worth reading through Difference between LIKE and ~ in Postgres to understand the difference. `
create trigger doct_trigger
after delete on doctor
for each row
delete from patient where patient.PrimaryDoctor_SSN=doctor.SSN ;
Here is small utility class that converts JSON to DataFrame and back: Hope you find this helpful.
# -*- coding: utf-8 -*-
from pandas.io.json import json_normalize
class DFConverter:
#Converts the input JSON to a DataFrame
def convertToDF(self,dfJSON):
return(json_normalize(dfJSON))
#Converts the input DataFrame to JSON
def convertToJSON(self, df):
resultJSON = df.to_json(orient='records')
return(resultJSON)
Seeing this error during the use of Guzzle as well. The following header fixed it for me:
'headers' => [
'accept-encoding' => 'gzip, deflate',
],
I issued the request with Postman which gave me a complete response and no error. Then I started adding the headers that Postman sends to the Guzzle request and this was the one that fixed it.
Google Chrome Developer Tools has (a currently experimental) feature called CSS Overview which will allow you to find unused CSS rules.
To enable it follow these steps:
From the Notes of Fred Swartz (fredosaurus) :
There are two types of methods.
Instance methods are associated with an object and use the instance variables of that object. This is the default.
Static methods use no instance variables of any object of the class they are defined in. If you define a method to be static, you will be given a rude message by the compiler if you try to access any instance variables. You can access static variables, but except for constants, this is unusual. Static methods typically take all they data from parameters and compute something from those parameters, with no reference to variables. This is typical of methods which do some kind of generic calculation. A good example of this are the many utility methods in the predefined Math
class.
From outside the defining class, an instance method is called by prefixing it with an object, which is then passed as an implicit parameter to the instance method, eg, inputTF.setText("");
A static method is called by prefixing it with a class name, eg, Math.max(i,j);
. Curiously, it can also be qualified with an object, which will be ignored, but the class of the object will be used.
Here is a typical static method:
class MyUtils {
. . .
//================================================= mean
public static double mean(int[] p) {
int sum = 0; // sum of all the elements
for (int i=0; i<p.length; i++) {
sum += p[i];
}
return ((double)sum) / p.length;
}//endmethod mean
. . .
}
The only data this method uses or changes is from parameters (or local variables of course).
static
The above mean()
method would work just as well if it wasn't declared static, as long as it was called from within the same class. If called from outside the class and it wasn't declared static, it would have to be qualified (uselessly) with an object. Even when used within the class, there are good reasons to define a method as static when it could be.
There are two cases.
Called from within the same class
Just write the static method name. Eg:
// Called from inside the MyUtils class
double avgAtt = mean(attendance);
Called from outside the class
If a method (static or instance) is called from another class, something must be given before the method name to specify the class where the method is defined. For instance methods, this is the object that the method will access. For static methods, the class name should be specified. Eg:
// Called from outside the MyUtils class.
double avgAtt = MyUtils.mean(attendance);
If an object is specified before it, the object value will be ignored and the the class of the object will be used.
Altho a static
method can't access instance variables, it can access static
variables. A common use of static variables is to define "constants". Examples from the Java library are Math.PI
or Color.RED
. They are qualified with the class name, so you know they are static
. Any method, static
or not, can access static
variables. Instance variables can be accessed only by instance methods.
What's a little peculiar, and not recommended, is that an object of a class may be used instead of the class name to access static methods. This is bad because it creates the impression that some instance variables in the object are used, but this isn't the case.
char
is a primitive type, and it can hold a single character.
String
is instead a reference type, thus a full-blown object. It can hold any number of characters
(internally, String
objects save them in a char
array).
Primitive types in Java have advantages in term of speed and memory footprint. But they are not real objects, so there are some possibilities you lose using them. They cannot be used as Generic type parameters, they could not have methods or fields, and so on.
However, every Java primitive type has a corresponding full-blown object, and the conversion between them is done automagically by the compiler (this is called autoboxing).
You can for example do:
int i=12;
Integer l=i;
The compiler takes care of converting the int
to a Integer
.
if you need to limit download rate, use this code !!
<?php
$local_file = 'file.zip';
$download_file = 'name.zip';
// set the download rate limit (=> 20,5 kb/s)
$download_rate = 20.5;
if(file_exists($local_file) && is_file($local_file))
{
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($local_file));
header('Content-Disposition: filename='.$download_file);
flush();
$file = fopen($local_file, "r");
while(!feof($file))
{
// send the current file part to the browser
print fread($file, round($download_rate * 1024));
// flush the content to the browser
flush();
// sleep one second
sleep(1);
}
fclose($file);}
else {
die('Error: The file '.$local_file.' does not exist!');
}
?>
For more information click here
Working on a project I was stuck for some time on this concept - I ended up with a similar answer to Method 1 by @GSerg that worked great. Essentially I defined two formula ranges (using a few variables) and then used the Union concept. My example is from a larger project that I'm working on but hopefully the portion of code below can help some other people who might not know how to use the Union concept in conjunction with defined ranges and variables. I didn't include the entire code because at this point it's fairly long - if anyone wants more insight feel free to let me know.
First I declared all my variables as Public
Then I defined/set each variable
Lastly I set a new variable "SelectRanges" as the Union between the two other FormulaRanges
Public r As Long
Public c As Long
Public d As Long
Public FormulaRange3 As Range
Public FormulaRange4 As Range
Public SelectRanges As Range
With Sheet8
c = pvt.DataBodyRange.Columns.Count + 1
d = 3
r = .Cells(.Rows.Count, 1).End(xlUp).Row
Set FormulaRange3 = .Range(.Cells(d, c + 2), .Cells(r - 1, c + 2))
FormulaRange3.NumberFormat = "0"
Set FormulaRange4 = .Range(.Cells(d, c + c + 2), .Cells(r - 1, c + c + 2))
FormulaRange4.NumberFormat = "0"
Set SelectRanges = Union(FormulaRange3, FormulaRange4)
You can. Transparent canvas can be quickly faded by using destination-out global composite operation. It's not 100% perfect, sometimes it leaves some traces but it could be tweaked, depending what's needed (i.e. use 'source-over' and fill it with white color with alpha at 0.13, then fade to prepare the canvas).
// Fill canvas using 'destination-out' and alpha at 0.05
ctx.globalCompositeOperation = 'destination-out';
ctx.fillStyle = "rgba(255, 255, 255, 0.05)";
ctx.beginPath();
ctx.fillRect(0, 0, width, height);
ctx.fill();
// Set the default mode.
ctx.globalCompositeOperation = 'source-over';
on delete button click event
public void delete(View v){
ListView listview1;
ArrayList<E> datalist;
final int position = listview1.getPositionForView((View) v.getParent());
datalist.remove(position);
myAdapter.notifyDataSetChanged();
}
Let's say you have the DLLs build for both platforms, and they are in the following location:
C:\whatever\x86\whatever.dll
C:\whatever\x64\whatever.dll
You simply need to edit your .csproj file from this:
<HintPath>C:\whatever\x86\whatever.dll</HintPath>
To this:
<HintPath>C:\whatever\$(Platform)\whatever.dll</HintPath>
You should then be able to build your project targeting both platforms, and MSBuild will look in the correct directory for the chosen platform.
Here comes a rather obsqure idea. When every year dividable with 100 gets 365 days, what shall be done at this time? In the far future, when even years dividable with 400 only can get 365 days.
Then there is a possibility or reason to make corrections in years dividable with 80. Normal years will have 365 day and those dividable with 400 can get 366 days. Or is this a loose-loose situation.
Go to Tools
-> Java Platforms
. There, click on Add Platform, point it to C:\Program Files (x86)\Java\jdk1.6.0_25
. You can either set the another JDK version or remove existing versions.
Another solution suggested in the oracle (sun) site is,
netbeans.exe --jdkhome "C:\Program Files\jdk1.6.0_20"
I tried this on 6.9.1. You may change the JDK per project as well. You need to set the available JDKs via Java Platforms
dialog. Then, go to Run
-> Set Project Configuration
-> Customize
.
After that, in the opened Dialog box go to Build
-> Compile
. Set the version.
There are multiple ways of doing that you can use either place
or grid
or even the pack
method.
Sample code:
from tkinter import *
root = Tk()
l = Label(root, text="hello" )
l.pack(padx=6, pady=4) # where padx and pady represent the x and y axis respectively
# well you can also use side=LEFT inside the pack method of the label widget.
To place a widget to on basis of columns and rows , use the grid method:
but = Button(root, text="hello" )
but.grid(row=0, column=1)
ObjectReader reader = new ObjectMapper().readerFor(Map.class);
Map<String, String> map = reader.readValue("{\"foo\":\"val\"}");
Note that reader
instance is Thread Safe.
Posting a note here for users looking into this into the future. Google's libphonenumber
is what you most likely would want to use. There is wrappers for PHP, node.js, Java, etc. to use the data which Google has been collecting and reduces the requirements for maintaining large arrays of regex patterns to apply.
With HttpClient 4.5 you can do this:
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(new PoolingHttpClientConnectionManager()).build();
Note that this one implements Closeable (for shutting down of the connection manager).
It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:
#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))
In this example, the order of the factor will be the same as in the data.csv
file.
If you prefer a different order, you can order them by hand:
data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))
However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.
I know it's an old question, but I needed this solution too, and I acme with another solution.
I used an entrypoint.sh to execute the following line, and define a variable with the actual hostname for that instance:
HOST=`hostname --fqdn`
Then, I used it across my entrypoint script:
echo "Value: $HOST"
Hope this helps
I presume you've got validate_required() function from this page: http://www.w3schools.com/js/js_form_validation.asp?
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}
In this case your last condition will not work as you expect it.
You can replace it with this:
if (password.value != cpassword.value) {
alert("Your password and confirmation password do not match.");
cpassword.focus();
return false;
}
Inheritance is when a 'class' derives from an existing 'class'. So if you have a Person
class, then you have a Student
class that extends Person
, Student
inherits all the things that Person
has. There are some details around the access modifiers you put on the fields/methods in Person, but that's the basic idea. For example, if you have a private field on Person
, Student
won't see it because its private, and private fields are not visible to subclasses.
Polymorphism deals with how the program decides which methods it should use, depending on what type of thing it has. If you have a Person
, which has a read
method, and you have a Student
which extends Person
, which has its own implementation of read
, which method gets called is determined for you by the runtime, depending if you have a Person
or a Student
. It gets a bit tricky, but if you do something like
Person p = new Student();
p.read();
the read method on Student gets called. Thats the polymorphism in action. You can do that assignment because a Student
is a Person
, but the runtime is smart enough to know that the actual type of p
is Student.
Note that details differ among languages. You can do inheritance in javascript for example, but its completely different than the way it works in Java.
This is works faster than 0.1 milliseconds.
return (b >> bitNumber) & 1;
In Eclipse Photon navigate to Windows > Preferences > Maven > User Settings > User Setting
For "User settings" Browse to the settings.xml of the maven. ex. in my case maven it is located on the path C:\Program Files\Apache Software Distribution\apache-maven-3.5.4\conf\Settings.xml
Depending on the Settings.xml the Local Repository gets automatically configured to the specified location.
You can also rotate the ImageView
using a RotateAnimation
:
RotateAnimation rotateAnimation = new RotateAnimation(from, to,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
rotateAnimation.setInterpolator(new LinearInterpolator());
rotateAnimation.setDuration(ANIMATION_DURATION);
rotateAnimation.setFillAfter(true);
imageView.startAnimation(rotateAnimation);
rows and cols are required attributes, so you should have them whether you really need them or not. They set the number of rows and number of columns respectively.
Heard you can do this in postman:
Another simple way I found for using in LAN is
ssh [username@ip] uname -n
If you need to login command line will be
sshpass -p "[password]" ssh [username@ip] uname -n
How I solved this issue: 1. Be connected to the internet. 2. Open the Anaconda Prompt (looks like a regular command window). If you installed the .exe in your /name/user/ location you should be fine, if not navigate to it. Then start an environment.
conda info --envs
Then run
conda install -c anaconda anaconda-navigator
Press y when prompted (if prompted). It will being downloading the packages needed.
Then run your newly installed Anaconda Navigator
anaconda-navigator
It should start, and also appear in your regular windows 10 apps list.
The line you found just looks for the environmental variable PORT
, if it's defined it uses it, otherwise uses the default port 3000
. You have to define this environmental variable first (no need to be root)
export PORT=8080
node <your-app.js>
This solution is somewhat similar to the answer by Erwin Brandstetter, but uses only the sql language.
Not all PostgreSQL installations has the plpqsql language by default, this means you may have to call CREATE LANGUAGE plpgsql
before creating the function, and afterwards have to remove the language again, to leave the database in the same state as it was before (but only if the database did not have the plpgsql language to begin with). See how the complexity grows?
Adding the plpgsql may not be issue if you are running your script locally, however, if the script is used to set up schema at a customer it may not be desirable to leave changes like this in the customers database.
This solution is inspired by a post by Andreas Scherbaum.
-- Function which creates table
CREATE OR REPLACE FUNCTION create_table () RETURNS TEXT AS $$
CREATE TABLE table_name (
i int
);
SELECT 'extended_recycle_bin created'::TEXT;
$$
LANGUAGE 'sql';
-- Test if table exists, and if not create it
SELECT CASE WHEN (SELECT true::BOOLEAN
FROM pg_catalog.pg_tables
WHERE schemaname = 'public'
AND tablename = 'table_name'
) THEN (SELECT 'success'::TEXT)
ELSE (SELECT create_table())
END;
-- Drop function
DROP FUNCTION create_table();
The big-O notation has a companion called small-o notation. The big-O notation says the one function is asymptotical no more than
another. To say that one function is asymptotically less than
another, we use small-o notation. The difference between the big-O and small-o notations is analogous to the difference between <= (less than equal) and < (less than).
I'd guess that Remove
and Substring
would tie for first place, since they both slurp up a fixed-size portion of the string, whereas TrimStart
does a scan from the left with a test on each character and then has to perform exactly the same work as the other two methods. Seriously, though, this is splitting hairs.
I've been using ClosedXML and it works great!
ClosedXML makes it easier for developers to create Excel 2007/2010 files. It provides a nice object oriented way to manipulate the files (similar to VBA) without dealing with the hassles of XML Documents. It can be used by any .NET language like C# and Visual Basic (VB).
Here is another simpler way to check that.
$memory_limit = return_bytes(ini_get('memory_limit'));
if ($memory_limit < (64 * 1024 * 1024)) {
// Memory insufficient
}
/**
* Converts shorthand memory notation value to bytes
* From http://php.net/manual/en/function.ini-get.php
*
* @param $val Memory size shorthand notation string
*/
function return_bytes($val) {
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
$val = substr($val, 0, -1);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}
Fully example to demonstrate how jQuery query all data in HTML table.
Assume there is a table like the following in your HTML code.
<table id="someTable">
<thead>
<tr>
<td>title 0</td>
<td>title 1</td>
<td>title 2</td>
</tr>
</thead>
<tbody>
<tr>
<td>row 0 td 0</td>
<td>row 0 td 1</td>
<td>row 0 td 2</td>
</tr>
<tr>
<td>row 1 td 0</td>
<td>row 1 td 1</td>
<td>row 1 td 2</td>
</tr>
<tr>
<td>row 2 td 0</td>
<td>row 2 td 1</td>
<td>row 2 td 2</td>
</tr>
<tr> ... </tr>
<tr> ... </tr>
...
<tr> ... </tr>
<tr>
<td>row n td 0</td>
<td>row n td 1</td>
<td>row n td 2</td>
</tr>
</tbody>
</table>
Then, The Answer, the code to print all row all column, should like this
$('#someTable tbody tr').each( (tr_idx,tr) => {
$(tr).children('td').each( (td_idx, td) => {
console.log( '[' +tr_idx+ ',' +td_idx+ '] => ' + $(td).text());
});
});
After running the code, the result will show
[0,0] => row 0 td 0
[0,1] => row 0 td 1
[0,2] => row 0 td 2
[1,0] => row 1 td 0
[1,1] => row 1 td 1
[1,2] => row 1 td 2
[2,0] => row 2 td 0
[2,1] => row 2 td 1
[2,2] => row 2 td 2
...
[n,0] => row n td 0
[n,1] => row n td 1
[n,2] => row n td 2
Summary.
In the code,
tr_idx is the row index start from 0.
td_idx is the column index start from 0.
From this double-loop code,
you can get all loop-index and data in each td cell after comparing the Answer's source code and the output result.
Floating hint EditText:
Add below dependency in gradle:
compile 'com.android.support:design:22.2.0'
In layout:
<android.support.design.widget.TextInputLayout
android:id="@+id/text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="UserName"/>
</android.support.design.widget.TextInputLayout>
From the MDN docs on Function.prototype.bind()
:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
So, what does that mean?!
Well, let's take a function that looks like this :
var logProp = function(prop) {
console.log(this[prop]);
};
Now, let's take an object that looks like this :
var Obj = {
x : 5,
y : 10
};
We can bind our function to our object like this :
Obj.log = logProp.bind(Obj);
Now, we can run Obj.log
anywhere in our code :
Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10
This works, because we bound the value of this
to our object Obj
.
Where it really gets interesting, is when you not only bind a value for this
, but also for its argument prop
:
Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');
We can now do this :
Obj.logX(); // Output : 5
Obj.logY(); // Output : 10
Unlike with Obj.log
, we do not have to pass x
or y
, because we passed those values when we did our binding.
You add your ActionListener
twice to button
. So correct your code for button2
to
JButton button2 = new JButton("hello agin2");
panel.add(button2);
button2.addActionListener (new Action2());//note the button2 here instead of button
Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater
You should be able to use the @()
expression syntax:
<a class="@(User.Identity.IsAuthenticated ? "auth" : "anon")">My link here</a>
I used the page-checkout.php template to change the header for my cart page. I renamed it to page-cart.php in my /wp-content/themes/childtheme/woocommerce/. This gives you more control over the wrapping html, header and footer.
I have expanded on the previous suggestions. This works for me, with multiple radios coupled by the same name.
$("input[type='radio']").click(function()
{
var previousValue = $(this).attr('previousValue');
var name = $(this).attr('name');
if (previousValue == 'checked')
{
$(this).removeAttr('checked');
$(this).attr('previousValue', false);
}
else
{
$("input[name="+name+"]:radio").attr('previousValue', false);
$(this).attr('previousValue', 'checked');
}
});
To select properties a
AND b
of a X
element:
X[a][b]
To select properties a
OR b
of a X
element:
X[a],X[b]
There is now a handy guide for configuring PHP debugging in Visual Studio Code at http://blogs.msdn.com/b/nicktrog/archive/2016/02/11/configuring-visual-studio-code-for-php-development.aspx
From the link, the steps are:
Note there are specific details in the linked article, including the PHP values for your VS Code user config, and so on.
hope this helps
select DeptName from DEPARTMENT inner join EMPLOYEE using (DeptId) where Salary>1000 group by DeptName having count(*)>2
That message is usually an indication that some of your files have modification times later than the current system time. Since make
decides which files to compile when performing an incremental build by checking if a source files has been modified more recently than its object file, this situation can cause unnecessary files to be built, or worse, necessary files to not be built.
However, if you are building from scratch (not doing an incremental build) you can likely ignore this warning without consequence.
Modern Spring 5+ answer using WebClient
instead of RestTemplate
.
Configure WebClient
for a specific web-service or resource as a bean (additional properties can be configured).
@Bean
public WebClient localApiClient() {
return WebClient.create("http://localhost:8080/api/v3");
}
Inject and use the bean from your service(s).
@Service
public class UserService {
private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(3);
private final WebClient localApiClient;
@Autowired
public UserService(WebClient localApiClient) {
this.localApiClient = localApiClient;
}
public User getUser(long id) {
return localApiClient
.get()
.uri("/users/" + id)
.retrieve()
.bodyToMono(User.class)
.block(REQUEST_TIMEOUT);
}
}
sudo service mysql stop;
sudo service mysql start;
If the above process will not work let's check one the given code above you can stop Mysql server and again start server
You need to use Arrow function ()=>
ES6 feature to preserve this
context within setTimeout
.
// var that = this; // no need of this line
this.messageSuccess = true;
setTimeout(()=>{ //<<<---using ()=> syntax
this.messageSuccess = false;
}, 3000);
Grab the params from location.search with one line:
const params = new Map(this.props.location.search.slice(1).split('&').map(param => param.split('=')))
Then, simply:
if(params.get("year")){
//year exists. do something...
} else {
//year doesn't exist. do something else...
}
You can not make reference to static variable from non-static method. To understand this , you need to understand the difference between static and non-static.
Static variables are class variables , they belong to class with their only one instance , created at the first only. Non-static variables are initialized every time you create an object of the class.
Now coming to your question, when you use new() operator we will create copy of every non-static filed for every object, but it is not the case for static fields. That's why it gives compile time error if you are referencing a static variable from non-static method.
Easiest way is to turn the list to tuple
first
t = tuple(l)
query = "select name from studens where id IN {}".format(t)
Maybe it is not quite as elegant, but the following might also work. I suspect asynchronously this would not be a good solution.
$p = Start-Process myjob.bat -redirectstandardoutput $logtempfile -redirecterroroutput $logtempfile -wait
add-content $logfile (get-content $logtempfile)
Verified remedy from earlier postings:
1) Checked that the libhadoop.so.1.0.0
shipped with the Hadoop distribution was compiled for my machine architecture, which is x86_64:
[nova]:file /opt/hadoop-2.6.0/lib/native/libhadoop.so.1.0.0
/opt/hadoop-2.6.0/lib/native/libhadoop.so.1.0.0: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=3a80422c78d708c9a1666c1a8edd23676ed77dbb, not stripped
2) Added -Djava.library.path=<path>
to HADOOP_OPT
in hadoop-env.sh
:
export HADOOP_OPTS="$HADOOP_OPTS -Djava.net.preferIPv4Stack=true -Djava.library.path=/opt/hadoop-2.6.0/lib/native"
This indeed made the annoying warning disappear.
I could have used RegEx, they can provide elegant solution but they can cause performane issues. Here is one solution
char[] arr = str.ToCharArray();
arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c)
|| char.IsWhiteSpace(c)
|| c == '-')));
str = new string(arr);
When using the compact framework (which doesn't have FindAll)
Replace FindAll with1
char[] arr = str.Where(c => (char.IsLetterOrDigit(c) ||
char.IsWhiteSpace(c) ||
c == '-')).ToArray();
str = new string(arr);
char *a = new char[10];
My question is that how can I get the length of a char *
It is very simply.:) It is enough to add only one statement
size_t N = 10;
char *a = new char[N];
Now you can get the size of the allocated array
std::cout << "The size is " << N << std::endl;
Many mentioned here C standard function std::strlen. But it does not return the actual size of a character array. It returns only the size of stored string literal.
The difference is the following. if to take your code snippet as an example
char a[] = "aaaaa";
int length = sizeof(a)/sizeof(char); // length=6
then std::strlen( a ) will return 5 instead of 6 as in your code.
So the conclusion is simple: if you need to dynamically allocate a character array consider usage of class std::string
. It has methof size and its synonym length that allows to get the size of the array at any time.
For example
std::string s( "aaaaa" );
std::cout << s.length() << std::endl;
or
std::string s;
s.resize( 10 );
std::cout << s.length() << std::endl;
A function call cannot appear in a constant expression.
try this: (just an example)
#include <map>
#include <iostream>
using std::map;
using std::cout;
class myClass{
public:
static map<int,int> create_map()
{
map<int,int> m;
m[1] = 2;
m[3] = 4;
m[5] = 6;
return m;
}
const static map<int,int> myMap;
};
const map<int,int>myClass::myMap = create_map();
int main(){
map<int,int> t=myClass::create_map();
std::cout<<t[1]; //prints 2
}
I got the same exception. what i do to fix this is to pass instance of the dialog as parameter into function and use it instead of pass only context then using getContext(). this solution solve my problem, hope it can help
Output on Ubuntu 9.10 -> Ubuntu 12.04 with mono 2.10.8.1:
SpecialFolder.ApplicationData: /home/$USER/.config
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.ProgramFiles:
SpecialFolder.DesktopDirectory: /home/$USER/Desktop
SpecialFolder.LocalApplicationData: /home/$USER/.local/share
SpecialFolder.MyDocuments: /home/$USER
SpecialFolder.System:
SpecialFolder.Personal: /home/$USER
Output on Ubuntu 16.04 with mono 4.2.1
SpecialFolder.ApplicationData: /home/$USER/.config
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.ProgramFiles:
SpecialFolder.DesktopDirectory: /home/$USER/Desktop
SpecialFolder.LocalApplicationData: /home/$USER/.local/share
SpecialFolder.MyDocuments: /home/$USER
SpecialFolder.Desktop: /home/$USER/Desktop
SpecialFolder.Personal: /home/$USER
SpecialFolder.System:
SpecialFolder.Programs:
SpecialFolder.Favorites:
SpecialFolder.Startup:
SpecialFolder.Recent:
SpecialFolder.SendTo:
SpecialFolder.StartMenu:
SpecialFolder.MyMusic: /home/$USER/Music
SpecialFolder.MyVideos: /home/$USER/Videos
SpecialFolder.MyComputer:
SpecialFolder.NetworkShortcuts:
SpecialFolder.Fonts: /home/$USER/.fonts
SpecialFolder.Templates: /home/$USER/Templates
SpecialFolder.CommonStartMenu:
SpecialFolder.CommonPrograms:
SpecialFolder.CommonStartup:
SpecialFolder.CommonDesktopDirectory:
SpecialFolder.PrinterShortcuts:
SpecialFolder.InternetCache:
SpecialFolder.Cookies:
SpecialFolder.History:
SpecialFolder.Windows:
SpecialFolder.MyPictures: /home/$USER/Pictures
SpecialFolder.UserProfile: /home/$USER
SpecialFolder.SystemX86:
SpecialFolder.ProgramFilesX86:
SpecialFolder.CommonProgramFiles:
SpecialFolder.CommonProgramFilesX86:
SpecialFolder.CommonTemplates: /usr/share/templates
SpecialFolder.CommonDocuments:
SpecialFolder.CommonAdminTools:
SpecialFolder.AdminTools:
SpecialFolder.CommonMusic:
SpecialFolder.CommonPictures:
SpecialFolder.CommonVideos:
SpecialFolder.Resources:
SpecialFolder.LocalizedResources:
SpecialFolder.CommonOemLinks:
SpecialFolder.CDBurning:
where $USER is the current user
Output on Ubuntu 16.04 using dotnet core (3.0.100)
ApplicationData: /home/$USER/.config
CommonApplicationData: /usr/share
ProgramFiles:
DesktopDirectory: /home/$USER/Desktop
LocalApplicationData: /home/$USER/.local/share
MyDocuments: /home/$USER
System:
Personal: /home/$USER
Output on Android 6 using Xamarin 7.2
Environment.SpecialFolder.ApplicationData: /data/user/0/$APPNAME/files/.config
Environment.SpecialFolder.CommonApplicationData: /usr/share
Environment.SpecialFolder.ProgramFiles:
Environment.SpecialFolder.DesktopDirectory: /data/user/0/$APPNAME/files/Desktop
Environment.SpecialFolder.LocalApplicationData: /data/user/0/$APPNAME/files/.local/share
Environment.SpecialFolder.MyDocuments: /data/user/0/$APPNAME/files
Environment.SpecialFolder.Desktop: /data/user/0/$APPNAME/files/Desktop
Environment.SpecialFolder.Personal: /data/user/0/$APPNAME/files
Environment.SpecialFolder.Startup:
Environment.SpecialFolder.Recent:
Environment.SpecialFolder.SendTo:
Environment.SpecialFolder.StartMenu:
Environment.SpecialFolder.MyMusic: /data/user/0/$APPNAME/files/Music
Environment.SpecialFolder.MyVideos: /data/user/0/$APPNAME/files/Videos
Environment.SpecialFolder.MyComputer:
Environment.SpecialFolder.NetworkShortcuts:
Environment.SpecialFolder.Fonts: /data/user/0/$APPNAME/files/.fonts
Environment.SpecialFolder.Templates: /data/user/0/$APPNAME/files/Templates
Environment.SpecialFolder.CommonStartMenu:
Environment.SpecialFolder.CommonPrograms:
Environment.SpecialFolder.CommonStartup:
Environment.SpecialFolder.CommonDesktopDirectory:
Environment.SpecialFolder.PrinterShortcuts:
Environment.SpecialFolder.InternetCache:
Environment.SpecialFolder.Cookies:
Environment.SpecialFolder.History:
Environment.SpecialFolder.Windows:
Environment.SpecialFolder.MyPictures: /data/user/0/$APPNAME/files/Pictures
Environment.SpecialFolder.UserProfile: /data/user/0/$APPNAME/files
Environment.SpecialFolder.SystemX86:
Environment.SpecialFolder.ProgramFilesX86:
Environment.SpecialFolder.CommonProgramFiles:
Environment.SpecialFolder.CommonProgramFilesX86:
Environment.SpecialFolder.CommonTemplates: /usr/share/templates
Environment.SpecialFolder.CommonDocuments:
Environment.SpecialFolder.CommonAdminTools:
Environment.SpecialFolder.AdminTools:
Environment.SpecialFolder.CommonMusic:
Environment.SpecialFolder.CommonPictures:
Environment.SpecialFolder.CommonVideos:
Environment.SpecialFolder.Resources:
Environment.SpecialFolder.LocalizedResources:
Environment.SpecialFolder.CommonOemLinks:
Environment.SpecialFolder.CDBurning:
Where $APPNAME is the name of your Xamarin application (eg. MyApp.Droid)
Output on iOS Simulator 10.3 using Xamarin 7.2
ApplicationData: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/.config
CommonApplicationData: /usr/share
ProgramFiles: /Applications
DesktopDirectory: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Desktop
LocalApplicationData: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents
MyDocuments: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents
Desktop: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Desktop
MyDocuments: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents
Startup:
Recent:
SendTo:
StartMenu:
MyMusic: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Music
MyVideos: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Videos
MyComputer:
NetworkShortcuts:
Fonts: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/.fonts
Templates: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Templates
CommonStartMenu:
CommonPrograms:
CommonStartup:
CommonDesktopDirectory:
PrinterShortcuts:
InternetCache: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Library/Caches
Cookies:
History:
Windows:
MyPictures: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Documents/Pictures
UserProfile: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID
SystemX86:
ProgramFilesX86:
CommonProgramFiles:
CommonProgramFilesX86:
CommonTemplates: /usr/share/templates
CommonDocuments:
CommonAdminTools:
AdminTools:
CommonMusic:
CommonPictures:
CommonVideos:
Resources: /Users/$USER/Library/Developer/CoreSimulator/Devices/$DEVICEGUID/data/Containers/Data/Application/$APPLICATIONGUID/Library
LocalizedResources:
CommonOemLinks:
CDBurning:
Where $DEVICEGUID is the simulator GUID (depending on the selected simulator)
Output on ipad 10.3 using Xamarin 7.2
SpecialFolder.MyDocuments: /var/mobile/Containers/Data/Application/$APPLICATIONGUID/Documents
Output on ipad 13.3 using Xamarin 16.4
SpecialFolder.MyDocuments: /var/mobile/Containers/Data/Application/$APPLICATIONGUID/Documents
SpecialFolder.UserProfile: /private/var/mobile/Containers/Data/Application/$APPLICATIONGUID/Documents
Output on windows 10 using .net core 3.1
SpecialFolder.MyDocuments: C:\Users\$USER\Documents
Output on Ubuntu 18.04 using .net core 3.1
SpecialFolder.MyDocuments: /home/$USER
Output on MacOS Catalina using .net core 3.1
SpecialFolder.MyDocuments: /Users/$USER
I created an enhanced version, based on Trey Copland's fiddle, that I think is more like what you wanted. Added here for future reference to those who come here later. Fiddle example
<body>
<style>
.modal {
height: 390px;
border: 5px solid green;
}
.heading {
padding: 10px;
}
.content {
height: 300px;
overflow:auto;
border: 5px solid red;
}
.scrollable {
height: 1200px;
border: 5px solid yellow;
}
.footer {
height: 2em;
padding: .5em;
}
</style>
<div class="modal">
<div class="heading">
<h4>Heading</h4>
</div>
<div class="content">
<div class="scrollable" >hello</div>
</div>
<div class="footer">
Footer
</div>
</div>
</body>
It’s very easy with Z shell (zsh) globs:
wc -l ./**/*.php
If you are using Bash, you just need to upgrade. There is absolutely no reason to use Bash.
Store a unique salt for the user (generated from username + email for example), and store a password. On login, get the salt from database and hash salt + password.
Use bcrypt to hash the passwords.
Simple! Add at the end of dockerfile:
ENTRYPOINT service mysql start && /bin/bash
Just hit on this when trying to solve this type of thing my self.
I did a selector that deals with the element after being something other than a p.
.here .is.the #selector h4 + * {...}
Hope this helps anyone who finds it :)
For your current structure, you could also try the following:
select cash.Country, cash.Value, cheque.Value, cash.Value + cheque.Value as [Total]
from Cash
join Cheque
on cash.Country = cheque.Country
I think I prefer a union between the two tables, and a group by on the country name as mentioned above.
But I would also recommend normalising your tables. Ideally you'd have a country table, with Id and Name, and a payments table with: CountryId (FK to countries), Total, Type (cash/cheque)
This is a relatively new update, but it is much more straight forward. If you are using Jest 24.9.0 or higher you can just add testTimeout
to your config:
// in jest.config.js
module.exports = {
testTimeout: 30000
}
Here is how I do it and works both for create and edit:
//How to do it with enums
<div class="editor-field">
@Html.RadioButtonFor(x => x.gender, (int)Gender.Male) Male
@Html.RadioButtonFor(x => x.gender, (int)Gender.Female) Female
</div>
//And with Booleans
<div class="editor-field">
@Html.RadioButtonFor(x => x.IsMale, true) Male
@Html.RadioButtonFor(x => x.IsMale, false) Female
</div>
the provided values (true and false) are the values that the engine will render as the values for the html element i.e.:
<input id="IsMale" type="radio" name="IsMale" value="True">
<input id="IsMale" type="radio" name="IsMale" value="False">
And the checked property is dependent on the Model.IsMale value.
Razor engine seems to internally match the set radio button value to your model value, if a proper from and to string convert exists for it. So there is no need to add it as an html attribute in the helper method.
You can type:
grep -v -f A1 A2
Use this 'Split' function:
CREATE OR REPLACE FUNCTION Split (p_str varchar2) return sys_refcursor is
v_res sys_refcursor;
begin
open v_res for
WITH TAB AS
(SELECT p_str STR FROM DUAL)
select substr(STR, instr(STR, ',', 1, lvl) + 1, instr(STR, ',', 1, lvl + 1) - instr(STR, ',', 1, lvl) - 1) name
from
( select ',' || STR || ',' as STR from TAB ),
( select level as lvl from dual connect by level <= 100 )
where lvl <= length(STR) - length(replace(STR, ',')) - 1;
return v_res;
end;
You can't use this function in select statement like you described in question, but I hope you will find it still useful.
EDIT: Here are steps you need to do. 1. Create Object: create or replace type empy_type as object(value varchar2(512)) 2. Create Type: create or replace type t_empty_type as table of empy_type 3. Create Function:
CREATE OR REPLACE FUNCTION Split (p_str varchar2) return sms.t_empty_type is
v_emptype t_empty_type := t_empty_type();
v_cnt number := 0;
v_res sys_refcursor;
v_value nvarchar2(128);
begin
open v_res for
WITH TAB AS
(SELECT p_str STR FROM DUAL)
select substr(STR, instr(STR, ',', 1, lvl) + 1, instr(STR, ',', 1, lvl + 1) - instr(STR, ',', 1, lvl) - 1) name
from
( select ',' || STR || ',' as STR from TAB ),
( select level as lvl from dual connect by level <= 100 )
where lvl <= length(STR) - length(replace(STR, ',')) - 1;
loop
fetch v_res into v_value;
exit when v_res%NOTFOUND;
v_emptype.extend;
v_cnt := v_cnt + 1;
v_emptype(v_cnt) := empty_type(v_value);
end loop;
close v_res;
return v_emptype;
end;
Then just call like this:
SELECT * FROM (TABLE(split('a,b,c,d,g')))
Not as elegant perhaps as other approaches but it's pretty solid and easy to follow, esp. for people newer to Java. One thing that gets me about the String class is this: It's been around for a very long time and while it supports a global replace with regexp and a global replace with Strings (via CharSequences), that last doesn't have a simple boolean parameter: 'isCaseInsensitive'. Really, you'd've thought that just by adding that one little switch, all the trouble its absence causes for beginners especially could have been avoided. Now on JDK 7, String still doesn't support this one little addition!
Well anyway, I'll stop griping. For everyone in particular newer to Java, here's your cut-and-paste deus ex machina. As I said, not as elegant and won't win you any slick coding prizes, but it works and is reliable. Any comments, feel free to contribute. (Yes, I know, StringBuffer is probably a better choice of managing the two character string mutation lines, but it's easy enough to swap the techniques.)
public String replaceAll(String findtxt, String replacetxt, String str,
boolean isCaseInsensitive) {
if (str == null) {
return null;
}
if (findtxt == null || findtxt.length() == 0) {
return str;
}
if (findtxt.length() > str.length()) {
return str;
}
int counter = 0;
String thesubstr = "";
while ((counter < str.length())
&& (str.substring(counter).length() >= findtxt.length())) {
thesubstr = str.substring(counter, counter + findtxt.length());
if (isCaseInsensitive) {
if (thesubstr.equalsIgnoreCase(findtxt)) {
str = str.substring(0, counter) + replacetxt
+ str.substring(counter + findtxt.length());
// Failing to increment counter by replacetxt.length() leaves you open
// to an infinite-replacement loop scenario: Go to replace "a" with "aa" but
// increment counter by only 1 and you'll be replacing 'a's forever.
counter += replacetxt.length();
} else {
counter++; // No match so move on to the next character from
// which to check for a findtxt string match.
}
} else {
if (thesubstr.equals(findtxt)) {
str = str.substring(0, counter) + replacetxt
+ str.substring(counter + findtxt.length());
counter += replacetxt.length();
} else {
counter++;
}
}
}
return str;
}
I had a same kind of issue starting Genymotion on Ubuntu 16.04 and solved it in this way https://medium.com/@avanvitharana/genymotion-on-ubuntu-16-04-cb8ef8fc70e9#.6y0bgmmjb
You can use the accept attribute along with the . It doesn't work in IE and Safari.
Depending on your project scale and extensibility, you could use Struts. Struts offers two ways to limit the uploaded file type, declaratively and programmatically.
For more information: http://struts.apache.org/2.0.14/docs/file-upload.html#FileUpload-FileTypes
The way I solved my issue I am sure it will helps you too:
1.If you don't have any Edit Text-box in your fragment you can use below code
Here MainHomeFragment is main Fragment (When I press back button from second fragment it will take me too MainHomeFragment)
@Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
MainHomeFragment mainHomeFragment = new SupplierHomeFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, mainHomeFragment);
fragmentTransaction.commit();
return true;
}
return false;
}
}); }
2.If you have another fragment named as Somefragment and it has Edit text-box then you can do it by this way.
private EditText editText;
Then In,
onCreateView():
editText = (EditText) view.findViewById(R.id.editText);
Then Override OnResume,
@Override
public void onResume() {
super.onResume();
editText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
editTextOFS.clearFocus();
getView().requestFocus();
}
return false;
}
});
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
MainHomeFragment mainHomeFragment = new SupplierHomeFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, mainHomeFragment);
fragmentTransaction.commit();
return true;
}
return false;
}
});
}
That's all folks (amitamie.com) :-) ;-)
Mail.dll email component includes email template engine:
Here's the syntax overview:
<html>
<body>
Hi {FirstName} {LastName},
Here are your orders:
{foreach Orders}
Order '{Name}' sent to <strong>{Street}</strong>.
{end}
</body>
</html>
And the code that loads the template, fills data from c# object and sends an email:
Mail.Html(Template
.FromFile("template.txt")
.DataFrom(_contact)
.Render())
.Text("This is text version of the message.")
.From(new MailBox("[email protected]", "Alice"))
.To(new MailBox("[email protected]", "Bob"))
.Subject("Your order")
.UsingNewSmtp()
.WithCredentials("[email protected]", "password")
.Server("mail.com")
.WithSSL()
.Send();
You can get more info on email template engine blog post.
Or just download Mail.dll email component and give it a try.
Please note that this is a commercial product I've created.
I solved this problem by adding Newtonsoft.Json to the NuGet of the startup project.
For casting varchar fields/values to number format can be little hack used:
SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`
And if we want to align a checkbox to the right, we can use item-end.
<ion-checkbox checked="true" item-end></ion-checkbox>
If you presenting a controller without a Navigation Controller, you can call the following code from a method of the presented controller.
self.presentingViewController?.dismiss(animated: true, completion: nil)
If your ViewController is presented modally, optional presentingViewController will be not nil and the code will be executed.
See nodemailer's official guide to connecting Gmail:
https://community.nodemailer.com/using-gmail/
-
It works for me after doing this:
Like this:
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary) # {'a': 1, 'b': 2, 'c': 3}
Voila :-) The pairwise dict
constructor and zip
function are awesomely useful.
Can I control the HTTP headers sent by window.open (cross browser)?
No
If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window?
I need some cunning hacks...
It might help if you described the problem instead of asking if possible solutions would work.
High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.
LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.
Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.
As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.
Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.
You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:
In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file"
field, ostensibly for backward compatibility reasons.
So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.
With library(lubridate)
, numeric representations of date and time saved as the number of seconds since
1970-01-01 00:00:00 UTC, can be coerced into dates with as_datetime()
:
lubridate::as_datetime(1352068320)
[1] "2012-11-04 22:32:00 UTC"
One possibility is the next:
console.log([1, 2, 3].map(e => Math.random().toString(36).slice(2)).join('').split('').map(e => Math.random() > 0.5 ? e.toUpperCase() : e).join(''));
For anyone getting this exception while reading data from the stream, this may help. I was getting this exception when reading the HttpResponseMessage in a loop like this:
using (var remoteStream = await response.Content.ReadAsStreamAsync())
using (var content = File.Create(DownloadPath))
{
var buffer = new byte[1024];
int read;
while ((read = await remoteStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
await content.WriteAsync(buffer, 0, read);
await content.FlushAsync();
}
}
After some time I found out the culprit was the buffer size, which was too small and didn't play well with my weak Azure instance. What helped was to change the code to:
using (Stream remoteStream = await response.Content.ReadAsStreamAsync())
using (FileStream content = File.Create(DownloadPath))
{
await remoteStream.CopyToAsync(content);
}
CopyTo() method has a default buffer size of 81920. The bigger buffer sped up the process and the errors stopped immediately, most likely because the overall download speeds increased. But why would download speed matter in preventing this error?
It is possible that you get disconnected from the server because the download speeds drop below minimum threshold the server is configured to allow. For example, in case the application you are downloading the file from is hosted on IIS, it can be a problem with http.sys configuration:
"Http.sys is the http protocol stack that IIS uses to perform http communication with clients. It has a timer called MinBytesPerSecond that is responsible for killing a connection if its transfer rate drops below some kb/sec threshold. By default, that threshold is set to 240 kb/sec."
The issue is described in this old blogpost from TFS development team and concerns IIS specifically, but may point you in a right direction. It also mentions an old bug related to this http.sys attribute: link
In case you are using Azure app services and increasing the buffer size does not eliminate the problem, try to scale up your machine as well. You will be allocated more resources including connection bandwidth.
Let's say you have a tag someplace on the page which contains your loading message:
<div id='loadingmessage' style='display:none'>
<img src='loadinggraphic.gif'/>
</div>
You can add two lines to your ajax call:
function getData(p){
var page=p;
$('#loadingmessage').show(); // show the loading message.
$.ajax({
url: "loadData.php?id=<? echo $id; ?>",
type: "POST",
cache: false,
data: "&page="+ page,
success : function(html){
$(".content").html(html);
$('#loadingmessage').hide(); // hide the loading message
}
});
Perl is a context-based language. It doesn't do its work according to the data you give it. Instead, it figures out how to treat the data based on the operators you use and the context in which you use them. If you do numbers sorts of things, you get numbers:
# numeric addition with strings:
my $sum = '5.45' + '0.01'; # 5.46
If you do strings sorts of things, you get strings:
# string replication with numbers:
my $string = ( 45/2 ) x 4; # "22.522.522.522.5"
Perl mostly figures out what to do and it's mostly right. Another way of saying the same thing is that Perl cares more about the verbs than it does the nouns.
Are you trying to do something and it isn't working?
If there were a tie at the fourth position for mtcars$mpg then this should return all the ties:
top_mpg <- mtcars[ mtcars$mpg >= mtcars$mpg[order(mtcars$mpg, decreasing=TRUE)][4] , ]
> top_mpg
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
Since there is a tie at the 3-4 position you can test it by changing 4 to a 3, and it still returns 4 items. This is logical indexing and you might need to add a clause that removes the NA's or wrap which() around the logical expression. It's not much more difficult to do this "by" cyl:
Reduce(rbind, by(mtcars, mtcars$cyl,
function(d) d[ d$mpg >= d$mpg[order(d$mpg, decreasing=TRUE)][4] , ]) )
#-------------
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3
Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3
Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2
Incorporating my suggestion to @Ista:
Reduce(rbind, by(mtcars, mtcars$cyl, function(d) d[ d$mpg <= sort( d$mpg )[3] , ]) )
WARNING: contains sarcasm judiciously! YMMV...
Luigi's answer is complete and correct. This one is only to extend it a bit with an example of how you can gloriously overuse implicits, as it happens quite often in Scala projects. Actually so often, you can probably even find it in one of the "Best Practice" guides.
object HelloWorld {
case class Text(content: String)
case class Prefix(text: String)
implicit def String2Text(content: String)(implicit prefix: Prefix) = {
Text(prefix.text + " " + content)
}
def printText(text: Text): Unit = {
println(text.content)
}
def main(args: Array[String]): Unit = {
printText("World!")
}
// Best to hide this line somewhere below a pile of completely unrelated code.
// Better yet, import its package from another distant place.
implicit val prefixLOL = Prefix("Hello")
}
There seems to be a problem with some versions of R
and libcurl
. I have had the same problem on Mac (R version 3.2.2)
and Ubuntu (R version 3.0.2)
and in both instances it was resolved simply by running this before the install.packages
command
options(download.file.method = "wget")
The solution was suggested by a friend, however, I haven't been able to find it in any of the forums, hence submitting this answer for others.
inside the Android manifest file of your project, find the activity declaration of whose you want to fix the orientation and add the following piece of code ,
android:screenOrientation="landscape"
for landscape orientation and for portrait add the following code,
android:screenOrientation="portrait"
solution for swift 3 -
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
titleLabel.text = "change to red color"
titleLabel.textAlignment = .center
titleLabel.textColor = UIColor.red
Today 2021.01.14 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v84 for chosen solutions.
For all browsers
I perform 2 tests cases:
Below snippet presents solutions Aa Ab Ba Bb Ca Cb Da Db E F
// https://stackoverflow.com/questions/10398931/how-to-strToRemove-text-from-a-string
// https://stackoverflow.com/a/10398941/860099
function Aa(str,strToRemove) {
return str.replace(strToRemove,'');
}
// https://stackoverflow.com/a/63362111/860099
function Ab(str,strToRemove) {
return str.replaceAll(strToRemove,'');
}
// https://stackoverflow.com/a/23539019/860099
function Ba(str,strToRemove) {
let re = strToRemove.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // regexp escape char
return str.replace(new RegExp(re),'');
}
// https://stackoverflow.com/a/63362111/860099
function Bb(str,strToRemove) {
let re = strToRemove.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // regexp escape char
return str.replaceAll(new RegExp(re,'g'),'');
}
// https://stackoverflow.com/a/27098801/860099
function Ca(str,strToRemove) {
let start = str.indexOf(strToRemove);
return str.slice(0,start) + str.slice(start+strToRemove.length, str.length);
}
// https://stackoverflow.com/a/27098801/860099
function Cb(str,strToRemove) {
let start = str.search(strToRemove);
return str.slice(0,start) + str.slice(start+strToRemove.length, str.length);
}
// https://stackoverflow.com/a/23181792/860099
function Da(str,strToRemove) {
let start = str.indexOf(strToRemove);
return str.substr(0, start) + str.substr(start + strToRemove.length);
}
// https://stackoverflow.com/a/23181792/860099
function Db(str,strToRemove) {
let start = str.search(strToRemove);
return str.substr(0, start) + str.substr(start + strToRemove.length);
}
// https://stackoverflow.com/a/49857431/860099
function E(str,strToRemove) {
return str.split(strToRemove).join('');
}
// https://stackoverflow.com/a/45406624/860099
function F(str,strToRemove) {
var n = str.search(strToRemove);
while (str.search(strToRemove) > -1) {
n = str.search(strToRemove);
str = str.substring(0, n) + str.substring(n + strToRemove.length, str.length);
}
return str;
}
let str = "data-123";
let strToRemove = "data-";
[Aa,Ab,Ba,Bb,Ca,Cb,Da,Db,E,F].map( f=> console.log(`${f.name.padEnd(2,' ')} ${f(str,strToRemove)}`));
_x000D_
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
And here are example results for chrome
Try using the command: git status
I had the same problem. If you have installed first nodejs by apt and then you use the tar.gz from nodejs.org, you have to delete the folder located in /usr/lib/node_modules
.
Any definition is valid. As long as you are consistent in your implementation (always put equal nodes to the right, always put them to the left, or never allow them) then you're fine. I think it is most common to not allow them, but it is still a BST if they are allowed and place either left or right.
The bug you reference (bug 4787391) has been fixed in Java 8. Even if you are using an older version of Java, the System.getProperty("user.home")
approach is probably still the best. The user.home
approach seems to work in a very large number of cases. A 100% bulletproof solution on Windows is hard, because Windows has a shifting concept of what the home directory means.
If user.home
isn't good enough for you I would suggest choosing a definition of home directory
for windows and using it, getting the appropriate environment variable with System.getenv(String)
.