You could consider using CDYNE's PAV-I API that validates international addresses. international-address-verification They cover over 240 countries, so it should cover all of the countries that you are looking to validate for.
Through empirical testing and observation, as well as confirming with https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation, here is my version of a Python regex that correctly parses and validates a UK postcode:
UK_POSTCODE_REGEX = r'(?P<postcode_area>[A-Z]{1,2})(?P<district>(?:[0-9]{1,2})|(?:[0-9][A-Z]))(?P<sector>[0-9])(?P<postcode>[A-Z]{2})'
This regex is simple and has capture groups. It does not include all of the validations of legal UK postcodes, but only takes into account the letter vs number positions.
Here is how I would use it in code:
@dataclass
class UKPostcode:
postcode_area: str
district: str
sector: int
postcode: str
# https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation
# Original author of this regex: @jontsai
# NOTE TO FUTURE DEVELOPER:
# Verified through empirical testing and observation, as well as confirming with the Wiki article
# If this regex fails to capture all valid UK postcodes, then I apologize, for I am only human.
UK_POSTCODE_REGEX = r'(?P<postcode_area>[A-Z]{1,2})(?P<district>(?:[0-9]{1,2})|(?:[0-9][A-Z]))(?P<sector>[0-9])(?P<postcode>[A-Z]{2})'
@classmethod
def from_postcode(cls, postcode):
"""Parses a string into a UKPostcode
Returns a UKPostcode or None
"""
m = re.match(cls.UK_POSTCODE_REGEX, postcode.replace(' ', ''))
if m:
uk_postcode = UKPostcode(
postcode_area=m.group('postcode_area'),
district=m.group('district'),
sector=m.group('sector'),
postcode=m.group('postcode')
)
else:
uk_postcode = None
return uk_postcode
def parse_uk_postcode(postcode):
"""Wrapper for UKPostcode.from_postcode
"""
uk_postcode = UKPostcode.from_postcode(postcode)
return uk_postcode
Here are unit tests:
@pytest.mark.parametrize(
'postcode, expected', [
# https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation
(
'EC1A1BB',
UKPostcode(
postcode_area='EC',
district='1A',
sector='1',
postcode='BB'
),
),
(
'W1A0AX',
UKPostcode(
postcode_area='W',
district='1A',
sector='0',
postcode='AX'
),
),
(
'M11AE',
UKPostcode(
postcode_area='M',
district='1',
sector='1',
postcode='AE'
),
),
(
'B338TH',
UKPostcode(
postcode_area='B',
district='33',
sector='8',
postcode='TH'
)
),
(
'CR26XH',
UKPostcode(
postcode_area='CR',
district='2',
sector='6',
postcode='XH'
)
),
(
'DN551PT',
UKPostcode(
postcode_area='DN',
district='55',
sector='1',
postcode='PT'
)
)
]
)
def test_parse_uk_postcode(postcode, expected):
uk_postcode = parse_uk_postcode(postcode)
assert(uk_postcode == expected)
If someone is still interested in how to validate zip codes I've found a solution:
Using Google Geocoding API
we can check validity of ZIP code having both Country code and a ZIP code itself.
For example I live in Ukraine so I can check like this: https://maps.googleapis.com/maps/api/geocode/json?components=postal_code:80380|country:UA
Or using JS API: https://developers.google.com/maps/documentation/javascript/geocoding#ComponentFiltering
Where 80380
is valid ZIP for Ukraine, actually every (#####) is valid.
Google returns ZERO_RESULTS
status if nothing found.
Or OK
and a result if both are correct.
Hope this will be helpful.
oneline with jquery
$('<a>').attr('href', document.location.href).prop('hostname');
Bootstrap offers various table styles. Have a look at Base CSS - Tables for documentation and examples.
The following style gives great looking tables:
<table class="table table-striped table-bordered table-condensed">
...
</table>
This is a simple solution:
Example 1
my $var1 = "123abc";
print $var1 + 0;
Result
123
Example 2
my $var2 = "abc123";
print $var2 + 0;
Result
0
The key lies in the differences between references and instances and what the reference can promise and what the instance can really do.
ArrayList<A> a = new ArrayList<A>();
Here a
is a reference to an instance of a specific type - exactly an array list of A
s. More explicitly, a
is a reference to an array list that will accept A
s and will produce A
s. new ArrayList<A>()
is an instance of an array list of A
s, that is, an array list that will accept A
s and will produce A
s.
ArrayList<Integer> a = new ArrayList<Number>();
Here, a
is a reference to exactly an array list of Integers
, i.e. exactly an array list that can accept Integer
s and will produce Integer
s. It cannot point to an array list of Number
s. That array list of Number
s can not meet all the promises of ArrayList<Integer> a
(i.e. an array list of Number
s may produce objects that are not Integer
s, even though its empty right then).
ArrayList<Number> a = new ArrayList<Integer>();
Here, declaration of a
says that a
will refer to exactly an array list of Number
s, that is, exactly an array list that will accept Number
s and will produce Number
s. It cannot point to an array list of Integer
s, because the type declaration of a
says that a
can accept any Number
, but that array list of Integer
s cannot accept just any Number
, it can only accept Integer
s.
ArrayList<? extends Object> a= new ArrayList<Object>();
Here a
is a (generic) reference to a family of types rather than a reference to a specific type. It can point to any list that is member of that family. However, the trade-off for this nice flexible reference is that they cannot promise all of the functionality that it could if it were a type-specific reference (e.g. non-generic). In this case, a
is a reference to an array list that will produce Object
s. But, unlike a type-specific list reference, this a
reference cannot accept any Object
. (i.e. not every member of the family of types that a
can point to can accept any Object
, e.g. an array list of Integer
s can only accept Integer
s.)
ArrayList<? super Integer> a = new ArrayList<Number>();
Again, a
is a reference to a family of types (rather than a single specific type). Since the wildcard uses super
, this list reference can accept Integer
s, but it cannot produce Integer
s. Said another way, we know that any and every member of the family of types that a
can point to can accept an Integer
. However, not every member of that family can produce Integer
s.
PECS - Producer extends
, Consumer super
- This mnemonic helps you remember that using extends
means the generic type can produce the specific type (but cannot accept it). Using super
means the generic type can consume (accept) the specific type (but cannot produce it).
ArrayList<ArrayList<?>> a
An array list that holds references to any list that is a member of a family of array lists types.
= new ArrayList<ArrayList<?>>(); // correct
An instance of an array list that holds references to any list that is a member of a family of array lists types.
ArrayList<?> a
An reference to any array list (a member of the family of array list types).
= new ArrayList<?>()
ArrayList<?>
refers to any type from a family of array list types, but you can only instantiate a specific type.
See also How can I add to List<? extends Number> data structures?
Mixing plyr::mutate
and dplyr::case_when
works for me and is readable.
iris %>%
plyr::mutate(coolness =
dplyr::case_when(Species == "setosa" ~ "not cool",
Species == "versicolor" ~ "not cool",
Species == "virginica" ~ "super awesome",
TRUE ~ "undetermined"
)) -> testIris
head(testIris)
levels(testIris$coolness) ## NULL
testIris$coolness <- as.factor(testIris$coolness)
levels(testIris$coolness) ## ok now
testIris[97:103,4:6]
Bonus points if the column can come out of mutate as a factor instead of char! The last line of the case_when statement, which catches all un-matched rows is very important.
Petal.Width Species coolness
97 1.3 versicolor not cool
98 1.3 versicolor not cool
99 1.1 versicolor not cool
100 1.3 versicolor not cool
101 2.5 virginica super awesome
102 1.9 virginica super awesome
103 2.1 virginica super awesome
You can do it like this:
In your main view controller:
func showModal() {
let modalViewController = ModalViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
presentViewController(modalViewController, animated: true, completion: nil)
}
In your modal view controller:
class ModalViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.clearColor()
view.opaque = false
}
}
If you are working with a storyboard:
Just add a Storyboard Segue with Kind
set to Present Modally
to your modal view controller and on this view controller set the following values:
As Crashalot pointed out in his comment: Make sure the segue only uses Default
for both Presentation
and Transition
. Using Current Context
for Presentation
makes the modal turn black instead of remaining transparent.
You should leave out the domain http://example.com
in ProxyPass and ProxyPassReverse and leave it as /
. Additionally, you need to leave the /
at the end of example/
to where it is redirecting. Also, I had some trouble with http://example.com
vs. http://www.example.com
- only the www worked until I made the ServerName www.example.com, and the ServerAlias example.com. Give the following a go.
<VirtualHost *:80>
ProxyPreserveHost On
ProxyRequests Off
ServerName www.example.com
ServerAlias example.com
ProxyPass / http://localhost:8080/example/
ProxyPassReverse / http://localhost:8080/example/
</VirtualHost>
After you make these changes, add the needed modules and restart apache
sudo a2enmod proxy && sudo a2enmod proxy_http && sudo service apache2 restart
Shorter way is do it as follows:
private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
The proper way to do it is probably to break down the method by putting the try-catch block in a separate method, and use a return statement:
public void someMethod() {
try {
...
if (condition)
return;
...
} catch (SomeException e) {
...
}
}
If the code involves lots of local variables, you may also consider using a break
from a labeled block, as suggested by Stephen C:
label: try {
...
if (condition)
break label;
...
} catch (SomeException e) {
...
}
Try this (It's a nasty solution but It may work):
In the onCreate
method of your Activity
or in the onViewCreated
method of your fragment. Set a callback ready to be triggered when the RecyclerView
first render, like this:
vRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
calculeRecyclerViewFullHeight();
}
});
In the calculeRecyclerViewFullHeight
calculate the RecyclerView
full height based in the height of its children.
protected void calculateSwipeRefreshFullHeight() {
int height = 0;
for (int idx = 0; idx < getRecyclerView().getChildCount(); idx++ ) {
View v = getRecyclerView().getChildAt(idx);
height += v.getHeight();
}
SwipeRefreshLayout.LayoutParams params = getSwipeRefresh().getLayoutParams();
params.height = height;
getSwipeRefresh().setLayoutParams(params);
}
In my case my RecyclerView
is contain in a SwipeRefreshLayout
for that reason I'm setting the height to the SwipeRefreshView
and not to the RecyclerView
but if you don't have any SwipeRefreshView
then you can set the height to the RecyclerView
instead.
Let me know if this helped you or not.
The first answer will print a string with prefix b'. That means your string will be like this b'your_string' To solve this issue please add the following line of code.
encoded_string= base64.b64encode(img_file.read())
print(encoded_string.decode('utf-8'))
No difference here, but it matters when you have a type that has a constructor.
struct S {
constexpr S(int);
};
const S s0(0);
constexpr S s1(1);
s0
is a constant, but it does not promise to be initialized at compile-time. s1
is marked constexpr
, so it is a constant and, because S
's constructor is also marked constexpr
, it will be initialized at compile-time.
Mostly this matters when initialization at runtime would be time-consuming and you want to push that work off onto the compiler, where it's also time-consuming, but doesn't slow down execution time of the compiled program
You could also speed things up with a while
loop (see here: http://jsperf.com/javascript-while-vs-for-loops). Also much more terse and legible IMHO:
i = 10
while(i--)
//- iterate here
div= i
What you can do...
Create a new Instance Profile / Role that has the AmazonEC2RoleForSSM policy attached.
Attach this Instance Profile to the instance.
Use https://prestodb.io/docs/current/connector/kafka-tutorial.html
A super SQL engine, provided by Facebook, that connects on several data sources (Cassandra, Kafka, JMX, Redis ...).
PrestoDB is running as a server with optional workers (there is a standalone mode without extra workers), then you use a small executable JAR (called presto CLI) to make queries.
Once you have configured well the Presto server , you can use traditionnal SQL:
SELECT count(*) FROM TOPIC_NAME;
Note that iPhone 6 will use the 320pt (640px) resolution if you have enabled the 'Display Zoom' in iPhone > Settings > Display & Brightness > View.
You can avoid the loop and cut etc by using:
awk -F ':' '{system("ping " $1);}' config.txt
However it would be better if you post a snippet of your config.txt
I hope help you.
/// <summary>
/// Get the integer part of any decimal number passed trough a string
/// </summary>
/// <param name="decimalNumber">String passed</param>
/// <returns>teh integer part , 0 in case of error</returns>
private int GetIntPart(String decimalNumber)
{
if(!Decimal.TryParse(decimalNumber, NumberStyles.Any , new CultureInfo("en-US"), out decimal dn))
{
MessageBox.Show("String " + decimalNumber + " is not in corret format", "GetIntPart", MessageBoxButtons.OK, MessageBoxIcon.Error);
return default(int);
}
return Convert.ToInt32(Decimal.Truncate(dn));
}
FileNotFound
is just an unfortunate exception used to indicate that the web server returned a 404.
Square brackets:
jsObj['key' + i] = 'example' + 1;
In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length
property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0"
, "5"
, "207"
, and so on, are all treated specially in that their existence determines the value of length
. And, on top of that, the value of length
can be set to remove such properties. Setting the length
of an array to 0
effectively removes all properties whose names look like whole numbers.
OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ]
operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.
Thus, the way the [ ]
operator works in a for
loop iterating through an array:
for (var i = 0; i < myArray.length; ++i) {
var value = myArray[i]; // property access
// ...
}
is really no different from the way [ ]
works when accessing a property whose name is some computed string:
var value = jsObj["key" + i];
The [ ]
operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.
When setting property values using [ ]
, the story is the same except for the special behavior around maintaining the length
property. If you set a property with a numeric key on an array instance:
myArray[200] = 5;
then (assuming that "200" is the biggest numeric property name) the length
property will be updated to 201
as a side-effect of the property assignment. If the same thing is done to a plain object, however:
myObj[200] = 5;
there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5
in otherwise the exact same way.
One might think that because that length
behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length
but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:
var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;
var objJSON = JSON.stringify(obj);
the value of "objJSON" will be a string containing just ["hello world"]
; the "something" property will be lost.
If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:
var key = 'DYNAMIC_KEY',
obj = {
[key]: 'ES6!'
};
console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }
My favorite class, runs any method on another thread with just 2 lines of code.
class ThreadedExecuter<T> where T : class
{
public delegate void CallBackDelegate(T returnValue);
public delegate T MethodDelegate();
private CallBackDelegate callback;
private MethodDelegate method;
private Thread t;
public ThreadedExecuter(MethodDelegate method, CallBackDelegate callback)
{
this.method = method;
this.callback = callback;
t = new Thread(this.Process);
}
public void Start()
{
t.Start();
}
public void Abort()
{
t.Abort();
callback(null); //can be left out depending on your needs
}
private void Process()
{
T stuffReturned = method();
callback(stuffReturned);
}
}
usage
void startthework()
{
ThreadedExecuter<string> executer = new ThreadedExecuter<string>(someLongFunction, longFunctionComplete);
executer.Start();
}
string someLongFunction()
{
while(!workComplete)
WorkWork();
return resultOfWork;
}
void longFunctionComplete(string s)
{
PrintWorkComplete(s);
}
Beware that longFunctionComplete will NOT execute on the same thread as starthework.
For methods that take parameters you can always use closures, or expand the class.
ME.find({pictures: {$exists: true}})
Simple as that, this worked for me.
html
<textarea id="wmd-input" name="md-content"></textarea>
js
var textarea = $('#wmd-input'),
top = textarea.scrollTop(),
height = textarea.height();
if(top > 0){
textarea.css("height",top + height)
}
css
#wmd-input{
width: 100%;
overflow: hidden;
padding: 10px;
}
How about:
foreach(var s in listBox1.Items.ToArray())
{
MessageBox.Show(s);
//do stuff with (s);
listBox1.Items.Remove(s);
}
The ToArray makes a copy of the list, so you don't need to worry about it changing the list while you are processing it.
DateTime is a value type, which is why it can't be null. You can check for it to be equal to DateTime.MinValue
, or you can use Nullable(Of DateTime)
instead.
VB sometimes "helpfully" makes you think it's doing something it's not. When it lets you set a Date to Nothing, it's really setting it to some other value, maybe MinValue.
See this question for an extensive discussion of value types vs. reference types.
You can also make it work with RelativeLayout
. This reduces layout nesting a little bit ;)
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="@+id/toolbar"
layout="@layout/toolbar" />
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/toolbar" />
<View
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_below="@id/toolbar"
android:background="@drawable/toolbar_shadow" />
</RelativeLayout>
function resize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
render();
}
window.addEventListener('resize', resize, false); resize();
function render() { // draw to screen here
}
If the browser has a pdf plugin installed it executes the object, if not it uses Google's PDF Viewer to display it as plain HTML:
<object data="your_url_to_pdf" type="application/pdf">
<iframe src="https://docs.google.com/viewer?url=your_url_to_pdf&embedded=true"></iframe>
</object>
Debug symbols (.pdb) and XML doc (.xml) files make up a large percentage of the total size and should not be part of the regular deployment package. But it should be possible to access them in case they are needed.
One possible approach: at the end of the TFS build process, move them to a separate artifact.
I discovered in Bootstrap 4 you can do this:
center horizontal is indeed text-center
class
center vertical however using bootstrap classes is adding both mb-auto mt-auto
so that margin-top and margin bottom are set to auto.
Simple and effective.
Eslint 6.7.0 brought "ignorePatterns" to write it in .eslintrc.json like this example:
{
"ignorePatterns": ["fileToBeIgnored.js"],
"rules": {
//...
}
}
I found the following command to run from command line:
vlc.exe --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt
If anyone stumbles across this as it is the first result in google,
remember to specify the filename too in the SaveAs method.
Won't work
file_upload.PostedFile.SaveAs(Server.MapPath(SaveLocation));
You need this:
filename = Path.GetFileName(file_upload.PostedFile.FileName);
file_upload.PostedFile.SaveAs(Server.MapPath(SaveLocation + "\\" + filename));
I assumed the SaveAs method will automatically use the filename uploaded. Kept getting "Access denied" error. Not very descriptive of the actual problem
You can also do the following;
string json = myJObject.ToString(Newtonsoft.Json.Formatting.None);
One issue I noticed that could cause errors is that in rrichter's answer, the code below:
<img src="b.jpg" style="position: absolute; top: 30; left: 70;"/>
should include the px units within the style eg.
<img src="b.jpg" style="position: absolute; top: 30px; left: 70px;"/>
Other than that, the answer worked fine. Thanks.
Step 1: Add the submodule
git submodule add git://some_repository.git some_repository
Step 2: Fix the submodule to a particular commit
By default the new submodule will be tracking HEAD of the master branch, but it will NOT be updated as you update your primary repository. In order to change the submodule to track a particular commit or different branch, change directory to the submodule folder and switch branches just like you would in a normal repository.
git checkout -b some_branch origin/some_branch
Now the submodule is fixed on the development branch instead of HEAD of master.
From Two Guys Arguing — Tie Git Submodules to a Particular Commit or Branch .
I would try something like this for a Trim function that takes into account all white-space characters defined by the Unicode Standard (LTRIM and RTRIM do not even trim new-line characters!):
IF OBJECT_ID(N'dbo.IsWhiteSpace', N'FN') IS NOT NULL_x000D_
DROP FUNCTION dbo.IsWhiteSpace;_x000D_
GO_x000D_
_x000D_
-- Determines whether a single character is white-space or not (according to the UNICODE standard)._x000D_
CREATE FUNCTION dbo.IsWhiteSpace(@c NCHAR(1)) RETURNS BIT_x000D_
BEGIN_x000D_
IF (@c IS NULL) RETURN NULL;_x000D_
DECLARE @WHITESPACE NCHAR(31);_x000D_
SELECT @WHITESPACE = ' ' + NCHAR(13) + NCHAR(10) + NCHAR(9) + NCHAR(11) + NCHAR(12) + NCHAR(133) + NCHAR(160) + NCHAR(5760) + NCHAR(8192) + NCHAR(8193) + NCHAR(8194) + NCHAR(8195) + NCHAR(8196) + NCHAR(8197) + NCHAR(8198) + NCHAR(8199) + NCHAR(8200) + NCHAR(8201) + NCHAR(8202) + NCHAR(8232) + NCHAR(8233) + NCHAR(8239) + NCHAR(8287) + NCHAR(12288) + NCHAR(6158) + NCHAR(8203) + NCHAR(8204) + NCHAR(8205) + NCHAR(8288) + NCHAR(65279);_x000D_
IF (CHARINDEX(@c, @WHITESPACE) = 0) RETURN 0;_x000D_
RETURN 1;_x000D_
END_x000D_
GO_x000D_
_x000D_
IF OBJECT_ID(N'dbo.Trim', N'FN') IS NOT NULL_x000D_
DROP FUNCTION dbo.Trim;_x000D_
GO_x000D_
_x000D_
-- Removes all leading and tailing white-space characters. NULL is converted to an empty string._x000D_
CREATE FUNCTION dbo.Trim(@TEXT NVARCHAR(MAX)) RETURNS NVARCHAR(MAX)_x000D_
BEGIN_x000D_
-- Check tiny strings (NULL, 0 or 1 chars)_x000D_
IF @TEXT IS NULL RETURN N'';_x000D_
DECLARE @TEXTLENGTH INT = LEN(@TEXT);_x000D_
IF @TEXTLENGTH < 2 BEGIN_x000D_
IF (@TEXTLENGTH = 0) RETURN @TEXT;_x000D_
IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, 1, 1)) = 1) RETURN '';_x000D_
RETURN @TEXT;_x000D_
END_x000D_
-- Check whether we have to LTRIM/RTRIM_x000D_
DECLARE @SKIPSTART INT;_x000D_
SELECT @SKIPSTART = dbo.IsWhiteSpace(SUBSTRING(@TEXT, 1, 1));_x000D_
DECLARE @SKIPEND INT;_x000D_
SELECT @SKIPEND = dbo.IsWhiteSpace(SUBSTRING(@TEXT, @TEXTLENGTH, 1));_x000D_
DECLARE @INDEX INT;_x000D_
IF (@SKIPSTART = 1) BEGIN_x000D_
IF (@SKIPEND = 1) BEGIN_x000D_
-- FULLTRIM_x000D_
-- Determine start white-space length_x000D_
SELECT @INDEX = 2;_x000D_
WHILE (@INDEX < @TEXTLENGTH) BEGIN -- Hint: The last character is already checked_x000D_
-- Stop loop if no white-space_x000D_
IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
-- Otherwise assign index as @SKIPSTART_x000D_
SELECT @SKIPSTART = @INDEX;_x000D_
-- Increase character index_x000D_
SELECT @INDEX = (@INDEX + 1);_x000D_
END_x000D_
-- Return '' if the whole string is white-space_x000D_
IF (@SKIPSTART = (@TEXTLENGTH - 1)) RETURN ''; _x000D_
-- Determine end white-space length_x000D_
SELECT @INDEX = (@TEXTLENGTH - 1);_x000D_
WHILE (@INDEX > 1) BEGIN _x000D_
-- Stop loop if no white-space_x000D_
IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
-- Otherwise increase @SKIPEND_x000D_
SELECT @SKIPEND = (@SKIPEND + 1);_x000D_
-- Decrease character index_x000D_
SELECT @INDEX = (@INDEX - 1);_x000D_
END_x000D_
-- Return trimmed string_x000D_
RETURN SUBSTRING(@TEXT, @SKIPSTART + 1, @TEXTLENGTH - @SKIPSTART - @SKIPEND);_x000D_
END _x000D_
-- LTRIM_x000D_
-- Determine start white-space length_x000D_
SELECT @INDEX = 2;_x000D_
WHILE (@INDEX < @TEXTLENGTH) BEGIN -- Hint: The last character is already checked_x000D_
-- Stop loop if no white-space_x000D_
IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
-- Otherwise assign index as @SKIPSTART_x000D_
SELECT @SKIPSTART = @INDEX;_x000D_
-- Increase character index_x000D_
SELECT @INDEX = (@INDEX + 1);_x000D_
END_x000D_
-- Return trimmed string_x000D_
RETURN SUBSTRING(@TEXT, @SKIPSTART + 1, @TEXTLENGTH - @SKIPSTART);_x000D_
END ELSE BEGIN_x000D_
-- RTRIM_x000D_
IF (@SKIPEND = 1) BEGIN_x000D_
-- Determine end white-space length_x000D_
SELECT @INDEX = (@TEXTLENGTH - 1);_x000D_
WHILE (@INDEX > 1) BEGIN _x000D_
-- Stop loop if no white-space_x000D_
IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
-- Otherwise increase @SKIPEND_x000D_
SELECT @SKIPEND = (@SKIPEND + 1);_x000D_
-- Decrease character index_x000D_
SELECT @INDEX = (@INDEX - 1);_x000D_
END_x000D_
-- Return trimmed string_x000D_
RETURN SUBSTRING(@TEXT, 1, @TEXTLENGTH - @SKIPEND);_x000D_
END _x000D_
END_x000D_
-- NO TRIM_x000D_
RETURN @TEXT;_x000D_
END_x000D_
GO
_x000D_
I tried install a lib that depends lxml
and nothing works. I see a message when build was started: "Building without Cython", so after install cython
with apt-get install cython
, lxml
was installed.
I am able to download it using apple's download website today. https://developer.apple.com/download/
I do not have a paid apple developer account. Before I was only able to see xcode 8.3.3 but somehow today xcode 9 beta also appeared.
There's a flag for that:
In [11]: df = pd.DataFrame([["foo1"], ["foo2"], ["bar"], [np.nan]], columns=['a'])
In [12]: df.a.str.contains("foo")
Out[12]:
0 True
1 True
2 False
3 NaN
Name: a, dtype: object
In [13]: df.a.str.contains("foo", na=False)
Out[13]:
0 True
1 True
2 False
3 False
Name: a, dtype: bool
See the str.replace
docs:
na : default NaN, fill value for missing values.
So you can do the following:
In [21]: df.loc[df.a.str.contains("foo", na=False)]
Out[21]:
a
0 foo1
1 foo2
You could write a method that would do it directly via sql I suppose.
Would look something like this:
Variables:
$store_id = 1;
$product_id = 1234;
$attribute_code = 'manufacturer';
Query:
SELECT value FROM eav_attribute_option_value WHERE option_id IN (
SELECT option_id FROM eav_attribute_option WHERE FIND_IN_SET(
option_id,
(SELECT value FROM catalog_product_entity_varchar WHERE
entity_id = '$product_id' AND
attribute_id = (SELECT attribute_id FROM eav_attribute WHERE
attribute_code='$attribute_code')
)
) > 0) AND
store_id='$store_id';
You would have to get the value from the correct table based on the attribute's backend_type (field in eav_attribute) though so it takes at least 1 additional query.
Put quotes around the <?php echo $cname; ?>
to make sure Javascript accepts it as a string, also consider escaping.
Find root build.gradle
file and add google maven repo inside allprojects
tag
repositories {
mavenLocal()
mavenCentral()
maven { // <-- Add this
url 'https://maven.google.com/'
name 'Google'
}
}
It's better to use specific version instead of variable version
compile 'com.android.support:appcompat-v7:27.0.0'
If you're using Android Plugin for Gradle 3.0.0 or latter version
repositories {
mavenLocal()
mavenCentral()
google() //---> Add this
}
and inject dependency in this way :
implementation 'com.android.support:appcompat-v7:27.0.0'
In Unicode the answer is not easily given. The problem, as you already pointed out, are the encodings.
Given any English sentence without diacritic characters, the answer for UTF-8 would be as many bytes as characters and for UTF-16 it would be number of characters times two.
The only encoding where (as of now) we can make the statement about the size is UTF-32. There it's always 32bit per character, even though I imagine that code points are prepared for a future UTF-64 :)
What makes it so difficult are at least two things:
U+20AC
can be represented either as three-byte sequence E2 82 AC
or four-byte sequence F0 82 82 AC
.To add a prefix to all files and folders in the current directory using util-linux's rename
(as opposed to prename
, the perl variant from Debian and certain other systems), you can do:
rename '' <prefix> *
This finds the first occurrence of the empty string (which is found immediately) and then replaces that occurrence with your prefix, then glues on the rest of the file name to the end of that. Done.
For suffixes, you need to use the perl version or use find.
In fact the cache location depends on the GRADLE_USER_HOME
environment variable value.
By default, it is $USER_HOME/.gradle
on Unix-OS based and %userprofile%.\gradle
on Windows.
But if you set this variable, the cache directory would be located from this path.
And whatever the case, you should dig into caches\modules-2\files-2.1
to find the dependencies.
Programmatically: Run time
You can do programmatically using setTypeface():
textView.setTypeface(null, Typeface.NORMAL); // for Normal Text
textView.setTypeface(null, Typeface.BOLD); // for Bold only
textView.setTypeface(null, Typeface.ITALIC); // for Italic
textView.setTypeface(null, Typeface.BOLD_ITALIC); // for Bold and Italic
XML: Design Time
You can set in XML as well:
android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"
Hope this will help
Summved
Using ERRORLEVEL when it's available is the easiest option. However, if you're calling an external program to perform some task, and it doesn't return proper codes, you can pipe the output to 'find' and check the errorlevel from that.
c:\mypath\myexe.exe | find "ERROR" >nul2>nul
if not ERRORLEVEL 1 (
echo. Uh oh, something bad happened
exit /b 1
)
Or to give more info about what happened
c:\mypath\myexe.exe 2&1> myexe.log
find "Invalid File" "myexe.log" >nul2>nul && echo.Invalid File error in Myexe.exe && exit /b 1
find "Error 0x12345678" "myexe.log" >nul2>nul && echo.Myexe.exe was unable to contact server x && exit /b 1
One of my favorite parts about registers is using them as macros!
Let's say you are dealing with a tab-delimited value file as such:
ID Df %Dev Lambda
1 0 0.000000 0.313682
2 1 0.023113 0.304332
3 1 0.044869 0.295261
4 1 0.065347 0.286460
5 1 0.084623 0.277922
6 1 0.102767 0.269638
7 1 0.119845 0.261601
Now you decide that you need to add a percentage sign at the end of the %Dev field (starting from 2nd line). We'll make a simple macro in the (arbitrarily selected) m
register as follows:
Press: qm
: To start recording macro under m
register.
EE
: Go to the end of the 3rd column.
a
: Insert mode to append to the end of this column.
%
: Type the percent sign we want to add.
<ESC>
: Get back into command mode.
j0
: Go to beginning of next line.
q
: Stop recording macro
We can now just type @m
to run this macro on the current line. Furthermore, we can type @@
to repeat, or 100@m
to do this 100 times! Life's looking pretty good.
At this point you should be saying, "But what does this have to do with registers?"
Excellent point. Let's investigate what is in the contents of the m
register by typing "mp
. We then get the following:
EEa%<ESC>j0
At first this looks like you accidentally opened a binary file in notepad, but upon second glance, it's the exact sequence of characters in our macro!
You are a curious person, so let's do something interesting and edit this line of text to insert a !
instead of boring old %
.
EEa!<ESC>j0
Then let's yank this into the n
register by typing B"nyE
. Then, just for kicks, let's run the n
macro on a line of our data using @n
....
It added a !
.
Essentially, running a macro is like pressing the exact sequence of keys in that macro's register. If that isn't a cool register trick, I'll eat my hat.
According to Flexbugs:
In IE 10-11,
min-height
declarations on flex containers work to size the containers themselves, but their flex item children do not seem to know the size of their parents. They act as if no height has been set at all.
Here are a couple of workarounds:
<aside>
and <section>
:html {
height: 100%;
}
body {
display: flex;
flex-direction: column;
height: 100%;
margin: 0;
}
header,
footer {
background: #7092bf;
}
main {
flex: 1;
display: flex;
}
aside, section {
overflow: auto;
}
aside {
flex: 0 0 150px;
background: #3e48cc;
}
section {
flex: 1;
background: #9ad9ea;
}
_x000D_
<header>
<p>header</p>
</header>
<main>
<aside>
<p>aside</p>
</aside>
<section>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
</section>
</main>
<footer>
<p>footer</p>
</footer>
_x000D_
html {
height: 100%;
}
body {
display: flex;
flex-direction: column;
height: 100%;
margin: 0;
}
header,
footer {
background: #7092bf;
}
main {
flex: 1 0 auto;
display: flex;
}
aside {
flex: 0 0 150px;
background: #3e48cc;
}
section {
flex: 1;
background: #9ad9ea;
}
_x000D_
<header>
<p>header</p>
</header>
<main>
<aside>
<p>aside</p>
</aside>
<section>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
</section>
</main>
<footer>
<p>footer</p>
</footer>
_x000D_
If you want to know the number of visitors (as is titled in the question) and not the number of pageviews, then you'll need to create a custom report.
Google Analytics has changed the terminology they use within the reports. Now, visits is named "sessions" and unique visitors is named "users."
User - A unique person who has visited your website. Users may visit your website multiple times, and they will only be counted once.
Session - The number of different times that a visitor came to your site.
Pageviews - The total number of pages that a user has accessed.
Not the perfect answer but works better for people using Github:
Go to your repo: Insights -> Network
Have you googled about it - insert update delete access vb.net, there are lots of reference about this.
Insert Update Delete Navigation & Searching In Access Database Using VB.NET
what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB
is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.
it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:
Example code snippet:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class DBUtil
Private connectionString As String
Public Sub New()
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=d:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
End Sub
Public Function GetCategories() As DataSet
Dim query As String = "SELECT * FROM Categories"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Categories")
End Function
Public SubUpdateCategories(ByVal name As String)
Dim query As String = "update Categories set name = 'new2' where name = ?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
Return FillDataSet(cmd, "Categories")
End Sub
Public Function GetItems() As DataSet
Dim query As String = "SELECT * FROM Items"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Items")
End Function
Public Function GetItems(ByVal categoryID As Integer) As DataSet
'Create the command.
Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("category_ID", categoryID)
'Fill the dataset.
Return FillDataSet(cmd, "Items")
End Function
Public Sub AddCategory(ByVal name As String)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Categories "
insertSQL &= "VALUES(?)"
Dim cmd As New OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Name", name)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Public Sub AddItem(ByVal title As String, ByVal description As String, _
ByVal price As Decimal, ByVal categoryID As Integer)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Items "
insertSQL &= "(Title, Description, Price, Category_ID)"
insertSQL &= "VALUES (?, ?, ?, ?)"
Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Title", title)
cmd.Parameters.AddWithValue("Description", description)
cmd.Parameters.AddWithValue("Price", price)
cmd.Parameters.AddWithValue("CategoryID", categoryID)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=D:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
con.ConnectionString = connectionString
cmd.Connection = con
Dim adapter As New OleDbDataAdapter(cmd)
Dim ds As New DataSet()
Try
con.Open()
adapter.Fill(ds, tableName)
Finally
con.Close()
End Try
Return ds
End Function
End Class
Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back
From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):
1.10 Empty Operator -
empty A
The
empty
operator is a prefix operator that can be used to determine if a value is null or empty.To evaluate
empty A
- If
A
isnull
, returntrue
- Otherwise, if
A
is the empty string, then returntrue
- Otherwise, if
A
is an empty array, then returntrue
- Otherwise, if
A
is an emptyMap
, returntrue
- Otherwise, if
A
is an emptyCollection
, returntrue
- Otherwise return
false
So, considering the interfaces, it works on Collection
and Map
only. In your case, I think Collection
is the best option. Or, if it's a Javabean-like object, then Map
. Either way, under the covers, the isEmpty()
method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException
.
i think i'd try with MAX something like this:
SELECT staff_id, max( date ) from owner.table group by staff_id
then link in your other columns:
select staff_id, site_id, pay_level, latest
from owner.table,
( SELECT staff_id, max( date ) latest from owner.table group by staff_id ) m
where m.staff_id = staff_id
and m.latest = date
Assuming you're currently on the branch you want to rename:
git branch -m newname
This is documented in the manual for git-branch
, which you can view using
man git-branch
or
git help branch
Specifically, the command is
git branch (-m | -M) [<oldbranch>] <newbranch>
where the parameters are:
<oldbranch>
The name of an existing branch to rename.
<newbranch>
The new name for an existing branch. The same restrictions as for <branchname> apply.
<oldbranch>
is optional, if you want to rename the current branch.
Try via Composer Create-Project
You may also install Laravel by issuing the Composer create-project command in your terminal:
composer create-project laravel/laravel {directory} "5.0.*" --prefer-dist
SELECT
p1.Person,
p1.`GROUP`,
p1.Age
FROM
person AS p1
WHERE
(
SELECT
COUNT( DISTINCT ( p2.age ) )
FROM
person AS p2
WHERE
p2.`GROUP` = p1.`GROUP`
AND p2.Age >= p1.Age
) < 2
ORDER BY
p1.`GROUP` ASC,
p1.age DESC
The control searches for a view in the following order:
As you do not have xxx.cshtml
in those locations, it returns a "view not found" error.
Solution: You can use the complete path of your view:
Like
PartialView("~/views/ABC/XXX.cshtml", zyxmodel);
Make sure you read SilverlightFox's answer. It highlights a more important reason.
The reason is mostly that if you know the source of a request you may want to customize it a little bit.
For instance lets say you have a website which has many recipes. And you use a custom jQuery framework to slide recipes into a container based on a link they click.
The link may be www.example.com/recipe/apple_pie
Now normally that returns a full page, header, footer, recipe content and ads. But if someone is browsing your website some of those parts are already loaded. So you can use an AJAX to get the recipe the user has selected but to save time and bandwidth don't load the header/footer/ads.
Now you can just write a secondary endpoint for the data like www.example.com/recipe_only/apple_pie
but that's harder to maintain and share to other people.
But it's easier to just detect that it is an ajax request making the request and then returning only a part of the data. That way the user wastes less bandwidth and the site appears more responsive.
The frameworks just add the header because some may find it useful to keep track of which requests are ajax and which are not. But it's entirely dependent on the developer to use such techniques.
It's actually kind of similar to the Accept-Language
header. A browser can request a website please show me a Russian version of this website without having to insert /ru/ or similar in the URL.
function configureDropDownLists(ddl1, ddl2) {_x000D_
var colours = ['Black', 'White', 'Blue'];_x000D_
var shapes = ['Square', 'Circle', 'Triangle'];_x000D_
var names = ['John', 'David', 'Sarah'];_x000D_
_x000D_
switch (ddl1.value) {_x000D_
case 'Colours':_x000D_
ddl2.options.length = 0;_x000D_
for (i = 0; i < colours.length; i++) {_x000D_
createOption(ddl2, colours[i], colours[i]);_x000D_
}_x000D_
break;_x000D_
case 'Shapes':_x000D_
ddl2.options.length = 0;_x000D_
for (i = 0; i < shapes.length; i++) {_x000D_
createOption(ddl2, shapes[i], shapes[i]);_x000D_
}_x000D_
break;_x000D_
case 'Names':_x000D_
ddl2.options.length = 0;_x000D_
for (i = 0; i < names.length; i++) {_x000D_
createOption(ddl2, names[i], names[i]);_x000D_
}_x000D_
break;_x000D_
default:_x000D_
ddl2.options.length = 0;_x000D_
break;_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
function createOption(ddl, text, value) {_x000D_
var opt = document.createElement('option');_x000D_
opt.value = value;_x000D_
opt.text = text;_x000D_
ddl.options.add(opt);_x000D_
}
_x000D_
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">_x000D_
<option value=""></option>_x000D_
<option value="Colours">Colours</option>_x000D_
<option value="Shapes">Shapes</option>_x000D_
<option value="Names">Names</option>_x000D_
</select>_x000D_
_x000D_
<select id="ddl2">_x000D_
</select>
_x000D_
1. Browser-native HTML inline embedding:
<embed
src="http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&navpanes=0&scrollbar=0"
type="application/pdf"
frameBorder="0"
scrolling="auto"
height="100%"
width="100%"
></embed>
<iframe
src="http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&navpanes=0&scrollbar=0"
frameBorder="0"
scrolling="auto"
height="100%"
width="100%"
></iframe>
Pro:
Cons:
2. Google Docs Viewer:
<iframe
src="https://drive.google.com/viewerng/viewer?embedded=true&url=http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&scrollbar=0"
frameBorder="0"
scrolling="auto"
height="100%"
width="100%"
></iframe>
Pro:
Cons:
3. Other solutions to embed PDF:
IMPORTANT NOTE:
Please check the X-Frame-Options HTTP response header. It should be SAMEORIGIN.
X-Frame-Options SAMEORIGIN;
I ran into this problem with my new Nexus 4 and an APK built with Adobe AIR. I already had android:installLocation="preferExternal" in my manifest. I noticed I was also calling adb install
with the -s
option (Install package on the shared mass storage such as sdcard.) which seemed like overkill.
Removing the -s
flag from adb install
fixed the issue for me.
I've just written a new (friendly) command line utility to do this. It doesn’t rely on Finder/AppleScript, or on any of the (deprecated) Alias Manager APIs, and it’s easy to configure and use.
Anyway, anyone who is interested can find it on PyPi; the documentation is available on Read The Docs.
For the fun of it here's an implementation based on the callback approach:
const char* find(const char* s,
const char* e,
int (*pred)(char))
{
while( s != e && !pred(*s) ) ++s;
return s;
}
void split_on_ws(const char* s,
const char* e,
void (*callback)(const char*, const char*))
{
const char* p = s;
while( s != e ) {
s = find(s, e, isspace);
callback(p, s);
p = s = find(s, e, isnotspace);
}
}
void handle_word(const char* s, const char* e)
{
// handle the word that starts at s and ends at e
}
int main()
{
split_on_ws(some_str, some_str + strlen(some_str), handle_word);
}
If you have another variable also referring to the same dictionary, there is a big difference:
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d = {}
>>> d2
{'stuff': 'things'}
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d.clear()
>>> d2
{}
This is because assigning d = {}
creates a new, empty dictionary and assigns it to the d
variable. This leaves d2
pointing at the old dictionary with items still in it. However, d.clear()
clears the same dictionary that d
and d2
both point at.
As of March 2016, pip install numpy
works on Windows without a Fortran compiler. See here.
pip install scipy
still tries to use a compiler.
July 2018: mojoken reports pip install scipy
working on Windows without a Fortran compiler.
Axios is a promise based HTTP client for the browser and node.js.
It offers automatic transforms for JSON data and it's the official recommendation from the Vue.js team when migrating from the 1.0 version which included a REST client by default.
Performing a
GET
request// Make a request for a user with a given ID axios.get('http://query.yahooapis.com/v1/publ...') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Or even just axios(url)
is enough as a GET
request is the default.
Change your append calls to say
...append(iter->first)
and
... append(iter->second)
Additionally, the line
std::string* strToReturn = new std::string("");
allocates a string on the heap. If you intend to actually return a pointer to this dynamically allocated string, the return should be changed to std::string*.
Alternatively, if you don't want to worry about managing that object on the heap, change the local declaration to
std::string strToReturn("");
and change the 'append' calls to use reference syntax...
strToReturn.append(...)
instead of
strToReturn->append(...)
Be aware that this will construct the string on the stack, then copy it into the return variable. This has performance implications.
I ran into similar problems using Python 3.4.3 & 3.5.2 and Django 1.11.3. However, when I upgraded to Python 3.6.1 the problems went away.
You can read more about it here: https://docs.python.org/3/whatsnew/3.6.html#json
If you're not tied to a specific version of Python, just consider upgrading to 3.6 or later.
<form action="" method="POST" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="file[]" multiple/>
<input type="submit" name="submit" value="Upload Image" />
</form>
Using FOR Loop
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
for ($x = 0; $x < count($_FILES['file']['name']); $x++) {
$file_name = $_FILES['file']['name'][$x];
$file_tmp = $_FILES['file']['tmp_name'][$x];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>
Using FOREACH Loop
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
foreach ($_FILES['file']['name'] as $key => $value) {
$file_name = $_FILES['file']['name'][$key];
$file_tmp = $_FILES['file']['tmp_name'][$key];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>
Lucas's answer about core dumps is good. In my .cshrc I have:
alias core 'ls -lt core; echo where | gdb -core=core -silent; echo "\n"'
to display the backtrace by entering 'core'. And the date stamp, to ensure I am looking at the right file :(.
Added: If there is a stack corruption bug, then the backtrace applied to the core dump is often garbage. In this case, running the program within gdb can give better results, as per the accepted answer (assuming the fault is easily reproducible). And also beware of multiple processes dumping core simultaneously; some OS's add the PID to the name of the core file.
It's old question but just in case someone bump on this tread...
var input = document.getElementById("your_input");
var file = input.value.split("\\");
var fileName = file[file.length-1];
No need for regex, jQuery....
For example, you have collection ArrayList with elements Student class:
List stuList = new ArrayList();
Student s1 = new Student("Raju");
Student s2 = new Student("Harish");
stuList.add(s1);
stuList.add(s2);
//now you can convert this collection stuList to Array like this
Object[] stuArr = stuList.toArray(); // <----- toArray() function will convert collection to array
import subprocess
output = str(subprocess.Popen("ntpq -p",shell = True,stdout = subprocess.PIPE,
stderr = subprocess.STDOUT).communicate()[0])
This is one line solution
Actually Windows does have a utility that encodes and decodes base64 - CERTUTIL
I'm not sure what version of Windows introduced this command.
To encode a file:
certutil -encode inputFileName encodedOutputFileName
To decode a file:
certutil -decode encodedInputFileName decodedOutputFileName
There are a number of available verbs and options available to CERTUTIL.
To get a list of nearly all available verbs:
certutil -?
To get help on a particular verb (-encode for example):
certutil -encode -?
To get complete help for nearly all verbs:
certutil -v -?
Mysteriously, the -encodehex
verb is not listed with certutil -?
or certutil -v -?
. But it is described using certutil -encodehex -?
. It is another handy function :-)
Regarding David Morales' comment, there is a poorly documented type option to the -encodehex
verb that allows creation of base64 strings without header or footer lines.
certutil [Options] -encodehex inFile outFile [type]
A type of 1 will yield base64 without the header or footer lines.
See https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p56536 for a brief listing of the available type formats. And for a more in depth look at the available formats, see https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p57918.
Not investigated, but the -decodehex
verb also has an optional trailing type argument.
Try this on the PowerShell command line:
. .\MyFunctions.ps1
A1
The dot operator is used for script include.
Another simple way to hack it:
seq 20 | xargs -Iz echo "Hi there"
run echo 20 times.
Notice that seq 20 | xargs -Iz echo "Hi there z"
would output:
Hi there 1
Hi there 2
...
Simply follow the code
public static String getFormatedDate(String strDate,StringsourceFormate,
String destinyFormate) {
SimpleDateFormat df;
df = new SimpleDateFormat(sourceFormate);
Date date = null;
try {
date = df.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
df = new SimpleDateFormat(destinyFormate);
return df.format(date);
}
and pass the value into the function like that,
getFormatedDate("21:30:00", "HH:mm", "hh:mm aa");
or checkout this documentation SimpleDateFormat for StringsourceFormate and destinyFormate.
Try this:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class WriteImage
{
public static void main( String[] args )
{
BufferedImage image = null;
try {
URL url = new URL("URL_IMAGE");
image = ImageIO.read(url);
ImageIO.write(image, "jpg",new File("C:\\out.jpg"));
ImageIO.write(image, "gif",new File("C:\\out.gif"));
ImageIO.write(image, "png",new File("C:\\out.png"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script>
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script type="text/javascript" >
function openOnImageClick()
{
//alert("Jai Sh Raam");
// document.getElementById("images").src = "fruits.jpg";
var img = document.createElement('img');
img.setAttribute('src', 'tiger.jpg');
img.setAttribute('width', '200');
img.setAttribute('height', '150');
document.getElementById("images").appendChild(img);
}
</script>
</head>
<body>
<h1>Screen Shot View</h1>
<p>Click the Tiger to display the Image</p>
<div id="images" >
</div>
<img src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />
<img src="Logo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />
</body>
</html>
I thought TemplateBinding does not support Freezable types (which includes brush objects). To get around the problem. One can make use of TemplatedParent
Just wanted to add on to what @aioobe mentioned above...
In that approach you use HTML to color code your text. Though this is one of the most frequently used ways to color code the label text, but is not the most efficient way to do it.... considering that fact that each label will lead to HTML being parsed, rendering, etc. If you have large UI forms to be displayed, every millisecond counts to give a good user experience.
You may want to go through the below and give it a try....
Jide OSS (located at https://jide-oss.dev.java.net/) is a professional open source library with a really good amount of Swing components ready to use. They have a much improved version of JLabel named StyledLabel. That component solves your problem perfectly... See if their open source licensing applies to your product or not.
This component is very easy to use. If you want to see a demo of their Swing Components you can run their WebStart demo located at www.jidesoft.com (http://www.jidesoft.com/products/1.4/jide_demo.jnlp). All of their offerings are demo'd... and best part is that the StyledLabel is compared with JLabel (HTML and without) in terms of speed! :-)
A screenshot of the perf test can be seen at (http://img267.imageshack.us/img267/9113/styledlabelperformance.png)
In my case, I was using InstallUtil.exe
which was causing an error. To install the .Net Core
service in window best way to use sc
command.
More information here Exe installation throwing error The module was expected to contain an assembly manifest .Net Core
sub selectVar ()
dim x,y as integer
let srange = "A" & x & ":" & "m" & y
range(srange).select
end sub
I think this is the simplest way.
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
Here is an interesting case I thought I should share.
Let's say that you have an array of objects and an array of selected filters.
let arr = [
{ id: 'x', tags: ['foo'] },
{ id: 'y', tags: ['foo', 'bar'] },
{ id: 'z', tags: ['baz'] }
];
const filters = ['foo'];
To apply the selected filters to this structure we can
if (filters.length > 0)
arr = arr.filter(obj =>
obj.tags.some(tag => filters.includes(tag))
);
// [
// { id: 'x', tags: ['foo'] },
// { id: 'y', tags: ['foo', 'bar'] }
// ]
You can use COALESCE
in conjunction with NULLIF
for a short, efficient solution:
COALESCE( NULLIF(yourField,'') , '0' )
The NULLIF
function will return null if yourField
is equal to the second value (''
in the example), making the COALESCE
function fully working on all cases:
QUERY | RESULT
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null ,''),'0') | '0'
SELECT COALESCE(NULLIF('' ,''),'0') | '0'
SELECT COALESCE(NULLIF('foo' ,''),'0') | 'foo'
That is the mode with which you are opening the file. "wb" means that you are writing to the file (w), and that you are writing in binary mode (b).
Check out the documentation for more: clicky
Python has two kinds of sorts: a sort method (or "member function") and a sort function. The sort method operates on the contents of the object named -- think of it as an action that the object is taking to re-order itself. The sort function is an operation over the data represented by an object and returns a new object with the same contents in a sorted order.
Given a list of integers named l
the list itself will be reordered if we call l.sort()
:
>>> l = [1, 5, 2341, 467, 213, 123]
>>> l.sort()
>>> l
[1, 5, 123, 213, 467, 2341]
This method has no return value. But what if we try to assign the result of l.sort()
?
>>> l = [1, 5, 2341, 467, 213, 123]
>>> r = l.sort()
>>> print(r)
None
r
now equals actually nothing. This is one of those weird, somewhat annoying details that a programmer is likely to forget about after a period of absence from Python (which is why I am writing this, so I don't forget again).
The function sorted()
, on the other hand, will not do anything to the contents of l
, but will return a new, sorted list with the same contents as l
:
>>> l = [1, 5, 2341, 467, 213, 123]
>>> r = sorted(l)
>>> l
[1, 5, 2341, 467, 213, 123]
>>> r
[1, 5, 123, 213, 467, 2341]
Be aware that the returned value is not a deep copy, so be cautious about side-effecty operations over elements contained within the list as usual:
>>> spam = [8, 2, 4, 7]
>>> eggs = [3, 1, 4, 5]
>>> l = [spam, eggs]
>>> r = sorted(l)
>>> l
[[8, 2, 4, 7], [3, 1, 4, 5]]
>>> r
[[3, 1, 4, 5], [8, 2, 4, 7]]
>>> spam.sort()
>>> eggs.sort()
>>> l
[[2, 4, 7, 8], [1, 3, 4, 5]]
>>> r
[[1, 3, 4, 5], [2, 4, 7, 8]]
As suggested by other answers, --build-arg
may be the solution.
In my case, I had to add --network=host
in addition to the --build-arg
options.
docker build -t <TARGET> --build-arg http_proxy=http://<IP:PORT> --build-arg https_proxy=http://<IP:PORT> --network=host .
The method jQuery (v1.10) uses to find this is:
var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
That is:
window.pageXOffset
first and uses that if it exists.document.documentElement.scrollLeft
.document.documentElement.clientLeft
if it exists.The subtraction of document.documentElement.clientLeft
/ Top
only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.
Sometime in the future Comment out the following code in web.config
<!--<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>-->
update the to the following code.
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
<customErrors mode="Off"/>
<trust level="Full"/>
</system.web>
The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.
I think ADTC's solution is better, but mine's also works.
Here is the other solution I found
select p.name
from person p
where instr(p.name,chr(8211)) > 0; --contains the character chr(8211)
--at least 1 time
Thank you.
There is no extra advantage for each of them. It totally depends on your scenario. Code below shows their difference.
Before inserts your html here
<div id="mainTabsDiv">
Prepend inserts your html here
<div id="homeTabDiv">
<span>
Home
</span>
</div>
<div id="aboutUsTabDiv">
<span>
About Us
</span>
</div>
<div id="contactUsTabDiv">
<span>
Contact Us
</span>
</div>
Append inserts your html here
</div>
After inserts your html here
As string processing is expensive, and FORMAT more so, I am surprised that Asher/Aaron Dietz response is not higher, if not top; the question is seeking ISO 8601 date, and isn't specifically requesting it as a string type.
The most efficient method would be any of these (I've included the answer Asher/Aaron Dietz have already suggested for completeness):
All versions
select cast(getdate() as date)
select convert(date, getdate())
2008 and higher
select convert(date, current_timestamp)
ANSI SQL equivalent 2008 and higher
select cast(current_timestamp as date)
References:
https://sqlperformance.com/2015/06/t-sql-queries/format-is-nice-and-all-but
https://en.wikipedia.org/wiki/ISO_8601
https://www.w3schools.com/sql/func_sqlserver_current_timestamp.asp
As long as they are attributes like classes and ids you can remove them by javascript/jQuery class modifiers.
document.getElementById("MyElement").className = "";
There is no way to remove specific tag CSS other than overriding them (or using another element).
You could create a dict comprehension of just the elements whose values are None, and then update back into the original:
tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)
Update - did some performance tests
Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.
This should work:
select * from mytable where 'Journal'=ANY(pub_types);
i.e. the syntax is <value> = ANY ( <array> )
. Also notice that string literals in postresql are written with single quotes.
Using static cast would probably result in something like this:
// This does not prevent a possible type overflow
const char char_max = -1;
int i = 48;
char c = (i & char_max);
To prevent possible type overflow you could do this:
const char char_max = (char)(((unsigned char) char(-1)) / 2);
int i = 128;
char c = (i & char_max); // Would always result in positive signed values.
Where reinterpret_cast would probably just directly convert to char, without any cast safety. -> Never use reinterpret_cast if you can also use static_cast. If you're casting between classes, static_cast will also ensure, that the two types are matching (the object is a derivate of the cast type).
If your object a polymorphic type and you don't know which one it is, you should use dynamic_cast which will perform a type check at runtime and return nullptr if the types do not match.
IF you need const_cast you most likely did something wrong and should think about possible alternatives to fix const correctness in your code.
You can go to File -> Preferences -> Keyboard Shortcut. Once you are there, you can search for navigate. Then, you will see all shortcuts set for your VS Code environment related to navigation. In my case, it was only Alt + '-' to get my cursor back.
If you are getting this error on a server machine try give access to the folder you got the real windows service exe. You should go to the security tab and select the Local Service as user and should give full access. You should do the same for the exe too.
From the command-line:
echo '{"one":1,"two":2}' | python -mjson.tool
which outputs:
{
"one": 1,
"two": 2
}
Programmtically, the Python manual describes pretty-printing JSON:
>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
{
"4": 5,
"6": 7
}
if you want to get the index values, you can simply do:
dataframe.index
this will output a pandas.core.index
You can add manually in the manifest file within manifest tag by:
<uses-permission android:name="android.permission.CAMERA"/>
This permission is required to be able to access the camera device.
import requests
url = requests.get("http://yahoo.com")
htmltext = url.text
print(htmltext)
This will work similar to urllib.urlopen
.
Just disable the VIA protocol in sql server configuration manager
You should put the print function in your view-details.php file and call it once the file is loaded, by either using
<body onload="window.print()">
or
$(document).ready(function () {
window.print();
});
At the time the script is executed, the button does not exist because the DOM is not fully loaded. The easiest solution would be to put the script block after the form.
Another solution would be to capture the window.onload
event or use the jQuery library (overkill if you only have this one JavaScript).
Nowadays, I use the following, based on the Padam's answer:
$ python --version
Python 3.6.5
And this is how it looks:
from urllib.parse import urlparse
def is_url(url):
try:
result = urlparse(url)
return all([result.scheme, result.netloc])
except ValueError:
return False
Just use is_url("http://www.asdf.com")
.
Hope it helps!
But svn log is still in reverse order, i.e. most recent entries are output first, scrolling off the top of my terminal and gone. I really want to see the last entries, i.e. the sorting order must be chronological. The only command that does this seems to be svn log -r 1:HEAD
but that takes much too long on a repository with some 10000 entries. I've come up this this:
Display the last 10 subversion entries in chronological order:
svn log -r $(svn log -l 10 | grep '^r[0-9]* ' | tail -1 | cut -f1 -d" "):HEAD
Open report in Report designer
Go to View menu -> Report data
I've a sample for multiple data with their subnode 3 list , each list has attribute and child attribute:
var list1 = {
name: "Role A",
name_selected: false,
subs: [{
sub: "Read",
id: 1,
selected: false
}, {
sub: "Write",
id: 2,
selected: false
}, {
sub: "Update",
id: 3,
selected: false
}],
};
var list2 = {
name: "Role B",
name_selected: false,
subs: [{
sub: "Read",
id: 1,
selected: false
}, {
sub: "Write",
id: 2,
selected: false
}],
};
var list3 = {
name: "Role B",
name_selected: false,
subs: [{
sub: "Read",
id: 1,
selected: false
}, {
sub: "Update",
id: 3,
selected: false
}],
};
Add these to Array :
newArr.push(list1);
newArr.push(list2);
newArr.push(list3);
$scope.itemDisplayed = newArr;
Show them in html:
<li ng-repeat="item in itemDisplayed" class="ng-scope has-pretty-child">
<div>
<ul>
<input type="checkbox" class="checkall" ng-model="item.name_selected" ng-click="toggleAll(item)" />
<span>{{item.name}}</span>
<div>
<li ng-repeat="sub in item.subs" class="ng-scope has-pretty-child">
<input type="checkbox" kv-pretty-check="" ng-model="sub.selected" ng-change="optionToggled(item,item.subs)"><span>{{sub.sub}}</span>
</li>
</div>
</ul>
</div>
</li>
And here is the solution to check them:
$scope.toggleAll = function(item) {
var toogleStatus = !item.name_selected;
console.log(toogleStatus);
angular.forEach(item, function() {
angular.forEach(item.subs, function(sub) {
sub.selected = toogleStatus;
});
});
};
$scope.optionToggled = function(item, subs) {
item.name_selected = subs.every(function(itm) {
return itm.selected;
})
}
jsfiddle demo
Simply my project wasn't in htdocs thats why it was showing me an this error make sure you put your project in HTdocs not in directory inside it
You can fix this issue by deleting browser cookie from the begining of time. I have tried this and it is working fine for me.
To delete only cookies:
I just noticed that this question is quite old. Nevertheless, I consider the following aspects to be worth adding:
Use MongoDB if you don't know yet how you're going to query your data.
MongoDB is suited for Hackathons, startups or every time you don't know how you'll query the data you inserted. MongoDB does not make any assumptions on your underlying schema. While MongoDB is schemaless and non-relational, this does not mean that there is no schema at all. It simply means that your schema needs to be defined in your app (e.g. using Mongoose). Besides that, MongoDB is great for prototyping or trying things out. Its performance is not that great and can't be compared to Redis.
Use Redis in order to speed up your existing application.
Redis can be easily integrated as a LRU cache. It is very uncommon to use Redis as a standalone database system (some people prefer referring to it as a "key-value"-store). Websites like Craigslist use Redis next to their primary database. Antirez (developer of Redis) demonstrated using Lamernews that it is indeed possible to use Redis as a stand alone database system.
Redis does not make any assumptions based on your data.
Redis provides a bunch of useful data structures (e.g. Sets, Hashes, Lists), but you have to explicitly define how you want to store you data. To put it in a nutshell, Redis and MongoDB can be used in order to achieve similar things. Redis is simply faster, but not suited for prototyping. That's one use case where you would typically prefer MongoDB. Besides that, Redis is really flexible. The underlying data structures it provides are the building blocks of high-performance DB systems.
Caching
Caching using MongoDB simply doesn't make a lot of sense. It would be too slow.
If you have enough time to think about your DB design.
You can't simply throw in your documents into Redis. You have to think of the way you in which you want to store and organize your data. One example are hashes in Redis. They are quite different from "traditional", nested objects, which means you'll have to rethink the way you store nested documents. One solution would be to store a reference inside the hash to another hash (something like key: [id of second hash]). Another idea would be to store it as JSON, which seems counter-intuitive to most people with a *SQL-background.
If you need really high performance.
Beating the performance Redis provides is nearly impossible. Imagine you database being as fast as your cache. That's what it feels like using Redis as a real database.
If you don't care that much about scaling.
Scaling Redis is not as hard as it used to be. For instance, you could use a kind of proxy server in order to distribute the data among multiple Redis instances. Master-slave replication is not that complicated, but distributing you keys among multiple Redis-instances needs to be done on the application site (e.g. using a hash-function, Modulo etc.). Scaling MongoDB by comparison is much simpler.
Prototyping, Startups, Hackathons
MongoDB is perfectly suited for rapid prototyping. Nevertheless, performance isn't that good. Also keep in mind that you'll most likely have to define some sort of schema in your application.
When you need to change your schema quickly.
Because there is no schema! Altering tables in traditional, relational DBMS is painfully expensive and slow. MongoDB solves this problem by not making a lot of assumptions on your underlying data. Nevertheless, it tries to optimize as far as possible without requiring you to define a schema.
TL;DR - Use Redis if performance is important and you are willing to spend time optimizing and organizing your data. - Use MongoDB if you need to build a prototype without worrying too much about your DB.
Further reading:
target="_blank"
attribute will do the job.
Just don't forget to add rel="noopener noreferrer"
to solve the potential vulnerability. More on that here: https://dev.to/ben/the-targetblank-vulnerability-by-example
<a href="https://www.google.com/" target="_blank" rel="noopener noreferrer">Searcher</a>
In MySQL, the word 'type' is a Reserved Word.
No, there is no nonsense like that. Something we have not missed in Python for 20 years.
.htaccess
is in DOS format, change it to UNIX format (in Notepad++, click Edit>Convert
).htaccess
is in UTF8 Without-BOM, make it WITH BOM.grep -Fv -e 'Nopaging the limit is' -e 'keyword to remove is'
-F
matches by literal strings (instead of regex)
-v
inverts the match
-e
allows for multiple search patterns (all literal and inverted)
Overall just add display:block; to your span. You can leave your html unchanged.
You can do it with the following css:
p {
font-size:24px;
font-weight: 300;
-webkit-font-smoothing: subpixel-antialiased;
margin-top:0px;
}
p span {
font-size:16px;
font-style: italic;
margin-top:20px;
padding-left:10px;
display:inline-block;
}
Loggers only log the message, i.e. they create the log records (or logging requests). They do not publish the messages to the destinations, which is taken care of by the Handlers. Setting the level of a logger, only causes it to create log records matching that level or higher.
You might be using a ConsoleHandler
(I couldn't infer where your output is System.err or a file, but I would assume that it is the former), which defaults to publishing log records of the level Level.INFO
. You will have to configure this handler, to publish log records of level Level.FINER
and higher, for the desired outcome.
I would recommend reading the Java Logging Overview guide, in order to understand the underlying design. The guide covers the difference between the concept of a Logger and a Handler.
Editing the handler level
1. Using the Configuration file
The java.util.logging properties file (by default, this is the logging.properties
file in JRE_HOME/lib
) can be modified to change the default level of the ConsoleHandler:
java.util.logging.ConsoleHandler.level = FINER
2. Creating handlers at runtime
This is not recommended, for it would result in overriding the global configuration. Using this throughout your code base will result in a possibly unmanageable logger configuration.
Handler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(Level.FINER);
Logger.getAnonymousLogger().addHandler(consoleHandler);
No, but the 32-bit version runs just fine on 64-bit Windows.
If you want to round up, use half adjusting. Add 0.5 to the number to be rounded up and use the INT() function.
answer = INT(x + 0.5)
Why not make a nice extension method on the MemoryStream type?
public static class MemoryStreamExtensions
{
static object streamLock = new object();
public static void WriteLine(this MemoryStream stream, string text, bool flush)
{
byte[] bytes = Encoding.UTF8.GetBytes(text + Environment.NewLine);
lock (streamLock)
{
stream.Write(bytes, 0, bytes.Length);
if (flush)
{
stream.Flush();
}
}
}
public static void WriteLine(this MemoryStream stream, string formatString, bool flush, params string[] strings)
{
byte[] bytes = Encoding.UTF8.GetBytes(String.Format(formatString, strings) + Environment.NewLine);
lock (streamLock)
{
stream.Write(bytes, 0, bytes.Length);
if (flush)
{
stream.Flush();
}
}
}
public static void WriteToConsole(this MemoryStream stream)
{
lock (streamLock)
{
long temporary = stream.Position;
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8, false, 0x1000, true))
{
string text = reader.ReadToEnd();
if (!String.IsNullOrEmpty(text))
{
Console.WriteLine(text);
}
}
stream.Position = temporary;
}
}
}
Of course, be careful when using these methods in conjunction with the standard ones. :) ...you'll need to use that handy streamLock if you do, for concurrency.
If the application is already open (even in background), it will be restored by "start" command. Exit the program if running then /max or /min will work
Try either killall -15 mongod/ killall mongod Even after this if this doesnt work then remove the db storage folder by typing the following commands sudo rm -rf /data/db sudo mkdir /data/db sudo chmod 777 /data/db
why do I have to pass seconds = uptime to timedelta
Because timedelta objects can be passed seconds, milliseconds, days, etc... so you need to specify what are you passing in (this is why you use the explicit key). Typecasting to int
is superfluous as they could also accept floats.
and why does the string casting works so nicely that I get HH:MM:SS ?
It's not the typecasting that formats, is the internal __str__
method of the object. In fact you will achieve the same result if you write:
print datetime.timedelta(seconds=int(uptime))
document.getElementsByClassName("classstringhere").length
The document.getElementsByClassName("classstringhere")
method returns an array of all the elements with that class name, so .length
gives you the amount of them.
You can actually write to a named pipe using its name, btw.
Open a command shell as Administrator to get around the default "Access is denied" error:
echo Hello > \\.\pipe\PipeName
You can run several copies of your script in parallel, each copy for different input data, e.g. to process all *.cfg files on 4 cores:
ls *.cfg | xargs -P 4 -n 1 read_cfg.sh
The read_cfg.sh script takes just one parameters (as enforced by -n)
Bootstrap 4 provides the Collapse component for that. It's using JavaScript behind the scenes, but you don't have to write any JavaScript yourself.
This feature works for <button>
and <a>
.
If you use a <button>
, you must set the data-toggle
and data-target
attributes:
<button type="button" data-toggle="collapse" data-target="#collapseExample">
Toggle
</button>
<div class="collapse" id="collapseExample">
Lorem ipsum
</div>
If you use a <a>
, you must use set href
and data-toggle
:
<a data-toggle="collapse" href="#collapseExample">
Toggle
</a>
<div class="collapse" id="collapseExample">
Lorem ipsum
</div>
Talking about .hpp extension, I find it useful when people are supposed to know that this header file contains C++ an not C, like using namespaces or template etc, by the moment they see the files, so they won't try to feed it to a C compiler! And I also like to name header files which contain not only declarations but implementations as well, as .hpp files. like header files including template classes. Although that's just my opinion and of course it's not supposed to be right! :)
if you want to add directly to input as attribute, use this
onclick="return false;"
<input id = "btnPlay" type="button" onclick="return false;" value="play" />
this will prevent form submit behaviour
You need to use HAVING
, not WHERE
.
The difference is: the WHERE
clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT
function.
HAVING
is like WHERE
, only it happens after the COUNT
value has been computed, so it'll work as you expect. Rewrite your subquery as:
( -- where that pid is in the set:
SELECT c2.pid -- of pids
FROM Catalog AS c2 -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)
I prefer to make it without delegates and segues. It can be done with custom init or by setting optional values.
1. Custom init
class ViewControllerA: UIViewController {
func openViewControllerB() {
let viewController = ViewControllerB(string: "Blabla", completionClosure: { success in
print(success)
})
navigationController?.pushViewController(animated: true)
}
}
class ViewControllerB: UIViewController {
private let completionClosure: ((Bool) -> Void)
init(string: String, completionClosure: ((Bool) -> Void)) {
self.completionClosure = completionClosure
super.init(nibName: nil, bundle: nil)
title = string
}
func finishWork() {
completionClosure()
}
}
2. Optional vars
class ViewControllerA: UIViewController {
func openViewControllerB() {
let viewController = ViewControllerB()
viewController.string = "Blabla"
viewController.completionClosure = { success in
print(success)
}
navigationController?.pushViewController(animated: true)
}
}
class ViewControllerB: UIViewController {
var string: String? {
didSet {
title = string
}
}
var completionClosure: ((Bool) -> Void)?
func finishWork() {
completionClosure?()
}
}
ECMAScript 6 introduces the easily polyfillable Object.assign
:
The
Object.assign()
method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}
The own length
property of the array is not copied because it isn't enumerable.
Also, you can use ES8 spread syntax on objects to achieve the same result:
{ ...['a', 'b', 'c'] }
This answer support the @ macrocosme suggestion.
I am using heat map as hist2d plot. Additionally I use cmin=0.5 for no count value and cmap for color, r represent the reverse of given color.
# np.arange(data.min(), data.max()+binwidth, binwidth)
bin_x = np.arange(0.6, 7 + 0.3, 0.3)
bin_y = np.arange(12, 58 + 3, 3)
plt.hist2d(data=fuel_econ, x='displ', y='comb', cmin=0.5, cmap='viridis_r', bins=[bin_x, bin_y]);
plt.xlabel('Dispalcement (1)');
plt.ylabel('Combine fuel efficiency (mpg)');
plt.colorbar();
Also, if your table has no ID column, or sorting by id doesn't return you the last row, you can always use sqlite schema native 'rowid' field.
SELECT column
FROM table
WHERE rowid = (SELECT MAX(rowid) FROM table);
I would recommend a little research on Money Pattern. Martin Fowler in his book Analysis pattern has covered this in more detail.
public class Money {
private static final Currency USD = Currency.getInstance("USD");
private static final RoundingMode DEFAULT_ROUNDING = RoundingMode.HALF_EVEN;
private final BigDecimal amount;
private final Currency currency;
public static Money dollars(BigDecimal amount) {
return new Money(amount, USD);
}
Money(BigDecimal amount, Currency currency) {
this(amount, currency, DEFAULT_ROUNDING);
}
Money(BigDecimal amount, Currency currency, RoundingMode rounding) {
this.currency = currency;
this.amount = amount.setScale(currency.getDefaultFractionDigits(), rounding);
}
public BigDecimal getAmount() {
return amount;
}
public Currency getCurrency() {
return currency;
}
@Override
public String toString() {
return getCurrency().getSymbol() + " " + getAmount();
}
public String toString(Locale locale) {
return getCurrency().getSymbol(locale) + " " + getAmount();
}
}
Coming to the usage:
You would represent all monies using Money
object as opposed to BigDecimal
. Representing money as big decimal will mean that you will have the to format the money every where you display it. Just imagine if the display standard changes. You will have to make the edits all over the place. Instead using the Money
pattern you centralize the formatting of money to a single location.
Money price = Money.dollars(38.28);
System.out.println(price);
$gender = $_POST['gender'];
echo $gender;
it will echoes the selected value.
I wrote a snippet that allows you to send emails rendered with templates stored in the database. An example:
EmailTemplate.send('expense_notification_to_admin', {
# context object that email template will be rendered with
'expense': expense_request,
})
The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH
clause. See this article for one example of translating a CONNECT BY
into a WITH
(technically a recursive CTE) -- the example is for DB2 but I believe it will work on SQL Server as well.
Edit: apparently the original querant requires a specific example, here's one from the IBM site whose URL I already gave. Given a table:
CREATE TABLE emp(empid INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(10),
salary DECIMAL(9, 2),
mgrid INTEGER);
where mgrid
references an employee's manager's empid
, the task is, get the names of everybody who reports directly or indirectly to Joan
. In Oracle, that's a simple CONNECT
:
SELECT name
FROM emp
START WITH name = 'Joan'
CONNECT BY PRIOR empid = mgrid
In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that's worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):
WITH n(empid, name) AS
(SELECT empid, name
FROM emp
WHERE name = 'Joan'
UNION ALL
SELECT nplus1.empid, nplus1.name
FROM emp as nplus1, n
WHERE n.empid = nplus1.mgrid)
SELECT name FROM n
Oracle's START WITH
clause becomes the first nested SELECT
, the base case of the recursion, to be UNION
ed with the recursive part which is just another SELECT
.
SQL Server's specific flavor of WITH
is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.
Just Remove * from your select clause, and mention all column names explicitly and omit the FIRSTNAME column. After this write CONCAT(FIRSTNAME, ',', LASTNAME) AS FIRSTNAME. The above query will give you the only one FIRSTNAME column.
My OneLiner:
var MyList = new List<MyType>(MyDico.Values);
I'd like to point out the Vaex package.
Vaex is a python library for lazy Out-of-Core DataFrames (similar to Pandas), to visualize and explore big tabular datasets. It can calculate statistics such as mean, sum, count, standard deviation etc, on an N-dimensional grid up to a billion (109) objects/rows per second. Visualization is done using histograms, density plots and 3d volume rendering, allowing interactive exploration of big data. Vaex uses memory mapping, zero memory copy policy and lazy computations for best performance (no memory wasted).
Have a look at the documentation: https://vaex.readthedocs.io/en/latest/ The API is very close to the API of pandas.
When you say "called" I'm going to assume you mean an ID tag.
To make it cross-brower, I wouldn't suggest using the CSS3 []
, although it is an option. This being said, give each of your textboxes a class like "tb" and the radio button "rb".
Then:
#divContainer .tb { width: 150px }
#divContainer .rb { width: 20px }
This assumes you are using the same classes elsewhere, if not, this will suffice:
.tb { width: 150px }
.rb { width: 20px }
As @David mentioned, to access anything within the division itself:
#divContainer [element] { ... }
Where [element] is whatever HTML element you need.
Integer foo[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
List<Integer> list = Arrays.asList(foo);
// or
Iterable<Integer> iterable = Arrays.asList(foo);
Though you need to use an Integer
array (not an int
array) for this to work.
For primitives, you can use guava:
Iterable<Integer> fooBar = Ints.asList(foo);
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>15.0</version>
<type>jar</type>
</dependency>
For Java8: (from Jin Kwon's answer)
final int[] arr = {1, 2, 3};
final PrimitiveIterator.OfInt i1 = Arrays.stream(arr).iterator();
final PrimitiveIterator.OfInt i2 = IntStream.of(arr).iterator();
final Iterator<Integer> i3 = IntStream.of(arr).boxed().iterator();
I had the same 404 issue and none of the up-voted solutions here worked. In my case I have a sub application with its own web.config and I had a clear tag inside the parent's httpModules web.config section. In IIS all of the parent's web.config settings applies to sub application.
<system.web>
<httpModules>
<clear/>
</httpModules>
</system.web>
The solution is to remove the 'clear' tag and possibly add inheritInChildApplications="false" in the parent's web.config. The inheritInChildApplications is for IIS to not apply the config settings to the sub application.
<location path="." inheritInChildApplications="false">
<system.web>
....
<system.web>
</location>
You could use an onclick
event handler in order to get the input value for the text field. Make sure you give the field an unique id
attribute so you can refer to it safely through document.getElementById()
:
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">
. Create new elements by means of document.createElement()
, and use appendChild()
to append each of them to the container. You might be interested in outputting a meaningful name
attribute (e.g. name="member"+i
for each of the dynamically generated <input>
s if they are to be submitted in a form.
Notice you could also create <br/>
elements with document.createElement('br')
. If you want to just output some text, you can use document.createTextNode()
instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes()
and removeChild()
together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Number of inputs to create
var number = document.getElementById("member").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
<a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
<div id="container"/>
</body>
</html>
_x000D_
See a working sample in this JSFiddle.
For others who are experiencing with the same problem, here is the description of the bug in php + patch https://bugs.php.net/bug.php?id=44522
The correct syntax is
set def off;
insert into tablename values( 'J&J');
Just using this code: If you want backpressed disable, you dont use super.OnBackPressed();
@Override
public void onBackPressed() {
}
Check for "projtemp" and then check if the previous one is a number entry (like 19,18..etc..) if that is so then get the row no of that proj temp ....
and if that is not so ..then re-check that the previous entry is projtemp or a number entry ...
Collection initializers are only available in VB.NET 2010, released 2010-04-12:
Dim theVar = New List(Of String) From { "one", "two", "three" }
Below is a class that can be used in Windows environment, requires ActivePython. You can also inherit for other logging handlers (StreamHandler etc.)
class SyncronizedFileHandler(logging.FileHandler):
MUTEX_NAME = 'logging_mutex'
def __init__(self , *args , **kwargs):
self.mutex = win32event.CreateMutex(None , False , self.MUTEX_NAME)
return super(SyncronizedFileHandler , self ).__init__(*args , **kwargs)
def emit(self, *args , **kwargs):
try:
win32event.WaitForSingleObject(self.mutex , win32event.INFINITE)
ret = super(SyncronizedFileHandler , self ).emit(*args , **kwargs)
finally:
win32event.ReleaseMutex(self.mutex)
return ret
And here is an example that demonstrates usage:
import logging
import random , time , os , sys , datetime
from string import letters
import win32api , win32event
from multiprocessing import Pool
def f(i):
time.sleep(random.randint(0,10) * 0.1)
ch = random.choice(letters)
logging.info( ch * 30)
def init_logging():
'''
initilize the loggers
'''
formatter = logging.Formatter("%(levelname)s - %(process)d - %(asctime)s - %(filename)s - %(lineno)d - %(message)s")
logger = logging.getLogger()
logger.setLevel(logging.INFO)
file_handler = SyncronizedFileHandler(sys.argv[1])
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
#must be called in the parent and in every worker process
init_logging()
if __name__ == '__main__':
#multiprocessing stuff
pool = Pool(processes=10)
imap_result = pool.imap(f , range(30))
for i , _ in enumerate(imap_result):
pass
If you're using Dapper.SimpleSave:
//no safety checks
public static int Create<T>(object param)
{
using (SqlConnection conn = new SqlConnection(GetConnectionString()))
{
conn.Open();
conn.Create<T>((T)param);
return (int) (((T)param).GetType().GetProperties().Where(
x => x.CustomAttributes.Where(
y=>y.AttributeType.GetType() == typeof(Dapper.SimpleSave.PrimaryKeyAttribute).GetType()).Count()==1).First().GetValue(param));
}
}
Here are brief list:
JQuery with JSON stuff. (http://www.w3schools.com/xml/xml_http.asp)
$_SESSION - probably best way
Custom cookie - will not *always* work.
HTTP headers - some proxy can block it.
database such MySQL, Postgres or something else such Redis or Memcached (e.g. similar to home-made session, "locked" by IP address)
APC - similar to database, will not *always* work.
HTTP_REFERRER
URL hash parameter , e.g. http://domain.com/page.php#param - you will need some JavaScript to collect the hash. - gmail heavy use this.
I'd aditionally recommend putting the output of var_dump() or printr into a pre tag when outputting to a browser.
print "<pre>";
print_r($dataset);
print "</pre>";
Will give a more readable result.
I found the it wonderful to cover multiple variants of date time format like this:
final DateTimeFormatterBuilder dtfb = new DateTimeFormatterBuilder();
dtfb.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"))
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0);
So, I'm coming late to the party, but here's my two cents - philosophically adding to Colin Hebert's answer.
At a high level your question deals with the difference between objects and types. While there are many cars (objects), there is only one Car class (type). Declaring something as static means that you are operating in the "type" space. There is only one. The top-level class keyword already defines a type in the "type" space. As a result "public static class Car" is redundant.
From perlfaq5: How can I read in an entire file all at once?:
You can use the File::Slurp module to do it in one step.
use File::Slurp;
$all_of_it = read_file($filename); # entire file in scalar
@all_lines = read_file($filename); # one line per element
The customary Perl approach for processing all the lines in a file is to do so one line at a time:
open (INPUT, $file) || die "can't open $file: $!";
while (<INPUT>) {
chomp;
# do something with $_
}
close(INPUT) || die "can't close $file: $!";
This is tremendously more efficient than reading the entire file into memory as an array of lines and then processing it one element at a time, which is often--if not almost always--the wrong approach. Whenever you see someone do this:
@lines = <INPUT>;
you should think long and hard about why you need everything loaded at once. It's just not a scalable solution. You might also find it more fun to use the standard Tie::File module, or the DB_File module's $DB_RECNO bindings, which allow you to tie an array to a file so that accessing an element the array actually accesses the corresponding line in the file.
You can read the entire filehandle contents into a scalar.
{
local(*INPUT, $/);
open (INPUT, $file) || die "can't open $file: $!";
$var = <INPUT>;
}
That temporarily undefs your record separator, and will automatically close the file at block exit. If the file is already open, just use this:
$var = do { local $/; <INPUT> };
For ordinary files you can also use the read function.
read( INPUT, $var, -s INPUT );
The third argument tests the byte size of the data on the INPUT filehandle and reads that many bytes into the buffer $var.
In the spring framework, there is an annotation called the repository, and in the description of this annotation, there is useful information about the repository, which I think it is useful for this discussion.
Indicates that an annotated class is a "Repository", originally defined by Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects".
Teams implementing traditional Java EE patterns such as "Data Access Object" may also apply this stereotype to DAO classes, though care should be taken to understand the distinction between Data Access Object and DDD-style repositories before doing so. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.
A class thus annotated is eligible for Spring DataAccessException translation when used in conjunction with a PersistenceExceptionTranslationPostProcessor. The annotated class is also clarified as to its role in the overall application architecture for the purpose of tooling, aspects, etc.
Swift 4 and 5
HTTP POST request
using URLSession API
in Swift 4
func postRequest(username: String, password: String, completion: @escaping ([String: Any]?, Error?) -> Void) {
//declare parameter as a dictionary which contains string as key and value combination.
let parameters = ["name": username, "password": password]
//create the url with NSURL
let url = URL(string: "https://www.myserver.com/api/login")!
//create the session object
let session = URLSession.shared
//now create the Request object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to data object and set it as request body
} catch let error {
print(error.localizedDescription)
completion(nil, error)
}
//HTTP Headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request, completionHandler: { data, response, error in
guard error == nil else {
completion(nil, error)
return
}
guard let data = data else {
completion(nil, NSError(domain: "dataNilError", code: -100001, userInfo: nil))
return
}
do {
//create json object from data
guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else {
completion(nil, NSError(domain: "invalidJSONTypeError", code: -100009, userInfo: nil))
return
}
print(json)
completion(json, nil)
} catch let error {
print(error.localizedDescription)
completion(nil, error)
}
})
task.resume()
}
@objc func submitAction(_ sender: UIButton) {
//call postRequest with username and password parameters
postRequest(username: "username", password: "password") { (result, error) in
if let result = result {
print("success: \(result)")
} else if let error = error {
print("error: \(error.localizedDescription)")
}
}
Using Alamofire:
let parameters = ["name": "username", "password": "password123"]
Alamofire.request("https://www.myserver.com/api/login", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
I assume your tables are table1 and table2 respectively, and your solution is;
(select * from table1 MINUS select * from table2)
UNION ALL
(select * from table2 MINUS select * from table1)
if you had only one field to "DISTINCT", you could use:
SELECT COUNT(DISTINCT DocumentId)
FROM DocumentOutputItems
and that does return the same query plan as the original, as tested with SET SHOWPLAN_ALL ON. However you are using two fields so you could try something crazy like:
SELECT COUNT(DISTINCT convert(varchar(15),DocumentId)+'|~|'+convert(varchar(15), DocumentSessionId))
FROM DocumentOutputItems
but you'll have issues if NULLs are involved. I'd just stick with the original query.
If you want to pass the variable to your proxy backend, you have to set it with the proxy module.
location / {
proxy_pass http://example.com;
proxy_set_header Host example.com;
proxy_set_header HTTP_Country-Code $geoip_country_code;
proxy_pass_request_headers on;
}
And now it's passed to the proxy backend.
To get around the html
vs body
issue, I fixed this by not animating the css directly but rather calling window.scrollTo();
on each step:
$({myScrollTop:window.pageYOffset}).animate({myScrollTop:300}, {
duration: 600,
easing: 'swing',
step: function(val) {
window.scrollTo(0, val);
}
});
This works nicely without any refresh gotchas as it's using cross-browser JavaScript.
Have a look at http://james.padolsey.com/javascript/fun-with-jquerys-animate/ for more information on what you can do with jQuery's animate function.
try this ,
$presentyear = '2013-08-16 12:00:00';
$nextyear = date("M d,Y",mktime(0, 0, 0, date("m",strtotime($presentyear )), date("d",strtotime($presentyear )), date("Y",strtotime($presentyear ))+5));
echo $nextyear;
It's used in Kotlin
appCompatActivity?.getSupportFragmentManager()?.popBackStack()
As long as you have initialized moment-timezone with the data for the zones you want, your code works as expected.
You are correctly converting the moment to the time zone, which is reflected in the second line of output from momentObj.format()
.
Switching to UTC doesn't just drop the offset, it changes back to the UTC time zone. If you're going to do that, you don't need the original .tz()
call at all. You could just do moment.utc()
.
Perhaps you are just trying to change the output format string? If so, just specify the parameters you want to the format
method:
momentObj.format("YYYY-MM-DD HH:mm:ss")
Regarding the last to lines of your code - when you go back to a Date
object using toDate()
, you are giving up the behavior of moment.js and going back to JavaScript's behavior. A JavaScript Date
object will always be printed in the local time zone of the computer it's running on. There's nothing moment.js can do about that.
A couple of other little things:
While the moment constructor can take a Date
, it is usually best to not use one. For "now", don't use moment(new Date())
. Instead, just use moment()
. Both will work but it's unnecessarily redundant. If you are parsing from a string, pass that string directly into moment. Don't try to parse it to a Date
first. You will find moment's parser to be much more reliable.
Time Zones like MST7MDT
are there for backwards compatibility reasons. They stem from POSIX style time zones, and only a few of them are in the TZDB data. Unless absolutely necessary, you should use a key such as America/Denver
.
Happened to me today.
My issue was that I had too many tabs open (I didn't know they were open) with source code on them.
If you close all the tabs, maybe you will unconfuse IntelliJ into indexing the dependencies correctly
Try something like gem uninstall rjb --version 1.3.4
.
You've missed the id out before the NOT; it needs to be specified.
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
You're not running a module -- you're running subroutines/functions that happen to be stored in modules.
If you put the code in a standalone module and don't specify scope in the definitions of your subroutines/functions, they will be public by default, and callable from anywhere within your application. This means that you can call them with RunCode in a macro, from the class modules of forms/reports, from standalone class modules, or for the functions, from SQL (with some caveats).
Given that you were trying to implement in VBA something that you felt was too complicated for SQL, SQL is the likely context in which you want to execute the code. So, you should just be able to call your function within the SQL statement:
SELECT MyTable.PersonID, MyTable.FirstName, MyTable.LastName, FormatAddress([Address], [City], [State], [Zip], [Country]) As Address
FROM MyTable;
That SQL calls a public function called FormatAddress() that takes as arguments the components of an address and formats them appropriately. It's a trivial example as you likely would not need a VBA function for that purpose, but the point is that this is how you call functions from within a SQL statement.
Subroutines (i.e., code that returns no value) are not callable from within SQL statements.
Just to point onto the example posted by Mathew
public sealed class Singleton
{
// Because Singleton's constructor is private, we must explicitly
// give the Lazy<Singleton> a delegate for creating the Singleton.
private static readonly Lazy<Singleton> instanceHolder =
new Lazy<Singleton>(() => new Singleton());
private Singleton()
{
...
}
public static Singleton Instance
{
get { return instanceHolder.Value; }
}
}
before the Lazy was born we would have done it this way:
private static object lockingObject = new object();
public static LazySample InstanceCreation()
{
if(lazilyInitObject == null)
{
lock (lockingObject)
{
if(lazilyInitObject == null)
{
lazilyInitObject = new LazySample ();
}
}
}
return lazilyInitObject ;
}
I like the -=[4]
way mentioned in other answers to delete the elements whose value is 4.
But there is this way:
[2,4,6,3,8,6].delete_if { |i| i == 6 }
=> [2, 4, 3, 8]
mentioned somewhere in "Basic Array Operations", after it mentions the map
function.
You can use any one of the below methods
If you are using java.text.DecimalFormat
DecimalFormat decimalFormat = NumberFormat.getCurrencyInstance();
decimalFormat.setMinimumFractionDigits(2);
System.out.println(decimalFormat.format(4.0));
OR
DecimalFormat decimalFormat = new DecimalFormat("#0.00");
System.out.println(decimalFormat.format(4.0));
If you want to convert it into simple string format
System.out.println(String.format("%.2f", 4.0));
All the above code will print 4.00
This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570
I guess the counter-intuitive part of the question is: if this is correct C:
if (a == 1) {
int b = 10;
}
then why is this not also correct C?
if (a == 1)
int b = 10;
I mean, a one-line conditional if
statement should be fine either with or without braces, right?
The answer lies in the grammar of the if
statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10
line is a declaration, not a statement, and the grammar for the if
statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.
And just for the sake of answering the question completely -- this has nothing to do with scope. The b
variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror
anyways ;-)
(6.7) declaration: declaration-speci?ers init-declarator-listopt ; static_assert-declaration (6.7) init-declarator-list: init-declarator init-declarator-list , init-declarator (6.7) init-declarator: declarator declarator = initializer (6.8) statement: labeled-statement compound-statement expression-statement selection-statement iteration-statement jump-statement (6.8.2) compound-statement: { block-item-listopt } (6.8.4) selection-statement: if ( expression ) statement if ( expression ) statement else statement switch ( expression ) statement
If you need to remove text inside nested parentheses, too, then:
var prevStr;
do {
prevStr = str;
str = str.replace(/\([^\)\(]*\)/, "");
} while (prevStr != str);
Just keep in mind there are 2 spaces between Aug and 26. Other wise your find command will not work.
find . -type f -exec ls -l {} \; | egrep "Aug 26";
--user
installs in site.USER_SITE
.
For my case, it was /Users/.../Library/Python/2.7/bin
. So I have added that to my PATH (in ~/.bash_profile
file):
export PATH=$PATH:/Users/.../Library/Python/2.7/bin
To answer the question more generaly how to redirect standard output to a variable ?
do the following :
from io import StringIO
import sys
result = StringIO()
sys.stdout = result
result_string = result.getvalue()
If you need to do that only in some function do the following :
old_stdout = sys.stdout
# your function containing the previous lines
my_function()
sys.stdout = old_stdout
this is because deleting projects or class libraries from solution and adding projects after deleting with same name. best thing is delete solution file and add projects to it.this works for me (I did this using vsCode)
Thanks for commenting, I understand what you mean but I didn't want to check old values. I just wanted to get a pointer to that view.
Looking at someone else's code I have just found a workaround, you can access the root of a layout using LayoutInflater
.
The code is the following, where this
is an Activity:
final LayoutInflater factory = getLayoutInflater();
final View textEntryView = factory.inflate(R.layout.landmark_new_dialog, null);
landmarkEditNameView = (EditText) textEntryView.findViewById(R.id.landmark_name_dialog_edit);
You need to get the inflater for this
context, access the root view through the inflate method and finally call findViewById
on the root view of the layout.
Hope this is useful for someone! Bye
Select your project properties from Project Tab Then Application->Resource->Icon And Manifest->change the default icon
This works in Visual studio 2019 finely Note:Only files with .ico format can be added as icon
I fixed it by uninstalling Android SDK Platform (4.4W) and then reinstalling it. I also restarted Eclipse after the installation.
@echo off
net use z: /delete
cmdkey /add:servername /user:userserver /pass:userstrongpass
net use z: \\servername\userserver /savecred /persistent:yes
set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs"
echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT%
echo sLinkFile = "%USERPROFILE%\Desktop\userserver_in_server.lnk" >> %SCRIPT%
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT%
echo oLink.TargetPath = "Z:\" >> %SCRIPT%
echo oLink.Save >> %SCRIPT%
cscript /nologo %SCRIPT%
del %SCRIPT%
I think it is much more simple solution:
window.location = (""+window.location).replace(/#[A-Za-z0-9_]*$/,'')+"#myAnchor"
This method does not reload the website, and sets the focus on the anchors which are needed for screen reader.
In my case I had to remove the ngNoForm
attribute from my <form>
tag.
If you you want to import FormsModule in your application but want to skip a specific form, you can use the ngNoForm directive which will prevent ngForm from being added to the form
Reference: https://www.techiediaries.com/angular-ngform-ngnoform-template-reference-variable/
In ECMAScript implementations (for instance, ActionScript or JavaScript), Array()
is a constructor function and []
is part of the array literal grammar. Both are optimized and executed in completely different ways, with the literal grammar not being dogged by the overhead of calling a function.
PHP, on the other hand, has language constructs that may look like functions but aren't treated as such. Even with PHP 5.4, which supports []
as an alternative, there is no difference in overhead because, as far as the compiler/parser is concerned, they are completely synonymous.
// Before 5.4, you could only write
$array = array(
"foo" => "bar",
"bar" => "foo",
);
// As of PHP 5.4, the following is synonymous with the above
$array = [
"foo" => "bar",
"bar" => "foo",
];
If you need to support older versions of PHP, use the former syntax. There's also an argument for readability but, being a long-time JS developer, the latter seems rather natural to me. I actually made the mistake of trying to initialise arrays using []
when I was first learning PHP.
This change to the language was originally proposed and rejected due to a majority vote against by core developers with the following reason:
This patch will not be accepted because slight majority of the core developers voted against. Though if you take a accumulated mean between core developers and userland votes seems to show the opposite it would be irresponsible to submit a patch witch is not supported or maintained in the long run.
However, it appears there was a change of heart leading up to 5.4, perhaps influenced by the implementations of support for popular databases like MongoDB (which use ECMAScript syntax).
In Visual Studio, Right Click your project -> On the left pane click the Build tab,
under Platform Target select x86 (or more generally the architecture to match with the library you are linking to)
I hope this helps someone! :)
If you're using Python 2.x, try installing a urllib2 opener. That should print out your headers, although you may have to combine that with other openers you're using to hit the HTTPS.
import urllib2
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)))
urllib2.urlopen(url)
You can always use System.Resources.ResourceManager
which returns the cached ResourceManager
used by this class. Since chan1
and chan2
represent two different images, you may use System.Resources.ResourceManager.GetObject(string name)
which returns an object matching your input with the project resources
Example
object O = Resources.ResourceManager.GetObject("chan1"); //Return an object from the image chan1.png in the project
channelPic.Image = (Image)O; //Set the Image property of channelPic to the returned object as Image
Notice: Resources.ResourceManager.GetObject(string name)
may return null
if the string specified was not found in the project resources.
Thanks,
I hope you find this helpful :)
New installers (.msi downloaded from https://nodejs.org) have "Add to PATH" option. By default it is selected. Make sure that you leave it checked.