Drop the parentheses and commas:
myBackupFunction ".." "..." "xx"
And the function should look like this:
function myBackupFunction() {
# Here $1 is the first parameter, $2 the second, etc.
}
Conclusion,
to_char
works in its own way
So,
Always use this format YYYY-MM-DD for comparison instead of MM-DD-YY or DD-MM-YYYY or any other format
ES6 with Async / Await ,
let meaningOfLife = false;
async function waitForMeaningOfLife(){
while (true){
if (meaningOfLife) { console.log(42); return };
await null; // prevents app from hanging
}
}
waitForMeaningOfLife();
setTimeout(()=>meaningOfLife=true,420)
> df <- data.frame(matrix(ncol = 300, nrow = 100))
> dim(df)
[1] 100 300
See also: Which C I/O library should be used in C++ code?
struct Item
{
std::string artist;
std::string c;
integer price; // in cents (as floating point is not acurate)
std::string Genre;
integer disc;
integer sale;
integer tax;
};
std::cout << "Sales Report for September 15, 2010\n"
<< "Artist Title Price Genre Disc Sale Tax Cash\n";
FOREACH(Item loop,data)
{
fprintf(stdout,"%8s%8s%8.2f%7s%1s%8.2f%8.2f\n",
, loop.artist
, loop.title
, loop.price / 100.0
, loop.Genre
, loop.disc , "%"
, loop.sale / 100.0
, loop.tax / 100.0);
// or
std::cout << std::setw(8) << loop.artist
<< std::setw(8) << loop.title
<< std::setw(8) << fixed << setprecision(2) << loop.price / 100.0
<< std::setw(8) << loop.Genre
<< std::setw(7) << loop.disc << std::setw(1) << "%"
<< std::setw(8) << fixed << setprecision(2) << loop.sale / 100.0
<< std::setw(8) << fixed << setprecision(2) << loop.tax / 100.0
<< "\n";
// or
std::cout << boost::format("%8s%8s%8.2f%7s%1s%8.2f%8.2f\n")
% loop.artist
% loop.title
% loop.price / 100.0
% loop.Genre
% loop.disc % "%"
% loop.sale / 100.0
% loop.tax / 100.0;
}
We are also getting the same error while we are trying to access a same resource with in milliseconds. Like if i try to POST
some data to www.abc.com/blog
and with in milliseconds an other request will also go for the same resource i.e. www.abc.com/blog
from the same user. So it'll give the 409
error.
Another way to check if you have multiple python versions installed, from the terminal.
-MBP:~python3 -m pip show pyperclip
Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-
MBP:~ python -m pip show pyperclip
Location: /Users/umeshvuyyuru/Library/Python/2.7/lib/python/site-packages
I did achieve this like so
form i {_x000D_
left: -25px;_x000D_
top: 23px;_x000D_
border: none;_x000D_
position: relative;_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
float: left;_x000D_
color: #29a038;_x000D_
}
_x000D_
<form>_x000D_
_x000D_
<i class="fa fa-link"></i>_x000D_
_x000D_
<div class="form-group string optional profile_website">_x000D_
<input class="string optional form-control" placeholder="http://your-website.com" type="text" name="profile[website]" id="profile_website">_x000D_
</div>_x000D_
_x000D_
<i class="fa fa-facebook"></i>_x000D_
<div class="form-group url optional profile_facebook_url">_x000D_
<input class="string url optional form-control" placeholder="http://facebook.com/your-account" type="url" name="profile[facebook_url]" id="profile_facebook_url">_x000D_
</div>_x000D_
_x000D_
<i class="fa fa-twitter"></i>_x000D_
<div class="form-group url optional profile_twitter_url">_x000D_
<input class="string url optional form-control" placeholder="http://twitter.com/your-account" type="url" name="profile[twitter_url]" id="profile_twitter_url">_x000D_
</div>_x000D_
_x000D_
<i class="fa fa-instagram"></i>_x000D_
<div class="form-group url optional profile_instagram_url">_x000D_
<input class="string url optional form-control" placeholder="http://instagram.com/your-account" type="url" name="profile[instagram_url]" id="profile_instagram_url">_x000D_
</div>_x000D_
_x000D_
<input type="submit" name="commit" value="Add profile">_x000D_
</form>
_x000D_
The result looks like this:
Please note that I am using Ruby on Rails so my resulting code looks a bit blown up. The view code in slim is actually very concise:
i.fa.fa-link
= f.input :website, label: false
i.fa.fa-facebook
= f.input :facebook_url, label: false
i.fa.fa-twitter
= f.input :twitter_url, label: false
i.fa.fa-instagram
= f.input :instagram_url, label: false
I prefer to use:
string result = "myFile_" + DateTime.Now.ToFileTime() + ".txt";
What does ToFileTime() do?
Converts the value of the current DateTime object to a Windows file time.
public long ToFileTime()
A Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). Windows uses a file time to record when an application creates, accesses, or writes to a file.
No.
The content-type should be whatever it is known to be, if you know it. application/octet-stream
is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.
You can combine the use of Content-Disposition
with other content-types, such as image/png
or even text/html
to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html
but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).
RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline
to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename
part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.
Hence:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"
Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"
Means "This is a PNG image. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: inline; filename="picture.png"
Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".
Of those browsers that recognise inline
some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).
This is called an initialization list. It is for passing arguments to the constructor of a parent class. Here is a good link explaining it: Initialization Lists in C++
I use []
.
This will solve your issue
var entries=new List<T>();
var selectedItems = new List<T>();
for (var i = 0; i !=10; i++)
{
var rdm = new Random().Next(entries.Count);
while (selectedItems.Contains(entries[rdm]))
rdm = new Random().Next(entries.Count);
selectedItems.Add(entries[rdm]);
}
@last_run_time
is a 9.4. User-Defined Variables and last_run_time datetime
one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.
Try: SELECT last_run_time;
UPDATE
Example:
/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$
CREATE PROCEDURE `sp_test`()
BEGIN
DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
DECLARE last_run_time DATETIME DEFAULT NULL;
DECLARE current_run_time DATETIME DEFAULT NOW();
-- Define the last run time
SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);
-- if there is no last run time found then use yesterday as starting point
IF(last_run_time IS NULL) THEN
SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
END IF;
SELECT last_run_time;
-- Insert variables in table2
INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$
DELIMITER ;
Javadoc to the rescue :
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace
nextLine
is probably the method you should use.
Updating to use tibble()
You can pass a named vector of length greater than 1 to the by
argument of left_join()
:
library(dplyr)
d1 <- tibble(
x = letters[1:3],
y = LETTERS[1:3],
a = rnorm(3)
)
d2 <- tibble(
x2 = letters[3:1],
y2 = LETTERS[3:1],
b = rnorm(3)
)
left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))
This happens because you try to access plotOptions
property using string name
. TypeScript understands that name
may have any value, not only property name from plotOptions
. So TypeScript requires to add index signature to plotOptions
, so it knows that you can use any property name in plotOptions
. But I suggest to change type of name
, so it can only be one of plotOptions
properties.
interface trainInfo {
name: keyof typeof plotOptions;
x: Array<number>;
y: Array<number>;
type: string;
mode: string;
}
Now you'll be able to use only property names that exist in plotOptions
.
You also have to slightly change your code.
First assign array to some temp variable, so TS knows array type:
const plotDataTemp: Array<trainInfo> = [
{
name: "train_1",
x: data.filtrationData.map((i: any) => i["1-CumVol"]),
y: data.filtrationData.map((i: any) => i["1-PressureA"]),
type: "scatter",
mode: "lines"
},
// ...
}
Then filter:
const plotData = plotDataTemp.filter(({ name }) => plotOptions[name]);
If you're getting data from API and have no way to type check props at compile time the only way is to add index signature to your plotOptions
:
type tplotOptions = {
[key: string]: boolean
}
const plotOptions: tplotOptions = {
train_1: true,
train_2: true,
train_3: true,
train_4: true
}
#header {
top:0;
width:100%;
position:fixed;
background-color:#FFF;
}
#content {
position:static;
margin-top:100px;
}
After reading all comments and answers I am going to explain an optimal solution for this problem. The best option is @rik's solution, so my improvement is base on his.
Instead of having to ask each FragmentClass like
if(FragmentClass1){
...
if(FragmentClass2){
...
}
Create your own interface, and maker your child fragments implement it, something like
public interface MyChildFragment {
void updateView(int position);
}
Then, you can do something like this to initiate and update your inner fragments.
Fragment childFragment = (Fragment) mViewPagerDetailsAdapter.instantiateItem(mViewPager,mViewPager.getCurrentItem());
if (childFragment != null) {
((MyChildFragment) childFragment).updateView();
}
P.S. Be careful where you put that code, if you call insatiateItem before the system actually create it the savedInstanceState
of your child fragment will be null therefor
public void onCreate(@Nullable Bundle savedInstanceState){
super(savedInstanceState)
}
Will crash your app.
Good luck
`My vbs file path :
D:\QTP Practice\Driver\Testany.vbs'
objShell = CreateObject("Shell.Application")
objShell.ShellExecute "cmd.exe","/k echo test", "", "runas", 1
set x=createobject("wscript.shell")
wscript.sleep(2000)
x.sendkeys "CD\"&"{ENTER}"&"cd D:"&"{ENTER}"&"cd "&"QTP Practice\Driver"&"{ENTER}"&"Testany.vbs"&"{ENTER}"
--from google search and some tuning, working for me
just type SET SQL_SAFE_UPDATES = 0; before the delete or update and set to 1 again SET SQL_SAFE_UPDATES = 1
The first snippet is correct, but you need to call it after onMeasure()
gets executed. Otherwise the size is not yet measured for the view.
arr=("sharlock" "bomkesh" "feluda" ) ##declare array
len=${#arr[*]} #determine length of array
# iterate with for loop
for (( i=0; i<len; i++ ))
do
echo ${arr[$i]}
done
select to.chargeid,t0.po,i.chargetype from invoice i
inner join
(select chargeid,max(servicemonth)po from invoice
group by chargeid)t0
on i.chargeid=t0.chargeid
The above query will work if the distinct charge id has different chargetype combinations.Hope this simple query helps with little performance time into consideration...
What is the value range? Is it 0 through 10? If so, then try:
SELECT REPLICATE('0',2-LEN(@t)) + CAST(@t AS VARCHAR)
That handles 0 through 9 as well as 10 through 99.
Now, tinyint can go up to the value of 255. If you want to handle > 99 through 255, then try this solution:
declare @t TINYINT
set @t =233
SELECT ISNULL(REPLICATE('0',2-LEN(@t)),'') + CAST(@t AS VARCHAR)
To understand the solution, the expression to the left of the + calculates the number of zeros to prefix to the string.
In case of the value 3, the length is 1. 2 - 1 is 1. REPLICATE Adds one zero. In case of the value 10, the length is 2. 2 - 2 is 0. REPLICATE Adds nothing. In the case of the value 100, the length is -1 which produces a NULL. However, the null value is handled and set to an empty string.
Now if you decide that because tinyint can contain up to 255 and you want your formatting as three characters, just change the 2-LEN to 3-LEN in the left expression and you're set.
Try adding a semi colon to the end of your structure:
struct sotrudnik {
string name;
string speciality;
string razread;
int zarplata;
} //Semi colon here
There can be more than one main method in a single program. Others are Overloaded method. This overloaded method works fine under a single main method
public class MainMultiple{
public static void main(String args[]){
main(122);
main('f');
main("hello java");
}
public static void main(int i){
System.out.println("Overloaded main()"+i);
}
public static void main(char i){
System.out.println("Overloaded main()"+i);
}
public static void main(String str){
System.out.println("Overloaded main()"+str);
}
}
The answer will not work when using the overload to indicate the template @Html.DisplayFor(x => x.Foos, "YourTemplateName)
.
Seems to be designed that way, see this case. Also the exception the framework gives (about the type not been as expected) is quite misleading and fooled me on the first try (thanks @CodeCaster)
In this case you have to use @foreach
@foreach (var item in Model.Foos)
{
@Html.DisplayFor(x => item, "FooTemplate")
}
I think you are not configured properly,
if you are using XAMPP then you can easily send mail from localhost.
for example you can configure C:\xampp\php\php.ini
and c:\xampp\sendmail\sendmail.ini
for gmail to send mail.
in C:\xampp\php\php.ini
find extension=php_openssl.dll
and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.
in php.ini file find [mail function]
and change
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(use the above send mail path only and it will work)
Now Open C:\xampp\sendmail\sendmail.ini
. Replace all the existing code in sendmail.ini with following code
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]
Now you have done!! create php file with mail function and send mail from localhost.
Update
First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()
).
You can set the following settings in your PHP.ini:
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
Short answer:
int
uses up 4 bytes of memory (and it CANNOT contain a decimal), double
uses 8 bytes of memory. Just different tools for different purposes.
In case anyone is interested in a general one-liner, simply get the current ticks and use it to set the new ticks by sampling every other tick.
ax.set_xticks(ax.get_xticks()[::2])
Prior to PHP 5.2.0 and above you should use filter_input()
which is especially created for that to get a specific external user inputs such as get, post or cookie variables by name and optionally filters it to avoid any XSS/Injection attacks on your site. For example:
$user = filter_input(INPUT_POST, 'username');
You may use one of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.
By using optional 3rd argument, you can extend it by variety of filters (for validating, sanitizing, filtering or other), e.g. FILTER_SANITIZE_SPECIAL_CHARS
, FILTER_SANITIZE_ENCODED
, etc.
For example:
<?php
$search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
$search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
echo "You have searched for $search_html.\n";
echo "<a href='?search=$search_url'>Search again.</a>";
?>
The syntax is:
mixed
filter_input
( int $type , string $variable_name [, int $filter = FILTER_DEFAULT [, mixed $options ]] )(PHP 5 >= 5.2.0, PHP 7)
See also: Why is better to use filter_input()?
This post helped me A LOT!
I added UIViewAlertForUnsatisfiableConstraints symbolic breakpoint with suggested action:
Obj-C project
po [[UIWindow keyWindow] _autolayoutTrace]
Swift project
expr -l objc++ -O -- [[UIWindow keyWindow] _autolayoutTrace]
With this hint, the log became more detailed, and It was easier for me identify which view had the constraint broken.
UIWindow:0x7f88a8e4a4a0
| UILayoutContainerView:0x7f88a8f23b70
| | UINavigationTransitionView:0x7f88a8ca1970
| | | UIViewControllerWrapperView:0x7f88a8f2aab0
| | | | •UIView:0x7f88a8ca2880
| | | | | *UIView:0x7f88a8ca2a10
| | | | | | *UIButton:0x7f88a8c98820'Archived'
| | | | | | | UIButtonLabel:0x7f88a8cb0e30'Archived'
| | | | | | *UIButton:0x7f88a8ca22d0'Download'
| | | | | | | UIButtonLabel:0x7f88a8cb04e0'Download'
| | | | | | *UIButton:0x7f88a8ca1580'Deleted'
| | | | | | | UIButtonLabel:0x7f88a8caf100'Deleted'
| | | | | *UIView:0x7f88a8ca33e0
| | | | | *_UILayoutGuide:0x7f88a8ca35b0
| | | | | *_UILayoutGuide:0x7f88a8ca4090
| | | | | _UIPageViewControllerContentView:0x7f88a8f1a390
| | | | | | _UIQueuingScrollView:0x7f88aa031c00
| | | | | | | UIView:0x7f88a8f38070
| | | | | | | UIView:0x7f88a8f381e0
| | | | | | | | •UIView:0x7f88a8f39fa0, MISSING HOST CONSTRAINTS
| | | | | | | | | *UIButton:0x7f88a8cb9bf0'Retrieve data'- AMBIGUOUS LAYOUT for UIButton:0x7f88a8cb9bf0'Retrieve data'.minX{id: 170}, UIButton:0x7f88a8cb9bf0'Retrieve data'.minY{id: 171}
| | | | | | | | | *UIImageView:0x7f88a8f3ad80- AMBIGUOUS LAYOUT for UIImageView:0x7f88a8f3ad80.minX{id: 172}, UIImageView:0x7f88a8f3ad80.minY{id: 173}
| | | | | | | | | *App.RecordInfoView:0x7f88a8cbe530- AMBIGUOUS LAYOUT for App.RecordInfoView:0x7f88a8cbe530.minX{id: 174}, App.RecordInfoView:0x7f88a8cbe530.minY{id: 175}, App.RecordInfoView:0x7f88a8cbe530.Width{id: 176}, App.RecordInfoView:0x7f88a8cbe530.Height{id: 177}
| | | | | | | | | | +UIView:0x7f88a8cc1d30- AMBIGUOUS LAYOUT for UIView:0x7f88a8cc1d30.minX{id: 178}, UIView:0x7f88a8cc1d30.minY{id: 179}, UIView:0x7f88a8cc1d30.Width{id: 180}, UIView:0x7f88a8cc1d30.Height{id: 181}
| | | | | | | | | | | *UIView:0x7f88a8cc1ec0- AMBIGUOUS LAYOUT for UIView:0x7f88a8cc1ec0.minX{id: 153}, UIView:0x7f88a8cc1ec0.minY{id: 151}, UIView:0x7f88a8cc1ec0.Width{id: 154}, UIView:0x7f88a8cc1ec0.Height{id: 165}
| | | | | | | | | | | | *UIView:0x7f88a8e68e10- AMBIGUOUS LAYOUT for UIView:0x7f88a8e68e10.minX{id: 155}, UIView:0x7f88a8e68e10.minY{id: 150}, UIView:0x7f88a8e68e10.Width{id: 156}
| | | | | | | | | | | | *UIImageView:0x7f88a8e65de0- AMBIGUOUS LAYOUT for UIImageView:0x7f88a8e65de0.minX{id: 159}, UIImageView:0x7f88a8e65de0.minY{id: 182}
| | | | | | | | | | | | *UILabel:0x7f88a8e69080'8-6-2015'- AMBIGUOUS LAYOUT for UILabel:0x7f88a8e69080'8-6-2015'.minX{id: 183}, UILabel:0x7f88a8e69080'8-6-2015'.minY{id: 184}, UILabel:0x7f88a8e69080'8-6-2015'.Width{id: 185}
| | | | | | | | | | | | *UILabel:0x7f88a8cc0690'16:34'- AMBIGUOUS LAYOUT for UILabel:0x7f88a8cc0690'16:34'.minX{id: 186}, UILabel:0x7f88a8cc0690'16:34'.minY{id: 187}, UILabel:0x7f88a8cc0690'16:34'.Width{id: 188}, UILabel:0x7f88a8cc0690'16:34'.Height{id: 189}
| | | | | | | | | | | | *UIView:0x7f88a8cc2050- AMBIGUOUS LAYOUT for UIView:0x7f88a8cc2050.minX{id: 161}, UIView:0x7f88a8cc2050.minY{id: 166}, UIView:0x7f88a8cc2050.Width{id: 163}
| | | | | | | | | | | | *UIImageView:0x7f88a8e69d90- AMBIGUOUS LAYOUT for UIImageView:0x7f88a8e69d90.minX{id: 190}, UIImageView:0x7f88a8e69d90.minY{id: 191}, UIImageView:0x7f88a8e69d90.Width{id: 192}, UIImageView:0x7f88a8e69d90.Height{id: 193}
| | | | | | | | | | | *UIView:0x7f88a8f3cc00
| | | | | | | | | | | | *UIView:0x7f88a8e618d0
| | | | | | | | | | | | *UIImageView:0x7f88a8e5ba10
| | | | | | | | | | | | *UIView:0x7f88a8f3cd70
| | | | | | | | | | | | *UIImageView:0x7f88a8e58e10
| | | | | | | | | | | | *UIImageView:0x7f88a8e5e7a0
| | | | | | | | | | | | *UIView:0x7f88a8f3cee0
| | | | | | | | | | | *UIView:0x7f88a8f3dc70
| | | | | | | | | | | | *UIView:0x7f88a8e64dd0
| | | | | | | | | | | | *UILabel:0x7f88a8e65290'Average flow rate'
| | | | | | | | | | | | *UILabel:0x7f88a8e712d0'177.0 ml/s'
| | | | | | | | | | | | *UILabel:0x7f88a8c97150'1299.4'
| | | | | | | | | | | | *UIView:0x7f88a8f3dde0
| | | | | | | | | | | | *UILabel:0x7f88a8f3df50'Maximum flow rate'
| | | | | | | | | | | | *UILabel:0x7f88a8cbfdb0'371.6 ml/s'
| | | | | | | | | | | | *UILabel:0x7f88a8cc0230'873.5'
| | | | | | | | | | | | *UIView:0x7f88a8f3e2a0
| | | | | | | | | | | | *UILabel:0x7f88a8f3e410'Total volume'
| | | | | | | | | | | | *UILabel:0x7f88a8cc0f20'371.6 ml'
| | | | | | | | | | | | *UIView:0x7f88a8f3e870
| | | | | | | | | | | | *UILabel:0x7f88a8f3ea00'Time do max. flow'
| | | | | | | | | | | | *UILabel:0x7f88a8cc0ac0'3.6 s'
| | | | | | | | | | | | *UIView:0x7f88a8f3ee10
| | | | | | | | | | | | *UILabel:0x7f88a8f3efa0'Flow time'
| | | | | | | | | | | | *UILabel:0x7f88a8cbf980'2.1 s'
| | | | | | | | | | | | *UIView:0x7f88a8f3f3e0
| | | | | | | | | | | | *UILabel:0x7f88a8f3f570'Voiding time'
| | | | | | | | | | | | *UILabel:0x7f88a8cc17e0'3.5 s'
| | | | | | | | | | | | *UIView:0x7f88a8f3f9a0
| | | | | | | | | | | | *UILabel:0x7f88a8f3fb30'Voiding delay'
| | | | | | | | | | | | *UILabel:0x7f88a8cc1380'1.0 s'
| | | | | | | | | | | | *UIView:0x7f88a8e65000
| | | | | | | | | | | | *UIButton:0x7f88a8e52f20'Show'
| | | | | | | | | | | | *UIImageView:0x7f88a8e6e1d0
| | | | | | | | | | | | *UIButton:0x7f88a8e52c90'Send'
| | | | | | | | | | | | *UIImageView:0x7f88a8e61bb0
| | | | | | | | | | | | *UIButton:0x7f88a8e528e0'Delete'
| | | | | | | | | | | | *UIImageView:0x7f88a8e6b3f0
| | | | | | | | | | | | *UIView:0x7f88a8f3ff60
| | | | | | | | | *UIActivityIndicatorView:0x7f88a8cba080
| | | | | | | | | | UIImageView:0x7f88a8cba700
| | | | | | | | | *_UILayoutGuide:0x7f88a8cc3150
| | | | | | | | | *_UILayoutGuide:0x7f88a8cc3b10
| | | | | | | UIView:0x7f88a8f339c0
| | UINavigationBar:0x7f88a8c96810
| | | _UINavigationBarBackground:0x7f88a8e45c00
| | | | UIImageView:0x7f88a8e46410
| | | UINavigationItemView:0x7f88a8c97520'App'
| | | | UILabel:0x7f88a8c97cc0'App'
| | | UINavigationButton:0x7f88a8e3e850
| | | | UIImageView:0x7f88a8e445b0
| | | _UINavigationBarBackIndicatorView:0x7f88a8f2b530
Legend:
* - is laid out with auto layout
+ - is laid out manually, but is represented in the layout engine because translatesAutoresizingMaskIntoConstraints = YES
• - layout engine host
Then I paused execution and I changed problematic view's background color with the command (replacing 0x7f88a8cc2050
with the memory address of your object of course)...
Obj-C
expr ((UIView *)0x7f88a8cc2050).backgroundColor = [UIColor redColor]
Swift 3.0
expr -l Swift -- import UIKit
expr -l Swift -- unsafeBitCast(0x7f88a8cc2050, to: UIView.self).backgroundColor = UIColor.red
... and the result It was awesome!
Simply amazing! Hope It helps.
If you are strictly trying to run the emulator from the command line try this in OSX.
"/Applications/Android Studio.app/sdk/tools/emulator" -avd <NAMEOFDEVICE> -netspeed full -netdelay none
You can simplify it by adding an alias to the .bash_profile, and sending it to a background job.
alias android='/Applications/Android\ Studio.app/sdk/tools/emulator <NAMEOFDEVICE> -netspeed full -netdelay none &'
Let Bash know about the changes.
source ~/.bash_profile
As described in this blog post, here is a method to round the corners of a UIView:
+(void)roundView:(UIView *)view onCorner:(UIRectCorner)rectCorner radius:(float)radius
{
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds
byRoundingCorners:rectCorner
cornerRadii:CGSizeMake(radius, radius)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = view.bounds;
maskLayer.path = maskPath.CGPath;
[view.layer setMask:maskLayer];
[maskLayer release];
}
The cool part about it is that you can select which corners you want rounded up.
I couldn't get the above code to work.
Google does a great explanation though here: http://code.google.com/apis/maps/documentation/javascript/basics.html#DetectingUserLocation
Where they first use the W3C Geolocation method and then offer the Google.gears fallback method for older browsers.
The example is here:
http://code.google.com/apis/maps/documentation/javascript/examples/map-geolocation.html
string RemoveChar(string str, char c)
{
string result;
for (size_t i = 0; i < str.size(); i++)
{
char currentChar = str[i];
if (currentChar != c)
result += currentChar;
}
return result;
}
This is how I did it.
Or you could do as Antoine mentioned:
See this question which answers the same problem. In your case:
#include <algorithm> str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());
I know that if you were to change that to an href you'd do:
$("a#link1").click(function(event) { event.preventDefault(); $('div.link1').show(); //whatever else you want to do });
so if you want to keep it with the div, I'd try
$("div.clickable").click(function(event) { event.preventDefault(); window.location = $(this).attr("url"); });
We use getModifierState
to check for caps lock, it's only a member of a mouse or keyboard event so we cannot use an onfocus
. The most common two ways that the password field will gain focus is with a click in or a tab. We use onclick
to check for a mouse click within the input, and we use onkeyup
to detect a tab from the previous input field. If the password field is the only field on the page and is auto-focused then the event will not happen until the first key is released, which is ok but not ideal, you really want caps lock tool tips to display once the password field gains focus, but for most cases this solution works like a charm.
HTML
<input type="password" id="password" onclick="checkCapsLock(event)" onkeyup="checkCapsLock(event)" />
JS
function checkCapsLock(e) {
if (e.getModifierState("CapsLock")) {
console.log("Caps");
}
}
You need to set basicHttpBinding -> MaxReceivedMessageSize in the client configuration.
string countryName = "USA";
DataTable dt = new DataTable();
int id = (from DataRow dr in dt.Rows
where (string)dr["CountryName"] == countryName
select (int)dr["id"]).FirstOrDefault();
Do we really need a Boost library for seemingly such a simple task?
To replace all occurences of a substring use this function:
std::string ReplaceString(std::string subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:
void ReplaceStringInPlace(std::string& subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
Tests:
std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;
std::cout << "ReplaceString() return value: "
<< ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not modified: "
<< input << std::endl;
ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: "
<< input << std::endl;
Output:
Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def
You have to use the NotifyIcon control from System.Windows.Forms, or alternatively you can use the Notify Icon API provided by Windows API. WPF Provides no such equivalent, and it has been requested on Microsoft Connect several times.
I have code on GitHub which uses System.Windows.Forms
NotifyIcon Component from within a WPF application, the code can be viewed at https://github.com/wilson0x4d/Mubox/blob/master/Mubox.QuickLaunch/AppWindow.xaml.cs
Here are the summary bits:
Create a WPF Window with ShowInTaskbar=False, and which is loaded in a non-Visible State.
At class-level:
private System.Windows.Forms.NotifyIcon notifyIcon = null;
During OnInitialize():
notifyIcon = new System.Windows.Forms.NotifyIcon();
notifyIcon.Click += new EventHandler(notifyIcon_Click);
notifyIcon.DoubleClick += new EventHandler(notifyIcon_DoubleClick);
notifyIcon.Icon = IconHandles["QuickLaunch"];
During OnLoaded():
notifyIcon.Visible = true;
And for interaction (shown as notifyIcon.Click and DoubleClick above):
void notifyIcon_Click(object sender, EventArgs e)
{
ShowQuickLaunchMenu();
}
From here you can resume the use of WPF Controls and APIs such as context menus, pop-up windows, etc.
It's that simple. You don't exactly need a WPF Window to host to the component, it's just the most convenient way to introduce one into a WPF App (as a Window is generally the default entry point defined via App.xaml), likewise, you don't need a WPF Wrapper or 3rd party control, as the SWF component is guaranteed present in any .NET Framework installation which also has WPF support since it's part of the .NET Framework (which all current and future .NET Framework versions build upon.) To date, there is no indication from Microsoft that SWF support will be dropped from the .NET Framework anytime soon.
Hope that helps.
It's a little cheese that you have to use a pre-3.0 Framework Component to get a tray-icon, but understandably as Microsoft has explained it, there is no concept of a System Tray within the scope of WPF. WPF is a presentation technology, and Notification Icons are an Operating System (not a "Presentation") concept.
A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process. You aren't getting or posting any application data at this point, just establishing the connection, itself.
A socket timeout is the timeout when waiting for individual packets. It's a common misconception that a socket timeout is the timeout to receive the full response. So if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.
First save the .mat file as:
save('test.mat', '-v7')
After that, in Python, use the usual loadmat
function:
import scipy.io as sio
test = sio.loadmat('test.mat')
Select * from Table name ..i.e(are you save table name in sql(TEST) k.
Select * from TEST then you will execute your project.
A dirty trick I somtimes use, is hiding variables in the 'name' attribute (that I normally don't use for other purposes):
select onFocus=(this.name=this.value) onChange=someFunction(this.name,this.value)><option...
Somewhat unexpectedly, both the old and the new value is then submitted to someFunction(oldValue,newValue)
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, 5); // Adding 5 days
String output = sdf.format(c.getTime());
System.out.println(output);
Can you define further processing?
You can use a for loop to almost do this, but there's no easy way to insert CR/LF into an environment variable, so you'll have everything in one line. (you may be able to work around this depending on what you need to do.)
You're also limited to less than about 8k text files this way. (You can't create a single env var bigger than around 8k.)
Bill's suggestion of a for loop is probably what you need. You process the file one line at a time:
(use %i
at a command line %%i
in a batch file)
for /f "tokens=1 delims=" %%i in (file.txt) do echo %%i
more advanced:
for /f "tokens=1 delims=" %%i in (file.txt) do call :part2 %%i
goto :fin
:part2
echo %1
::do further processing here
goto :eof
:fin
The simplest modification (to the code in your question) is this:
Range("A" & Rows.Count).End(xlUp).Select
Selection.EntireRow.Delete
Which can be simplified to:
Range("A" & Rows.Count).End(xlUp).EntireRow.Delete
Note: though the original question asked was for javascript, it can be done jQuery by below solution
you can extend jquery if you want here is the sample code for one slice:
jQuery.extend({
sliceMe: function(obj, str) {
var returnJsonObj = null;
$.each( obj, function(name, value){
alert("name: "+name+", value: "+value);
if(name==str){
returnJsonObj = JSON.stringify("{"+name+":"+value+"}");
}
});
return returnJsonObj;
}
});
var elmo = {
color: 'red',
annoying: true,
height: 'unknown',
meta: { one: '1', two: '2'}
};
var temp = $.sliceMe(elmo,"color");
alert(JSON.stringify(temp));
here is the fiddle for same: http://jsfiddle.net/w633z/
It's evident that you've managed to mess up your PATH
variable. (Your current PATH
doesn't contain any location where common utilities are located.)
Try:
PATH=/bin:/usr/bin:/usr/local/bin:${PATH}
export PATH
Alternatively, for "resetting" zsh, specify the complete path to the shell:
exec /bin/zsh
or
exec /usr/bin/zsh
For what it's worth.
$('.js-toggle-edit').on('click', function (e) {
var bool = $('.js-editable').prop('readonly');
$('.js-editable').prop('readonly', ! bool);
})
Keep in mind you can pass a closure to .prop(), and do a per element check. But in this case it doesn't matter, it's just a mass toggle.
Not sure when this changed, but with the latest version of typescript, you just need to use import moment from 'moment';
and everything else should work as normal.
Looks like moment recent fixed their import. As of at least 2.24.0
you'll want to use import * as moment from 'moment';
I use WinMerge. It is free and works pretty well (works for files and directories).
For Windows
I had the same problem, I tried to reinstall and didn't worked for me.
Remove "C:\Program Files(x86)\nodejs"
from your system enviorment PATH
and thats it!
Where are you configuring your authenticated URL pattern(s)? I only see one uri in your code.
Do you have multiple configure(HttpSecurity) methods or just one? It looks like you need all your URIs in the one method.
I have a site which requires authentication to access everything so I want to protect /*. However in order to authenticate I obviously want to not protect /login. I also have static assets I'd like to allow access to (so I can make the login page pretty) and a healthcheck page that shouldn't require auth.
In addition I have a resource, /admin, which requires higher privledges than the rest of the site.
The following is working for me.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login**").permitAll()
.antMatchers("/healthcheck**").permitAll()
.antMatchers("/static/**").permitAll()
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.antMatchers("/**").access("hasRole('ROLE_USER')")
.and()
.formLogin().loginPage("/login").failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.csrf();
}
NOTE: This is a first match wins so you may need to play with the order. For example, I originally had /** first:
.antMatchers("/**").access("hasRole('ROLE_USER')")
.antMatchers("/login**").permitAll()
.antMatchers("/healthcheck**").permitAll()
Which caused the site to continually redirect all requests for /login back to /login. Likewise I had /admin/** last:
.antMatchers("/**").access("hasRole('ROLE_USER')")
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
Which resulted in my unprivledged test user "guest" having access to the admin interface (yikes!)
create table test (a int, b int , c int, d int);
alter table test drop column b, d;
Be aware that DROP COLUMN does not physically remove the data, and for fixed length types (int, numeric, float, datetime, uniqueidentifier etc) the space is consumed even for records added after the columns were dropped. To get rid of the wasted space do ALTER TABLE ... REBUILD
.
I have written a crontab deploy tool in python: https://github.com/monklof/deploycron
pip install deploycron
Install your crontab is very easy, this will merge the crontab into the system's existing crontab.
from deploycron import deploycron
deploycron(content="* * * * * echo hello > /tmp/hello")
Justin has correctly shown the expansion in the case where the join is just followed by a select
. If you've got something else, it becomes more tricky due to transparent identifiers - the mechanism the C# compiler uses to propagate the scope of both halves of the join.
So to change Justin's example slightly:
var result = from sc in enumerableOfSomeClass
join soc in enumerableOfSomeOtherClass
on sc.Property1 equals soc.Property2
where sc.X + sc.Y == 10
select new { SomeClass = sc, SomeOtherClass = soc }
would be converted into something like this:
var result = enumerableOfSomeClass
.Join(enumerableOfSomeOtherClass,
sc => sc.Property1,
soc => soc.Property2,
(sc, soc) => new { sc, soc })
.Where(z => z.sc.X + z.sc.Y == 10)
.Select(z => new { SomeClass = z.sc, SomeOtherClass = z.soc });
The z
here is the transparent identifier - but because it's transparent, you can't see it in the original query :)
At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload
maybe. Something like this:
<html>
<head>
<title></title>
<script type="text/javascript">
window.onload = function(){
var refButton = document.getElementById("btnButton");
refButton.onclick = function() {
alert('I am clicked!');
}
};
</script>
</head>
<body>
<form id="form1">
<div>
<input id="btnButton" type="button" value="Click me"/>
</div>
</form>
</body>
</html>
If you want to change the permissions of an existing file, use chmod (change mode):
$itWorked = chmod ("/yourdir/yourfile", 0777);
If you want all new files to have certain permissions, you need to look into setting your umode
. This is a process setting that applies a default modification to standard modes.
It is a subtractive one. By that, I mean a umode
of 022
will give you a default permission of 755
(777 - 022 = 755
).
But you should think very carefully about both these options. Files created with that mode will be totally unprotected from changes.
simply execute -
git stash
it will remove all your local changes. and you can also use it later by executing -
git stash apply
I'm not cool enough for comments. I fixed the plunker from the accepted answer to work for rc2. Nothing fancy, links to the CDN were just broken is all.
'@angular/core': {
main: 'bundles/core.umd.js',
defaultExtension: 'js'
},
'@angular/compiler': {
main: 'bundles/compiler.umd.js',
defaultExtension: 'js'
},
'@angular/common': {
main: 'bundles/common.umd.js',
defaultExtension: 'js'
},
'@angular/platform-browser-dynamic': {
main: 'bundles/platform-browser-dynamic.umd.js',
defaultExtension: 'js'
},
'@angular/platform-browser': {
main: 'bundles/platform-browser.umd.js',
defaultExtension: 'js'
},
There are many ways to do this, one way is:
sqlite3 auction.db
Followed by:
sqlite> .read create.sql
In general, the SQLite project has really fantastic documentation! I know we often reach for Google before the docs, but in SQLite's case, the docs really are technical writing at its best. It's clean, clear, and concise.
When taking Distinct we have to cast into IEnumerable too. If list is model means, need to write code like this
IEnumerable<T> ids = list.Select(x => x).Distinct();
Setting the CSS property after you have used .show()
should work. Maybe you are targeting the wrong element on your HTML page.
$('#foo').css('display', 'inline-block');
But if you are not using any effects of .show(), .hide()
why don't you set those CSS properties manually like:
$('#foo').css('display','none');
$('#foo').css('display','inline-block');
I was able to fix my problem by using a combination of $.ajaxSetup and appending a timestamp to the url of my post (not to the post parameters/body). This based on the recommendations of previous answers
$(document).ready(function(){
$.ajaxSetup({ type:'POST', headers: {"cache-control","no-cache"}});
$('#myForm').submit(function() {
var data = $('#myForm').serialize();
var now = new Date();
var n = now.getTime();
$.ajax({
type: 'POST',
url: 'myendpoint.cfc?method=login&time='+n,
data: data,
success: function(results){
if(results.success) {
window.location = 'app.cfm';
} else {
console.log(results);
alert('login failed');
}
}
});
});
});
nzd$date <- format(as.Date(nzd$date), "%Y/%m/%d")
In the above piece of code, there are two mistakes. First of all, when you are reading nzd$date
inside as.Date
you are not mentioning in what format you are feeding it the date
. So, it tries it's default set format to read it. If you see the help
doc, ?as.Date
you will see
format
A character string. If not specified, it will try "%Y-%m-%d" then "%Y/%m/%d" on the first non-NA element, and give an error if neither works. Otherwise, the processing is via strptime
The second mistake is: even though you would like to read it in %Y-%m-%d
format, inside format
you wrote "%Y/%m/%d"
.
Now, the correct way of doing it is:
> nzd <- data.frame(date=c("31/08/2011", "31/07/2011", "30/06/2011"),
+ mid=c(0.8378,0.8457,0.8147))
> nzd
date mid
1 31/08/2011 0.8378
2 31/07/2011 0.8457
3 30/06/2011 0.8147
> nzd$date <- format(as.Date(nzd$date, format = "%d/%m/%Y"), "%Y-%m-%d")
> head(nzd)
date mid
1 2011-08-31 0.8378
2 2011-07-31 0.8457
3 2011-06-30 0.8147
Press the start button. In the search box type "cmd", then press Ctrl+Shift+Enter
On Mac: /Library/PostgreSQL/9.0/data/base
The directory can't be entered, but you can look at the content via: sudo du -hc data
It sounds like the data you're really looking for can be accessed via secondary URL called by some javascript on the primary page.
While you could try running javascript on the server to handle this, a simpler approach to might be to load up the page using Firefox and use a tool like Charles or Firebug to identify exactly what that secondary URL is. Then you can just query that URL directly for the data you are interested in.
The use of that
is not really necessary if you make a workaround with the use of call()
or apply()
:
var car = {};
car.starter = {};
car.start = function(){
this.starter.active = false;
var activateStarter = function(){
// 'this' now points to our main object
this.starter.active = true;
};
activateStarter.apply(this);
};
These examples work fine:
nohup sh prog.sh proglog.log 2>&1 &
For loop you can use like this :
for i in {1..10}; do sh prog.sh; sleep 1; done prog.log 2>&1 &
It works in background and does not show any output.
Please refer this link[1]. Visual Studio code has mentioned a brief explanation for this error message. I also encountered the same error. Adding the below parameter in the relavant file will fix this issue.
fs.inotify.max_user_watches=524288
For merging small sets, using the above function is fine. However, if you are merging large amounts of data, I'd suggest looking into http://mbk.projects.postgresql.org
The current best practice that I'm aware of is:
On some level Chris Pietschmann is correct. SQL isn't Turing complete (at least without stored procedures) yet people will list that as a language, TeX is Turing complete but most people regard it as a markup language.
Having said that: if you are just applying for jobs, not arguing formal logic, I would just list them all as technologies. Things like .NET aren't languages but would probably be listed as well.
In an attempt to solve a similar situation I've come across this example and adapted it. It uses JQUERY UI Dialog as Nikhil D suggested. Here is a look at the code:
HTML:
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<input type="button" id="box" value="Confirm the thing?" />
<div id="dialog-confirm"></div>
JavaScript:
$('#box').click(function buttonAction() {
$("#dialog-confirm").html("Do you want to do the thing?");
// Define the Dialog and its properties.
$("#dialog-confirm").dialog({
resizable: false,
modal: true,
title: "Do the thing?",
height: 250,
width: 400,
buttons: {
"Yes": function() {
$(this).dialog('close');
alert("Yes, do the thing");
},
"No": function() {
$(this).dialog('close');
alert("Nope, don't do the thing");
}
}
});
});
$('#box').click(buttonAction);
I have a few more tweaks I need to do to make this example work for my application. Will update this if I see it fit into the answer. Hope this helps someone.
Set the set the Email Message IsBodyHtml = true
Take your object that contains your email contents Serialize the object and use xml/xslt to generate the html content.
If you want to do AlternateViews do the same thing that jmein only use a different xslt template to create the plain text content.
one of the major advantages to this is if you want to change your layout all you have to do update the xslt template.
@ChrisPratt's answer about the use of Display Template is wrong. The correct code to make it work is:
@model DateTime?
@if (Model.HasValue)
{
@Convert.ToDateTime(Model).ToString("MM/dd/yyyy")
}
That's because .ToString()
for Nullable<DateTime>
doesn't accept Format
parameter.
If you have already created a localhost connection and its still showing can not connect then goto taskbar and find the MySQL notifier icon. Click on that and check whether your connection name is running or stopped. If its stopped then start or restart. I was facing the same issue but it fixed my problem.
<% %>
: Executes the ruby code <%= %>
: Prints into Erb file. Or browser <% -%>
: Avoids line break after expression. <%# %>
: ERB commentAlso look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.
Given a folder name, walk through its entire hierarchy recursively.
#! /usr/local/bin/python3
# findLargeFiles.py - given a folder name, walk through its entire hierarchy
# - print folders and files within each folder
import os
def recursive_walk(folder):
for folderName, subfolders, filenames in os.walk(folder):
if subfolders:
for subfolder in subfolders:
recursive_walk(subfolder)
print('\nFolder: ' + folderName + '\n')
for filename in filenames:
print(filename + '\n')
recursive_walk('/name/of/folder')
If, like me, you're running gVim on Windows then your .vimrc file may be sourcing another 'example' Vimscript file that automatically sets textwidth
(in my case to 78
) for text files.
My answer to a similar question as this one – How to stop gVim wrapping text at column 80 – on the Vi and Vim Stack Exchange site:
In my case, Vitor's comment suggested I run the following:
:verbose set tw?
Doing so gave me the following output:
textwidth=78 Last set from C:\Program Files (x86)\Vim\vim74\vimrc_example.vim
In vimrc_example.vim, I found the relevant lines:
" Only do this part when compiled with support for autocommands. if has("autocmd") ... " For all text files set 'textwidth' to 78 characters. autocmd FileType text setlocal textwidth=78 ...
And I found that my .vimrc is sourcing that file:
source $VIMRUNTIME/vimrc_example.vim
In my case, I don't want
textwidth
to be set for any files, so I just commented out the relevant line in vimrc_example.vim.
It uses a parametric description of the segment, and projects the point into the line defined by the segment. As the parameter goes from 0 to 1 in the segment, if the projection is outside this bounds, we compute the distance to the corresponding enpoint, instead of the straight line normal to the segment.
Clear["Global`*"];
distance[{start_, end_}, pt_] :=
Module[{param},
param = ((pt - start).(end - start))/Norm[end - start]^2; (*parameter. the "."
here means vector product*)
Which[
param < 0, EuclideanDistance[start, pt], (*If outside bounds*)
param > 1, EuclideanDistance[end, pt],
True, EuclideanDistance[pt, start + param (end - start)] (*Normal distance*)
]
];
Plotting result:
Plot3D[distance[{{0, 0}, {1, 0}}, {xp, yp}], {xp, -1, 2}, {yp, -1, 2}]
Plot those points nearer than a cutoff distance:
Contour Plot:
One of the reasons for this error is the use of the jaxb implementation from the jdk. I am not sure why such a problem can appear in pretty simple xml parsing situations. You may use the latest version of the jaxb library from a public maven repository:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.12</version>
</dependency>
Your code is fine, just replace the following line:
JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));
with this line:
JSONArray jsonMainArr = mainJSON.getJSONArray("source");
If you run this as administrator, that error should go away
With Bootstrap 4 .hidden-*
classes were completely removed (yes, they were replaced by hidden-*-*
but those classes are also gone from v4 alphas).
Starting with v4-beta, you can combine .d-*-none
and .d-*-block
classes to achieve the same result.
visible-* was removed as well; instead of using explicit .visible-*
classes, make the element visible by not hiding it (again, use combinations of .d-none .d-md-block). Here is the working example:
<div class="col d-none d-sm-block">
<span class="vcard">
…
</span>
</div>
<div class="col d-none d-xl-block">
<div class="d-none d-md-block">
…
</div>
<div class="d-none d-sm-block">
…
</div>
</div>
class="hidden-xs"
becomes class="d-none d-sm-block"
(or d-none d-sm-inline-block) ...
<span class="d-none d-sm-inline">hidden-xs</span>
<span class="d-none d-sm-inline-block">hidden-xs</span>
An example of Bootstrap 4 responsive utilities:
<div class="d-none d-sm-block"> hidden-xs
<div class="d-none d-md-block"> visible-md and up (hidden-sm and down)
<div class="d-none d-lg-block"> visible-lg and up (hidden-md and down)
<div class="d-none d-xl-block"> visible-xl </div>
</div>
</div>
</div>
<div class="d-sm-none"> eXtra Small <576px </div>
<div class="d-none d-sm-block d-md-none d-lg-none d-xl-none"> SMall =576px </div>
<div class="d-none d-md-block d-lg-none d-xl-none"> MeDium =768px </div>
<div class="d-none d-lg-block d-xl-none"> LarGe =992px </div>
<div class="d-none d-xl-block"> eXtra Large =1200px </div>
<div class="d-xl-none"> hidden-xl (visible-lg and down)
<div class="d-lg-none d-xl-none"> visible-md and down (hidden-lg and up)
<div class="d-md-none d-lg-none d-xl-none"> visible-sm and down (or hidden-md and up)
<div class="d-sm-none"> visible-xs </div>
</div>
</div>
</div>
You don't use the :
syntax - pull
always modifies the currently checked-out branch. Thus:
git pull origin my_remote_branch
while you have my_local_branch
checked out will do what you want.
Since you already have the tracking branch set, you don't even need to specify - you could just do...
git pull
while you have my_local_branch
checked out, and it will update from the tracked branch.
Using a simple link for an action such as removing a record looks dangerous to me : what if a crawler is trying to index your pages ? It will ignore any javascript and follow every link, probably not a good thing.
You'd better use a form with method="POST".
And then you will have an event "OnSubmit" to do exactly what you want...
<!DOCTYPE html>_x000D_
<html>_x000D_
<style>_x000D_
button {_x000D_
backround: #ccc;_x000D_
padding: 14px;_x000D_
width: 400px;_x000D_
font-size: 32px;_x000D_
}_x000D_
#demo {_x000D_
font-size: 20px;_x000D_
font-family: Arial;_x000D_
font-weight: bold;_x000D_
}_x000D_
</style>_x000D_
<body>_x000D_
_x000D_
<p>Click the button to decode.</p>_x000D_
_x000D_
<button onclick="entitycode()">Html Code</button>_x000D_
_x000D_
<p id="demo"></p>_x000D_
_x000D_
_x000D_
<script>_x000D_
function entitycode() {_x000D_
var uri = "quotation = ark __ ' = apostrophe __ & = ampersand __ < = less-than __ > = greater-than __ non- = reaking space __ ¡ = inverted exclamation mark __ ¢ = cent __ £ = pound __ ¤ = currency __ ¥ = yen __ ¦ = broken vertical bar __ § = section __ ¨ = spacing diaeresis __ © = copyright __ ª = feminine ordinal indicator __ « = angle quotation mark (left) __ ¬ = negation __ ­ = soft hyphen __ ® = registered trademark __ ¯ = spacing macron __ ° = degree __ ± = plus-or-minus __ ² = superscript 2 __ ³ = superscript 3 __ ´ = spacing acute __ µ = micro __ ¶ = paragraph __ · = middle dot __ ¸ = spacing cedilla __ ¹ = superscript 1 __ º = masculine ordinal indicator __ » = angle quotation mark (right) __ ¼ = fraction 1/4 __ ½ = fraction 1/2 __ ¾ = fraction 3/4 __ ¿ = inverted question mark __ × = multiplication __ ÷ = division __ À = capital a, grave accent __ Á = capital a, acute accent __ Â = capital a, circumflex accent __ Ã = capital a, tilde __ Ä = capital a, umlaut mark __ Å = capital a, ring __ Æ = capital ae __ Ç = capital c, cedilla __ È = capital e, grave accent __ É = capital e, acute accent __ Ê = capital e, circumflex accent __ Ë = capital e, umlaut mark __ Ì = capital i, grave accent __ Í = capital i, acute accent __ Î = capital i, circumflex accent __ Ï = capital i, umlaut mark __ Ð = capital eth, Icelandic __ Ñ = capital n, tilde __ Ò = capital o, grave accent __ Ó = capital o, acute accent __ Ô = capital o, circumflex accent __ Õ = capital o, tilde __ Ö = capital o, umlaut mark __ Ø = capital o, slash __ Ù = capital u, grave accent __ Ú = capital u, acute accent __ Û = capital u, circumflex accent __ Ü = capital u, umlaut mark __ Ý = capital y, acute accent __ Þ = capital THORN, Icelandic __ ß = small sharp s, German __ à = small a, grave accent __ á = small a, acute accent __ â = small a, circumflex accent __ ã = small a, tilde __ ä = small a, umlaut mark __ å = small a, ring __ æ = small ae __ ç = small c, cedilla __ è = small e, grave accent __ é = small e, acute accent __ ê = small e, circumflex accent __ ë = small e, umlaut mark __ ì = small i, grave accent __ í = small i, acute accent __ î = small i, circumflex accent __ ï = small i, umlaut mark __ ð = small eth, Icelandic __ ñ = small n, tilde __ ò = small o, grave accent __ ó = small o, acute accent __ ô = small o, circumflex accent __ õ = small o, tilde __ ö = small o, umlaut mark __ ø = small o, slash __ ù = small u, grave accent __ ú = small u, acute accent __ û = small u, circumflex accent __ ü = small u, umlaut mark __ ý = small y, acute accent __ þ = small thorn, Icelandic __ ÿ = small y, umlaut mark";_x000D_
var enc = encodeURI(uri);_x000D_
var dec = decodeURI(enc);_x000D_
var res = dec;_x000D_
document.getElementById("demo").innerHTML = res;_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Try This Simple and Effective
.home > span + .red{
border:1px solid red;
}
Simpler would be:
=TRIM(RIGHT(SUBSTITUTE(TRIM(A2)," ",REPT(" ",99)),99))
You can use A2
in place of TRIM(A2)
if you are sure that your data doesn't contain any unwanted spaces.
Based on concept explained by Rick Rothstein: http://www.excelfox.com/forum/showthread.php/333-Get-Field-from-Delimited-Text-String
Sorry for being necroposter!
By using regular expression: $string = preg_replace('/\s+By.*$/', '', $string)
idTABLE.parentElement.innerHTML = '<span>123 element</span> 456';
while this works, it's still recommended to use getElementById
: Do DOM tree elements with ids become global variables?
replaceChild
would work fine if you want to go to the trouble of building up your replacement, element by element, using document.createElement
and appendChild
, but I don't see the point.
Swift 5
var dict = ["key1":"Value1", "key2":"Value2"]
let k = dict.keys
var a: [String]()
a.append(contentsOf: k)
This works for me.
Subscribing to the IUS Community Project Repository
cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh
Run the script:
sudo bash setup-ius.sh
Upgrading mod_php with Apache
This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.
Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.
sudo yum remove php-cli mod_php php-common
Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.
sudo yum install mod_php70u php70u-cli php70u-mysqlnd
Finally, restart Apache to load the new version of mod_php:
sudo apachectl restart
You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:
systemctl status httpd
a solution i developed and much more stable than any other:
public class URLParamEncoder {
public static String encode(String input) {
StringBuilder resultStr = new StringBuilder();
for (char ch : input.toCharArray()) {
if (isUnsafe(ch)) {
resultStr.append('%');
resultStr.append(toHex(ch / 16));
resultStr.append(toHex(ch % 16));
} else {
resultStr.append(ch);
}
}
return resultStr.toString();
}
private static char toHex(int ch) {
return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10);
}
private static boolean isUnsafe(char ch) {
if (ch > 128 || ch < 0)
return true;
return " %$&+,/:;=?@<>#%".indexOf(ch) >= 0;
}
}
There's a lot of misunderstanding being displayed here. Unicode isn't an encoding, but the Unicode standard is devoted primarily to encoding anyway.
ISO 10646 is the international character set you (probably) care about. It defines a mapping between a set of named characters (e.g., "Latin Capital Letter A" or "Greek small letter alpha") and a set of code points (a number assigned to each -- for example, 61 hexadecimal and 3B1 hexadecimal for those two respectively; for Unicode code points, the standard notation would be U+0061 and U+03B1).
At one time, Unicode defined its own character set, more or less as a competitor to ISO 10646. That was a 16-bit character set, but it was not UTF-16; it was known as UCS-2. It included a rather controversial technique to try to keep the number of necessary characters to a minimum (Han Unification -- basically treating Chinese, Japanese and Korean characters that were quite a bit alike as being the same character).
Since then, the Unicode consortium has tacitly admitted that that wasn't going to work, and now concentrate primarily on ways to encode the ISO 10646 character set. The primary methods are UTF-8, UTF-16 and UCS-4 (aka UTF-32). Those (except for UTF-8) also have LE (little endian) and BE (big-endian) variants.
By itself, "Unicode" could refer to almost any of the above (though we can probably eliminate the others that it shows explicitly, such as UTF-8). Unqualified use of "Unicode" probably happens the most often on Windows, where it will almost certainly refer to UTF-16. Early versions of Windows NT adopted Unicode when UCS-2 was current. After UCS-2 was declared obsolete (around Win2k, if memory serves), they switched to UTF-16, which is the most similar to UCS-2 (in fact, it's identical for characters in the "basic multilingual plane", which covers a lot, including all the characters for most Western European languages).
You want to use TWO brackets, so if you are doing a VLOOKUP sort of action:
df = pd.merge(df,df2[['Key_Column','Target_Column']],on='Key_Column', how='left')
This will give you everything in the original df + add that one corresponding column in df2 that you want to join.
More info
To find a compiler, you'll have 1 per .net version installed, type in a command prompt.
dir c:\Windows\Microsoft.NET\vbc.exe /a/s
Windows Forms
For a Windows Forms version (no console window and we don't get around to actually creating any forms - though you can if you want).
Compile line in a command prompt.
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe "%userprofile%\desktop\VBS2Exe.vb"
Text for VBS2EXE.vb
Imports System.Windows.Forms
Partial Class MyForm : Inherits Form
Private Sub InitializeComponent()
End Sub
Public Sub New()
InitializeComponent()
End Sub
Public Shared Sub Main()
Dim sc as object
Dim Scrpt as string
sc = createObject("MSScriptControl.ScriptControl")
Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34)
With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
End With
sc.addcode(Scrpt)
End Sub
End Class
Using these optional parameters gives you an icon and manifest. A manifest allows you to specify run as normal, run elevated if admin, only run elevated.
/win32icon: Specifies a Win32 icon file (.ico) for the default Win32 resources.
/win32manifest: The provided file is embedded in the manifest section of the output PE.
In theory, I have UAC off so can't test, but put this text file on the desktop and call it vbs2exe.manifest, save as UTF-8.
The command line
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" "%userprofile%\desktop\VBS2Exe.vb"
The manifest
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0"
processorArchitecture="*" name="VBS2EXE" type="win32" />
<description>Script to Exe</description>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security> <requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator"
uiAccess="false" /> </requestedPrivileges>
</security> </trustInfo> </assembly>
Hopefully it will now ONLY run as admin.
Give Access To a Host's Objects
Here's an example giving the vbscript access to a .NET object.
Imports System.Windows.Forms
Partial Class MyForm : Inherits Form
Private Sub InitializeComponent()
End Sub
Public Sub New()
InitializeComponent()
End Sub
Public Shared Sub Main()
Dim sc as object
Dim Scrpt as string
sc = createObject("MSScriptControl.ScriptControl")
Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34) & ":msgbox meScript.state"
With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
.addobject("meScript", SC, true)
End With
sc.addcode(Scrpt)
End Sub
End Class
To Embed version info
Download vbs2exe.res file from https://skydrive.live.com/redir?resid=E2F0CE17A268A4FA!121 and put on desktop.
Download ResHacker from http://www.angusj.com/resourcehacker
Open vbs2exe.res file in ResHacker. Edit away. Click Compile button. Click File menu - Save.
Type
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" /win32resource:"%userprofile%\desktop\VBS2Exe.res" "%userprofile%\desktop\VBS2Exe.vb"
If you’re using python 3+ this may also occur if you’re using private variables that start with double underscore, e.g., self.__yourvariable. Just something to take note of for some of you who may run into this issue.
You can use the onejar-maven-plugin for packaging. Basically, it assembles your project and its dependencies in as one jar, including not just your project jar file, but also all external dependencies as a "jar of jars", e.g.
<build>
<plugins>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<version>1.4.4</version>
<executions>
<execution>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Note 1: Configuration options is available at the project home page.
Note 2: For one reason or the other, the onejar-maven-plugin project is not published at Maven Central. However jolira.com tracks the original project and publishes it to with the groupId com.jolira
.
One way that I've found really useful in situations like this is to go old-school and use the Jet OLEDB provider, together with a schema.ini file to read large tab-delimited files in using ADO.Net. Obviously, this method is really only useful if you know the format of the file to be imported.
public void ImportCsvFile(string filename)
{
FileInfo file = new FileInfo(filename);
using (OleDbConnection con =
new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
file.DirectoryName + "\";
Extended Properties='text;HDR=Yes;FMT=TabDelimited';"))
{
using (OleDbCommand cmd = new OleDbCommand(string.Format
("SELECT * FROM [{0}]", file.Name), con))
{
con.Open();
// Using a DataReader to process the data
using (OleDbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// Process the current reader entry...
}
}
// Using a DataTable to process the data
using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
{
DataTable tbl = new DataTable("MyTable");
adp.Fill(tbl);
foreach (DataRow row in tbl.Rows)
{
// Process the current row...
}
}
}
}
}
Once you have the data in a nice format like a datatable, filtering out the data you need becomes pretty trivial.
In C and C++ you have these least requirements (i.e actual implementations can have larger magnitudes)
signed char: -2^07+1 to +2^07-1
short: -2^15+1 to +2^15-1
int: -2^15+1 to +2^15-1
long: -2^31+1 to +2^31-1
long long: -2^63+1 to +2^63-1
Now, on particular implementations, you have a variety of bit ranges. The wikipedia article describes this nicely.
All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.
If you have accidentally removed DLL file from php/ext
folder, just add it back (get the copy from XAMPP zip archive - its downloadable).
If you have deleted the accompanying INI configuration line from php.ini
file, add it back as well:
extension=php_mbstring.dll
Also, ensure to restart your webserver (Apache) using XAMPP control panel.
Additional Info on Enabling PHP Extensions
/XAMPP/php/ext
directory)extension_dir = "ext"
)This a simpler method , and it will return the date in simple yyyy-mm-dd format , Here it is
function incDay(date, n) {
var fudate = new Date(new Date(date).setDate(new Date(date).getDate() + n));
fudate = fudate.getFullYear() + '-' + (fudate.getMonth() + 1) + '-' + fudate.toDateString().substring(8, 10);
return fudate;
}
example :
var tomorrow = incDay(new Date(), 1); // the next day of today , aka tomorrow :) .
var spicaldate = incDay("2020-11-12", 1); // return "2020-11-13" .
var somedate = incDay("2020-10-28", 5); // return "2020-11-02" .
Note
incDay(new Date("2020-11-12"), 1);
incDay("2020-11-12", 1);
will return the same result .
If you want to copy from searchContent to content, then code should be as follows
BeanUtils.copyProperties(content, searchContent);
You need to reverse the parameters as above in your code.
From API,
public static void copyProperties(Object dest, Object orig)
throws IllegalAccessException,
InvocationTargetException)
Parameters:
dest - Destination bean whose properties are modified
orig - Origin bean whose properties are retrieved
Revisit all your queries, maybe you have some query that select without ROWLOCK/FOR UPDATE hint from the same table you have SELECT FOR UPDATE.
MSSQL often escalates those row locks to page-level locks (even table-level locks, if you don't have index on field you are querying), see this explanation. Since you ask for FOR UPDATE, i could assume that you need transacion-level(e.g. financial, inventory, etc) robustness. So the advice on that site is not applicable to your problem. It's just an insight why MSSQL escalates locks.
If you are already using MSSQL 2005(and up), they are MVCC-based, i think you should have no problem with row-level lock using ROWLOCK/UPDLOCK hint. But if you are already using MSSQL 2005 and up, try to check some of your queries which query the same table you want to FOR UPDATE if they escalate locks by checking the fields on their WHERE clause if they have index.
P.S.
I'm using PostgreSQL, it also uses MVCC have FOR UPDATE, i don't encounter same problem. Lock escalations is what MVCC solves, so i would be surprised if MSSQL 2005 still escalate locks on table with WHERE clauses that doesn't have index on its fields. If that(lock escalation) is still the case for MSSQL 2005, try to check the fields on WHERE clauses if they have index.
Disclaimer: my last use of MSSQL is version 2000 only.
Your code is in the <head>
=> runs before the elements are rendered, so document.getElementById('compute');
returns null, as MDN promise...
element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.
Solutions:
What is the jQuery ready
event and why is it needed?
(why no just JavaScript's load event):
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...
ready
docs
Instead of using -c, just pipe it to wc -l.
grep string * | wc -l
This will list each occurrence on a single line and then count the number of lines.
This will miss instances where the string occurs 2+ times on one line, though.
Just use break, like that:
int cont = 0;
foreach (ListViewItem lvi in listView.Items) {
if(cont==50) { //if listViewItem reach 50 break out.
break;
}
cont++; //increment cont.
}
This was so hard for me to have on item click listener in the activity and also to have click listener for single view of the item that will not trigger on item click listener. After playing around with Jacob Tabak's answer I respect his answer for on item click if no other touch actions inside item are presented.
I have a custom OnClickListener
interface that have on item click event which holds the clicked item's view and the item position from the adapter. I present an instance of it in the constructor(or it can be with setter) and attach it to the view holder container click listener.
I also have other click listener in the Adapter(Can be in the view holder) which will handle current View click from the container.
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyViewHolder> {
private ArrayList<String> mData;
private OnItemClickListener mOnItemClickListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
public MyRecyclerAdapter(ArrayList<String> itemsData,
OnItemClickListener onItemClickListener) {
mOnItemClickListener = onItemClickListener;
this.mData = itemsData;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View layoutView = LayoutInflater.from(mContext).inflate(
R.layout.list_item, parent, false);
final MyViewHolder viewHolder = new MyViewHolder(layoutView);
viewHolder.container.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mOnItemClickListener.onItemClick(v, viewHolder.getAdapterPosition());
}
});
viewH?lder.button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//do button click work here with
// mData.get( viewHolder.getAdapterPosition() );
}
});
return viewHolder;
}
@Override
public int getItemCount() {
return mData.size();
}}
In the activity you need to initialize the adapter by passing instance of the OnItemClickListener
public class FeedActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
.....
MyRecyclerAdapter adapter = new MyRecyclerAdapter(new ArrayList<String>(), new OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
///list item was clicked
}
});
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mFeedsAdapter);
}
And my ViewHolder
public class MyViewHolder extends RecyclerView.ViewHolder {
public Button button;
public View container;
public MyViewHolder(View itemLayoutView) {
super(itemLayoutView);
container = itemLayoutView;
button = (Button) itemLayoutView.findViewById(R.id.button);
}}
So I was having this problem too and I have written this function:
/***Working function for ajax loading Start*****************/_x000D_
function fuweco_loadMoreContent(elmId/*element ID without #*/,ajaxLink/*php file path*/,postParameterObject/*post parameters list as JS object with properties (new Object())*/,tillElementEnd/*point of scroll when must be started loading from AJAX*/){_x000D_
var _x000D_
contener = $("#"+elmId),_x000D_
contenerJS = document.getElementById(elmId);_x000D_
if(contener.length !== 0){_x000D_
var _x000D_
elmFullHeight = _x000D_
contener.height()+_x000D_
parseInt(contener.css("padding-top").slice(0,-2))+_x000D_
parseInt(contener.css("padding-bottom").slice(0,-2)),_x000D_
SC_scrollTop = contenerJS.scrollTop,_x000D_
SC_max_scrollHeight = contenerJS.scrollHeight-elmFullHeight;_x000D_
if(SC_scrollTop >= SC_max_scrollHeight - tillElementEnd){_x000D_
$("#"+elmId).unbind("scroll");_x000D_
$.post(ajaxLink,postParameterObject)_x000D_
.done(function(data){_x000D_
if(data.length != 0){_x000D_
$("#"+elmId).append(data);_x000D_
$("#"+elmId).scroll(function (){_x000D_
fuweco_reloaderMore(elmId,ajaxLink,postParameterObject);_x000D_
});_x000D_
}_x000D_
});_x000D_
}_x000D_
}_x000D_
}_x000D_
/***Working function for ajax loading End*******************/_x000D_
/***Sample function Start***********************************/_x000D_
function reloaderMore(elementId) {_x000D_
var_x000D_
contener = $("#"+elementId),_x000D_
contenerJS = document.getElementById(elementId)_x000D_
;_x000D_
_x000D_
if(contener.length !== 0){_x000D_
var_x000D_
elmFullHeight = contener.height()+(parseInt(contener.css("padding-top").slice(0,-2))+parseInt(contener.css("padding-bottom").slice(0,-2))),_x000D_
SC_scrollTop = contenerJS.scrollTop,_x000D_
SC_max_scrollHeight = contenerJS.scrollHeight-elmFullHeight_x000D_
;_x000D_
if(SC_scrollTop >= SC_max_scrollHeight - 200){_x000D_
$("#"+elementId).unbind("scroll");_x000D_
$("#"+elementId).append('<div id="elm1" style="margin-bottom:15px;"><h1>Was loaded</h1><p>Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content.</p></div>');_x000D_
$("#"+elementId).delay(300).scroll(function (){reloaderMore(elementId);});_x000D_
}_x000D_
}_x000D_
}_x000D_
/***Sample function End*************************************/_x000D_
/***Sample function Use Start*******************************/_x000D_
$(document).ready(function(){_x000D_
$("#t1").scrollTop(0).scroll(function (){_x000D_
reloaderMore("t1");_x000D_
});_x000D_
});_x000D_
/***Sample function Use End*********************************/
_x000D_
.reloader {_x000D_
border: solid 1px red;_x000D_
overflow: auto;_x000D_
overflow-x: hidden;_x000D_
min-height: 400px;_x000D_
max-height: 400px;_x000D_
min-width: 400px;_x000D_
max-width: 400px;_x000D_
height: 400px;_x000D_
width: 400px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<div class="reloader" id="t1">_x000D_
<div id="elm1" style="margin-bottom:15px;">_x000D_
<h1>Some text for header.</h1>_x000D_
<p>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
</p>_x000D_
</div>_x000D_
<div id="elm2" style="margin-bottom:15px;">_x000D_
<h1>Some text for header.</h1>_x000D_
<p>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
</p>_x000D_
</div>_x000D_
<div id="elm3" style="margin-bottom:15px;">_x000D_
<h1>Some text for header.</h1>_x000D_
<p>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
</p>_x000D_
</div> _x000D_
</div>
_x000D_
I hope it will be helpfully for other programmers.
With Swift 3, you can choose one of the following ways to solve your problem.
sorted(by:?)
with a Movie
class that does not conform to Comparable
protocolIf your Movie
class does not conform to Comparable
protocol, you must specify in your closure the property on which you wish to use Array's sorted(by:?)
method.
Movie
class declaration:
import Foundation
class Movie: CustomStringConvertible {
let name: String
var date: Date
var description: String { return name }
init(name: String, date: Date = Date()) {
self.name = name
self.date = date
}
}
Usage:
let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")
let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted(by: { $0.name < $1.name })
// let sortedMovies = movies.sorted { $0.name < $1.name } // also works
print(sortedMovies)
/*
prints: [Avatar, Piranha II: The Spawning, Titanic]
*/
sorted(by:?)
with a Movie
class that conforms to Comparable
protocolHowever, by making your Movie
class conform to Comparable
protocol, you can have a much concise code when you want to use Array's sorted(by:?)
method.
Movie
class declaration:
import Foundation
class Movie: CustomStringConvertible, Comparable {
let name: String
var date: Date
var description: String { return name }
init(name: String, date: Date = Date()) {
self.name = name
self.date = date
}
static func ==(lhs: Movie, rhs: Movie) -> Bool {
return lhs.name == rhs.name
}
static func <(lhs: Movie, rhs: Movie) -> Bool {
return lhs.name < rhs.name
}
}
Usage:
let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")
let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted(by: { $0 < $1 })
// let sortedMovies = movies.sorted { $0 < $1 } // also works
// let sortedMovies = movies.sorted(by: <) // also works
print(sortedMovies)
/*
prints: [Avatar, Piranha II: The Spawning, Titanic]
*/
sorted()
with a Movie
class that conforms to Comparable
protocolBy making your Movie
class conform to Comparable
protocol, you can use Array's sorted()
method as an alternative to sorted(by:?)
.
Movie
class declaration:
import Foundation
class Movie: CustomStringConvertible, Comparable {
let name: String
var date: Date
var description: String { return name }
init(name: String, date: Date = Date()) {
self.name = name
self.date = date
}
static func ==(lhs: Movie, rhs: Movie) -> Bool {
return lhs.name == rhs.name
}
static func <(lhs: Movie, rhs: Movie) -> Bool {
return lhs.name < rhs.name
}
}
Usage:
let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")
let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted()
print(sortedMovies)
/*
prints: [Avatar, Piranha II: The Spawning, Titanic]
*/
More a comment than an answer - but I cannot add comments yet: Thanks for your help, the count was the easy part. Just for others that might come here. I hope that it will save you some time.
It took me a while to get the attributes from the rows and to understand how to access them from the data() Object (that the data() is an Array and the Attributes can be read by adding them with a dot and not with brackets:
$('#button').click( function () {
for (var i = 0; i < table.rows('.selected').data().length; i++) {
console.log( table.rows('.selected').data()[i].attributeNameFromYourself);
}
} );
(by the way: I get the data for my table using AJAX and JSON)
You can loop through variable with list of directories:
- name: Copy files from several directories
copy:
src: "{{ item }}"
dest: "/etc/fooapp/"
owner: root
mode: "0600"
loop: "{{ files }}"
vars:
files:
- "dir1/"
- "dir2/"
To add interceptor to a spring boot application, do the following
Create an interceptor class
public class MyCustomInterceptor implements HandlerInterceptor{
//unimplemented methods comes here. Define the following method so that it
//will handle the request before it is passed to the controller.
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response){
//your custom logic here.
return true;
}
}
Define a configuration class
@Configuration
public class MyConfig extends WebMvcConfigurerAdapter{
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(new MyCustomInterceptor()).addPathPatterns("/**");
}
}
Thats it. Now all your requests will pass through the logic defined under preHandle() method of MyCustomInterceptor.
I had the same issue when trying to use php composer install
in a local directory on my Apache server for a laravel project I cloned from Github. My problem was I had already setup composer
globally on my Ubuntu 18 machine.
Adding sudo
instead of php
started the install of a whole slew of packages listed in the json.lock
file i.e. sudo composer install
.
It's been a while when the question has been asked and C# changed not much but became a bit better. Take a look Nullable reference types (C# reference)
string notNull = "Hello";
string? nullable = default;
notNull = nullable!; // null forgiveness
C# as a language a "bit" outdated from modern languages and became misleading.
for instance in typescript
, swift
there's a "?" to clearly say it's a nullable type, be careful. It's pretty clear and it's awesome. C# doesn't/didn't have this ability, as a result, a simple contract IPerson very misleading. As per C# FirstName and LastName could be null but is it true? is per business logic FirstName/LastName really could be null? the answer is we don't know because C# doesn't have the ability to say it directly.
interface IPerson
{
public string FirstName;
public string LastName;
}
For the GUI itself:
PyQT is pretty much the reference.
Another way to develop a rapid user interface is to write a web app, have it run locally and display the app in the browser.
Plus, if you go for the Tkinter option suggested by lubos hasko you may want to try portablepy to have your app run on Windows environment without Python.
You can set the hours, minutes, seconds and microseconds to whatever you like
datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
but trutheality's answer is probably best when they are all to be zero and you can just compare the .date()
s of the times
Maybe it is faster though if you have to compare hundreds of datetimes because you only need to do the replace()
once vs hundreds of calls to date()
I encountered this error while trying to convert Tiff images to Jpeg. For me the issue stemmed from the tiff dimensions being too large. Anything up to around 62000 pixels was fine, anything above this size produced the error.
If you're using Python 2.5, this won't work, but for people using 2.6 or 2.7, try
from __future__ import print_function
print("abcd", end='')
print("efg")
results in
abcdefg
For those using 3.x, this is already built-in.
There is an interesting discussion here: http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/307d658a-f677-40f2-bdef-e6352b0bfe9e/ My understanding of this thread is that freeing small allocations are not reflected in Private Bytes or Working Set.
Long story short:
if I call
p=malloc(1000);
free(p);
then the Private Bytes reflect only the allocation, not the deallocation.
if I call
p=malloc(>512k);
free(p);
then the Private Bytes correctly reflect the allocation and the deallocation.
Assuming you're currently on the branch you want to rename:
git branch -m newname
This is documented in the manual for git-branch
, which you can view using
man git-branch
or
git help branch
Specifically, the command is
git branch (-m | -M) [<oldbranch>] <newbranch>
where the parameters are:
<oldbranch>
The name of an existing branch to rename.
<newbranch>
The new name for an existing branch. The same restrictions as for <branchname> apply.
<oldbranch>
is optional, if you want to rename the current branch.
You can also try this simple one-liner code. Just call the alert method on onclick attribute.
<button id="some_id1" onclick="alert(this.id)"></button>
There's a good open source version called Obfuscar. Seems to work fine. Types, properties, fields, methods can be excluded. The original is here: https://code.google.com/p/obfuscar/, but since it seems to not be updated anymore
You can also just open synaptic and search for libgtk, it will show you exactly which lib is installed.
Adding my own experience :
r = requests.get(download_url)
when I tried to download a file specified in the url.
The error was
HTTPSConnectionPool(host, port=443): Max retries exceeded with url (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))
I corrected it by adding verify = False
in the function as follows :
r = requests.get(download_url + filename)
open(filename, 'wb').write(r.content)
r = requests.get('https://api.github.com', auth=('user', 'pass'))
r
is a response. It has a request attribute which has the information you need.
r.request.allow_redirects r.request.headers r.request.register_hook
r.request.auth r.request.hooks r.request.response
r.request.cert r.request.method r.request.send
r.request.config r.request.params r.request.sent
r.request.cookies r.request.path_url r.request.session
r.request.data r.request.prefetch r.request.timeout
r.request.deregister_hook r.request.proxies r.request.url
r.request.files r.request.redirect r.request.verify
r.request.headers
gives the headers:
{'Accept': '*/*',
'Accept-Encoding': 'identity, deflate, compress, gzip',
'Authorization': u'Basic dXNlcjpwYXNz',
'User-Agent': 'python-requests/0.12.1'}
Then r.request.data
has the body as a mapping. You can convert this with urllib.urlencode
if they prefer:
import urllib
b = r.request.data
encoded_body = urllib.urlencode(b)
depending on the type of the response the .data
-attribute may be missing and a .body
-attribute be there instead.
Hi here is how i did it in one Project :
@Html.DropDownListFor(model => model.MyOption,
new List<SelectListItem> {
new SelectListItem { Value = "0" , Text = "Option A" },
new SelectListItem { Value = "1" , Text = "Option B" },
new SelectListItem { Value = "2" , Text = "Option C" }
},
new { @class="myselect"})
I hope it helps Somebody. Thanks
open
is a new access level in Swift 3, introduced with the implementation
of
It is available with the Swift 3 snapshot from August 7, 2016, and with Xcode 8 beta 6.
In short:
open
class is accessible and subclassable outside of the
defining module. An open
class member is accessible and
overridable outside of the defining module.public
class is accessible but not subclassable outside of the
defining module. A public
class member is accessible but
not overridable outside of the defining module.So open
is what public
used to be in previous
Swift releases and the access of public
has been restricted.
Or, as Chris Lattner puts it in
SE-0177: Allow distinguishing between public access and public overridability:
“open” is now simply “more public than public”, providing a very simple and clean model.
In your example, open var hashValue
is a property which is accessible and can be overridden in NSObject
subclasses.
For more examples and details, have a look at SE-0117.
Remove the method, I suspect you might also need to remove it from your Form.Designer
.
Otherwise: Application.Exit();
Should work.
That's why the designer is bad for you. :)
For me, "BackgroundQuery:=False" did not work alone But adding a "DoEvents" resolved problem
.QueryTable.Refresh BackgroundQuery:=False
VBA.Interaction.DoEvents
You can't. You need to create another php script to return the image data, e.g. getImage.php. Change catalog.php to:
<body>
<img src="getImage.php?id=1" width="175" height="200" />
</body>
Then getImage.php is
<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$link = mysql_connect("localhost", "root", "");
mysql_select_db("dvddb");
$sql = "SELECT dvdimage FROM dvd WHERE id=$id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['dvdimage'];
?>
Use a list comprehension like this:
main_list = [item for item in list_2 if item not in list_1]
Output:
>>> list_1 = ["a", "b", "c", "d", "e"]
>>> list_2 = ["a", "f", "c", "m"]
>>>
>>> main_list = [item for item in list_2 if item not in list_1]
>>> main_list
['f', 'm']
Edit:
Like mentioned in the comments below, with large lists, the above is not the ideal solution. When that's the case, a better option would be converting list_1
to a set
first:
set_1 = set(list_1) # this reduces the lookup time from O(n) to O(1)
main_list = [item for item in list_2 if item not in set_1]
The claims that you have to mock it at the top of your file are false.
Mock a named ES Import:
// import the named module
import { useWalkthroughAnimations } from '../hooks/useWalkthroughAnimations';
// mock the file and its named export
jest.mock('../hooks/useWalkthroughAnimations', () => ({
useWalkthroughAnimations: jest.fn()
}));
// do whatever you need to do with your mocked function
useWalkthroughAnimations.mockReturnValue({ pageStyles, goToNextPage, page });
I encountered the same problem with:
Spring Boot version = 1.5.10
Spring Security version = 4.2.4
The problem occurred on the endpoints, where the ModelAndView
viewName was defined with a preceding forward slash. Example:
ModelAndView mav = new ModelAndView("/your-view-here");
If I removed the slash it worked fine. Example:
ModelAndView mav = new ModelAndView("your-view-here");
I also did some tests with RedirectView and it seemed to work with a preceding forward slash.
All answers are great. Here is an example use case for multiple add address: The ability to add as many email you want on demand with a web form:
See it in action with jsfiddle here (except the php processor)
### Send unlimited email with a web form
# Form for continuously adding e-mails:
<button type="button" onclick="emailNext();">Click to Add Another Email.</button>
<div id="addEmail"></div>
<button type="submit">Send All Emails</button>
# Script function:
<script>
function emailNext() {
var nextEmail, inside_where;
nextEmail = document.createElement('input');
nextEmail.type = 'text';
nextEmail.name = 'emails[]';
nextEmail.className = 'class_for_styling';
nextEmail.style.display = 'block';
nextEmail.placeholder = 'Enter E-mail Here';
inside_where = document.getElementById('addEmail');
inside_where.appendChild(nextEmail);
return false;
}
</script>
# PHP Data Processor:
<?php
// ...
// Add the rest of your $mailer here...
if ($_POST[emails]){
foreach ($_POST[emails] AS $postEmail){
if ($postEmail){$mailer->AddAddress($postEmail);}
}
}
?>
So what it does basically is to generate a new input text box on every click with the name "emails[]".
The [] added at the end makes it an array when posted.
Then we go through each element of the array with "foreach" on PHP side adding the:
$mailer->AddAddress($postEmail);
This should be OK, but is Internet Explorer specific:
<td title="lineone
linetwo
etc...">
As others have mentioned, the only other way is to use an HTML + JavaScript based tooltip if you're only interested in the tooltip. If this is for accessibility then you will probably need to stick to just single lines for consistency.
I use double quotes in general, but not for any specific reason - Probably just out of habit from Java.
I guess you're also more likely to want apostrophes in an inline literal string than you are to want double quotes.
<form class="col-xs-12" method="post" action="/News/AddNews" enctype="multipart/form-data">
<div class="form-group">
<input type="file" class="form-control" name="image" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary col-xs-12">Add</button>
</div>
</form>
My Action Is
[HttpPost]
public IActionResult AddNews(IFormFile image)
{
Tbl_News tbl_News = new Tbl_News();
if (image!=null)
{
//Set Key Name
string ImageName= Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);
//Get url To Save
string SavePath = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot/img",ImageName);
using(var stream=new FileStream(SavePath, FileMode.Create))
{
image.CopyTo(stream);
}
}
return View();
}
Go to Tools-->Firebase in your Android Studio and click on Connect your app to Firebase. They will set it up for you.
Be aware that need to change both location:
File > Settings... > Editor > Code Style > "Hard Wrap at"
and
File > Settings... > Editor > Code Style > (your language) > Wrapping and Braces > Hard wrap at
No need to find
. If you are just looking for a pattern within a specific directory, this should suffice:
grep -hn FOO /your/path/*.bar
Where -h
is the parameter to hide the filename, as from man grep
:
-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search.
Note that you were using
-H, --with-filename
Print the file name for each match. This is the default when there is more than one file to search.
Java 1.5 introduced the Scanner class for handling input from file and streams.
It is used for getting integers from a file and would look something like this:
List<Integer> integers = new ArrayList<Integer>();
Scanner fileScanner = new Scanner(new File("c:\\file.txt"));
while (fileScanner.hasNextInt()){
integers.add(fileScanner.nextInt());
}
Check the API though. There are many more options for dealing with different types of input sources, differing delimiters, and differing data types.
For me works using &autoplay=1&mute=1
/tmp/myfile
first line text
wanted text
other text
the command
$ grep -n "wanted text" /tmp/myfile | awk -F ":" '{print $1}'
2
Detect key press, including key combinations:
window.addEventListener('keydown', function (e) {
if (e.ctrlKey && e.keyCode == 90) {
// Ctrl + z pressed
}
});
Benefit here is that you are not overwriting any global properties, but instead merely introducing a side effect. Not good, but definitely a whole lot less nefarious than other suggestions on here.
On Windows add following lines to _vimrc
" store backup, undo, and swap files in temp directory
set directory=$HOME/temp//
set backupdir=$HOME/temp//
set undodir=$HOME/temp//
I use this single liner method which does the work for me-
using System.ComponentModel.DataAnnotations;
public bool IsValidEmail(string source)
{
return new EmailAddressAttribute().IsValid(source);
}
Per the comments, this will "fail" if the source
(the email address) is null.
public static bool IsValidEmailAddress(this string address) => address != null && new EmailAddressAttribute().IsValid(address);
Here is updated working version for me which will get City/Town, It looks like some fields are modified in the json response. Referring previous answers for this questions. ( Thanks to Michal & one more reference : Link
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
// Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng);
}
function errorFunction() {
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({latLng: latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var arrAddress = results;
console.log(results);
$.each(arrAddress, function(i, address_component) {
if (address_component.types[0] == "locality") {
console.log("City: " + address_component.address_components[0].long_name);
itemLocality = address_component.address_components[0].long_name;
}
});
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
JavaScript has the Array.prototype.some()
method:
[1, 2, 3].some((num) => num % 2 === 0);
returns true
because there's (at least) one even number in the array.
In general, the Array
class in JavaScript's standard library is quite poor compared to Ruby's Enumerable. There's no isEmpty
method and .some()
requires that you pass in a function or you'll get an undefined is not a function
error. You can define your own .isEmpty()
as well as a .any()
that is closer to Ruby's like this:
Array.prototype.isEmpty = function() {
return this.length === 0;
}
Array.prototype.any = function(func) {
return this.some(func || function(x) { return x });
}
Libraries like underscore.js and lodash provide helper methods like these, if you're used to Ruby's collection methods, it might make sense to include them in your project.
Change it to this:
switch (enumExample) {
case VALUE_A: {
//..
break;
}
}
The clue is in the error. You don't need to qualify case
labels with the enum type, just its value.
Since there is no accepted answer I will try to answer this one:
[s] - seconds
Replace a string :
$str = str_replace("\n", '', $str);
u using also like, (%n, %t, All Special characters, numbers, char,. etc)
which means any thing u can replace in a string.
To validate phone numbers for a specific region in Android, use libPhoneNumber from Google, and the following code as an example:
public boolean isPhoneNumberValid(String phoneNumber, String countryCode)
{
//NOTE: This should probably be a member variable.
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try
{
PhoneNumber numberProto = phoneUtil.parse(phoneNumber, countryCode);
return phoneUtil.isValidNumber(numberProto);
}
catch (NumberParseException e)
{
System.err.println("NumberParseException was thrown: " + e.toString());
}
return false;
}
I assume you use Graphics.CopyFromScreen
to get the screenshot.
You can use P/Invoke to GetForegroundWindow (and then get its position and size) to determine which region you need to copy from.
I do like TRAC - this plugin might be helpful for your task: http://trac-hacks.org/wiki/RepoSearchPlugin
The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:
function getMachine(color, qty) {
var returnValue = null;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
returnValue = thisArray[3];
return false; // this breaks out of the each
}
});
return returnValue;
}
var retval = getMachine(color, qty);
NOTE: Community Edition doesn't support JEE.
First, you will need to install a local Tomcat server. It sounds like you may have already done this.
Next, on the toolbar at the top of IntelliJ, click the down arrow just to the left of the Run and Debug icons. There will be an option to Edit Configurations. In the resulting popup, click the Add icon, then click Tomcat and Local.
From that dialog, you will need to click the Configure... button next to Application Server to tell IntelliJ where Tomcat is installed.
Was able to fix the issue by updating NVIDIA device drivers to the latest (v446.14). NVIDIA drivers download link here.
code for a simple copy.
cp -r ./SourceFolder ./DestFolder
code for a copy with success result
cp -rv ./SourceFolder ./DestFolder
code for Forcefully if source contains any readonly file it will also copy
cp -rf ./SourceFolder ./DestFolder
for details help
cp --help
parentElement.prepend(newFirstChild);
This is a new addition in (likely) ES7. It is now vanilla JS, probably due to the popularity in jQuery. It is currently available in Chrome, FF, and Opera. Transpilers should be able to handle it until it becomes available everywhere.
P.S. You can directly prepend strings
parentElement.prepend('This text!');
Links: developer.mozilla.org - Polyfill
It doesn't look like there's any built-in way to do it in insert mode, which was the question. Some of the other answers are correct for normal mode, as well as pointing out that a custom mapping could be created to add the functionality in insert mode.
Honestly, you should probably do most of your deleting in normal mode. ^W is neat to know about but I'm not sure I can think of a situation where I'd rather do it than esc to go into normal mode and have the more powerful deletion commands at my disposal.
Vim is very different from a number of other editors (including TextMate) in this way. If you're using it productively, you'll probably find that you don't spend very much time in insert mode.
Use numpy.dot
or a.dot(b)
. See the documentation here.
>>> a = np.array([[ 5, 1 ,3],
[ 1, 1 ,1],
[ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])
This occurs because numpy arrays are not matrices, and the standard operations *, +, -, /
work element-wise on arrays. Instead, you could try using numpy.matrix
, and *
will be treated like matrix multiplication.
Also know there are other options:
As noted below, if using python3.5+ the @
operator works as you'd expect:
>>> print(a @ b)
array([16, 6, 8])
If you want overkill, you can use numpy.einsum
. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.
>>> np.einsum('ji,i->j', a, b)
array([16, 6, 8])
As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul
, which works like numpy.dot
with two major exceptions: no scalar multiplication but it works with stacks of matrices.
>>> np.matmul(a, b)
array([16, 6, 8])
numpy.inner
functions the same way as numpy.dot
for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).
>>> np.inner(a, b)
array([16, 6, 8])
# Beware using for matrix-matrix multiplication though!
>>> b = a.T
>>> np.dot(a, b)
array([[35, 9, 10],
[ 9, 3, 4],
[10, 4, 6]])
>>> np.inner(a, b)
array([[29, 12, 19],
[ 7, 4, 5],
[ 8, 5, 6]])
If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot
with the optional argument axes=1
:
>>> np.tensordot(a, b, axes=1)
array([16, 6, 8])
Don't use numpy.vdot
if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m
vs n
).
public static String[] textSort(String[] words) {
for (int i = 0; i < words.length; i++) {
for (int j = i + 1; j < words.length; j++) {
if (words[i].compareTo(words[j]) > 0) {
String temp = words[i];
words[i] = words[j];
words[j] = temp;
}
}
}
return words;
}
UPDATE: I now have a complete turnkey, all-in-one answer, see https://stackoverflow.com/a/49019950/300224. Only took 3 years to figure out!
According to the Travis documentation: https://github.com/travis-ci/travis-ci there is a concoction of projects that collude to deliver the Travis CI web service we know and love. The following subset of projects appears to allow local make test
functionality using the .travis.yml
in your project:
travis-build creates the build
script for each job. It takes the configuration from the .travis.yml
file and
creates a bash
script that is then run in the build environment by
travis-worker.
travis-cookbooks holds the Chef cookbooks that are used to provision the build environments.
travis-worker is responsible for running the build scripts in a clean environment. It streams the log output to travis-logs and pushes state updates (build starting/finishing) to travis-hub.
(The other subprojects are responsible for communicating with GitHub, their web interface, email, and their API.)
Meteor's strength is in it's real-time updates feature which works well for some of the social applications you see nowadays where you see everyone's updates for what you're working on. These updates center around replicating subsets of a MongoDB collection underneath the covers as local mini-mongo (their client side MongoDB subset) database updates on your web browser (which causes multiple render events to be fired on your templates). The latter part about multiple render updates is also the weakness. If you want your UI to control when the UI refreshes (e.g., classic jQuery AJAX pages where you load up the HTML and you control all the AJAX calls and UI updates), you'll be fighting this mechanism.
Meteor uses a nice stack of Node.js plugins (Handlebars.js, Spark.js, Bootstrap css, etc. but using it's own packaging mechanism instead of npm) underneath along w/ MongoDB for the storage layer that you don't have to think about. But sometimes you end up fighting it as well...e.g., if you want to customize the Bootstrap theme, it messes up the loading sequence of Bootstrap's responsive.css file so it no longer is responsive (but this will probably fix itself when Bootstrap 3.0 is released soon).
So like all "full stack frameworks", things work great as long as your app fits what's intended. Once you go beyond that scope and push the edge boundaries, you might end up fighting the framework...
The main difference is that the connection can be made via Unix Domain Socket, as stated here: localhost vs. 127.0.0.1
Name both your submit buttons the same
<input name="submit" type="submit" id="submit" value="Save" />
<input name="submit" type="submit" id="process" value="Process" />
Then in your controller get the value of submit. Only the button clicked will pass its value.
public ActionResult Index(string submit)
{
Response.Write(submit);
return View();
}
You can of course assess that value to perform different operations with a switch block.
public ActionResult Index(string submit)
{
switch (submit)
{
case "Save":
// Do something
break;
case "Process":
// Do something
break;
default:
throw new Exception();
break;
}
return View();
}
Note that HasValue
will return true for an empty Guid
.
bool validGuid = SomeProperty.HasValue && SomeProperty != Guid.Empty;
You can alternatively use NamedParameterJdbcTemplate
(naming can be useful when you have many parameters)
Map<String, Object> params = new HashMap<>();
params.put("var1",value1);
params.put("var2",value2);
namedJdbcTemplate.update(
"INSERT INTO schema.tableName (column1, column2) VALUES (:var1, :var2)",
params
);
So simple just use abs((a) - (b)).
will work seamless without any additional care in signs(positive , negative)
def get_distance(p1,p2):
return abs((p1) - (p2))
get_distance(0,2)
2
get_distance(0,2)
2
get_distance(-2,0)
2
get_distance(2,-1)
3
get_distance(-2,-1)
1
async() => {
let body = await model.find().or([
{ name: 'something'},
{ nickname: 'somethang'}
]).exec();
console.log(body);
}
/* Gives an array of the searched query!
returns [] if not found */
This issue should now be fixed. Update rubygems (gem update --system
), make sure openssl is at the latest version on your OS, or try these tips of it's still not working: http://railsapps.github.com/openssl-certificate-verify-failed.html
In my case, the problem was in vscode.
I use windows and installed Ubuntu on my computer, so vscode terminal uses the Ubuntu. I just go to settings.json and change to cmd.exe again
Inspired by TheIT, I just got this to work by manipulating the manifest file but in a slightly different fashion. Set the icon in the application setting so that the majority of the activities get the icon. On the activity where you want to show the logo, add the android:logo attribute to the activity declaration. In the following example, only LogoActivity should have the logo, while the others will default to icon.
<application
android:name="com.your.app"
android:icon="@drawable/your_icon"
android:label="@string/app_name">
<activity
android:name="com.your.app.LogoActivity"
android:logo="@drawable/your_logo"
android:label="Logo Activity" >
<activity
android:name="com.your.app.IconActivity1"
android:label="Icon Activity 1" >
<activity
android:name="com.your.app.IconActivity2"
android:label="Icon Activity 2" >
</application>
Hope this helps someone else out!
One way would be to first flatten the list with a SelectMany
:
subList.SelectMany(m => m).Where(k => k.Key.Equals("valueTitle"));
Alternate method to run 32-bit scripts on 64-bit machine: %windir%\syswow64\cscript.exe vbscriptfile.vbs
Update to Android Studio 3.0.1 which treats these as warnings. Android 3.0 was treating such warnings as errors and hence causing the gradle sync operation to fail.
The UNION operator is just for combining two or more SELECT statements.
While JOIN is for selecting rows from each table, either by the inner, outer, left or right method.
Refer to here and here . There is a better explanation with examples.
Wow! Mean this that you must learn a different programming language just to send two keys to the keyboard? There are simpler ways for you to achieve the same thing. :-)
The Batch file below is an example that start another program (cmd.exe in this case), send a command to it and then send an Up Arrow key, that cause to recover the last executed command. The Batch file is simple enough to be understand with no problems, so you may modify it to fit your needs.
@if (@CodeSection == @Batch) @then
@echo off
rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"
rem Start the other program in the same Window
start "" /B cmd
%SendKeys% "echo off{ENTER}"
set /P "=Wait and send a command: " < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "echo Hello, world!{ENTER}"
set /P "=Wait and send an Up Arrow key: [" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{UP}"
set /P "=] Wait and send an Enter key:" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{ENTER}"
%SendKeys% "exit{ENTER}"
goto :EOF
@end
// JScript section
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));
For a list of key names for SendKeys, see: http://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx
For example:
LEFT ARROW {LEFT}
RIGHT ARROW {RIGHT}
For a further explanation of this solution, see: GnuWin32 openssl s_client conn to WebSphere MQ server not closing at EOF, hangs
ES6 introduce template strings for concatenation. Template Strings use back-ticks (``) rather than the single or double quotes we're used to with regular strings. A template string could thus be written as follows:
// Simple string substitution
let name = "Brendan";
console.log(`Yo, ${name}!`);
// => "Yo, Brendan!"
var a = 10;
var b = 10;
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);
//=> JavaScript first appeared 20 years ago. Crazy!
FYI: g++ offers the non-standard __PRETTY_FUNCTION__ macro. Until just now I did not know about C99 __func__ (thanks Evan!). I think I still prefer __PRETTY_FUNCTION__ when it's available for the extra class scoping.
PS:
static string getScopedClassMethod( string thePrettyFunction )
{
size_t index = thePrettyFunction . find( "(" );
if ( index == string::npos )
return thePrettyFunction; /* Degenerate case */
thePrettyFunction . erase( index );
index = thePrettyFunction . rfind( " " );
if ( index == string::npos )
return thePrettyFunction; /* Degenerate case */
thePrettyFunction . erase( 0, index + 1 );
return thePrettyFunction; /* The scoped class name. */
}
Briefly, no.
You can import all of the functions in the script into your environment with source
(help source
for details), which will then allow you to call them. This also has the effect of executing the script, so take care.
There is no way to call a function from a shell script as if it were a shared library.
List <String> list = new ArrayList();
list.add("behold");
list.add("bend");
list.add("bet");
list.add("bear");
list.add("beat");
list.add("become");
list.add("begin");
List <String> listClone = new ArrayList<String>();
Pattern pattern = Pattern.compile("bea",Pattern.CASE_INSENSITIVE); //incase u r not concerned about upper/lower case
for (String string : list) {
if(pattern.matcher(string).find()) {
listClone.add(string);
continue;
}
}
System.out.println(listClone);
You can't group by literals, only columns.
You are probably looking for something like this:
select
LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000), PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1) as pathinfo,
qvalues.name,
qvalues.compound,
qvalues.rid
from batchinfo join qvalues on batchinfo.rowid=qvalues.rowid
where LEN(datapath)>4
group by pathinfo, qvalues.name, qvalues.compound
having rid!=MAX(rid)
First of all, you have to give that first expression a column name with as
. Then you have to specify the names of the columns in the group by expression.
F# is essentially the C++ of functional programming languages. They kept almost everything from Objective Caml, including the really stupid parts, and threw it on top of the .NET runtime in such a way that it brings in all the bad things from .NET as well.
For example, with Objective Caml you get one type of null, the option<T>. With F# you get three types of null, option<T>, Nullable<T>, and reference nulls. This means if you have an option you need to first check to see if it is "None", then you need to check if it is "Some(null)".
F# is like the old Java clone J#, just a bastardized language just to attract attention. Some people will love it, a few of those will even use it, but in the end it is still a 20-year-old language tacked onto the CLR.
You can see many options as answer for your question, however you can use "-1" where the session never expires. Since you do not know how much time it will take for the thread to complete. E.g.:
<session-config>
<session-timeout>-1</session-timeout>
</session-config>
Or if you don't want a timeout happening for some purpose:
<session-config>
<session-timeout>0</session-timeout>
</session-config>
Another option could be increase the number to 1000, etc, etc, bla, bla, bla.
But if you really want to stop and you consider that is unnecessary for your application to force the user to logout, just add a logout button and the user will decide when to leave.
Here is what you can do to solve the problem if you do not need to force to logout, and in you are loading files that could take time base on server and your computer speed and the size of the file.
<!-- sets the default session timeout to 60 minutes. -->
<!-- <session-config>
<session-timeout>60</session-timeout>
</session-config> -->
Just comment it or deleted that's it! Tan tararantan, tan tan!
I divide the operators, for the purpose of teaching, into four categories:
It is fortunate, then, that most categories are represented in the question:
-> // Automatically imported method
||= // Syntactic sugar
++= // Syntactic sugar/composition or common method
<= // Common method
_._ // Typo, though it's probably based on Keyword/composition
:: // Common method
:+= // Common method
The exact meaning of most of these methods depend on the class that is defining them. For example, <=
on Int
means "less than or equal to". The first one, ->
, I'll give as example below. ::
is probably the method defined on List
(though it could be the object of the same name), and :+=
is probably the method defined on various Buffer
classes.
So, let's see them.
There are some symbols in Scala that are special. Two of them are considered proper keywords, while others are just "reserved". They are:
// Keywords
<- // Used on for-comprehensions, to separate pattern from generator
=> // Used for function types, function literals and import renaming
// Reserved
( ) // Delimit expressions and parameters
[ ] // Delimit type parameters
{ } // Delimit blocks
. // Method call and path separator
// /* */ // Comments
# // Used in type notations
: // Type ascription or context bounds
<: >: <% // Upper, lower and view bounds
<? <! // Start token for various XML elements
" """ // Strings
' // Indicate symbols and characters
@ // Annotations and variable binding on pattern matching
` // Denote constant or enable arbitrary identifiers
, // Parameter separator
; // Statement separator
_* // vararg expansion
_ // Many different meanings
These are all part of the language, and, as such, can be found in any text that properly describe the language, such as Scala Specification(PDF) itself.
The last one, the underscore, deserve a special description, because it is so widely used, and has so many different meanings. Here's a sample:
import scala._ // Wild card -- all of Scala is imported
import scala.{ Predef => _, _ } // Exception, everything except Predef
def f[M[_]] // Higher kinded type parameter
def f(m: M[_]) // Existential type
_ + _ // Anonymous function placeholder parameter
m _ // Eta expansion of method into method value
m(_) // Partial function application
_ => 5 // Discarded parameter
case _ => // Wild card pattern -- matches anything
f(xs: _*) // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequence
I probably forgot some other meaning, though.
So, if you did not find the symbol you are looking for in the list above, then it must be a method, or part of one. But, often, you'll see some symbol and the documentation for the class will not have that method. When this happens, either you are looking at a composition of one or more methods with something else, or the method has been imported into scope, or is available through an imported implicit conversion.
These can still be found on ScalaDoc: you just have to know where to look for them. Or, failing that, look at the index (presently broken on 2.9.1, but available on nightly).
Every Scala code has three automatic imports:
// Not necessarily in this order
import _root_.java.lang._ // _root_ denotes an absolute path
import _root_.scala._
import _root_.scala.Predef._
The first two only make classes and singleton objects available. The third one contains all implicit conversions and imported methods, since Predef
is an object itself.
Looking inside Predef
quickly show some symbols:
class <:<
class =:=
object <%<
object =:=
Any other symbol will be made available through an implicit conversion. Just look at the methods tagged with implicit
that receive, as parameter, an object of type that is receiving the method. For example:
"a" -> 1 // Look for an implicit from String, AnyRef, Any or type parameter
In the above case, ->
is defined in the class ArrowAssoc
through the method any2ArrowAssoc
that takes an object of type A
, where A
is an unbounded type parameter to the same method.
So, many symbols are simply methods on a class. For instance, if you do
List(1, 2) ++ List(3, 4)
You'll find the method ++
right on the ScalaDoc for List. However, there's one convention that you must be aware when searching for methods. Methods ending in colon (:
) bind to the right instead of the left. In other words, while the above method call is equivalent to:
List(1, 2).++(List(3, 4))
If I had, instead 1 :: List(2, 3)
, that would be equivalent to:
List(2, 3).::(1)
So you need to look at the type found on the right when looking for methods ending in colon. Consider, for instance:
1 +: List(2, 3) :+ 4
The first method (+:
) binds to the right, and is found on List
. The second method (:+
) is just a normal method, and binds to the left -- again, on List
.
So, here's a few syntactic sugars that may hide a method:
class Example(arr: Array[Int] = Array.fill(5)(0)) {
def apply(n: Int) = arr(n)
def update(n: Int, v: Int) = arr(n) = v
def a = arr(0); def a_=(v: Int) = arr(0) = v
def b = arr(1); def b_=(v: Int) = arr(1) = v
def c = arr(2); def c_=(v: Int) = arr(2) = v
def d = arr(3); def d_=(v: Int) = arr(3) = v
def e = arr(4); def e_=(v: Int) = arr(4) = v
def +(v: Int) = new Example(arr map (_ + v))
def unapply(n: Int) = if (arr.indices contains n) Some(arr(n)) else None
}
val Ex = new Example // or var for the last example
println(Ex(0)) // calls apply(0)
Ex(0) = 2 // calls update(0, 2)
Ex.b = 3 // calls b_=(3)
// This requires Ex to be a "val"
val Ex(c) = 2 // calls unapply(2) and assigns result to c
// This requires Ex to be a "var"
Ex += 1 // substituted for Ex = Ex + 1
The last one is interesting, because any symbolic method can be combined to form an assignment-like method that way.
And, of course, there's various combinations that can appear in code:
(_+_) // An expression, or parameter, that is an anonymous function with
// two parameters, used exactly where the underscores appear, and
// which calls the "+" method on the first parameter passing the
// second parameter as argument.
First of all we will get source and destination points between which we have to draw route. Then we will pass these attribute to below function.
public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString.append(Double.toString( sourcelog));
urlString.append("&destination=");// to
urlString.append(Double.toString( destlat));
urlString.append(",");
urlString.append(Double.toString( destlog));
urlString.append("&sensor=false&mode=driving&alternatives=true");
urlString.append("&key=YOUR_API_KEY");
return urlString.toString();
}
This function will make the url that we will send to get Direction API response. Then we will parse that response . The parser class is
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public String getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
This parser will return us string. We will call it like that.
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
Now we will send this string to our drawpath function. The drawpath function is
public void drawPath(String result) {
try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor("#05b1fb"))//Google maps blue color
.geodesic(true)
);
/*
for(int z = 0; z<list.size()-1;z++){
LatLng src= list.get(z);
LatLng dest= list.get(z+1);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(2)
.color(Color.BLUE).geodesic(true));
}
*/
}
catch (JSONException e) {
}
}
Above code will draw the path on mMap. The code of decodePoly is
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng( (((double) lat / 1E5)),
(((double) lng / 1E5) ));
poly.add(p);
}
return poly;
}
As direction call may take time so we will do all this in Asynchronous task. My Asynchronous task was
private class connectAsyncTask extends AsyncTask<Void, Void, String>{
private ProgressDialog progressDialog;
String url;
connectAsyncTask(String urlPass){
url = urlPass;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
@Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if(result!=null){
drawPath(result);
}
}
}
I hope it will help.
To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode). However, considering your reason for doing this is due to the length of the URI, using JSON will be self-defeating (introducing more characters than required).
I suggest you send your parameters in body of a POST request, either in regular CGI style (param1=val1¶m2=val2
) or JSON (parsed by your API upon receipt)
Note that starting Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), it's possible to improve a bit on Krzysztof Krason's solution by capturing the match result directly within the if condition as a variable and re-use it in the condition's body:
# pattern = '<title>(.*)</title>'
# text = '<title>hello</title>'
if match := re.search(pattern, text, re.IGNORECASE):
title = match.group(1)
# hello
for me adding /
worked at the end of location of folder.
Hence, if you are copying into folder, don't forget to put /
For Disable Right Click Option
<script type="text/javascript">
var message="Function Disabled!";
function clickIE4(){
if (event.button==2){
alert(message);
return false;
}
}
function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}
if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}
document.oncontextmenu=new Function("alert(message);return false")
</script>