The bold property of the font itself is read only, but the actual font property of the text box is not. You can change the font of the textbox to bold as follows:
textBox1.Font = new Font(textBox1.Font, FontStyle.Bold);
And then back again:
textBox1.Font = new Font(textBox1.Font, FontStyle.Regular);
I think the java.lang.UnsupportedOperationException
is what you are looking for.
android:inputMethod
is deprecated, instead use inputType
:
android:inputType="numberPassword"
Although this is an old document, but it helped me resolve the problem of 'HintPath' being ignored on another machine. It was because the referenced DLL needed to be in source control as well:
Excerpt:
To include and then reference an outer-system assembly 1. In Solution Explorer, right-click the project that needs to reference the assembly,,and then click Add Existing Item. 2. Browse to the assembly, and then click OK. The assembly is then copied into the project folder and automatically added to VSS (assuming the project is already under source control). 3. Use the Browse button in the Add Reference dialog box to set a file reference to assembly in the project folder.
In C++ you are supposed to declare functions before you can use them. In your code integrate
is not declared before the point of the first call to integrate
. The same applies to sum
. Hence the error. Either reorder your definitions so that function definition precedes the first call to that function, or introduce a [forward] non-defining declaration for each function.
Additionally, defining external non-inline functions in header files in a no-no in C++. Your definitions of SkewNormalEvalutatable::SkewNormalEvalutatable
, getSkewNormal
, integrate
etc. have no business being in header file.
Also SkewNormalEvalutatable e();
declaration in C++ declares a function e
, not an object e
as you seem to assume. The simple SkewNormalEvalutatable e;
will declare an object initialized by default constructor.
Also, you receive the last parameter of integrate
(and of sum
) by value as an object of Evaluatable
type. That means that attempting to pass SkewNormalEvalutatable
as last argument of integrate
will result in SkewNormalEvalutatable
getting sliced to Evaluatable
. Polymorphism won't work because of that. If you want polymorphic behavior, you have to receive this parameter by reference or by pointer, but not by value.
foo = ['a', 'b', 'c', 'd', 'e']
number_of_samples = 1
In python 2:
random_items = random.sample(population=foo, k=number_of_samples)
In python 3:
random_items = random.choices(population=foo, k=number_of_samples)
You need to write SSIS to copy the table and its data, constraints and triggers. We have in our organization a software called Kal Admin by kalrom Systems that has a free version for downloading (I think that the copy tables feature is optional)
Check out this blog. It has a ton of information. Also if installing through brew don´t miss this note:
You may need to link the Java bindings into the Java Extensions folder:
$ sudo mkdir -p /Library/Java/Extensions
$ sudo ln -s /usr/local/lib/libsvnjavahl-1.dylib /Library/Java/Extensions/libsvnjavahl-1.dylib
You need to
#include <string>
<iostream>
declares cout
, cin
, not string
.
Another alternative is;
sudo iptables -A INPUT -p tcp --dport 8000 -s ! 1.2.3.4 -j DROP
I had similar issue that 3 bridged virtualmachine just need access eachother with different combination, so I have tested this command and it works well.
Edit**
According to Fernando comment and this link exclamation mark (
!
) will be placed before than-s
parameter:
sudo iptables -A INPUT -p tcp --dport 8000 ! -s 1.2.3.4 -j DROP
I'm using chrome too and facing same problem on my localhost. I did a lot of things like clear using CCleaner and restart OS. But my problem was solved with clearing cookie. In order to clear cookie:
OR
A classic "or" would be |
. For example, ab|de
would match either side of the expression.
However, for something like your case you might want to use the ?
quantifier, which will match the previous expression exactly 0 or 1 times (1 times preferred; i.e. it's a "greedy" match). Another (probably more relyable) alternative would be using a custom character group:
\d+\s+[A-Z\s]+\s+[A-Z][A-Za-z]+
This pattern will match:
\d+
: One or more numbers.\s+
: One or more whitespaces.[A-Z\s]+
: One or more uppercase characters or space characters\s+
: One or more whitespaces.[A-Z][A-Za-z\s]+
: An uppercase character followed by at least one more character (uppercase or lowercase) or whitespaces.If you'd like a more static check, e.g. indeed only match ABC
and A ABC
, then you can combine a (non-matching) group and define the alternatives inside (to limit the scope):
\d (?:ABC|A ABC) Street
Or another alternative using a quantifier:
\d (?:A )?ABC Street
in Visual studio 2010 (VB NET)i try the following and works fine
Dim HtmlSample As String = <anything>what ever you want to type here with multiline strings</anything>
dim Test1 as string =<a>onother multiline example</a>
Template argument deduction for class templates
[*this]{ std::cout << could << " be " << useful << '\n'; }
[[fallthrough]]
, [[nodiscard]]
, [[maybe_unused]]
attributes
using
in attributes to avoid having to repeat an attribute namespace.
Compilers are now required to ignore non-standard attributes they don't recognize.
Simple static_assert(expression);
with no string
no throw
unless throw()
, and throw()
is noexcept(true)
.
std::tie
with auto
const auto [it, inserted] = map.insert( {"foo", bar} );
it
and inserted
with deduced type from the pair
that map::insert
returns.std::array
s and relatively flat structsif (init; condition)
and switch (init; condition)
if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
if(decl)
to cases where decl
isn't convertible-to-bool sensibly.Generalizing range-based for loops
Fixed order-of-evaluation for (some) expressions with some modifications
.then
on future work.Forward progress guarantees (FPG) (also, FPGs for parallel algorithms)
u8'U', u8'T', u8'F', u8'8'
character literals (string already existed)
inherited constructors fixes to some corner cases (see P0136R0 for examples of behavior changes)
std::string
like reference-to-character-array or substringstring const&
again. Also can make parsing a bajillion times faster."hello world"sv
char_traits
std::byte
off more than they could chew.
std::invoke
std::apply
std::make_from_tuple
, std::apply
applied to object construction
is_invocable
, is_invocable_r
, invoke_result
result_of
is_invocable<Foo(Args...), R>
is "can you call Foo
with Args...
and get something compatible with R
", where R=void
is default.invoke_result<Foo, Args...>
is std::result_of_t<Foo(Args...)>
but apparently less confusing?[class.directory_iterator]
and [class.recursive_directory_iterator]
fstream
s can be opened with path
s, as well as with const path::value_type*
strings.
for_each_n
reduce
transform_reduce
exclusive_scan
inclusive_scan
transform_exclusive_scan
transform_inclusive_scan
Added for threading purposes, exposed even if you aren't using them threaded
atomic<T>
::is_always_lockfree
std::lock
pain when locking more than one mutex at a time.std
algorithms, and related machinery[func.searchers]
and [alg.search]
std::function
for allocatorsstd::sample
, sampling from a range?
try_emplace
and insert_or_assign
Splicing for map<>
, unordered_map<>
, set<>
, and unordered_set<>
non-const .data()
for string.
non-member std::size
, std::empty
, std::data
std::begin
/end
The emplace
family of functions now returns a reference to the created object.
unique_ptr<T[]>
fixes and other unique_ptr
tweaks.weak_from_this
and some fixed to shared from thisstd
datatype improvements:{}
construction of std::tuple
and other improvementsC++17 library is based on C11 instead of C99
Reserved std[0-9]+
for future standard libraries
std
implementations exposedstd::clamp()
std::clamp( a, b, c ) == std::max( b, std::min( a, c ) )
roughlygcd
and lcm
std::uncaught_exceptions
std::as_const
std::bool_constant
_v
template variablesstd::void_t<T>
std::owner_less<void>
std::less<void>
, but for smart pointers to sort based on contentsstd::chrono
polishstd::conjunction
, std::disjunction
, std::negation
exposedstd::not_fn
std
std::less
.<codecvt>
memory_order_consume
result_of
, replaced with invoke_result
shared_ptr::unique
, it isn't very threadsafeIsocpp.org has has an independent list of changes since C++14; it has been partly pillaged.
Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.
Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.
Additional entries pillaged from SD-6 feature-test list.
clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.
these slides had some features missing elsewhere.
While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:
register
, keyword reserved for future usebool b; ++b;
<functional>
stuff, random_shuffle
std::function
There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:
P0505R0 (constexpr chrono)
P0418R2 (atomic tweaks)
P0512R0 (template argument deduction tweaks)
P0490R0 (structured binding tweaks)
P0513R0 (changes to std::hash
)
P0502R0 (parallel exceptions)
P0509R1 (updating restrictions on exception handling)
P0012R1 (make exception specifications be part of the type system)
P0510R0 (restrictions on variants)
P0504R0 (tags for optional/variant/any)
P0497R0 (shared ptr tweaks)
P0508R0 (structured bindings node handles)
P0521R0 (shared pointer use count and unique changes?)
https://isocpp.org/files/papers/p0636r0.html
Closing conformation alert:
Private Sub cmd_exit_click()
' By clicking on the button the MsgBox will appear
If MsgBox("Are you sure want to exit now?", MsgBoxStyle.YesNo, "closing warning") = MsgBoxResult.Yes Then ' If you select yes in the MsgBox then it will close the window
Me.Close() ' Close the window
Else
' Will not close the application
End If
End Sub
You could use Hortonworks spark-llap library like this
import com.hortonworks.hwc.HiveWarehouseSession
df.write
.format("com.hortonworks.spark.sql.hive.llap.HiveWarehouseConnector")
.mode("append")
.option("table", "myDatabase.myTable")
.save()
function
getValue(input){
var value = input.value ? parseInt(input.value) : 0;
let min = input.min;
let max = input.max;
if(value < min)
return parseInt(min);
else if(value > max)
return parseInt(max);
else return value;
}
Usages
changeDotColor = (event) => {
let value = this.getValue(event.target) //value will be always number
console.log(value)
console.log(typeof value)
}
Now all clients allow to do it, but it's not pretty simple.
In any Telegram client:
Administrators
You have set #slider
as absolute
, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, #content
div is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.
You can read about CSS positioning here
If you set both to relative
, the divs will be one after the other, as shown here:
#slider {
position:relative;
left:0;
height:400px;
border-style:solid;
border-width:5px;
}
#slider img {
width:100%;
}
#content {
position:relative;
}
#content #text {
position:relative;
width:950px;
height:215px;
color:red;
}
The key is to rewrite this query so that it can be used as a subquery.
SELECT firstname,
lastname,
list.address
FROM list
INNER JOIN (SELECT address
FROM list
GROUP BY address
HAVING COUNT(id) > 1) dup
ON list.address = dup.address;
This is how I edited my vue.config.js so that I could expose NODE_ENV to the frontend (I'm using Vue-CLI):
vue.config.js
const webpack = require('webpack');
// options: https://github.com/vuejs/vue-cli/blob/dev/docs/config.md
module.exports = {
// default baseUrl of '/' won't resolve properly when app js is being served from non-root location
baseUrl: './',
outputDir: 'dist',
configureWebpack: {
plugins: [
new webpack.DefinePlugin({
// allow access to process.env from within the vue app
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV)
}
})
]
}
};
First you can write the code:
{ [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];}
after that
{ #define cellHeight 80 // You can change according to your req.<br>
#define cellWidth 320 // You can change according to your req.<br>
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"seprater_line.png"]];
imgView.frame = CGRectMake(0, cellHeight, cellWidth, 1);
[customCell.contentView addSubview:imgView];
return customCell;
}
}
With the Python library pandas
, you can easily create column names and infer data types from a csv file.
from sqlalchemy import create_engine
import pandas as pd
engine = create_engine('postgresql://user:pass@localhost/db_name')
df = pd.read_csv('/path/to/csv_file')
df.to_sql('pandas_db', engine)
The if_exists
parameter can be set to replace or append to an existing table, e.g. df.to_sql('pandas_db', engine, if_exists='replace')
. This works for additional input file types as well, docs here and here.
Does two lines count?
awk '{ sum += $1; }
END { print sum; }' "$@"
You can then use it without the superfluous 'cat':
sum < FileWithColumnOfNumbers.txt
sum FileWithColumnOfNumbers.txt
FWIW: on MacOS X, you can do it with a one-liner:
awk '{ sum += $1; } END { print sum; }' "$@"
Use r.URL.Query()
when you appending to existing query, if you are building new set of params use the url.Values
struct like so
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
)
func main() {
req, err := http.NewRequest("GET","http://api.themoviedb.org/3/tv/popular", nil)
if err != nil {
log.Print(err)
os.Exit(1)
}
// if you appending to existing query this works fine
q := req.URL.Query()
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
// or you can create new url.Values struct and encode that like so
q := url.Values{}
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
req.URL.RawQuery = q.Encode()
fmt.Println(req.URL.String())
// Output:
// http://api.themoviedb.org/3/tv/popularanother_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}
It's a linefeed character. How you use it would be up to you.
Is there any command in Linux through which i can know if the process is in hang state.
There is no command, but once I had to do a very dumb hack to accomplish something similar. I wrote a Perl script which periodically (every 30 seconds in my case):
ps
to find list of PIDs of the watched processes (along with exec time, etc)gdb
attaching to the process using its PID, dumping stack trace from it using thread apply all where
, detaching from the processBut that was very very very very crude hack, done to reach an about-to-be-missed deadline and it was removed a few days later, after a fix for the buggy application was finally installed.
Otherwise, as all other responders absolutely correctly commented, there is no way to find whether the process hung or not: simply because the hang might occur for way to many reasons, often bound to the application logic.
The only way is for application itself being capable of indicating whether it is alive or not. Simplest way might be for example a periodic log message "I'm alive".
public void swapnumber(int a,int b){
a = a+b-(b=a);
System.out.println("a = "+a +" b= "+b);
}
We resolved our issues by re-installing the Oracle Database Client. Somehow the installation wasn't successful on 1 of the workstations (even though there was no logging), however when comparing size/files/folders of the Oracle directory to a working client workstation, there was a significant amount of files that were missing. Once we performed a clean install, everything worked perfectly.
I have a local install of tensorflow 1.15.0 (with tensorboard obviously included) on MacOS.
For me, the path to the relevant file within my user directory is Library/Python/3.7/lib/python/site-packages/tensorboard/main.py. So, which
does not work for me, but you have to look for the file named main.py, which is weird since it apparently is named something else for other users.
This feature was added in Compose 1.6.
Reference: https://docs.docker.com/compose/compose-file/#args
services:
web:
build:
context: .
args:
FOO: foo
With await
support and bluebird promise:
await bluebird.delay(1000);
This will work like a synchronous sleep(1)
of c language. My favorite solution.
An algorithm is the description of an automated solution to a problem. What the algorithm does is precisely defined. The solution could or could not be the best possible one but you know from the start what kind of result you will get. You implement the algorithm using some programming language to get (a part of) a program.
Now, some problems are hard and you may not be able to get an acceptable solution in an acceptable time. In such cases you often can get a not too bad solution much faster, by applying some arbitrary choices (educated guesses): that's a heuristic.
A heuristic is still a kind of an algorithm, but one that will not explore all possible states of the problem, or will begin by exploring the most likely ones.
Typical examples are from games. When writing a chess game program you could imagine trying every possible move at some depth level and applying some evaluation function to the board. A heuristic would exclude full branches that begin with obviously bad moves.
In some cases you're not searching for the best solution, but for any solution fitting some constraint. A good heuristic would help to find a solution in a short time, but may also fail to find any if the only solutions are in the states it chose not to try.
Took me couple trials, had same issue, this worked for me:
Check your spelling at -
(BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
I corrected mine at textField
instead of textfield
, capitalise "F"... and bingo!! it worked..
$type_array = array();
while($row = mysql_fetch_assoc($result)) {
$type_array[] = $row['type'];
}
$('img').mouseover(function(){
var newSrc = $(this).attr("src").replace("image.gif", "imageover.gif");
$(this).attr("src", newSrc);
});
$('img').mouseout(function(){
var newSrc = $(this).attr("src").replace("imageover.gif", "image.gif");
$(this).attr("src", newSrc);
});
I would suggest:
DECLARE @sqlStatement nvarchar(MAX),
@tableName nvarchar(50) = 'TripEvent',
@columnName nvarchar(50) = 'CreatedDate';
SELECT @sqlStatement = 'ALTER TABLE ' + @tableName + ' DROP CONSTRAINT ' + dc.name + ';'
FROM sys.default_constraints AS dc
LEFT JOIN sys.columns AS sc
ON (dc.parent_column_id = sc.column_id)
WHERE dc.parent_object_id = OBJECT_ID(@tableName)
AND type_desc = 'DEFAULT_CONSTRAINT'
AND sc.name = @columnName
PRINT' ['+@tableName+']:'+@@SERVERNAME+'.'+DB_NAME()+'@'+CONVERT(VarChar, GETDATE(), 127)+'; '+@sqlStatement;
IF(LEN(@sqlStatement)>0)EXEC sp_executesql @sqlStatement
Unlike traditional RBDMs, mongoDB doesn't allow you to define any random field as the primary key, the _id field MUST exist for all standard documents.
For this reason, it doesn't make sense to create a separate uuid field.
In mongoose, the ObjectId type is used not to create a new uuid, rather it is mostly used to reference other documents.
Here is an example:
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var Schema_Product = new Schema({
categoryId : ObjectId, // a product references a category _id with type ObjectId
title : String,
price : Number
});
As you can see, it wouldn't make much sense to populate categoryId with a ObjectId.
However, if you do want a nicely named uuid field, mongoose provides virtual properties that allow you to proxy (reference) a field.
Check it out:
var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var Schema_Category = new Schema({
title : String,
sortIndex : String
});
Schema_Category.virtual('categoryId').get(function() {
return this._id;
});
So now, whenever you call category.categoryId, mongoose just returns the _id instead.
You can also create a "set" method so that you can set virtual properties, check out this link for more info
Im no expert with flex but I got there by setting the basis to 50% for the two items i was dealing with. Grow to 1 and shrink to 0.
Inline styling: flex: '1 0 50%',
I tried user968421's answer and the OP's solution but the browser popped up a security error for a checkout page. I can't tell you why exactly.
Our host (Site Ground) couldn't figure it out either.
The final solution was close, but a slight tweak to user968421's answer (side note: unlike the OP, I was trying to redirect to the corresponding page, not just to the homepage so I maintained the back reference [the $1
after the domain] from user968421's answer):
RewriteEngine on
RewriteRule (.*) https://newdomain.com/$1 [R=301,L]
Got the tweak from this htaccess redirect generator recommended by a Host Gator article (desperate times, desperate measures, amiright?).
This error message is displayed when you have an error in your query which caused it to fail. It will manifest itself when using:
mysql_fetch_array
/mysqli_fetch_array()
mysql_fetch_assoc()
/mysqli_fetch_assoc()
mysql_num_rows()
/mysqli_num_rows()
Note: This error does not appear if no rows are affected by your query. Only a query with an invalid syntax will generate this error.
Troubleshooting Steps
Make sure you have your development server configured to display all errors. You can do this by placing this at the top of your files or in your config file: error_reporting(-1);
. If you have any syntax errors this will point them out to you.
Use mysql_error()
. mysql_error()
will report any errors MySQL encountered while performing your query.
Sample usage:
mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db($db_name) or die("cannot select DB");
$sql = "SELECT * FROM table_name";
$result = mysql_query($sql);
if (false === $result) {
echo mysql_error();
}
Run your query from the MySQL command line or a tool like phpMyAdmin. If you have a syntax error in your query this will tell you what it is.
Make sure your quotes are correct. A missing quote around the query or a value can cause a query to fail.
Make sure you are escaping your values. Quotes in your query can cause a query to fail (and also leave you open to SQL injections). Use mysql_real_escape_string()
to escape your input.
Make sure you are not mixing mysqli_*
and mysql_*
functions. They are not the same thing and cannot be used together. (If you're going to choose one or the other stick with mysqli_*
. See below for why.)
Other tips
mysql_*
functions should not be used for new code. They are no longer maintained and the community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide, this article will help to choose. If you care to learn, here is good PDO tutorial.
Using ngClass
to disabled the button for invalid form is not good practice in Angular2 when its providing inbuilt features to enable and disable the button if form is valid and invalid respectively without doing any extra efforts/logic.
[disabled]
will do all thing like if form is valid then it will be enabled and if form is invalid then it will be disabled automatically.
See Example:
<form (ngSubmit)="f.form.valid" #f="ngForm" novalidate>
<input type="text" placeholder="Name" [(ngModel)]="txtName" name="txtname" #textname="ngModel" required>
<input type="button" class="mdl-button" [disabled]="!f.form.valid" (click)="onSave()" name="">
One thing that I have to add is that there is no reference in C.
Secondly, this is the language syntax convention. & - is an address operator but it also mean a reference - all depends on usa case
If there was some "reference" keyword instead of & you could write
int CDummy::isitme (reference CDummy param)
but this is C++ and we should accept it advantages and disadvantages...
Most things have been said already, but I can just add that I've used HSQL, Derby and Berkely DB in a few of my pet projects and they all worked just fine. So I don't think it really matters much to be honest. One thing worth mentioning is that HSQL saves itself as a text file with SQL statements which is quite good. Makes it really easy for when you are developing to do tests and setup data quickly. Can also do quick edits if needed. Guess you could easily transfer all that to any database if you ever need to change as well :)
Not sure why no one is using semicolons. This is how it works for me:
=CONCATENATE(LEFT(A1;1); B1)
Solutions with comma produce an error in Excel.
lista = list.sort(lista)
This should be
lista.sort()
The .sort()
method is in-place, and returns None. If you want something not in-place, which returns a value, you could use
sorted_list = sorted(lista)
Aside #1: please don't call your lists list
. That clobbers the builtin list type.
Aside #2: I'm not sure what this line is meant to do:
print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")
is it simply
print "value 1a + value 2 = value 3a value 4"
? In other words, I don't know why you're calling str on things which are already str.
Aside #3: sometimes you use print("something")
(Python 3 syntax) and sometimes you use print "something"
(Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..
The exception TypeError: 'NoneType' object is not subscriptable
happens because the value of lista
is actually None
. You can reproduce TypeError
that you get in your code if you try this at the Python command line:
None[0]
The reason that lista
gets set to None is because the return value of list.sort()
is None
... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).
If you do not want to alter the original version you can use
other_list = sorted(lista)
Check Your Skype, I had the problem because skype reserved port 80 for incoming calls, I unchecked it , and it works fine.
On CentOS machine, the oneliner bash that worked for me was:
if ssh <servername> "stat <filename> > /dev/null 2>&1"; then echo "file exists"; else echo "file doesnt exits"; fi
It needed I/O redirection (as the top answer) as well as quotes around the command to be run on remote.
I found using while IFS='=' read -r
to be a bit slow (I don't know why, maybe someone could briefly explain in a comment or point to a SO answer?). I also found @Nicolai answer very neat as a one-liner, but very inefficient as it will scan the entire properties file over and over again for every single call of prop
.
I found a solution that answers the question, performs well and it is a one-liner (bit verbose line though).
The solution does sourcing but massages the contents before sourcing:
#!/usr/bin/env bash
source <(grep -v '^ *#' ./app.properties | grep '[^ ] *=' | awk '{split($0,a,"="); print gensub(/\./, "_", "g", a[1]) "=" a[2]}')
echo $db_uat_user
Explanation:
grep -v '^ *#'
: discard comment lines
grep '[^ ] *='
: discards lines without =
split($0,a,"=")
: splits line at =
and stores into array a
, i.e. a[1] is the key, a[2] is the value
gensub(/\./, "_", "g", a[1])
: replaces .
with _
print gensub... "=" a[2]}
concatenates the result of gensub
above with =
and value.
Edit: As others pointed out, there are some incompatibilities issues (awk) and also it does not validate the contents to see if every line of the property file is actually a kv pair. But the goal here is to show the general idea for a solution that is both fast and clean. Sourcing seems to be the way to go as it loads the properties once that can be used multiple times.
I used this:
HTML
<div class="container">
<div class="parent">
<div class="child">
<div class="inner-container"></div>
</div>
</div>
</div>
CSS
.container {
overflow-x: hidden;
}
.child {
position: relative;
width: 200%;
left: -50%;
}
.inner-container{
max-width: 1179px;
margin:0 auto;
}
sometimes require a carriage return:
os.popen("sudo -S %s"%(command), 'w').write('mypass\n')
Assgining a value that starts with a "=" will kick in formula evaluation and gave in my case the above mentioned error #1004. Prepending it with a space was the ticket for me.
You need to map attributes to aesthetics (colours within the aes statement) to produce a legend.
cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h, fill = "BAR"),colour="#333333")+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols) + scale_fill_manual(name="Bar",values=cols) +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
I understand where Roland is coming from, but since this is only 3 attributes, and complications arise from superimposing bars and error bars this may be reasonable to leave the data in wide format like it is. It could be slightly reduced in complexity by using geom_pointrange.
To change the background color for the error bars legend in the original, add + theme(legend.key = element_rect(fill = "white",colour = "white"))
to the plot specification. To merge different legends, you typically need to have a consistent mapping for all elements, but it is currently producing an artifact of a black background for me. I thought guide = guide_legend(fill = NULL,colour = NULL)
would set the background to null for the legend, but it did not. Perhaps worth another question.
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols, guide = guide_legend(fill = NULL,colour = NULL)) +
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
To get rid of the black background in the legend, you need to use the override.aes
argument to the guide_legend
. The purpose of this is to let you specify a particular aspect of the legend which may not be being assigned correctly.
ggplot(data=data,aes(x=a)) +
geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) + #red
geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) + #red
geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) +
geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) + #blue
geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) + #blue
geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) +
scale_colour_manual(name="Error Bars",values=cols,
guide = guide_legend(override.aes=aes(fill=NA))) +
scale_fill_manual(name="Bar",values=cols, guide="none") +
ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
ylim(0,1.6) +
theme_bw() +
theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
theme(axis.title.y = element_text(size = 15, vjust=0.3))
You can use GCD (in the example with a 10 second delay):
let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
self.functionToCall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
self.functionToCall()
})
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
//call any function
}
simple way to do this... here are the example
cd program files
cd poweriso
piso mount D:\<Filename.iso> <Virtual Drive>
Pause
this will mount the ISO image to the specific drive...use
Found this answer here and wanted to reference it as it appear much cleaner than the accepted answer:
function blobToDataURL(blob, callback) {
var fileReader = new FileReader();
fileReader.onload = function(e) {callback(e.target.result);}
fileReader.readAsDataURL(blob);
}
For someone who want to use onchange event directly on file input, set onchange="somefunction()
, example code from the link:
<html>
<body>
<script language="JavaScript">
function inform(){
document.form1.msg.value = "Filename has been changed";
}
</script>
<form name="form1">
Please choose a file.
<input type="file" name="uploadbox" size="35" onChange='inform()'>
<br><br>
Message:
<input type="text" name="msg" size="40">
</form>
</body>
</html>
Try ::after on previous element.
Open angular.json file and find budgets
keyword.
It should look like:
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
As you’ve probably guessed you can increase the maximumWarning
value to prevent this warning, i.e.:
"budgets": [
{
"type": "initial",
"maximumWarning": "4mb", <===
"maximumError": "5mb"
}
]
A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.
In our case budget is the limit for bundle sizes.
See also:
You should also properly configure the maximum memory allocations for MapReduce. From this HortonWorks tutorial:
[...]
Each machine in our cluster has 48 GB of RAM. Some of this RAM should be >reserved for Operating System usage. On each node, we’ll assign 40 GB RAM for >YARN to use and keep 8 GB for the Operating System
For our example cluster, we have the minimum RAM for a Container (yarn.scheduler.minimum-allocation-mb) = 2 GB. We’ll thus assign 4 GB for Map task Containers, and 8 GB for Reduce tasks Containers.
In mapred-site.xml:
mapreduce.map.memory.mb
: 4096
mapreduce.reduce.memory.mb
: 8192Each Container will run JVMs for the Map and Reduce tasks. The JVM heap size should be set to lower than the Map and Reduce memory defined above, so that they are within the bounds of the Container memory allocated by YARN.
In mapred-site.xml:
mapreduce.map.java.opts
:-Xmx3072m
mapreduce.reduce.java.opts
:-Xmx6144m
The above settings configure the upper limit of the physical RAM that Map and Reduce tasks will use.
To sum it up:
mapreduce
configs, not the mapred
ones. EDIT: This comment is not applicable anymore now that you've edited your question.java.opts
settings listed above.Finally, you may want to check this other SO question that describes a similar problem (and solution).
Update 2019/04/16: It seems copy/paste is now officially supported in Windows build >= 17643. Take a look at Rich Turner's answer. This can be enabled through the same settings menu described below by clicking the checkbox next to "Use Ctrl+Shift+C/V as Copy/Paste".
Another solution would be to enable "QuickEdit Mode" and then you can paste by right-clicking in the terminal.
To enable QuickEdit Mode, right-click on the toolbar (or simply click on the icon in the upper left corner), select Properties, and in the Options tab, click the checkbox next to QuickEdit Mode.
With this mode enabled, you can also copy text in the terminal by clicking and dragging. Once a selection is made, you can press Enter or right-click to copy.
Solution for PHP 5.2 with DateTime objects. But startDate MUST be before endDate.
function createRange($startDate, $endDate) {
$tmpDate = new DateTime($startDate);
$tmpEndDate = new DateTime($endDate);
$outArray = array();
do {
$outArray[] = $tmpDate->format('Y-m-d');
} while ($tmpDate->modify('+1 day') <= $tmpEndDate);
return $outArray;
}
Using:
$dates = createRange('2010-10-01', '2010-10-05');
$dates contain:
Array( '2010-10-01', '2010-10-02', '2010-10-03', '2010-10-04', '2010-10-05' )
As other's have mentioned, PHP's cURL functions will allow you to perform advanced HTTP requests. You can also use file_get_contents
to access REST APIs:
$payload = file_get_contents('http://api.someservice.com/SomeMethod?param=value');
Starting with PHP 5 you can also create a stream context which will allow you to change headers or post data to the service.
DateUtils.formatElapsedTime(long)
, formats an elapsed time in the form "MM:SS
" or "H:MM:SS
" . It returns the String you are looking for. You can find the documentation here
GlobalConfiguration
class is part of Microsoft.AspNet.WebApi.WebHost
nuget package...Have you upgraded this package to Web API 2?
This is the way I would do it : saying that "list" is a <List<t>>
where t is a class with a Name and a Value field; but of course you can do it with any other class type.
list = list.Where(c=>c.Name == "height")
.Select( new t(){Name = c.Name, Value = 30})
.Union(list.Where(c=> c.Name != "height"))
.ToList();
This works perfectly ! It's a simple linq expression without any loop logic. The only thing you should be aware is that the order of the lines in the result dataset will be different from the order you had in the source dataset. So if sorting is important to you, just reproduce the same order by clauses in the final linq query.
Here's what i use in .NET 4.8 to make a HTTP POST request. With this code one can send multiple POST requests at a time Asynchronously. At the end of each request an event is raised. And also at the end of all request another event is raised.
The one bellow is the core class:
Imports System.ComponentModel
Imports System.Text.RegularExpressions
Imports System.Timers
Imports System.Windows.Forms
Imports AeonLabs
Imports AeonLabs.Environment
Imports Newtonsoft.Json
Public Class HttpDataCore
Public Property url As String
Public Property state As New environmentVarsCore
Public Property errorMessage As String = ""
Public Property statusMessage As String
Public Property threadCount As Integer = 25
Public Property numberOfRetryAttempts = 5
Public Property queue As List(Of _queue_data_struct)
Public Property queueBWorker As Integer() ' has the size of threadCount
Public Property queueLock As New Object
Public Property retryAttempts As New _retry_attempts
Public Property dataStatistics As List(Of _data_statistics)
Public Property loadingCounter As Integer
Public Property CompletionPercentage As Integer ' value range 0-100
Public Property IsBusy As Boolean
Public Structure _queue_data_struct
Dim vars As Dictionary(Of String, String)
Dim filenameOrSavePath As String ' full address file name or full adress folder path
Dim misc As Dictionary(Of String, String)
Dim status As Integer ' -1 - completed; 0- not sent yet; 1-already sent / processing
End Structure
Public Structure _retry_attempts
Dim counter As Integer
Dim pattern As Integer
Dim previousPattern As Integer
Dim errorMessage As String
End Structure
Public Structure _data_statistics
Dim filesize As Double
Dim bytesSentReceived As Double
Dim speed As Double
End Structure
Public WithEvents RestartQueueTimer As New Timers.Timer
Public bwDataRequest() As BackgroundWorker
Public Event requestCompleted(sender As Object, requestData As String) 'TODO add misc vars
Private sendToQueue As Boolean
Public Sub New(ByVal Optional _state As environmentVarsCore = Nothing, ByVal Optional _url As String = "")
queue = New List(Of _queue_data_struct)
dataStatistics = New List(Of _data_statistics)
loadingCounter = 0
sendToQueue = False
If _state IsNot Nothing AndAlso _url.Equals("") Then
url = _state.ServerBaseAddr & _state.ApiServerAddrPath
ElseIf Not _url.Equals("") Then
url = _url
Else
Throw New System.Exception("Initialization err: state and url cannot be both null at same time")
End If
If _state IsNot Nothing Then
state = _state
End If
End Sub
Public Sub loadQueue(ByVal vars As Dictionary(Of String, String), ByVal Optional misc As Dictionary(Of String, String) = Nothing, ByVal Optional filenameOrSavePath As String = Nothing)
Dim queueItem As New _queue_data_struct
queueItem.vars = New Dictionary(Of String, String)
queueItem.misc = New Dictionary(Of String, String)
queueItem.vars = vars
queueItem.status = 0
queueItem.misc = misc
queueItem.filenameOrSavePath = filenameOrSavePath
queue.Add(queueItem)
End Sub
Public Sub clearQueue()
loadingCounter = 0
queue = New List(Of _queue_data_struct)
End Sub
Public Sub startRequest()
If bwDataRequest(0) Is Nothing Then
Throw New Exception("You need to call initialze first")
Exit Sub
End If
'startSendQueue()
IsBusy = True
AddHandler RestartQueueTimer.Elapsed, New ElapsedEventHandler(AddressOf QueueTimerTick)
With RestartQueueTimer
.Enabled = True
.Interval = 500
.Start()
End With
End Sub
Private Sub QueueTimerTick(ByVal sender As Object, ByVal e As ElapsedEventArgs)
If QueuesToComplete(queue).Equals(0) And QueuesToSend(queue).Equals(0) Then
RestartQueueTimer.Stop()
queue = New List(Of _queue_data_struct)
RaiseEvent requestCompleted(Me, Nothing)
IsBusy = False
Exit Sub
End If
If retryAttempts.counter >= numberOfRetryAttempts Then 'ToDo a retry number of attempts before quits
Threading.Thread.CurrentThread.CurrentUICulture = Globalization.CultureInfo.GetCultureInfo(state.currentLang)
Dim MsgBox As messageBoxForm
MsgBox = New messageBoxForm(retryAttempts.errorMessage & ". " & My.Resources.strings.tryAgain & " ?", My.Resources.strings.question, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If MsgBox.ShowDialog() = DialogResult.Yes Then
Dim retry As _retry_attempts
With retry
.counter = 0
.previousPattern = -1
.pattern = 0
.errorMessage = ""
End With
retryAttempts = retry
startSendQueue()
Else
RestartQueueTimer.Stop()
queue = New List(Of _queue_data_struct)
RaiseEvent requestCompleted(Me, Nothing)
IsBusy = False
Exit Sub
End If
Exit Sub
ElseIf Not sendToQueue And QueuesToSend(queue) > 0 Then
startSendQueue()
End If
End Sub
Private Sub startSendQueue()
sendToQueue = True
While QueuesToSend(queue) > 0
For shtIndex = 0 To threadCount
For i = 0 To queue.Count - 1
If Not bwDataRequest(shtIndex).IsBusy Then
SyncLock queueLock
If queue.ElementAt(i).status.Equals(0) Then
Dim data As New _queue_data_struct
data.vars = queue.ElementAt(i).vars
data.status = 1
data.misc = queue.ElementAt(i).misc
data.filenameOrSavePath = queue.ElementAt(i).filenameOrSavePath
queue(i) = data
queueBWorker(shtIndex) = i
dataStatistics(shtIndex) = (New _data_statistics)
bwDataRequest(shtIndex).RunWorkerAsync(queue(i))
Threading.Thread.Sleep(50)
End If
End SyncLock
End If
Next i
Next shtIndex
End While
sendToQueue = False
End Sub
Public Function QueuesToSend(queue As List(Of _queue_data_struct)) As Integer
Dim counter As Integer = 0
For i = 0 To queue.Count - 1
If queue(i).status.Equals(0) Then
counter += 1
End If
Next i
Return counter
End Function
Public Function QueuesToComplete(queue As List(Of _queue_data_struct)) As Integer
Dim counter As Integer = 0
For i = 0 To queue.Count - 1
If queue(i).status.Equals(1) Then
counter += 1
End If
Next i
Return counter
End Function
Public Function QueuesMultiHash(queue As List(Of _queue_data_struct)) As Integer
Dim counter As Integer = 0
For i = 0 To queue.Count - 1
If queue(i).status.Equals(1) Then
counter += i
End If
Next i
Return counter
End Function
Public Function IsBase64String(ByVal s As String) As Boolean
s = s.Trim()
Return (s.Length Mod 4 = 0) AndAlso Regex.IsMatch(s, "^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None)
End Function
'+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Public Function ConvertDataToArray(key As String, fields As String(), response As String) As Dictionary(Of String, List(Of String))
If GetMessage(response).Equals("1001") Then
Threading.Thread.CurrentThread.CurrentUICulture = Globalization.CultureInfo.GetCultureInfo(state.currentLang)
errorMessage = "{'error':true,'message':'" & My.Resources.strings.errorNoRecordsFound & "'}"
Return Nothing
End If
Try
Dim jsonResult = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(response)
If jsonResult.ContainsKey(key) Then
If Not jsonResult.Item(key).item(0).Count.Equals(fields.Length) Then
Threading.Thread.CurrentThread.CurrentUICulture = Globalization.CultureInfo.GetCultureInfo(state.currentLang)
errorMessage = "{'error':true,'message':'" & My.Resources.strings.JsonFieldsMismatch & ". table(" & key & "'}"
Return Nothing
Else
Dim results = New Dictionary(Of String, List(Of String))
For k = 0 To fields.Length - 1
Dim fieldValues As List(Of String) = New List(Of String)
For i = 0 To jsonResult.Item(key).Count - 1
fieldValues.Add(jsonResult.Item(key).item(i).item(k).ToString)
Next i
results.Add(fields(k), fieldValues)
Next k
Return results
End If
Else
Threading.Thread.CurrentThread.CurrentUICulture = Globalization.CultureInfo.GetCultureInfo(state.currentLang)
errorMessage = "{'error':true,'message':'" & My.Resources.strings.JsonkeyNotFound & " (" & key & "'}"
Return Nothing
End If
Catch ex As Exception
errorMessage = "{'error':true,'message':'" & ex.ToString & "'}"
errorMessage = ex.ToString
Return Nothing
End Try
End Function
End Class
the AeonLabs.Envoriment
is a class with a collection or fields and properties.
And the one bellow is for making a POST request:
Imports System.ComponentModel
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Web
Imports System.Web.Script.Serialization
Imports System.Windows.Forms
Imports AeonLabs.Environment
Imports AeonLabs.Security
Public Class HttpDataPostData
Inherits HttpDataCore
Public Event updateProgress(sender As Object, misc As Dictionary(Of String, String))
Public Event dataArrived(sender As Object, requestData As String, misc As Dictionary(Of String, String))
Public Sub New(ByVal Optional _state As environmentVarsCore = Nothing, ByVal Optional _url As String = "")
MyBase.New(_state, _url)
End Sub
Public Sub initialize(ByVal Optional _threadCount As Integer = 0)
If Not _threadCount.Equals(0) Then
threadCount = _threadCount
End If
ReDim bwDataRequest(threadCount)
ReDim queueBWorker(threadCount)
For shtIndex = 0 To threadCount
dataStatistics.Add(New _data_statistics)
bwDataRequest(shtIndex) = New System.ComponentModel.BackgroundWorker
bwDataRequest(shtIndex).WorkerReportsProgress = True
bwDataRequest(shtIndex).WorkerSupportsCancellation = True
AddHandler bwDataRequest(shtIndex).DoWork, AddressOf bwDataRequest_DoWork
AddHandler bwDataRequest(shtIndex).RunWorkerCompleted, AddressOf bwDataRequest_RunWorkerCompleted
Next shtIndex
Dim retry As _retry_attempts
With retry
.counter = 0
.previousPattern = -1
.pattern = 0
.errorMessage = ""
End With
retryAttempts = retry
End Sub
Private Sub bwDataRequest_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
' Find out the Index of the bWorker that called this DoWork (could be cleaner, I know)
Dim Y As Integer
Dim Index As Integer = Nothing
For Y = 0 To UBound(bwDataRequest)
If sender.Equals(bwDataRequest(Y)) Then
Index = Y
Exit For
End If
Next Y
Dim queue As _queue_data_struct
queue = e.Argument
Dim vars As New Dictionary(Of String, String)
vars = queue.vars
'TODO translation need to be local
If Not System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() Then
Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(state.currentLang)
e.Result = "{'error':true,'message':'" & My.Resources.strings.errorNoNetwork & "'}"
Exit Sub
End If
If vars Is Nothing Then
e.Result = "{'error':true,'message':'missconfiguration vars'}"
Exit Sub
End If
If Not vars.ContainsKey("id") Then
vars.Add("id", state.userId)
End If
If Not vars.ContainsKey("pid") Then
Dim appId As New FingerPrint
vars.Add("pid", appId.Value)
End If
If Not vars.ContainsKey("language") Then
vars.Add("language", state.currentLang)
End If
If Not vars.ContainsKey("origin") Then
vars.Add("origin", state.softwareAccessMode)
End If
Dim serializer As New JavaScriptSerializer()
Dim json As String = serializer.Serialize(vars)
Dim encryption As New AesCipher(state)
Dim encrypted As String = HttpUtility.UrlEncode(encryption.encrypt(json))
Dim PostData = "origin=" & state.softwareAccessMode & "&data=" & encrypted
Dim request As WebRequest = WebRequest.Create(url)
Dim responseFromServer As String = ""
Dim decrypted As String = ""
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(PostData)
request.ContentType = "application/x-www-form-urlencoded"
request.Headers.Add("Authorization", state.ApiHttpHeaderToken & "-" & state.softwareAccessMode)
request.ContentLength = byteArray.Length
Try
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
responseFromServer = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
If response.StatusCode = HttpStatusCode.Accepted Or response.StatusCode = 200 Then
If IsBase64String(responseFromServer) And Not responseFromServer.Equals("") Then
decrypted = encryption.decrypt((responseFromServer)).Replace("\'", "'")
Else
Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(state.currentLang)
decrypted = "{'error':true,'encrypted':false,'message':'" & My.Resources.strings.contactingCommServer & " |" & responseFromServer & "|'}"
End If
Else
Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(state.currentLang)
decrypted = "{'error':true,'message':'" & My.Resources.strings.contactingCommServer & " (" & response.StatusCode & ")', 'statuscode':'" & response.StatusCode & "'}"
End If
Catch ex As Exception
Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(state.currentLang)
decrypted = "{'error':true,'message':'" & My.Resources.strings.contactingCommServer & " (" & ex.Message.ToString.Replace("'", "\'") & ")'}"
End Try
e.Result = decrypted.Replace("\'", "'")
End Sub
Private Sub bwDataRequest_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs)
' Find out the Index of the bWorker that called this DoWork (could be cleaner, I know)
Dim Y As Integer
Dim Index As Integer = Nothing
Dim data As New _queue_data_struct
For Y = 0 To UBound(bwDataRequest)
If sender.Equals(bwDataRequest(Y)) Then
Index = Y
Exit For
End If
Next Y
If IsResponseOk(e.Result, "statuscode") Then
data = New _queue_data_struct
data = queue(queueBWorker(Index))
data.status = 0 're queue the file
SyncLock queueLock
queue(queueBWorker(Index)) = data
End SyncLock
Dim errorMsg As String = GetMessage(e.Result)
Dim retry As _retry_attempts
With retry
.counter = retryAttempts.counter
.previousPattern = retryAttempts.previousPattern
.pattern = retryAttempts.pattern
.errorMessage = retryAttempts.errorMessage
End With
retry.errorMessage = If(retryAttempts.errorMessage.IndexOf(errorMsg) > -1, retryAttempts.errorMessage, retryAttempts.errorMessage & System.Environment.NewLine & errorMsg)
retry.pattern = QueuesMultiHash(queue)
If retry.previousPattern.Equals(retry.pattern) Then
retry.counter += 1
Else
retry.counter = 1
retry.previousPattern = retryAttempts.pattern
End If
retryAttempts = retry
Exit Sub
End If
data = New _queue_data_struct
data = queue(queueBWorker(Index))
data.status = -1 'completed sucessfully status
SyncLock queueLock
queue(queueBWorker(Index)) = data
End SyncLock
loadingCounter += 1
CompletionPercentage = (loadingCounter / queue.Count) * 100
statusMessage = "Loading data from the cloud ..."
RaiseEvent updateProgress(Me, queue(queueBWorker(Index)).misc)
RaiseEvent dataArrived(Me, e.Result, queue(queueBWorker(Index)).misc)
End Sub
End Class
The Aoenlabs.Security is a class for sending POST data encrypted using standard encryption algorithms
To find any sub-string from large string:
string_value:=('This is String,Please search string 'Ple');
Then to find the string 'Ple'
from String_value
we can do as:
select substr(string_value,instr(string_value,'Ple'),length('Ple')) from dual;
You will find result: Ple
you should use "append" mode redirection >>
instead of >
You can also use command palette:
Does the same thing as the terminal.
Two options:
Install Oracle client on the PC you want to run your program on
Use Oracle.ManagedDataAccess.dll
You can get it on NuGet (search 'oracle managed') or download ODP.NET_Managed.zip (link is to a beta version, but points you in the right direction)
I use this so that the computers I deploy onto don't need Oracle client installed.
N.B. in my opinion this is good for console apps but annoying if you intend to install your application, so I install the client in that case.
if your text doesn't spill over two rows then you can do line-height: ;
in your CSS, the more line-height you give, the lower on the container it will hold.
The NetworkInfo
class is deprecated as of API level 29, along with the related access methods like ConnectivityManager#getNetworkInfo()
and ConnectivityManager#getActiveNetworkInfo()
.
The documentation now suggests people to use the ConnectivityManager.NetworkCallback
API for asynchronized callback monitoring, or use ConnectivityManager#getNetworkCapabilities
or ConnectivityManager#getLinkProperties
for synchronized access of network information
Callers should instead use the ConnectivityManager.NetworkCallback API to learn about connectivity changes, or switch to use ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties to get information synchronously.
To check if WiFi is connected, here's the code that I use:
Kotlin:
val connMgr = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
connMgr?: return false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val network: Network = connMgr.activeNetwork ?: return false
val capabilities = connMgr.getNetworkCapabilities(network)
return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
} else {
val networkInfo = connMgr.activeNetworkInfo ?: return false
return networkInfo.isConnected && networkInfo.type == ConnectivityManager.TYPE_WIFI
}
Java:
ConnectivityManager connMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connMgr == null) {
return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network network = connMgr.getActiveNetwork();
if (network == null) return false;
NetworkCapabilities capabilities = connMgr.getNetworkCapabilities(network);
return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
} else {
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
}
Remember to also add permission ACCESS_NETWORK_STATE
to your Manifest file.
$route: This is used for deep-linking URLs to controllers and views (HTML partials) and watches $location.url() in order to map the path from an existing definition of route.
When we use ngRoute, the route is configured with $routeProvider and when we use ui-router, the route is configured with $stateProvider and $urlRouterProvider.
<div ng-view></div>
$routeProvider
.when('/contact/', {
templateUrl: 'app/views/core/contact/contact.html',
controller: 'ContactCtrl'
});
<div ui-view>
<div ui-view='abc'></div>
<div ui-view='abc'></div>
</div>
$stateProvider
.state("contact", {
url: "/contact/",
templateUrl: '/app/Aisel/Contact/views/contact.html',
controller: 'ContactCtrl'
});
Ok folks, I ran into this problem this weekend when my OpenStack environment crashed. Another post about that coming soon on how to recover.
I found a solution that worked for me with a SQL Server instance running under the Ver 15.1 Distrib 10.1.21-MariaDB with Fedora 25 Server as the host. Do not listen to all the other posts that say your database is corrupted if you completely copied your old mariadb-server's /var/lib/mysql directory and the database you are copying is not already corrupted. This process is based on a system where the OS became corrupted but its files were still accessible.
Here are the steps I followed.
Make sure that you have completely uninstalled any current versions of SQL only on the NEW server. Also, make sure ALL mysql-server or mariadb-server processes on the NEW AND OLD servers have been halted by running:
service mysqld stop or service mariadb stop.
On the NEW SQL server go into the /var/lib/mysql directory and ensure that there are no files at all in this directory. If there are files in this directory then your process for removing the database server from the new machine did not work and is possibly corrupted. Make sure it completely uninstalled from the new machine.
On the OLD SQL server:
mkdir /OLDMYSQL-DIR cd /OLDMYSQL-DIR tar cvf mysql-olddirectory.tar /var/lib/mysql gzip mysql-olddirectory.tar
Make sure you have sshd running on both the OLD and NEW servers. Make sure there is network connectivity between the two servers.
On the NEW SQL server:
mkdir /NEWMYSQL-DIR
On the OLD SQL server:
cd /OLDMYSQL-DIR scp mysql-olddirectory.tar.gz @:/NEWMYSQL-DIR
On the NEW SQL server:
cd /NEWMYSQL-DIR gunzip mysql-olddirectory.tar.gz OR tar zxvf mysql-olddirectory.tar.gz (if tar zxvf doesn't work) tar xvf mysql-olddirectory.tar.gz
You should now have a "mysql" directory file sitting in the NEWMYSQL-DIR. Resist the urge to run a "cp" command alone with no switches. It will not work. Run the following "cp" command and ensure you use the same switches I did.
cd mysql/ cp -rfp * /var/lib/mysql/
Now you should have a copy of all of your old SQL server files on the NEW server with permissions in tact. On the NEW SQL server:
cd /var/lib/mysql/
VERY IMPORTANT STEP. DO NOT SKIP
> rm -rfp ib_logfile*
FOR MARIADB-SERVER and DNF:
> dnf install mariadb-server
> service mariadb restart
FOR MYSQL-SERVER and YUM:
> yum install mysql-server
> service mysqld restart
Beautiful explanation given by bobf for Boolean values : True or False? A Quick Reference Guide
Truth tests for different values
Result of the expression when $var is:
Expression | 1 | '0.0' | a string | 0 | empty str | undef
--------------------+--------+--------+----------+-------+-----------+-------
if( $var ) | true | true | true | false | false | false
if( defined $var ) | true | true | true | true | true | false
if( $var eq '' ) | false | false | false | false | true | true
if( $var == 0 ) | false | true | true | true | true | true
According to the HTML standard, you can not. The only valid values for the method attribute are get
and post
, corresponding to the GET and POST HTTP methods. <form method="put">
is invalid HTML and will be treated like <form>
, i.e. send a GET request.
Instead, many frameworks simply use a POST parameter to tunnel the HTTP method:
<form method="post" ...>
<input type="hidden" name="_method" value="put" />
...
Of course, this requires server-side unwrapping.
I did some benchmarks to compare the execution time of COUNT(*)
vs COUNT(id)
(id is the primary key of the table - indexed).
Number of trials: 10 * 1000 queries
Results:
COUNT(*)
is faster 7%
VIEW GRAPH: benchmarkgraph
My advice is to use: SELECT COUNT(*) FROM table
Some commentors already stated that answers to your question will not work for all distributions. Since you did not include CentOS in the question but only in the tags, I'd like to post here the topics one has to understand in order to have a control over his/her proceeding regardless of the distribution:
For your problem, one could start the script on sysinit by adding this line in /etc/inittab and make it respawn in case it terminates:
# start and respawn after termination
ttyS0::respawn:/bin/sh /path/to/my_script.sh
The script has to be made executable in advance of course:
chmod +x /path/to/my_script.sh
Hope this helps
The code below does the same thing as centering in the Interface Builder.
override func viewDidLoad() {
super.viewDidLoad()
// set up the view
let myView = UIView()
myView.backgroundColor = UIColor.blue
myView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myView)
// Add code for one of the constraint methods below
// ...
}
Method 1: Anchor Style
myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
Method 2: NSLayoutConstraint Style
NSLayoutConstraint(item: myView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint
Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint
Style.KOTLIN
Any Activity that restarts has its onResume() method executed first.
To use this method, do this:
override fun onResume() {
super.onResume()
// your code here
}
ifeq ($(GCC_MINOR), 4) CFLAGS += -fno-strict-overflow endif ifeq ($(GCC_MINOR), 5) CFLAGS += -fno-strict-overflow endif
Another you can consider using in this case is:
GCC42_OR_LATER = $(shell $(CXX) -v 2>&1 | $(EGREP) -c "^gcc version (4.[2-9]|[5-9])")
# -Wstrict-overflow: http://www.airs.com/blog/archives/120
ifeq ($(GCC42_OR_LATER),1)
CFLAGS += -Wstrict-overflow
endif
I actually use the same in my code because I don't want to maintain a separate config
or Configure
.
But you have to use a portable, non-anemic make
, like GNU make (gmake
), and not Posix's make
.
And it does not address the issue of logical AND
and OR
.
With the Hub command-line wrapper you can link it to git and then you can do
git pull-request
From the man page of hub:
git pull-request [-f] [TITLE|-i ISSUE|ISSUE-URL] [-b BASE] [-h HEAD]
Opens a pull request on GitHub for the project that the "origin" remote points to. The default head of the pull request is the current branch. Both base and head of the pull request can be explicitly given in one of the following formats: "branch", "owner:branch",
"owner/repo:branch". This command will abort operation if it detects that the current topic branch has local commits that are not yet pushed to its upstream branch on the remote. To skip this check, use -f.
If TITLE is omitted, a text editor will open in which title and body of the pull request can be entered in the same manner as git commit message.
If instead of normal TITLE an issue number is given with -i, the pull request will be attached to an existing GitHub issue. Alternatively, instead of title you can paste a full URL to an issue on GitHub.
I had the similar problem: EOF -warning and only part of data was loading with read.csv(). I tried the quotes="", but it only removed the EOF -warning.
But looking at the first row that was not loading, I found that there was a special character, an arrow ? (hexadecimal value 0x1A) in one of the cells. After deleting the arrow I got the data to load normally.
public class MenuFragment extends Fragment implements View.OnClickListener {
private Context mContext;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragmentMenuBinding binding=FragmentMenuBinding.inflate(inflater,container,false);
View view=binding.getRoot();
mContext=view.getContext();
return view;
}
}
Here is my approach by creating a wrapper to run tests from the command line:
#!/usr/bin/env python3
import os, sys, unittest, argparse, inspect, logging
if __name__ == '__main__':
# Parse arguments.
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("-?", "--help", action="help", help="show this help message and exit" )
parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", help="increase output verbosity" )
parser.add_argument("-d", "--debug", action="store_true", dest="debug", help="show debug messages" )
parser.add_argument("-h", "--host", action="store", dest="host", help="Destination host" )
parser.add_argument("-b", "--browser", action="store", dest="browser", help="Browser driver.", choices=["Firefox", "Chrome", "IE", "Opera", "PhantomJS"] )
parser.add_argument("-r", "--reports-dir", action="store", dest="dir", help="Directory to save screenshots.", default="reports")
parser.add_argument('files', nargs='*')
args = parser.parse_args()
# Load files from the arguments.
for filename in args.files:
exec(open(filename).read())
# See: http://codereview.stackexchange.com/q/88655/15346
def make_suite(tc_class):
testloader = unittest.TestLoader()
testnames = testloader.getTestCaseNames(tc_class)
suite = unittest.TestSuite()
for name in testnames:
suite.addTest(tc_class(name, cargs=args))
return suite
# Add all tests.
alltests = unittest.TestSuite()
for name, obj in inspect.getmembers(sys.modules[__name__]):
if inspect.isclass(obj) and name.startswith("FooTest"):
alltests.addTest(make_suite(obj))
# Set-up logger
verbose = bool(os.environ.get('VERBOSE', args.verbose))
debug = bool(os.environ.get('DEBUG', args.debug))
if verbose or debug:
logging.basicConfig( stream=sys.stdout )
root = logging.getLogger()
root.setLevel(logging.INFO if verbose else logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO if verbose else logging.DEBUG)
ch.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(name)s: %(message)s'))
root.addHandler(ch)
else:
logging.basicConfig(stream=sys.stderr)
# Run tests.
result = unittest.TextTestRunner(verbosity=2).run(alltests)
sys.exit(not result.wasSuccessful())
For sake of simplicity, please excuse my non-PEP8 coding standards.
Then you can create BaseTest class for common components for all your tests, so each of your test would simply look like:
from BaseTest import BaseTest
class FooTestPagesBasic(BaseTest):
def test_foo(self):
driver = self.driver
driver.get(self.base_url + "/")
To run, you simply specifying tests as part of the command line arguments, e.g.:
./run_tests.py -h http://example.com/ tests/**/*.py
You can use android:windowSoftInputMode="stateAlwaysHidden|adjustResize"
in AndroidManifest.xml for your current activity,
and use android:fitsSystemWindows="true"
in styles or rootLayout.
Check out the moment.js
library. It works with browsers as well as with Node.JS. Allows you to write
moment().hour();
or
moment().hours();
without prior writing of any functions.
You can also try clicking by JavaScript:
WebElement button = driver.findElement(By.id("someid"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].click();", button);
Also you can use jquery. In worst cases, for stubborn pages it may be necessary to do clicks by custom EXE application. But try the obvious solutions first.
GCC: GNU Compiler Collection
gcc
: GNU C Compiler
g++
: GNU C++ Compiler
The main differences:
gcc
will compile: *.c\*.cpp
files as C and C++ respectively.g++
will compile: *.c\*.cpp
files but they will all be treated as C++ files.g++
to link the object files it automatically links in the std C++ libraries (gcc
does not do this).gcc
compiling C files has fewer predefined macros.gcc
compiling *.cpp
and g++
compiling *.c\*.cpp
files has a few extra macros.Extra Macros when compiling *.cpp
files:
#define __GXX_WEAK__ 1
#define __cplusplus 1
#define __DEPRECATED 1
#define __GNUG__ 4
#define __EXCEPTIONS 1
#define __private_extern__ extern
Try this
import android.content.Context;
import android.graphics.Canvas;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.SeekBar;
/**
* Implementation of an easy vertical SeekBar, based on the normal SeekBar.
*/
public class VerticalSeekBar extends SeekBar {
/**
* The angle by which the SeekBar view should be rotated.
*/
private static final int ROTATION_ANGLE = -90;
/**
* A change listener registrating start and stop of tracking. Need an own listener because the listener in SeekBar
* is private.
*/
private OnSeekBarChangeListener mOnSeekBarChangeListener;
/**
* Standard constructor to be implemented for all views.
*
* @param context The Context the view is running in, through which it can access the current theme, resources, etc.
* @see android.view.View#View(Context)
*/
public VerticalSeekBar(final Context context) {
super(context);
}
/**
* Standard constructor to be implemented for all views.
*
* @param context The Context the view is running in, through which it can access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the view.
* @see android.view.View#View(Context, AttributeSet)
*/
public VerticalSeekBar(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
/**
* Standard constructor to be implemented for all views.
*
* @param context The Context the view is running in, through which it can access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the view.
* @param defStyle An attribute in the current theme that contains a reference to a style resource that supplies default
* values for the view. Can be 0 to not look for defaults.
* @see android.view.View#View(Context, AttributeSet, int)
*/
public VerticalSeekBar(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
}
/*
* (non-Javadoc) ${see_to_overridden}
*/
@Override
protected final void onSizeChanged(final int width, final int height, final int oldWidth, final int oldHeight) {
super.onSizeChanged(height, width, oldHeight, oldWidth);
}
/*
* (non-Javadoc) ${see_to_overridden}
*/
@Override
protected final synchronized void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
super.onMeasure(heightMeasureSpec, widthMeasureSpec);
setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
}
/*
* (non-Javadoc) ${see_to_overridden}
*/
@Override
protected final void onDraw(@NonNull final Canvas c) {
c.rotate(ROTATION_ANGLE);
c.translate(-getHeight(), 0);
super.onDraw(c);
}
/*
* (non-Javadoc) ${see_to_overridden}
*/
@Override
public final void setOnSeekBarChangeListener(final OnSeekBarChangeListener listener) {
// Do not use super for the listener, as this would not set the fromUser flag properly
mOnSeekBarChangeListener = listener;
}
/*
* (non-Javadoc) ${see_to_overridden}
*/
@Override
public final boolean onTouchEvent(@NonNull final MotionEvent event) {
if (!isEnabled()) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
setProgressInternally(getMax() - (int) (getMax() * event.getY() / getHeight()), true);
if (mOnSeekBarChangeListener != null) {
mOnSeekBarChangeListener.onStartTrackingTouch(this);
}
break;
case MotionEvent.ACTION_MOVE:
setProgressInternally(getMax() - (int) (getMax() * event.getY() / getHeight()), true);
break;
case MotionEvent.ACTION_UP:
setProgressInternally(getMax() - (int) (getMax() * event.getY() / getHeight()), true);
if (mOnSeekBarChangeListener != null) {
mOnSeekBarChangeListener.onStopTrackingTouch(this);
}
break;
case MotionEvent.ACTION_CANCEL:
if (mOnSeekBarChangeListener != null) {
mOnSeekBarChangeListener.onStopTrackingTouch(this);
}
break;
default:
break;
}
return true;
}
/**
* Set the progress by the user. (Unfortunately, Seekbar.setProgressInternally(int, boolean) is not accessible.)
*
* @param progress the progress.
* @param fromUser flag indicating if the change was done by the user.
*/
public final void setProgressInternally(final int progress, final boolean fromUser) {
if (progress != getProgress()) {
super.setProgress(progress);
if (mOnSeekBarChangeListener != null) {
mOnSeekBarChangeListener.onProgressChanged(this, progress, fromUser);
}
}
onSizeChanged(getWidth(), getHeight(), 0, 0);
}
/*
* (non-Javadoc) ${see_to_overridden}
*/
@Override
public final void setProgress(final int progress) {
setProgressInternally(progress, false);
}
}
plt.show()
should come after plt.savefig()
Explanation: plt.show()
clears the whole thing, so anything afterwards will happen on a new empty figure
We already have tons of options to get mean by group, adding one more from mosaic
package.
mosaic::mean(speed~dive, data = df)
#dive1 dive2
#0.579 0.440
This returns a named numeric vector, if needed a dataframe we can wrap it in stack
stack(mosaic::mean(speed~dive, data = df))
# values ind
#1 0.579 dive1
#2 0.440 dive2
data
set.seed(123)
df <- data.frame(dive=factor(sample(c("dive1","dive2"),10,replace=TRUE)),
speed=runif(10))
The awnser of @Alireza is totally correct, but you must notice that when using this code
var res = from element in list
group element by element.F1
into groups
select groups.OrderBy(p => p.F2).First();
which is simillar to this code because you ordering the list and then do the grouping so you are getting the first row of groups
var res = (from element in list)
.OrderBy(x => x.F2)
.GroupBy(x => x.F1)
.Select()
Now if you want to do something more complex like take the same grouping result but take the first element of F2 and the last element of F3 or something more custom you can do it by studing the code bellow
var res = (from element in list)
.GroupBy(x => x.F1)
.Select(y => new
{
F1 = y.FirstOrDefault().F1;
F2 = y.First().F2;
F3 = y.Last().F3;
});
So you will get something like
F1 F2 F3
-----------------------------------
Nima 1990 12
John 2001 2
Sara 2010 4
What does it mean to "unwrap the instance"? Why is it necessary?
As far as I can work out (this is very new to me, too)...
The term "wrapped" implies we should think of an Optional variable as a present, wrapped in shiny paper, which might (sadly!) be empty.
When "wrapped", the value of an Optional variable is an enum with two possible values (a little like a Boolean). This enum describes whether the variable holds a value (Some(T)
), or not (None
).
If there is a value, this can be obtained by "unwrapping" the variable (obtaining the T
from Some(T)
).
How is
john!.apartment = number73
different fromjohn.apartment = number73
? (Paraphrased)
If you write the name of an Optional variable (eg text john
, without the !
), this refers to the "wrapped" enum (Some/None), not the value itself (T). So john
isn't an instance of Person
, and it doesn't have an apartment
member:
john.apartment
// 'Person?' does not have a member named 'apartment'
The actual Person
value can be unwrapped in various ways:
john!
(gives the Person
value if it exists, runtime error if it is nil)if let p = john { println(p) }
(executes the println
if the value exists)john?.learnAboutSwift()
(executes this made-up method if the value exists)I guess you choose one of these ways to unwrap, depending upon what should happen in the nil case, and how likely that is. This language design forces the nil case to be handled explicitly, which I suppose improves safety over Obj-C (where it is easy to forget to handle the nil case).
Update:
The exclamation mark is also used in the syntax for declaring "Implicitly Unwrapped Optionals".
In the examples so far, the john
variable has been declared as var john:Person?
, and it is an Optional. If you want the actual value of that variable, you must unwrap it, using one of the three methods above.
If it were declared as var john:Person!
instead, the variable would be an Implicitly Unwrapped Optional (see the section with this heading in Apple's book). There is no need to unwrap this kind of variable when accessing the value, and john
can be used without additional syntax. But Apple's book says:
Implicitly unwrapped optionals should not be used when there is a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable.
Update 2:
The article "Interesting Swift Features" by Mike Ash gives some motivation for optional types. I think it is great, clear writing.
Update 3:
Another useful article about the implicitly unwrapped optional use for the exclamation mark: "Swift and the Last Mile" by Chris Adamson. The article explains that this is a pragmatic measure by Apple used to declare the types used by their Objective-C frameworks which might contain nil. Declaring a type as optional (using ?
) or implicitly unwrapped (using !
) is "a tradeoff between safety and convenience". In the examples given in the article, Apple have chosen to declare the types as implicitly unwrapped, making the calling code more convenient, but less safe.
Perhaps Apple might comb through their frameworks in the future, removing the uncertainty of implicitly unwrapped ("probably never nil") parameters and replacing them with optional ("certainly could be nil in particular [hopefully, documented!] circumstances") or standard non-optional ("is never nil") declarations, based on the exact behaviour of their Objective-C code.
It's the ternary form of the if-else operator. The above statement basically reads like this:
if ($add_review) then {
return FALSE; //$add_review evaluated as True
} else {
return $arg //$add_review evaluated as False
}
See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/
Assuming your array contains strings, you can use the following:
String[] data = new String[] {
"2009.07.25 20:24 Message A",
"2009.07.25 20:17 Message G",
"2009.07.25 20:25 Message B",
"2009.07.25 20:30 Message D",
"2009.07.25 20:01 Message F",
"2009.07.25 21:08 Message E",
"2009.07.25 19:54 Message R"
};
Arrays.sort(data, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
String t1 = s1.substring(0, 16); // date/time of s1
String t2 = s2.substring(0, 16); // date/time of s2
return t1.compareTo(t2);
}
});
If you have a two-dimensional array, the solution is also very similar:
String[][] data = new String[][] {
{ "2009.07.25 20:17", "Message G" },
{ "2009.07.25 20:25", "Message B" },
{ "2009.07.25 20:30", "Message D" },
{ "2009.07.25 20:01", "Message F" },
{ "2009.07.25 21:08", "Message E" },
{ "2009.07.25 19:54", "Message R" }
};
Arrays.sort(data, new Comparator<String[]>() {
@Override
public int compare(String[] s1, String[] s2) {
String t1 = s1[0];
String t2 = s2[0];
return t1.compareTo(t2);
}
});
Couple of ways. Firstly, if you're adding a row each time a [de]activation occurs, you can set the column default to GETDATE() and not set the value in the insert. Otherwise,
UPDATE TableName SET [ColumnName] = GETDATE() WHERE UserId = @userId
How does @Autowired
work internally?
Example:
class EnglishGreeting {
private Greeting greeting;
//setter and getter
}
class Greeting {
private String message;
//setter and getter
}
.xml file it will look alike if not using @Autowired
:
<bean id="englishGreeting" class="com.bean.EnglishGreeting">
<property name="greeting" ref="greeting"/>
</bean>
<bean id="greeting" class="com.bean.Greeting">
<property name="message" value="Hello World"/>
</bean>
If you are using @Autowired
then:
class EnglishGreeting {
@Autowired //so automatically based on the name it will identify the bean and inject.
private Greeting greeting;
//setter and getter
}
.xml file it will look alike if not using @Autowired
:
<bean id="englishGreeting" class="com.bean.EnglishGreeting"></bean>
<bean id="greeting" class="com.bean.Greeting">
<property name="message" value="Hello World"/>
</bean>
If still have some doubt then go through below live demo
This question will give you good insights on how to delete a record from a DataTable:
DataTable, How to conditionally delete rows
It would look like this:
DataRow[] drr = dt.Select("Student=' " + id + " ' ");
foreach (var row in drr)
row.Delete();
Don't forget that if you want to update your database, you are going to need to call the Update command. For more information on that, see this link:
With C++ 20 you can write the following:
template<typename T>
concept has_toString = requires(const T& t) {
t.toString();
};
template<typename T>
std::string optionalToString(const T& obj)
{
if constexpr (has_toString<T>)
return obj.toString();
else
return "toString not defined";
}
Use the .Clear
method.
Sheets("Test").Range("A1:C3").Clear
dataType:'jsonp',
You are making a JSONP request, but the server is responding with JSON.
The browser is refusing to try to treat the JSON as JSONP because it would be a security risk. (If the browser did try to treat the JSON as JSONP then it would, at best, fail).
See this question for more details on what JSONP is. Note that is a nasty hack to work around the Same Origin Policy that was used before CORS was available. CORS is a much cleaner, safer, and more powerful solution to the problem.
It looks like you are trying to make a cross-origin request and are throwing everything you can think of at it in one massive pile of conflicting instructions.
You need to understand how the Same Origin policy works.
See this question for an in-depth guide.
Now a few notes about your code:
contentType: 'application/json',
Remove that.
dataType:'jsonp',
Remove this. (You could make the server respond with JSONP instead, but CORS is better).
responseType:'application/json',
This is not an option supported by jQuery.ajax. Remove this.
xhrFields: { withCredentials: false },
This is the default. Unless you are setting it to true with ajaxSetup, remove this.
headers: { 'Access-Control-Allow-Credentials' : true, 'Access-Control-Allow-Origin':'*', 'Access-Control-Allow-Methods':'GET', 'Access-Control-Allow-Headers':'application/json', },
can you try this :
function f (){
fname = $("input[name='fname']").val();
lname = $("input[name='fname']").val();
att=form.attr("action") ;
$.post(att ,{fname : fname , lname :lname}).done(function(data){
alert(data);
});
return true;
}
Hope this is something what you are trying to do :
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Test {
private Map ttp = new HashMap();
public void test() {
Field declaredField = null;
try {
declaredField = Test.class.getDeclaredField("ttp");
boolean accessible = declaredField.isAccessible();
declaredField.setAccessible(true);
ConcurrentHashMap<Object, Object> concHashMap = new ConcurrentHashMap<Object, Object>();
concHashMap.put("key1", "value1");
declaredField.set(this, concHashMap);
Object value = ttp.get("key1");
System.out.println(value);
declaredField.setAccessible(accessible);
} catch (NoSuchFieldException
| SecurityException
| IllegalArgumentException
| IllegalAccessException e) {
e.printStackTrace();
}
}
public static void main(String... args) {
Test test = new Test();
test.test();
}
}
It prints :
value1
Use position: fixed
instead of position: absolute
.
See here.
Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.
@RestController
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {
@Value("${name}")//not necessary
private String name;//not necessary
private static String NAME_STATIC;
@Value("${name}")
public void setNameStatic(String name){
PropertyController.NAME_STATIC = name;
}
}
Just another example, almost one liner.
var date = new Date();_x000D_
console.log( (date.getMonth() < 9 ? '0': '') + (date.getMonth()+1) );
_x000D_
pathlib
module, introduced in Python 3.4 (PEP 428 — The pathlib module — object-oriented filesystem paths), makes path-related experience much much better.
$ pwd
/home/skovorodkin/stack
$ tree
.
+-- scripts
+-- 1.py
+-- 2.py
In order to get current working directory use Path.cwd()
:
from pathlib import Path
print(Path.cwd()) # /home/skovorodkin/stack
To get an absolute path to your script file, use Path.resolve()
method:
print(Path(__file__).resolve()) # /home/skovorodkin/stack/scripts/1.py
And to get path of a directory where your script is located, access .parent
(it is recommended to call .resolve()
before .parent
):
print(Path(__file__).resolve().parent) # /home/skovorodkin/stack/scripts
Remember that __file__
is not reliable in some situations: How do I get the path of the current executed file in Python?.
Please note, that Path.cwd()
, Path.resolve()
and other Path
methods return path objects (PosixPath
in my case), not strings. In Python 3.4 and 3.5 that caused some pain, because open
built-in function could only work with string or bytes objects, and did not support Path
objects, so you had to convert Path
objects to strings or use Path.open()
method, but the latter option required you to change old code:
$ cat scripts/2.py
from pathlib import Path
p = Path(__file__).resolve()
with p.open() as f: pass
with open(str(p)) as f: pass
with open(p) as f: pass
print('OK')
$ python3.5 scripts/2.py
Traceback (most recent call last):
File "scripts/2.py", line 11, in <module>
with open(p) as f:
TypeError: invalid file: PosixPath('/home/skovorodkin/stack/scripts/2.py')
As you can see open(p)
does not work with Python 3.5.
PEP 519 — Adding a file system path protocol, implemented in Python 3.6, adds support of PathLike
objects to open
function, so now you can pass Path
objects to open
function directly:
$ python3.6 scripts/2.py
OK
There is no portable function that allows to check if a key is hit and continue if not. This is always system dependent.
Solution for linux and other posix compliant systems:
Here, for Morgan Mattews's code provide kbhit()
functionality in a way compatible with any POSIX compliant system. He uses the trick of desactivating buffering at termios level.
Solution for windows:
For windows, Microsoft offers _kbhit()
Run these commands in the terminal:
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
Run these commands separately as each command requires confirmation & if run as a block, the command below the one currently running will cancel the confirmation (leading to the command not being run).
Please refer to How do I uninstall Mysql?
How about writing a custom attribute:
public class LocalizedDisplayNameAttribute: DisplayNameAttribute
{
public LocalizedDisplayNameAttribute(string resourceId)
: base(GetMessageFromResource(resourceId))
{ }
private static string GetMessageFromResource(string resourceId)
{
// TODO: Return the string from the resource file
}
}
which could be used like this:
public class MyModel
{
[Required]
[LocalizedDisplayName("labelForName")]
public string Name { get; set; }
}
Here is the true way to get binary representation of a number:
unsigned int i = *(unsigned int*) &x;
--- To set java path ---
There are two ways to set java path
A. Temporary
javac
If java is not installed, then you will see message:
javac is not recognized as internal or external command, operable program or batch file.
set path=C:\Program Files\Java\jdk1.8.0_121\bin
javac
You can check that path is set if not error has been raised.
It is important to note that these changes are only temporary from programs launched from this cmd.
NOTE: You might have to run the command line as admin
B. Permanent
path
in variable name
variable value
The path is now set permanently.
TIP: The tool "Rapid Environment Editor" (freeware) is great for modifying the environment variables and useful in that case
TIP2: There is also a faster way to access the Environment Variables: press Win+R keys, paste the following %windir%\System32\rundll32.exe sysdm.cpl,EditEnvironmentVariables
and press ENTER
If you are a jquery fan,use this
$(function() {
$(this).bind("contextmenu", function(e) {
e.preventDefault();
});
});
import {DomSanitizationService} from '@angular/platform-browser';
@Component({
templateUrl: 'build/pages/veeu/veeu.html'
})
export class VeeUPage {
trustedURL:any;
static get parameters() {
return [NavController, App, MenuController,
DomSanitizationService];
}
constructor(nav, app, menu, sanitizer) {
this.app = app;
this.nav = nav;
this.menu = menu;
this.sanitizer = sanitizer;
this.trustedURL = sanitizer.bypassSecurityTrustUrl(this.mediaItems[1].url);
}
}
<iframe [src]='trustedURL' width="640" height="360" frameborder="0"
webkitallowfullscreen mozallowfullscreen allowfullscreen>
</iframe>
User property binding instead of function.
As a matter of good practice I suggest you replace the post build event with a MS Build File Copy task.
List<T>.Add
adds a single element. Instead, use List<T>.AddRange
to add multiple values.
Additionally, List<T>.AddRange
takes an IEnumerable<T>
, so you don't need to convert tripDetails
into a List<TripDetails>
, you can pass it directly, e.g.:
tripDetailsCollection.AddRange(tripDetails);
Assuming that your current primary key constraint is called pk_history, you can replace the following lines:
ALTER TABLE history ADD PRIMARY KEY (id)
ALTER TABLE history
DROP CONSTRAINT userId
DROP CONSTRAINT name
with these:
ALTER TABLE history DROP CONSTRAINT pk_history
ALTER TABLE history ADD CONSTRAINT pk_history PRIMARY KEY (id)
If you don't know what the name of the PK is, you can find it with the following query:
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME = 'history'
In the latest version of the SDK, you would use the setBackgroundResource
method.
public void onClick(View v) {
if(v == ButtonName) {
ButtonName.setBackgroundResource(R.drawable.ImageResource);
}
}
use this library : Print.JS
with this library you can print both HTML and PDF.
<form method="post" action="#" id="printJS-form">
...
</form>
<button type="button" onclick="printJS('printJS-form', 'html')">
Print Form
</button>
This works on the latest version:
Go to https://graph.facebook.com/ (https://graph.facebook.com/fsintents for instance).
Copy your id Use this method:
public static Intent getOpenFacebookIntent(Context context) {
try {
context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/<id_here>"));
} catch (Exception e) {
return new Intent(Intent.ACTION_VIEW,Uri.parse("https://www.facebook.com/<user_name_here>"));
}
}
<Scatter
data={data}
// style={{ width: "50%", height: "50%" }}
options={{
scales: {
yAxes: [
{
scaleLabel: {
display: true,
labelString: "Probability",
},
},
],
xAxes: [
{
scaleLabel: {
display: true,
labelString: "Hours",
},
},
],
},
}}
/>
delete
will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:
> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> delete myArray[0]
true
> myArray[0]
undefined
Note that it is not in fact set to the value undefined
, rather the property is removed from the array, making it appear undefined. The Chrome dev tools make this distinction clear by printing empty
when logging the array.
> myArray[0]
undefined
> myArray
[empty, "b", "c", "d"]
myArray.splice(start, deleteCount)
actually removes the element, reindexes the array, and changes its length.
> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> myArray.splice(0, 2)
["a", "b"]
> myArray
["c", "d"]
Here's how you would do it in Kotlin
fun <T> myMethod(item: T) where T : ClassA, T : InterfaceB {
//your code here
}
Took me a while to aggregate an actual solution, but here's how to get rid of this compile error.
Open IntelliJ preferences.
Search for "compiler" (or something like "compi").
Scroll down to Maven -->java compiler. In the right panel will be a list of modules and their associated java compile version "target bytecode version."
Select a version >1.5. You may need to upgrade your jdk if one is not available.
A common pattern is to use
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
}
You can read the data faster if you assume there is no character encoding. e.g. ASCII-7 but it won't make much difference. It is highly likely that what you do with the data will take much longer.
EDIT: A less common pattern to use which avoids the scope of line
leaking.
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
for(String line; (line = br.readLine()) != null; ) {
// process the line.
}
// line is not visible here.
}
UPDATE: In Java 8 you can do
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(System.out::println);
}
NOTE: You have to place the Stream in a try-with-resource block to ensure the #close method is called on it, otherwise the underlying file handle is never closed until GC does it much later.
December 2018,
Looking for an AUTOPLAY, LOOP, MUTE youtube video for react.
Other answers didn't worked.
I found a solution with a library: react-youtube
class Video extends Component {
_onReady(event) {
// add mute
event.target.mute();
// add autoplay
event.target.playVideo();
}
render() {
const opts = {
width: '100%',
height: '700px',
playerVars: {
// remove video controls
controls: 0,
// remove related video
rel: 0
}
};
return (
<YouTube
videoId="oHg5SJYRHA0"
opts={opts}
// add autoplay
onReady={this._onReady}
// add loop
onEnd={this._onReady}
/>
)
}
}
This worked for me.
After trying a number of options and running into various issue with newer versions of Excel (2016) I came across this post from MS that worked like a charm. I enhanced it bit using some code from a post by danwagner.co
Private Declare PtrSafe Function CoCreateGuid Lib "ole32.dll" (Guid As GUID_TYPE) As LongPtr
Private Declare PtrSafe Function StringFromGUID2 Lib "ole32.dll" (Guid As GUID_TYPE, ByVal lpStrGuid As LongPtr, ByVal cbMax As Long) As LongPtr
Function CreateGuidString(Optional IncludeHyphens As Boolean = True, Optional IncludeBraces As Boolean = False)
Dim Guid As GUID_TYPE
Dim strGuid As String
Dim retValue As LongPtr
Const guidLength As Long = 39 'registry GUID format with null terminator {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
retValue = CoCreateGuid(Guid)
If retValue = 0 Then
strGuid = String$(guidLength, vbNullChar)
retValue = StringFromGUID2(Guid, StrPtr(strGuid), guidLength)
If retValue = guidLength Then
' valid GUID as a string
' remove them from the GUID
If Not IncludeHyphens Then
strGuid = Replace(strGuid, "-", vbNullString, Compare:=vbTextCompare)
End If
' If IncludeBraces is switched from the default False to True,
' leave those curly braces be!
If Not IncludeBraces Then
strGuid = Replace(strGuid, "{", vbNullString, Compare:=vbTextCompare)
strGuid = Replace(strGuid, "}", vbNullString, Compare:=vbTextCompare)
End If
CreateGuidString = strGuid
End If
End If
End Function
Public Sub TestCreateGUID()
Dim Guid As String
Guid = CreateGuidString() '<~ default
Debug.Print Guid
End Sub
There are additional options in the original MS post found here: https://answers.microsoft.com/en-us/msoffice/forum/msoffice_excel-msoffice_custom-mso_2010/guid-run-time-error-70-permission-denied/c9ee4076-98af-4032-bc87-40ad7aa7cb38
If you want to use Unix shell commands on Windows, you can use Windows Powershell, which includes both Windows and Unix commands as aliases. You can find more info on it in the documentation.
PowerShell supports aliases to refer to commands by alternate names. Aliasing allows users with experience in other shells to use common command names that they already know for similar operations in PowerShell.
The PowerShell equivalents may not produce identical results. However, the results are close enough that users can do work without knowing the PowerShell command name.
The ThreadPool.QueueUserWorkItem is pretty ideal for something simple. The only caveat is accessing a control from the other thread.
System.Threading.ThreadPool.QueueUserWorkItem(delegate {
DoSomethingThatDoesntInvolveAControl();
}, null);
You will need to run the lsnrctl utility on server A to start the listener. You would then connect from computer B using the following syntax:
sqlplus username/password@hostA:1521 /XE
The port information is optional if the default of 1521 is used.
Listener configuration documentation here. Remote connection documentation here.
I'll suggest Pyfdate
What is pyfdate?
Given Python's goal to be a powerful and easy-to-use scripting language, its features for working with dates and times are not as user-friendly as they should be. The purpose of pyfdate is to remedy that situation by providing features for working with dates and times that are as powerful and easy-to-use as the rest of Python.
the tutorial
To catch the names array, i use that:
$("input[name*='task']")
Create a plain text file (using notepad) and type the exact line you would use to run your Java file with the command prompt. Then change the extension to .bat and you're done.
Double clicking on this file would run your java program.
I reccommend one file for javac, one for java so you can troubleshoot if anything is wrong.
You could make your own plugins.
jQuery.fn.visible = function() {
return this.css('visibility', 'visible');
};
jQuery.fn.invisible = function() {
return this.css('visibility', 'hidden');
};
jQuery.fn.visibilityToggle = function() {
return this.css('visibility', function(i, visibility) {
return (visibility == 'visible') ? 'hidden' : 'visible';
});
};
If you want to overload the original jQuery toggle()
, which I don't recommend...
!(function($) {
var toggle = $.fn.toggle;
$.fn.toggle = function() {
var args = $.makeArray(arguments),
lastArg = args.pop();
if (lastArg == 'visibility') {
return this.visibilityToggle();
}
return toggle.apply(this, arguments);
};
})(jQuery);
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
win = tk. Tk()
image1 = Image. open("Aoran. jpg")
image2 = ImageTk. PhotoImage(image1)
image_label = ttk. Label(win , image =.image2)
image_label.place(x = 0 , y = 0)
win.mainloop()
<?php function writeUTF8File($filename,$content) { $f=fopen($filename,"w"); # Now UTF-8 - Add byte order mark fwrite($f, pack("CCC",0xef,0xbb,0xbf)); fwrite($f,$content); fclose($f); } ?>
For Node.JS users (or users utilizing Jade runtime in the browser), you can use Jade's escape function.
require('jade').runtime.escape(...);
No sense in writing it yourself if someone else is maintaining it. :)
you can make it using js file and ajax call. while validating data using js file we can read the text of selected dropdown
$("#dropdownid").val(); for value
$("#dropdownid").text(); for selected value
catch these into two variables and take it as inputs to ajax call for a php file
$.ajax
({
url:"callingphpfile.php",//url of fetching php
method:"POST", //type
data:"val1="+value+"&val2="+selectedtext,
success:function(data) //return the data
{
}
and in php you can get it as
if (isset($_POST["val1"])) {
$val1= $_POST["val1"] ;
}
if (isset($_POST["val2"])) {
$selectedtext= $_POST["val1"];
}
You have to give the values between 0 and 1.0. So divide the RGB values by 255.
myLabel.textColor= [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1] ;
Update:
You can also use this macro
#define Rgb2UIColor(r, g, b) [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:1.0]
and you can call in any of your class like this
myLabel.textColor = Rgb2UIColor(160, 97, 5);
This is the normal color synax
myLabel.textColor = UIColor(red: (160/255.0), green: (97/255.0), blue: (5/255.0), alpha: 1.0)
//The values should be between 0 to 1
Swift is not much friendly with macros
Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.
So we use extension for this
extension UIColor {
convenience init(_ r: Double,_ g: Double,_ b: Double,_ a: Double) {
self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
}
}
You can use it like
myLabel.textColor = UIColor(160.0, 97.0, 5.0, 1.0)
You need to specify the format:
DateTime date = DateTime.ParseExact(
"Tue, 1 Jan 2008 00:00:00 UTC",
"ddd, d MMM yyyy HH:mm:ss UTC",
CultureInfo.InvariantCulture);
NULL stands for a variable without value. To check if a variable is NULL you can either use is_null($var)
or the comparison (===
) with NULL. Both ways, however, generate a warning if the variable is not defined. Similar to isset($var)
and empty($var)
, which can be used as functions.
var_dump(is_null($var)); // true
var_dump($var === null); // true
var_dump(empty($var)); // true
Read more in How to check if a variable is NULL in PHP?
I've experienced a problem with length of None, which leads to Internal Server Error: TypeError: object of type 'NoneType' has no len()
My workaround is just displaying 0 if object is None and calculate length of other types, like list in my case:
{{'0' if linked_contacts == None else linked_contacts|length}}
Html code:
Change Title:
<input type="text" id="changeTitle" placeholder="Enter title tag">
<button id="changeTitle1">Click!</button>
Jquery code:
$(document).ready(function(){
$("#changeTitle1").click(function() {
$(document).prop('title',$("#changeTitle").val());
});
});
This assumes that the content is in column B on each sheet (since it's not clear how you determine the column on each sheet.) and the last row of that column is also the last row of the sheet.
$xlCellTypeLastCell = 11
$startRow = 5
$col = 2
$excel = New-Object -Com Excel.Application
$wb = $excel.Workbooks.Open("C:\Users\Administrator\my_test.xls")
for ($i = 1; $i -le $wb.Sheets.Count; $i++)
{
$sh = $wb.Sheets.Item($i)
$endRow = $sh.UsedRange.SpecialCells($xlCellTypeLastCell).Row
$city = $sh.Cells.Item($startRow, $col).Value2
$rangeAddress = $sh.Cells.Item($startRow + 1, $col).Address() + ":" + $sh.Cells.Item($endRow, $col).Address()
$sh.Range($rangeAddress).Value2 | foreach
{
New-Object PSObject -Property @{ City = $city; Area = $_ }
}
}
$excel.Workbooks.Close()
Create List of Single Item Repeated n Times in Python
Depending on your use-case, you want to use different techniques with different semantics.
For immutable items, like None, bools, ints, floats, strings, tuples, or frozensets, you can do it like this:
[e] * 4
Note that this is usually only used with immutable items (strings, tuples, frozensets, ) in the list, because they all point to the same item in the same place in memory. I use this frequently when I have to build a table with a schema of all strings, so that I don't have to give a highly redundant one to one mapping.
schema = ['string'] * len(columns)
Multiplying a list gives us the same elements over and over. The need for this is rare:
[iter(iterable)] * 4
This is sometimes used to map an iterable into a list of lists:
>>> iterable = range(12)
>>> a_list = [iter(iterable)] * 4
>>> [[next(l) for l in a_list] for i in range(3)]
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
We can see that a_list
contains the same range iterator four times:
>>> a_list
[<range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>]
I've used Python for a long time now, and I have seen very few use-cases where I would do the above with mutable objects.
Instead, to get, say, a mutable empty list, set, or dict, you should do something like this:
list_of_lists = [[] for _ in columns]
The underscore is simply a throwaway variable name in this context.
If you only have the number, that would be:
list_of_lists = [[] for _ in range(4)]
The _
is not really special, but your coding environment style checker will probably complain if you don't intend to use the variable and use any other name.
Beware doing this with mutable objects, when you change one of them, they all change because they're all the same object:
foo = [[]] * 4
foo[0].append('x')
foo now returns:
[['x'], ['x'], ['x'], ['x']]
But with immutable objects, you can make it work because you change the reference, not the object:
>>> l = [0] * 4
>>> l[0] += 1
>>> l
[1, 0, 0, 0]
>>> l = [frozenset()] * 4
>>> l[0] |= set('abc')
>>> l
[frozenset(['a', 'c', 'b']), frozenset([]), frozenset([]), frozenset([])]
But again, mutable objects are no good for this, because in-place operations change the object, not the reference:
l = [set()] * 4
>>> l[0] |= set('abc')
>>> l
[set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b'])]
First option (bad because of throw-catch, but MS will do work for you):
bool IsValidEmail(string email)
{
try {
var mail = new System.Net.Mail.MailAddress(email);
return true;
}
catch {
return false;
}
}
Second option is read I Knew How To Validate An Email Address Until I Read The RFC and RFC specification
Maybe, you can use the array syntax of javascript :
var finalObj =[json1 , json2]
Look the path for example this import is not correct import Navbar from '@/components/Navbar.vue' should look like this ** import Navbar from './components/Navbar.vue'**
<div class="preload">
<img src="http://i.imgur.com/KUJoe.gif">
</div>
<div class="content">
I would like to display a loading bar before the entire page is loaded.
</div>
$(function() {
$(".preload").fadeOut(2000, function() {
$(".content").fadeIn(1000);
});
});?
.content {display:none;}
.preload {
width:100px;
height: 100px;
position: fixed;
top: 50%;
left: 50%;
}
?
Ah, since I had no dependencies in my master project, "gradle dependencies" only lists those and not subproject dependencies so the correct command ended up being
gradle :<subproject>:dependencies
so for me this was
gradle :master:dependencies
Completing the solution of Ranadheer, using Server.MapPath to locate the file
System.Net.Mail.Attachment attachment;
attachment = New System.Net.Mail.Attachment(Server.MapPath("~/App_Data/hello.pdf"));
mail.Attachments.Add(attachment);
You could create a new List
and addAll()
of your other List
s to it. Then return an unmodifiable list with Collections.unmodifiableList()
.
Here is working code for all android versions as of API LEVEL 26+ with backward compatibility.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext(), "M_CH_ID");
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Hearty365")
.setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
.setContentTitle("Default notification")
.setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
.setContentInfo("Info");
NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());
UPDATE for API 26 to set Max priority
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Hearty365")
// .setPriority(Notification.PRIORITY_MAX)
.setContentTitle("Default notification")
.setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
.setContentInfo("Info");
notificationManager.notify(/*notification id*/1, notificationBuilder.build());
in the above i need a small change which i am trying to place but i am not able to do that, your output will look like this
<ul>
<li id="menu-item-13" class="depth0 parent"><a href="#">About Us</a>
<ul class="children level-0">
<li id="menu-item-17" class="depth1"><a href="#">Sample Page</a></li>
<li id="menu-item-16" class="depth1"><a href="#">About Us</a></li>
</ul>
</li>
</ul>
what i am looking for
<ul>
<li id="menu-item-13" class="depth0"><a class="parent" href="#">About Us</a>
<ul class="children level-0">
<li id="menu-item-17" class="depth1"><a href="#">Sample Page</a></li>
<li id="menu-item-16" class="depth1"><a href="#">About Us</a></li>
</ul>
</li>
</ul>
in the above one i have placed the parent class inside the parent anchor link that <li id="menu-item-13" class="depth0"><a class="parent" href="#">About Us</a>
Use the body of this loop to do whatever you want to with the digits
for digit in map(int, str(my_number)):
Basically, you have three options:
EXPOSE
nor -p
EXPOSE
EXPOSE
and -p
1) If you specify neither EXPOSE
nor -p
, the service in the container will only be accessible from inside the container itself.
2) If you EXPOSE
a port, the service in the container is not accessible from outside Docker, but from inside other Docker containers. So this is good for inter-container communication.
3) If you EXPOSE
and -p
a port, the service in the container is accessible from anywhere, even outside Docker.
The reason why both are separated is IMHO because:
The documentation explicitly states:
The
EXPOSE
instruction exposes ports for use within links.
It also points you to how to link containers, which basically is the inter-container communication I talked about.
PS: If you do -p
, but do not EXPOSE
, Docker does an implicit EXPOSE
. This is because if a port is open to the public, it is automatically also open to other Docker containers. Hence -p
includes EXPOSE
. That's why I didn't list it above as a fourth case.
i have Windows7 Python 3.4.1; following command suggested by Guss worked well
C:\Users>py -m pip install requests
Output
Downloading/unpacking requests
Installing collected packages: requests
Successfully installed requests
Cleaning up...
It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.
(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)
In Access 2007 - 2010, go to Database Tools and click Compact and Repair Database, and it will automatically reset the ID.
Just store the index generated in a variable, and then access the array using this varaible:
int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);
P.S. I usually don't like generating new Random
object per randoization - I prefer using a single Random
in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.
According to this approach, I will have some variable Random r
somewhere, and I will just use:
int idx = r.nextInt(fruits.length)
However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.
I use this for every external link:
window.onload = function(){
var anchors = document.getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
if (anchors[i].hostname != window.location.hostname) {
anchors[i].setAttribute('target', '_blank');
}
}
}
Create a text node and append it to the button element:
var t = document.createTextNode("test content");
b.appendChild(t);
If you added new storyboard then you have to check following points.
1) In your plist file check value of Main storyboard file base name (iPad) or (iPhone) should be matched with your storyboard file name (do not add extension .storyboard)
2) In storyboard there should be one view controller which set as Is initial view controller
3) Clean and build your project. :)
There are ToUnixTime()
and ToUnixTimeMs()
methods in DateTimeExtensions class
DateTime.UtcNow.ToUnixTimeMs()
In contrast to what the accepted answer proposes, the documentation says that for JSONArray() you must use put(value)
no add(value)
.
https://developer.android.com/reference/org/json/JSONArray.html#put(java.lang.Object)
(Android API 19-27. Kotlin 1.2.50)
It's not an inside joke
Apparently it's just an application checker for Goat Simulator - by Coffee Stain Studios
If you have Goat Simulator installed, you're a goat. If you don't have it installed, you're not a goat.
I imagine it was more of a personal experiment by one of the developers, most likely to find people with a common interest.
For those who fear to mess anything up in your vscode json settings this is pretty easy to follow.
Open "File -> Preferences -> Keyboard Shortcuts"
or "Code -> Preferences -> Keyboard Shortcuts"
for Mac Users
In the search bar type transform
.
By default you will not have anything under Keybinding
. Now double-click on Transform to Lowercase
or Transform to Uppercase
.
Press your desired combination of keys to set your keybinding. In this case if copying off of Sublime i will press ctrl+shift+u
for uppercase or ctrl+shift+l
for lowercase.
Press Enter
on your keyboard to save and exit. Do same for the other option.
Enjoy KEYBINDING
You can first check that the destination file exists or not and then make a decision based on the output of its result:
tasks:
- name: Check that the somefile.conf exists
stat:
path: /etc/file.txt
register: stat_result
- name: Create the file, if it doesnt exist already
file:
path: /etc/file.txt
state: touch
when: not stat_result.stat.exists
Both SOAP webservices and REST webservices can use the HTTP protocol and other protocols as well (just to mention SOAP can be the underlying protocol of REST). I will talk only about the HTTP protocol related SOAP and REST, because this is the most frequent usage of them.
SOAP ("simple" object access protocol) is a protocol (and a W3C standard). It defines how to create, send and process SOAP messages.
SOAP messages are XML documents with a specific structure: they contain an envelope which contains the header and the body section. The body contains the actual data - we want to send - in an XML format. There are two encoding styles, but we usually choose literal, which means that our application or its SOAP driver does the XML serialization and unserialization of the data.
SOAP messages travel as HTTP messages with SOAP+XML MIME subtype. These HTTP messages can be multipart, so optionally we can attach files to SOAP messages.
Obviously we use a client-server architecture, so the SOAP clients send requests to the SOAP webserices and the services send back responses to the clients. Most of the webservices use a WSDL file to describe the service. The WSDL file contains the XML Schema (XSD hereafter) of the data we want to send and the WSDL binding which defines how the webservice is bound to the HTTP protocol. There are two binding styles: RPC and document. By the RPC style binding the SOAP body contains the representation of an operation call with the parameters (HTTP requests) or the return values (HTTP response). The parameters and return values are validated against the XSD. By the document style binding the SOAP body contains an XML document which is validated against the XSD. I think the document binding style is better suited to event based systems, but I never used that binding style. The RPC binding style is more prevalent, so most people use SOAP for XML/RPC purposes by distributed applications. The webservices usually find each other by asking an UDDI server. UDDI servers are registries which store the location of the webservices.
So the - in my opinion - most prevalent SOAP webservice uses RPC binding style and literal encoding style and it has the following properties:
REST (representational state transfer) is an architecture style which is described in the dissertation of Roy Fielding. It does not concern about protocols like SOAP does. It starts with a null architecture style having no constraints and defines the constraints of the REST architecture one by one. People use the term RESTful for webservices which fulfill all of the REST constraints, but according to Roy Fielding, there are no such things as REST levels. When a webservice does not meet with every single REST constraint, then it is not a REST webservice.
Uniform interface
https://example.com/api/v1/users?offset=50&count=25
. URLs have some specifications, for example URLs with the same pathes but different queries are not identical, or the path part should contain the hierarhical data of the URL and the query part should contain the non-hierarchical data. These are the basics of how to create URLs by REST. Btw. the URL structure does matter only for the service developers, a real REST client does not concern with it. Another frequently asked question is API versioning, which is an easy one, because according to Fielding the only constant thing by resource is semantics. If the semantics change, then you can add a new version number. You can use classical 3 number versioning and add only the major number to the URLs (https://example.com/api/v1/
). So by backward compatible changes nothing happens, by non-backward compatible changes you will have a non-backward compatible semantics with a new API root https://example.com/api/v2/
. So the old clients won't break, because they can use the https://example.com/api/v1/
with the old semantics.PATCH https://example.com/api/v1/users/1 {name: "Mrs Smith"}
request where the {name: "Mrs Smith"}
is a JSON representation of the intended resource state, in other words: the new name. This happens vica-versa, the service sends representations of resources to the clients in order to change their states. For example if we want to read the new name, we can send a GET https://example.com/api/v1/users/1?fields="name"
retrieval request, which results in a 200 ok, {name: "Mrs Smith"}
response. So we can use this representation to change the client state, for example we can display a "Welcome to our page Mrs Smith!" message. A resource can have many representations depending on the resource identifier (URL) or the accept
header we sent with the request. For example we can send an image of Mrs Smith (probably not nude) if image/jpeg
is requested. Hypermedia as the engine of application state (HATEOAS hereafter) - Hypermedia is a media type which can contain hyperlinks. By the web we follow links - described by a hypermedia format (usually HTML) - to achieve a goal, instead of typing the URLs into the addres bar. REST follows the same concept, the representations sent by the service can contain hyperlinks. We use these hyperlinks to send requests to the service. With the response we get data (and probably more links) which we can use to build the new client state, and so on... So that's why hypermedia is the engine of application state (client state). You probably wonder how do clients recognize and follow the hyperlinks? By humans it is pretty simple, we read the title of the link, maybe fill input fields, and after that just a single click. By machines we have to add semantics to the links with RDF (by JSON-LD with Hydra) or with hypermedia specific solutions (for example IANA link relations and vendor specific MIME types by HAL+JSON). There are many machine readable XML and JSON hypermedia formats, just a short list of them:
Sometimes it is hard to choose...
So a REST webservice is very different from a SOAP webservice (with RPC binding style and literal encoding style)
and so on...
A SOAP RPC webservice does not meet all of the REST constraints:
In Python 3 zip
returns an iterator instead and needs to be passed to a list function to get the zipped tuples:
x = [1, 2, 3]; y = ['a','b','c']
z = zip(x, y)
z = list(z)
print(z)
>>> [(1, 'a'), (2, 'b'), (3, 'c')]
Then to unzip
them back just conjugate the zipped iterator:
x_back, y_back = zip(*z)
print(x_back); print(y_back)
>>> (1, 2, 3)
>>> ('a', 'b', 'c')
If the original form of list is needed instead of tuples:
x_back, y_back = zip(*z)
print(list(x_back)); print(list(y_back))
>>> [1,2,3]
>>> ['a','b','c']
If using Angular >= 1.4, here's the cleanest solution I've found that doesn't rely on anything custom or external:
angular.module('yourModule')
.config(function ($httpProvider, $httpParamSerializerJQLikeProvider){
$httpProvider.defaults.transformRequest.unshift($httpParamSerializerJQLikeProvider.$get());
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
});
And then you can do this anywhere in your app:
$http({
method: 'POST',
url: '/requesturl',
data: {
param1: 'value1',
param2: 'value2'
}
});
And it will correctly serialize the data as param1=value1¶m2=value2
and send it to /requesturl
with the application/x-www-form-urlencoded; charset=utf-8
Content-Type header as it's normally expected with POST requests on endpoints.
Try this :
function method1(){
// some code
}
function method2(){
// some code
}
$.ajax({
url:method1(),
success:function(){
method2();
}
})
To avoid confusion (as there seems to be some in the comments). Assuming you are on Jupyter:
%matplotlib inline
> displays the plots INSIDE the notebook
sns.plt.show()
> displays the plots OUTSIDE of the notebook
%matplotlib inline
will OVERRIDE sns.plt.show()
in the sense that plots will be shown IN the notebook even when sns.plt.show()
is called.
And yes, it is easy to include the line in to your config:
Automatically run %matplotlib inline in IPython Notebook
But it seems a better convention to keep it together with imports in the actual code.
head:
head - output the first part of files
head [OPTION]... [FILE]...
Print the first 10 lines of each FILE to standard output. With more than one FILE, precede each with a header giving the file name. With no FILE, or when FILE is -, read standard input.
Mandatory arguments to long options are mandatory for short options too.
-c, --bytes=[-]N
print the first N bytes of each file; with the leading '-', print all but the last N bytes of each file
I don't have an answer, but I do have an alternative.
If you use Fiddler2 to monitor traffic AND enable HTTPS Decryption, your development environment will not complain. This will not work on WinRT devices, such as Microsoft Surface, because you cannot install standard apps on them. But your development Win8 computer will be fine.
To enable HTTPS encryption in Fiddler2, go to Tools > Fiddler Options > HTTPS (Tab) > Check "Decrypt HTTPS Traffic".
I'm going to keep my eye on this thread hoping for someone to have an elegant solution.
A PIL only solution for creating a bi-level (black and white) image with a custom threshold:
from PIL import Image
img = Image.open('mB96s.png')
thresh = 200
fn = lambda x : 255 if x > thresh else 0
r = img.convert('L').point(fn, mode='1')
r.save('foo.png')
With just
r = img.convert('1')
r.save('foo.png')
you get a dithered image.
From left to right the input image, the black and white conversion result and the dithered result:
You can click on the images to view the unscaled versions.
Rewriting:
There are radical differences between mobile and desktop environment, as well as between the way in which applications were developed to a handful of years ago and today:
a) mobile devices need to conserve energy. Part of the value they offer. So you need to save resources. Threads are an expensive resource. Halt the progress of a thread is an unacceptable waste of this resource.
b) Nowadays the user is much more demanding. To assist them, we believe that it deserves to have full working CPU and the smallest possible expenditure of energy. Its application is not alone on the device, there is an unknow number of another apps running at same time and your app is not necessarily the most urgent.
c) system-level locks are not an option: a mobile device works with a number of events and services in the background and it is not right for any of them can be locked by an application.
Think about the user receiving a phone call while your "system lock" is working...
Based on the above facts, the answer to the proposed question are:
No. Workarounds do user experience get worse and it may make the mistake of blaming the system itself. This is unfair and penalizes the platform and all its developers.
No. This is strictly forbidden on the platform. No application can interfere with the operation of the system or other applications.
Yes. Including this aspect.
You only have to replace the WHERE with a LEFT JOIN:
SELECT CASE
WHEN S.Id IS NOT NULL AND S.Status = 1 AND ...) THEN 1
ELSE 0
END AS [Value]
FROM (SELECT @SiteId AS Id) R
LEFT JOIN Sites S ON S.Id = R.Id
This solution allows you to return default values for each column also, for example:
SELECT
CASE WHEN S.Id IS NULL THEN 0 ELSE S.Col1 END AS Col1,
S.Col2,
ISNULL(S.Col3, 0) AS Col3
FROM
(SELECT @Id AS Id) R
LEFT JOIN Sites S ON S.Id = R.Id AND S.Status = 1 AND ...
Error happens in your function declarations,look the following sentence!You need a semicolon!
AST_NODE* Statement(AST_NODE* node)
This will give the correct (custom) filter when the file dialog is showing:
<input type="file" accept=".jpg, .png, .jpeg, .gif, .bmp, .tif, .tiff|image/*">
You can use MD5() in mysql or md5() in php. To use salt add it to password before running md5, f.e.:
$salt ='my_string';
$hash = md5($salt . $password);
It's better to use different salt for every password. For this you have to save your salt in db (and also hash). While authentication user will send his login and pass. You will find his hash and salt in db and find out:
if ($hash == md5($salt . $_POST['password'])) {}
INNER JOIN = JOIN
INNER JOIN is the default if you don't specify the type when you use the word JOIN.
You can also use LEFT OUTER JOIN or RIGHT OUTER JOIN, in which case the word OUTER is optional, or you can specify CROSS JOIN.
OR
For an inner join, the syntax is:
SELECT ...
FROM TableA
[INNER] JOIN TableB(in other words, the "INNER" keyword is optional - results are the same with or without it)
Based on reference "Peter O".. Here is the java version
private static final float angleBetweenPoints(PointF a, PointF b) {
float deltaY = b.y - a.y;
float deltaX = b.x - a.x;
return (float) (Math.atan2(deltaY, deltaX)); }
You can use the simple/lightweight ng-file-upload directive. It supports drag&drop, file progress and file upload for non-HTML5 browsers with FileAPI flash shim
<div ng-controller="MyCtrl">
<input type="file" ngf-select="onFileSelect($files)" multiple>
</div>
JS:
//inject angular file upload directive.
angular.module('myApp', ['ngFileUpload']);
var MyCtrl = [ '$scope', 'Upload', function($scope, Upload) {
$scope.onFileSelect = function($files) {
Upload.upload({
url: 'my/upload/url',
file: $files,
}).progress(function(e) {
}).then(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}];
I use this:
public static <T> T getBean(Class<T> clazz) {
try {
String beanName = getBeanName(clazz);
FacesContext facesContext = FacesContext.getCurrentInstance();
return facesContext.getApplication().evaluateExpressionGet(facesContext, "#{" + beanName + "}", clazz);
//return facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(), null, nomeBean);
} catch (Exception ex) {
return null;
}
}
public static <T> String getBeanName(Class<T> clazz) {
ManagedBean managedBean = clazz.getAnnotation(ManagedBean.class);
String beanName = managedBean.name();
if (StringHelper.isNullOrEmpty(beanName)) {
beanName = clazz.getSimpleName();
beanName = Character.toLowerCase(beanName.charAt(0)) + beanName.substring(1);
}
return beanName;
}
And then call:
MyManageBean bean = getBean(MyManageBean.class);
This way you can refactor your code and track usages without problems.
Regular expressions work well if needing to find a range of starting characters. The following finds all employee names starting with A, B, C or D and adds the “UPPER” call in case a name is in the database with a starting lowercase letter. My query works in Oracle (I did not test other DB's). The following would return for example:
Adams
adams
Dean
dean
This query also ignores case in the ORDER BY via the "lower" call:
SELECT employee_name
FROM employees
WHERE REGEXP_LIKE(UPPER(TRIM(employee_name)), '^[A-D]')
ORDER BY lower(employee_name)
If you want to print the text of a UITableViewCell
according to its matching NSIndexPath
, you have to use UITableViewDelegate
's tableView:didSelectRowAtIndexPath:
method and get a reference of the selected UITableViewCell
with UITableView
's cellForRowAtIndexPath:
method.
For example:
import UIKit
class TableViewController: UITableViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
switch indexPath.row {
case 0: cell.textLabel?.text = "Bike"
case 1: cell.textLabel?.text = "Car"
case 2: cell.textLabel?.text = "Ball"
default: cell.textLabel?.text = "Boat"
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell = tableView.cellForRowAtIndexPath(indexPath)
print(selectedCell?.textLabel?.text)
// this will print Optional("Bike") if indexPath.row == 0
}
}
However, for many reasons, I would not encourage you to use the previous code. Your UITableViewCell
should only be responsible for displaying some content given by a model. In most cases, what you want is to print the content of your model (could be an Array
of String
) according to a NSIndexPath
. By doing things like this, you will separate each element's responsibilities.
Thereby, this is what I would recommend:
import UIKit
class TableViewController: UITableViewController {
let toysArray = ["Bike", "Car", "Ball", "Boat"]
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return toysArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = toysArray[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let toy = toysArray[indexPath.row]
print(toy)
// this will print "Bike" if indexPath.row == 0
}
}
As you can see, with this code, you don't have to deal with optionals and don't even need to get a reference of the matching UITableViewCell
inside tableView:didSelectRowAtIndexPath:
in order to print the desired text.
The PHPUnit documentation says used to say to include/require PHPUnit/Framework.php, as follows:
require_once ('PHPUnit/Framework/TestCase.php');
UPDATE
As of PHPUnit 3.5, there is a built-in autoloader class that will handle this for you:
require_once 'PHPUnit/Autoload.php';
Thanks to Phoenix for pointing this out!
You should use datetime
object, not str
.
>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'
To get the datetime object from the string, use datetime.datetime.strptime
:
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'
ES2015 the easiest way is to do something like
'X'.repeat(data.length)
X
being any string, data.length
being the desired length.
see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
Substrings with ${variablename:0:5}
are a bash feature, not available in basic shells. Are you sure you're running this under bash? Check the shebang line (at the beginning of the script), and make sure it's #!/bin/bash
, not #!/bin/sh
. And make sure you don't run it with the sh
command (i.e. sh scriptname
), since that overrides the shebang.
Surely:
if (useAdditionalClauses)
{
results =
results.Where(o => o.OrderStatus == OrderStatus.Open &&
o.CustomerID == customerID)
}
Or just another .Where()
call like this one (although I don't know why you would want to, unless it's split by another boolean control variable):
if (useAdditionalClauses)
{
results = results.Where(o => o.OrderStatus == OrderStatus.Open).
Where(o => o.CustomerID == customerID);
}
Or another reassignment to results
: `results = results.Where(blah).
page-break-inside: avoid; definitely does not work in webkit, in fact has been a known issue for 5+ years now https://bugs.webkit.org/show_bug.cgi?id=5097
As far as my research has gone, there is no known method to accomplish this (I am working on figuring out my own hack)
The advice I can give you is, to accomplish this functionality in FF, wrap the content that you don;t want to break ever inside a DIV (or any container) with overflow: auto (just be careful not to cause weird scroll bars to show up by sizing the container too small).
Sadly, FF is the only browser I managed to accomplish this in, and webkit is the one I am more worried about.
If your app is a Scala app, it must have a build.sbt
in the root directory, and that file must be checked into Git. You can confirm this by running:
$ git ls-files build.sbt
If that file exists and is checked into Git, try running this command:
$ heroku buildpacks:set heroku/scala
string apppath =
(new System.IO.FileInfo
(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).DirectoryName;