You can use json
like the following example.
PHP code:
echo json_encode($array);
$array
is array data, and the jQuery code is:
$.get("period/education/ajaxschoollist.php?schoolid="+schoolid, function(responseTxt, statusTxt, xhr){
var a = JSON.parse(responseTxt);
$("#hideschoolid").val(a.schoolid);
$("#section_id").val(a.section_id);
$("#schoolname").val(a.schoolname);
$("#country_id").val(a.country_id);
$("#state_id").val(a.state_id);
}
upload_max_filesize
is the limit of any single file.
post_max_size
is the limit of the entire body of the request, which could include multiple files.
Given post_max_size = 20M
and upload_max_filesize = 6M
you could upload up to 3 files of 6M each. If instead post_max_size = 6M
and upload_max_filesize = 20M
then you could only upload one 6M file before hitting post_max_size. It doesn't help to have upload_max_size
> post_max_size
.
It's not obvious how to recognize going over post_max_size
. $_POST
and $_FILES
will be empty, but $_SERVER['CONTENT_LENGTH']
will be > 0. If the client just didn't upload any post variables or files, then $_SERVER['CONTENT_LENGTH']
will be 0.
A version using iteration:
def toHex(decimal):
hex_str = ''
digits = "0123456789ABCDEF"
if decimal == 0:
return '0'
while decimal != 0:
hex_str += digits[decimal % 16]
decimal = decimal // 16
return hex_str[::-1] # reverse the string
numbers = [0, 16, 20, 45, 255, 456, 789, 1024]
print([toHex(x) for x in numbers])
print([hex(x) for x in numbers])
If its SQL Server you can do it on the column properties within design view
Try this?:
ALTER TABLE dbo.TableName
ADD CONSTRAINT DF_TableName_ColumnName
DEFAULT '01/01/2000' FOR ColumnName
I use stderr to store within a loop, and read from it outside. Here var i is initially set and read inside the loop as 1.
# reading lines of content from 2 files concatenated
# inside loop: write value of var i to stderr (before iteration)
# outside: read var i from stderr, has last iterative value
f=/tmp/file1
g=/tmp/file2
i=1
cat $f $g | \
while read -r s;
do
echo $s > /dev/null; # some work
echo $i > 2
let i++
done;
read -r i < 2
echo $i
Or use the heredoc method to reduce the amount of code in a subshell. Note the iterative i value can be read outside the while loop.
i=1
while read -r s;
do
echo $s > /dev/null
let i++
done <<EOT
$(cat $f $g)
EOT
let i--
echo $i
You might want to consider using a Collection
implementation instead of a flat array.
The Collection
interface defines a contains(Object o)
method, which returns true
/false
.
ArrayList
implementation defines an indexOf(Object o)
, which gives an index, but that method is not on all collection implementations.
Both these methods require proper implementations of the equals()
method, and you probably want a properly implemented hashCode()
method just in case you are using a hash based Collection
(e.g. HashSet
).
@RequestParam is use for query parameter(static values) like: http://localhost:8080/calculation/pow?base=2&ext=4
@PathVariable is use for dynamic values like : http://localhost:8080/calculation/sqrt/8
@RequestMapping(value="/pow", method=RequestMethod.GET)
public int pow(@RequestParam(value="base") int base1, @RequestParam(value="ext") int ext1){
int pow = (int) Math.pow(base1, ext1);
return pow;
}
@RequestMapping("/sqrt/{num}")
public double sqrt(@PathVariable(value="num") int num1){
double sqrtnum=Math.sqrt(num1);
return sqrtnum;
}
try this
new String[] {"One","Two","Three","Four"};
or
List<String> places = Arrays.asList("One", "Two", "Three");
Is there a more elegant way to write this code?
from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:
dates_dict[key].append(date)
I had this problem after upgrading to macOS Catalina.
The issue is resolved as follows:
whereis git 2. Add the location of git in settings file with your location:
settings.json
"git.path": "/usr/bin/git", Depending on your platform, the user settings file (settings.json) is located here:
Windows %APPDATA%\Code\User\settings.json
macOS $HOME/Library/Application Support/Code/User/settings.json
Linux $HOME/.config/Code/User/settings.json
If you need to remove white spaces at the end then here is a solution: https://www.geeksforgeeks.org/urlify-given-string-replace-spaces/
const stringQ1 = (string)=>{_x000D_
//remove white space at the end _x000D_
const arrString = string.split("")_x000D_
for(let i = arrString.length -1 ; i>=0 ; i--){_x000D_
let char = arrString[i];_x000D_
_x000D_
if(char.indexOf(" ") >=0){_x000D_
arrString.splice(i,1)_x000D_
}else{_x000D_
break;_x000D_
}_x000D_
}_x000D_
_x000D_
let start =0;_x000D_
let end = arrString.length -1;_x000D_
_x000D_
_x000D_
//add %20_x000D_
while(start < end){_x000D_
if(arrString[start].indexOf(' ') >=0){_x000D_
arrString[start] ="%20"_x000D_
_x000D_
}_x000D_
_x000D_
start++;_x000D_
}_x000D_
_x000D_
return arrString.join('');_x000D_
}_x000D_
_x000D_
console.log(stringQ1("Mr John Smith "))
_x000D_
I figured out that the plt.pause(0.001)
command is the only thing needed and nothing else.
plt.show() and plt.draw() are unnecessary and / or blocking in one way or the other. So here is a code that draws and updates a figure and keeps going. Essentially plt.pause(0.001) seems to be the closest equivalent to matlab's drawnow.
Unfortunately those plots will not be interactive (they freeze), except you insert an input() command, but then the code will stop.
The documentation of the plt.pause(interval) command states:
If there is an active figure, it will be updated and displayed before the pause...... This can be used for crude animation.
and this is pretty much exactly what we want. Try this code:
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(0, 51) # x coordinates
for z in range(10, 50):
y = np.power(x, z/10) # y coordinates of plot for animation
plt.cla() # delete previous plot
plt.axis([-50, 50, 0, 10000]) # set axis limits, to avoid rescaling
plt.plot(x, y) # generate new plot
plt.pause(0.1) # pause 0.1 sec, to force a plot redraw
Cursors are a mechanism to explicitly enumerate through the rows of a result set, rather than retrieving it as such.
However, while they may be more comfortable to use for programmers accustomed to writing While Not RS.EOF Do ...
, they are typically a thing to be avoided within SQL Server stored procedures if at all possible -- if you can write a query without the use of cursors, you give the optimizer a much better chance to find a fast way to implement it.
In all honesty, I've never found a realistic use case for a cursor that couldn't be avoided, with the exception of a few administrative tasks such as looping over all indexes in the catalog and rebuilding them. I suppose they might have some uses in report generation or mail merges, but it's probably more efficient to do the cursor-like work in an application that talks to the database, letting the database engine do what it does best -- set manipulation.
You can use destructuring to only focus on the part of your interest.
So you can do:
let str = "My cow always gives milk";
let [, result] = str.match(/\bcow\s+(.*?)\s+milk\b/) || [];
console.log(result);
_x000D_
In this way you ignore the first part (the complete match) and only get the capture group's match. The addition of || []
may be interesting if you are not sure there will be a match at all. In that case match
would return null
which cannot be destructured, and so we return []
instead in that case, and then result
will be null
.
The additional \b
ensures the surrounding words "cow" and "milk" are really separate words (e.g. not "milky"). Also \s+
is needed to avoid that the match includes some outer spacing.
Sending headers earlier than the normal course may have far reaching consequences. Below are just a few of them that happened to come to my mind at the moment:
While current PHP releases may have output buffering on, the actual production servers you will be deploying your code on are far more important than any development or testing machines. And they do not always tend to follow latest PHP trends immediately.
You may have headaches over inexplicable functionality loss. Say, you are implementing some kind payment gateway, and redirect user to a specific URL after successful confirmation by the payment processor. If some kind of PHP error, even a warning, or an excess line ending happens, the payment may remain unprocessed and the user may still seem unbilled. This is also one of the reasons why needless redirection is evil and if redirection is to be used, it must be used with caution.
You may get "Page loading canceled" type of errors in Internet Explorer, even in the most recent versions. This is because an AJAX response/json include contains something that it shouldn't contain, because of the excess line endings in some PHP files, just as I've encountered a few days ago.
If you have some file downloads in your app, they can break too, because of this. And you may not notice it, even after years, since the specific breaking habit of a download depends on the server, the browser, the type and content of the file (and possibly some other factors I don't want to bore you with).
Finally, many PHP frameworks including Symfony, Zend and Laravel (there is no mention of this in the coding guidelines but it follows the suit) and the PSR-2 standard (item 2.2) require omission of the closing tag. PHP manual itself (1,2), Wordpress, Drupal and many other PHP software I guess, advise to do so. If you simply make a habit of following the standard (and setup PHP-CS-Fixer for your code) you can forget the issue. Otherwise you will always need to keep the issue in your mind.
Bonus: a few gotchas (actually currently one) related to these 2 characters:
?>
. An example is Smarty, even the most recent versions of both 2.* and 3.* branch have this. So, as always, watch for third party code. Bonus in bonus: A regex for deleting needless PHP endings: replace (\s*\?>\s*)$
with empty text in all files that contain PHP code.If you really want an iterator-free solution, you can use numpy and its array round function.
import numpy as np
myList = list(np.around(np.array(myList),2))
A more elegant approach to build bigrams with python’s builtin zip()
.
Simply convert the original string into a list by split()
, then pass the list once normally and once offset by one element.
string = "I really like python, it's pretty awesome."
def find_bigrams(s):
input_list = s.split(" ")
return zip(input_list, input_list[1:])
def find_ngrams(s, n):
input_list = s.split(" ")
return zip(*[input_list[i:] for i in range(n)])
find_bigrams(string)
[('I', 'really'), ('really', 'like'), ('like', 'python,'), ('python,', "it's"), ("it's", 'pretty'), ('pretty', 'awesome.')]
CMake 3.13 on Ubuntu 16.04
This approach is more flexible because it doesn't constraint MY_VARIABLE to a type:
$ cat CMakeLists.txt
message("MY_VARIABLE=${MY_VARIABLE}")
if( MY_VARIABLE )
message("MY_VARIABLE evaluates to True")
endif()
$ mkdir build && cd build
$ cmake ..
MY_VARIABLE=
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=True
MY_VARIABLE=True
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=False
MY_VARIABLE=False
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=1
MY_VARIABLE=1
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=0
MY_VARIABLE=0
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
Simple:
if ( $name eq 'tom' && $password eq '123!'
|| $name eq 'frank' && $password eq '321!'
) {
(use the high-precedence &&
and ||
in expressions, reserving and
and or
for flow control, to avoid common precedence errors)
Better:
my %password = (
'tom' => '123!',
'frank' => '321!',
);
if ( exists $password{$name} && $password eq $password{$name} ) {
Standard SQL (or MySQL) does not permit the use of column aliases in a WHERE clause because
when the WHERE clause is evaluated, the column value may not yet have been determined.
(from MySQL documentation). What you can do is calculate the column value in the WHERE clause, save the value in a variable, and use it in the field list. For example you could do this:
SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,
@postcode AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
WHERE (@postcode := SUBSTRING(`locations`.`raw`,-6,4)) NOT IN
(
SELECT `postcode` FROM `postcodes` WHERE `region` IN
(
'australia'
)
)
This avoids repeating the expression when it grows complicated, making the code easier to maintain.
I was just looking for this... By using David's answer, I used a span and gave it some padding (height won't work + top margin issue)... Works like a charm;
See fiddle
<ul>
<li><a href="index.php">Home</a></li><span class="divider"></span>
<li><a href="about.php">About Us</a></li><span class="divider"></span>
<li><a href="#">Events</a></li><span class="divider"></span>
<li><a href="#">Forum</a></li><span class="divider"></span>
<li><a href="#">Contact</a></li>
</ul>
.divider {
border-left: 1px solid #8e1537;
padding: 29px 0 24px 0;
}
Here's a SCSS code (compiled css below) that will help you to easily control the tooltip colors, including the arrow (border and background for the arrow as well):
Note: you might need to add "important" in some places in order for the CSS rules to take effect. Note #2: the style here only works for TOP and BOTTOM tooltip layouts. Feel free to add some more styling (&.bs-tooltip-left, &.bs-tooltip-right, etc)
SCSS:
$tt-text-color: lime;
$tt-border-color: lime;
$tt-bg-color: black;
$arrow-border-color: lime;
$arrow-bg-color: black;
.tooltip {
.tooltip-inner {
background: $tt-bg-color;
color: $tt-text-color;
border: 2px solid $tt-border-color;
}
.arrow {
width: 11px;
height: 11px;
border: 2px solid $arrow-border-color;
bottom: 1px;
&:before {
width: 11px;
height: 11px;
background: $arrow-bg-color;
border: 0;
}
}
&.bs-tooltip-top {
.arrow {
transform: rotate(-135deg);
}
}
&.bs-tooltip-bottom {
.arrow {
transform: rotate(135deg);
top: 2px;
}
}
}
CSS:
.tooltip .tooltip-inner {
background: black;
color: lime;
border: 2px solid lime;
}
.tooltip .arrow {
width: 11px;
height: 11px;
border: 2px solid lime;
bottom: 1px;
}
.tooltip .arrow:before {
width: 11px;
height: 11px;
background: black;
border: 0;
}
.tooltip.bs-tooltip-top .arrow {
transform: rotate(-135deg);
}
.tooltip.bs-tooltip-bottom .arrow {
transform: rotate(135deg);
top: 2px;
}
Live Example:
jQuery(document).ready(function(){_x000D_
$('a').tooltip();_x000D_
});
_x000D_
.tooltip .tooltip-inner {_x000D_
background: black;_x000D_
color: lime;_x000D_
border: 2px solid lime;_x000D_
}_x000D_
.tooltip .arrow {_x000D_
width: 11px!important;_x000D_
height: 11px!important;_x000D_
border: 2px solid lime;_x000D_
bottom: 1px;_x000D_
}_x000D_
.tooltip .arrow:before {_x000D_
width: 11px;_x000D_
height: 11px;_x000D_
background: black;_x000D_
border: 0;_x000D_
}_x000D_
.tooltip.bs-tooltip-top .arrow {_x000D_
transform: rotate(-135deg);_x000D_
}_x000D_
.tooltip.bs-tooltip-bottom .arrow {_x000D_
transform: rotate(135deg);_x000D_
top: 2px;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>_x000D_
_x000D_
<div class="text-center py-4">_x000D_
<a class="cn-box big cn-copy" data-toggle="tooltip" data-placement="bottom" title="Hello There">_x000D_
try me_x000D_
</a>_x000D_
</div>
_x000D_
\documentclass{scrartcl}
\usepackage{amssymb}
\begin{document}
$\backslash$blacksquare: $\blacksquare$
$\backslash$square: $\square$
\end{document}
You can easily find such symbols with http://write-math.com
When you want to align it to the right, add \hfill
.
I use:
\renewcommand{\qed}{\hfill\blacksquare}
\newcommand{\qedwhite}{\hfill \ensuremath{\Box}}
What is a file with extension .sh?
It is a Bourne shell script. They are used in many variations of UNIX-like operating systems. They have no "language" and are interpreted by your shell (interpreter of terminal commands) or if the first line is in the form
#!/path/to/interpreter
they will use that particular interpreter. Your file has the first line:
#!/bin/bash
and that means that it uses Bourne Again Shell, so called bash. It is for all practical purposes a replacement for good old sh.
Depending upon the interpreter you will have different language in which the file is written.
Keep in mind, that in UNIX world, it is not the extension of the file that determines what the file is (see How to execute a shell script).
If you come from the world of DOS/Windows, you will be familiar with files that have .bat or .cmd extensions (batch files). They are not similar in content, but are akin in design.
How to execute a shell script
Unlike some silly operating systems, *nix does not rely exclusively on extensions to determine what to do with a file. Permissions are also used. This means that if you attempt to run the shell script after downloading it, it will be the same as trying to "run" any text file. The ".sh" extension is there only for your convenience to recognize that file.
You will need to make the file executable. Let's assume that you have downloaded your file as file.sh
, you can then run in your terminal:
chmod +x file.sh
chmod
is a command for changing file's permissions, +x
sets execute permissions (in this case for everybody) and finally you have your file name.
You can also do it in GUI. Most of the time you can right click on the file and select properties, in XUbuntu the permissions options look like this:
If you do not wish to change the permissions. You can also force the shell to run the command. In the terminal you can run:
bash file.sh
The shell should be the same as in the first line of your script.
How safe is it?
You may find it weird that you must perform another task manually in order to execute a file. But this is partially because of strong need for security.
Basically when you download and run a bash script, it is the same thing as somebody telling you "run all these commands in sequence on your computer, I promise that the results will be good and safe". Ask yourself if you trust the party that has supplied this file, ask yourself if you are sure that have downloaded the file from the same place as you thought, maybe even have a glance inside to see if something looks out of place (although that requires that you know something about *nix commands and bash programming).
Unfortunately apart from the warning above I cannot give a step-by-step description of what you should do to prevent evil things from happening with your computer; so just keep in mind that any time you get and run an executable file from someone you're actually saying, "Sure, you can use my computer to do something".
Question 1 query:
SELECT ta.C1
,ta.C2
,ta.C3
,ta.C4
FROM [TableA] ta
WHERE (SELECT COUNT(*)
FROM [TableA] ta2
WHERE ta.C2=ta2.C2
AND ta.C3=ta2.C3
AND ta.C4=ta2.C4)>1
Another way would be to use lftp:
lftp sftp://user:password@host -e "put local-file.name; bye"
The disadvantage of this method is that other users on the computer can read the password from tools like ps
and that the password can become part of your shell history.
A more secure alternative which is available since LFTP 4.5.0 is setting the LFTP_PASSWORD
environment variable and executing lftp with --env-password
. Here's a full example:
LFTP_PASSWORD="just_an_example"
lftp --env-password sftp://user@host -e "put local-file.name; bye"
LFTP also includes a cool mirroring feature (can include delete after confirmed transfer --Remove-source-files
):
lftp -e 'mirror -R /local/log/path/ /remote/path/' --env-password -u user sftp.foo.com
og:title
is one of the open graph meta tags. og:...
properties define objects in a social graph. They are used for example by Facebook.
og:title
stands for the title of your object as it should appear within the graph (see here for more http://ogp.me/ )
I suspect its a new feature since this post was created - pass parameters to the script block using $Using:var. Then its a simple mater to pass parameters provided the script is already on the machine or in a known network location relative to the machine
Taking the main example it would be:
icm -cn $Env:ComputerName {
C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -one "uno" -two "dos" -Debug -Clear $Using:Clear
}
(tensorflow)$ pip install --upgrade pip # for Python 2.7
(tensorflow)$ pip3 install --upgrade pip # for Python 3.n
(tensorflow)$ pip install --upgrade tensorflow # for Python 2.7
(tensorflow)$ pip3 install --upgrade tensorflow # for Python 3.n
(tensorflow)$ pip install --upgrade tensorflow-gpu # for Python 2.7 and GPU
(tensorflow)$ pip3 install --upgrade tensorflow-gpu # for Python 3.n and GPU
(tensorflow)$ pip install --upgrade tensorflow-gpu==1.4.1 # for a specific version
Details on install tensorflow.
Although this is the accepted answer, toto_tico's answer below is better :)
Try making the onclick js use 'return' to ensure the desired return value gets used...
<button type="button" value="click me" onclick="return check_me();" />
Use the wildcard "#" but beware that at some point you will have to somehow understand the data passing through the bus!
While you can set the locale exporting an env variable, you will have to do that every time you start a session. Setting a locale this way will solve the problem permanently:
sudo apt-get install locales
sudo locale-gen en_US.UTF-8
sudo echo "LANG=en_US.UTF-8" > /etc/default/locale
Use the RegExp object constructor to create a regular expression from a string:
var re = new RegExp("a|b", "i");
// same as
var re = /a|b/i;
Go to Attributes Inspector(right top corner) In the Simulated Metrics, which has Size, Orientation, Status Bar, Top Bar, Bottom Bar properties. For SIZE, change Inferred --> Freeform.
\s
matches any white-space character\S
matches any non-white-space character[^ ]
matches anything but a space character.Pick whichever is most appropriate.
I think library is a set of utilities to reach a goal (for example, sockets, cryptography, etc). Framework is library + RUNTIME EINVIRONNEMENT. For example, ASP.NET is a framework: it accepts HTTP requests, create page object, invoke lyfe cicle events, etc. Framework does all this, you write a bit of code which will be run at a specific time of the life cycle of current request!
Anyway, very interestering question!
I cannot get a match using Xpather, but the following worked for me with plain XML and XSL files in Microsoft's XML Notepad:
<xsl:value-of select="count(//td[text()=' '])" />
The value returned is 1, which is the correct value in my test case.
However, I did have to declare nbsp as an entity within my XML and XSL using the following:
<!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp " "> ]>
I'm not sure if that helps you, but I was able to actually find nbsp using an XPath expression.
Edit: My code sample actually contains the characters ' ' but the JavaScript syntax highlight converts it to the space character. Don't be mislead!
Using command line:
python -c "import scipy; print(scipy.__version__)"
On ng-build, file not found(404) error occur. So we can use below code
<ng-include src="'views/transaction/test.html'"></ng-include>
insted of,
<div ng-include="'views/transaction/test.html'"></div>
Use byte[] ptext = String.getBytes("UTF-8");
instead of getBytes()
. getBytes()
uses so-called "default encoding", which may not be UTF-8.
I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.
I found a link doing the same thing. Try following these steps.
You can try this(Python-for-PDF-Generation) or you can try PyQt, which has support for printing to pdf.
Python for PDF Generation
The Portable Document Format (PDF) lets you create documents that look exactly the same on every platform. Sometimes a PDF document needs to be generated dynamically, however, and that can be quite a challenge. Fortunately, there are libraries that can help. This article examines one of those for Python.
Read more at http://www.devshed.com/c/a/Python/Python-for-PDF-Generation/#whoCFCPh3TAks368.99
Regex-based searching is sometimes faster than generator approach:
RRR = re.compile(r'(.*)\n')
def f4(arg):
return (i.group(1) for i in RRR.finditer(arg))
I found that when you use the action buttons in expanded notifications, you have to write extra code and you are more constrained.
You have to manually cancel your notification when the user clicks an action button. The notification is only cancelled automatically for the default action.
Also if you start a broadcast receiver from the button, the notification drawer doesn't close.
I ended up creating a new NotificationActivity to address these issues. This intermediary activity without any UI cancels the notification and then starts the activity I really wanted to start from the notification.
I've posted sample code in a related post Clicking Android Notification Actions does not close Notification drawer.
#pragma mark
is used to tag the group of methods so you may easily find and detect methods from the Jump Bar. It may help you when your code files reach about 1000 lines and you want to find methods quickly through the category from Jump box.
In a long program it becomes difficult to remember and find a method name. So pragma mark allows you to categorize methods according to the work they do. For example, you tagged some tag for Table View Protocol Methods, AlertView Methods, Init Methods, Declaration etc.
#pragma mark
is the facility for XCode but it has no impact on your code. It merely helps to make it easier to find methods while coding.
do it like this
while true
do
[ -f /tmp/list.txt ] && break
sleep 2
done
ls -l /tmp/list.txt
Update 2020:
Unfortunately this is still happening:
I still don't know why, it would allow me to install without checking for dependencies. I have become accustomed to this kind of behavior when I am installing any application and to not see it is annoying. I suppose I should leave this personal opinions out of my solution but I have had to install this multiple times and have comes across some kind of dependency issue.
For any javadoc (not just the ones available for download) you can use the DownThemAll addon for Firefox with a suitable renaming mask, for example:
*subdirs*/*name*.*ext*
https://addons.mozilla.org/en-us/firefox/addon/downthemall/
https://www.downthemall.org/main/install-it/downthemall-3-0-7/
Edit: It's possible to use some older versions of the DownThemAll add-on with Pale Moon browser.
Just for documentation, sometimes you need to run the script as sudo
:
sudo Rscript path/to/your/file.R
If you came here looking for an answer to this question but not exactly the way the OP meant, ie how do you get multi-line CMD to work in a single line, I have a sort of dangerous answer for you.
Trying to use this with things that actually use piping, like say findstr
is quite problematic. The same goes for dealing with else
s. But if you just want a multi-line conditional command to execute directly from CMD and not via a batch file, this should do work well.
Let's say you have something like this in a batch that you want to run directly in command prompt:
@echo off
for /r %%T IN (*.*) DO (
if /i "%%~xT"==".sln" (
echo "%%~T" is a normal SLN file, and not a .SLN.METAPROJ or .SLN.PROJ file
echo Dumping SLN file contents
type "%%~T"
)
)
Now, you could use the line-continuation carat (^
) and manually type it out like this, but warning, it's tedious and if you mess up you can learn the joy of typing it all out again.
Well, it won't work with just ^
thanks to escaping mechanisms inside of parentheses shrug At least not as-written. You actually would need to double up the carats like so:
@echo off ^
More? for /r %T IN (*.sln) DO (^^
More? if /i "%~xT"==".sln" (^^
More? echo "%~T" is a normal SLN file, and not a .SLN.METAPROJ or .SLN.PROJ file^^
More? echo Dumping SLN file contents^^
More? type "%~T"))
Instead, you can be a dirty sneaky scripter from the wrong side of the tracks that don't need no carats by swapping them out for a single pipe (|
) per continuation of a loop/expression:
@echo off
for /r %T IN (*.sln) DO if /i "%~xT"==".sln" echo "%~T" is a normal SLN file, and not a .SLN.METAPROJ or .SLN.PROJ file | echo Dumping SLN file contents | type "%~T"
With this step set permission to gradlew
steps {
echo 'Compile project'
sh "chmod +x gradlew"
sh "./gradlew clean build --no-daemon"
}
Multi update was added recently, so is only available in the development releases (1.1.3). From the shell you do a multi update by passing true
as the fourth argument to update()
, where the the third argument is the upsert argument:
db.test.update({foo: "bar"}, {$set: {test: "success!"}}, false, true);
For versions of mongodb 2.2+ you need to set option multi true to update multiple documents at once.
db.test.update({foo: "bar"}, {$set: {test: "success!"}}, {multi: true})
For versions of mongodb 3.2+ you can also use new method updateMany()
to update multiple documents at once, without the need of separate multi
option.
db.test.updateMany({foo: "bar"}, {$set: {test: "success!"}})
You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:
var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
if(!pattern.test(userinput))
{
alert('not a valid e-mail address');
}?
If you simply need to view the table and run queries on it you can use this third party sdf viewer. It is a lightweight viewer that has all the basic functionalities and is ready to use after install.
and ofcourse, its Free.
Mutable default arguments don't generally do what you want. Instead, try this:
class Node:
def __init__(self, wordList=None, adjacencyList=None):
if wordList is None:
self.wordList = []
else:
self.wordList = wordList
if adjacencyList is None:
self.adjacencyList = []
else:
self.adjacencyList = adjacencyList
You can use a deep watcher for that:
watch: {
item: {
handler(val){
// do stuff
},
deep: true
}
}
This will now detect any changes to the objects in the item
array and additions to the array itself (when used with Vue.set). Here's a JSFiddle: http://jsfiddle.net/je2rw3rs/
EDIT
If you don't want to watch for every change on the top level object, and just want a less awkward syntax for watching nested objects directly, you can simply watch a computed
instead:
var vm = new Vue({
el: '#app',
computed: {
foo() {
return this.item.foo;
}
},
watch: {
foo() {
console.log('Foo Changed!');
}
},
data: {
item: {
foo: 'foo'
}
}
})
Here's the JSFiddle: http://jsfiddle.net/oa07r5fw/
You can try this in xml
sheet:
android:background="@color/background_color"
You need to escape those but don't just replace it by %2F
manually. You can use URLEncoder
for this.
Eg URLEncoder.encode(url, "UTF-8")
Then you can say
yourUrl = "www.musicExplained/index.cfm/artist/" + URLEncoder.encode(VariableName, "UTF-8")
surely you can do this with worksheet formulas, avoiding VBA entirely:
so for this value in say, column AV S:1 P:0 K:1 Q:1
you put this formula in column BC:
=MID(AV:AV,FIND("S",AV:AV)+2,1)
then these formulas in columns BD, BE...
=MID(AV:AV,FIND("P",AV:AV)+2,1)
=MID(AV:AV,FIND("K",AV:AV)+2,1)
=MID(AV:AV,FIND("Q",AV:AV)+2,1)
so these formulas look for the values S:1, P:1 etc in column AV. If the FIND
function returns an error, then 0 is returned by the formula, else 1 (like an IF, THEN, ELSE
Then you would just copy down the formulas for all the rows in column AV.
HTH Philip
Your module and your class AthleteList
have the same name. The line
import AthleteList
imports the module and creates a name AthleteList
in your current scope that points to the module object. If you want to access the actual class, use
AthleteList.AthleteList
In particular, in the line
return(AthleteList(templ.pop(0), templ.pop(0), templ))
you are actually accessing the module object and not the class. Try
return(AthleteList.AthleteList(templ.pop(0), templ.pop(0), templ))
Best answer is to use the from dateutil import parser
.
usage:
from dateutil import parser
datetime_obj = parser.parse('2018-02-06T13:12:18.1278015Z')
print datetime_obj
# output: datetime.datetime(2018, 2, 6, 13, 12, 18, 127801, tzinfo=tzutc())
It is possible get your approximate locate based on your IP address (wireless or fixed).
See for example hostip.info or maxmind which basically provide a mapping from IP address to geographical coordinates. The probably use many kinds of heuristics and datasources. This kind of system has probably enough accuracy to put you in right major city, in most cases.
Google probably uses somewhat similar approach in addition to WiFi tricks.
The problem is with your line
x=np.array ([x0*n])
Here you define x as a single-item array of -200.0. You could do this:
x=np.array ([x0,]*n)
or this:
x=np.zeros((n,)) + x0
Note: your imports are quite confused. You import numpy modules three times in the header, and then later import pylab (that already contains all numpy modules). If you want to go easy, with one single
from pylab import *
line in the top you could use all the modules you need.
The click event doesn't exist at that point where the event is defined. You can use live or delegate the event.
$('.deletelanguage').live('click',function(){
alert("success");
$('#LangTable').append(' <br>------------<br> <a class="deletelanguage">Now my class is deletelanguage. click me to test it is not working.</a>');
});
Yes, you need to close Connection
. Otherwise, the database client will typically keep the socket connection and other resources open.
I had exactly the same problem. I fixed it without rebuilding python, as follows:
Find another server with the same architecture (i386 or x86_64) and the same python version (example: 2.7.5). Yes, this is the hard part. You can try installing python from sources into another server if you can't find any server with the same python version.
In this another server, check if import ssl works. It should work.
If it works, then try to find the _ssl lilbrary as follows:
[root@myserver]# find / -iname _ssl.so
/usr/local/python27/lib/python2.7/lib-dynload/_ssl.so
Copy this file into the original server. Use the same destination folder: /usr/local/python27/lib/python2.7/lib-dynload/
Double check owner and permissions:
[root@myserver]# chown root:root _ssl.so
[root@myserver]# chmod 755 _ssl.so
Now you should be able to import ssl.
This worked for me in a CentOS 6.3 x86_64 environment with python 2.7.3. Also I had python 2.6.6 installed, but with ssl working fine.
You need to use the command pscp and forcing it to pass through sftp protocol. pscp is automatically installed when you install PuttY, a software to connect to a linux server through ssh.
When you have your pscp command here is the command line:
pscp -sftp -pw <yourPassword> "<pathToYourFile(s)>" <username>@<serverIP>:<PathInTheServerFromTheHomeDirectory>
These parameters (-sftp and -pw) are only available with pscp and not scp. You can also add -r if you want to upload everything in a folder in a recursive way.
Instead of using count(*)
you can SELECT *
and you will return all of the details that you want including data_type
:
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'Address'
MSDN Docs on INFORMATION_SCHEMA.COLUMNS
I don't know why, but I'm not seeing "Edge" in the userAgent like everyone else is talking about, so I had to take another route that may help some people.
Instead of looking at the navigator.userAgent, I looked at navigator.appName to distinguish if it was IE<=10 or IE11 and Edge. IE11 and Edge use the appName of "Netscape", while every other iteration uses "Microsoft Internet Explorer".
After we determine that the browser is either IE11 or Edge, I then looked to navigator.appVersion. I noticed that in IE11 the string was rather long with a lot of information inside of it. I arbitrarily picked out the word "Trident", which is definitely not in the navigator.appVersion for Edge. Testing for this word allowed me to distinguish the two.
Below is a function that will return a numerical value of which Internet Explorer the user is on. If on Microsoft Edge it returns the number 12.
Good luck and I hope this helps!
function Check_Version(){
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer'){
var ua = navigator.userAgent,
re = new RegExp("MSIE ([0-9]{1,}[\\.0-9]{0,})");
if (re.exec(ua) !== null){
rv = parseFloat( RegExp.$1 );
}
}
else if(navigator.appName == "Netscape"){
/// in IE 11 the navigator.appVersion says 'trident'
/// in Edge the navigator.appVersion does not say trident
if(navigator.appVersion.indexOf('Trident') === -1) rv = 12;
else rv = 11;
}
return rv;
}
First you need to create the directory:
sudo mkdir /usr/local/include
Second:
sudo chown -R $(whoami) $(brew --prefix)/*
What is a Pointer?
In all languages, a pointer is a type of variable that stores a memory address, and you can either ask them to tell you the address they are pointing at or the value at the address they are pointing at.
A pointer can be thought of as a sort-of book mark. Except, instead of being used to jump quickly to a page in a book, a pointer is used to keep track of or map blocks of memory.
Imagine your program's memory precisely like one big array of 65535 bytes.
Pointers point obediently
Pointers remember one memory address each, and therefore they each point to a single address in memory.
As a group, pointers remember and recall memory addresses, obeying your every command ad nauseum.
You are their king.
Pointers in C#
Specifically in C#, a pointer is an integer variable that stores a memory address between 0 and 65534.
Also specific to C#, pointers are of type int and therefore signed.
You can't use negatively numbered addresses though, neither can you access an address above 65534. Any attempt to do so will throw a System.AccessViolationException.
A pointer called MyPointer is declared like so:
int *MyPointer;
A pointer in C# is an int, but memory addresses in C# begin at 0 and extend as far as 65534.
Pointy things should be handled with extra special care
The word unsafe is intended to scare you, and for a very good reason: Pointers are pointy things, and pointy things e.g. swords, axes, pointers, etc. should be handled with extra special care.
Pointers give the programmer tight control of a system. Therefore mistakes made are likely to have more serious consequences.
In order to use pointers, unsafe code has to be enabled in your program's properties, and pointers have to be used exclusively in methods or blocks marked as unsafe.
Example of an unsafe block
unsafe
{
// Place code carefully and responsibly here.
}
How to use Pointers
When variables or objects are declared or instantiated, they are stored in memory.
int *MyPointer;
MyPointer = &MyVariable;
Once an address is assigned to a pointer, the following applies:
MyPointer = &MyVariable; // Set MyPointer to point at MyVariable
"MyPointer is pointing at " + *MyPointer;
Since a pointer is a variable that holds a memory address, this memory address can be stored in a pointer variable.
Example of pointers being used carefully and responsibly
public unsafe void PointerTest()
{
int x = 100; // Create a variable named x
int *MyPointer = &x; // Store the address of variable named x into the pointer named MyPointer
textBox1.Text = ((int)MyPointer).ToString(); // Displays the memory address stored in pointer named MyPointer
textBox2.Text = (*MyPointer).ToString(); // Displays the value of the variable named x via the pointer named MyPointer.
}
Notice the type of the pointer is an int. This is because C# interprets memory addresses as integer numbers (int).
Why is it int instead of uint?
There is no good reason.
Why use pointers?
Pointers are a lot of fun. With so much of the computer being controlled by memory, pointers empower a programmer with more control of their program's memory.
Memory monitoring.
Use pointers to read blocks of memory and monitor how the values being pointed at change over time.
Change these values responsibly and keep track of how your changes affect your computer.
Google JSESSIONID. This will explain how the Servlet API initially uses URL re-writing and then, if cookies are enabled, cookies to manage sessions.
HTTP is stateless so the client browser must send the id of its session to the server with each request. The server, through whatever means, uses this id to retrieve any data for that session making it available for the lifetime of the request.
CSS?
td {
padding-top: 2px;
padding-bottom: 2px;
}
I see only one reason your code to not work, missed quote after file name string:
VBScript:
FSO.GetFile("MyFile.txt[missed_quote_here]).Name = "Hello.txt"
JPA doesn't offer any support for derived property so you'll have to use a provider specific extension. As you mentioned, @Formula
is perfect for this when using Hibernate. You can use an SQL fragment:
@Formula("PRICE*1.155")
private float finalPrice;
Or even complex queries on other tables:
@Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)")
private Date firstOrderDate;
Where id
is the id
of the current entity.
The following blog post is worth the read: Hibernate Derived Properties - Performance and Portability.
Without more details, I can't give a more precise answer but the above link should be helpful.
Issue can be solved by adding CRT of msvcrtd.lib in the linker library. Because cryptlib.lib used CRT version of debug.
This should give you the current date minus 1 year:
select now() - interval '1 year';
In Oracle 12c, you can now specify the CURRVAL and NEXTVAL sequence pseudocolumns as default values for a column. Alternatively, you can use Identity columns; see:
E.g.,
CREATE SEQUENCE t1_seq;
CREATE TABLE t1 (
id NUMBER DEFAULT t1_seq.NEXTVAL,
description VARCHAR2(30)
);
The assembly was introduced with .NET 3.5 and is in the GAC.
Simply add a .NET reference to your project.
Project -> Right Click References
-> Select .NET
tab -> System.Web.Extensions
If it is not there, you need to install .NET 3.5 or 4.0.
i have a table like this in this below image,and i am going to find the 2nd largest number in "to_user" column..
Here is Answer
select MAX(to_user) FROM db.masterledger where to_user NOT IN (SELECT MAX(to_user) FROM db.masterledger);
The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.
Conclusion
Let's me explain more detail:
Question: How many Transaction we have? Answer: Only one
Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.
Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction
Go to the catch outside
Spring will set the rollBackOnly to true -> it determine we must
rollback the caller (processNextRegistrationMessage) also.
The persist() will rollback itself first.
Question: Why we change PROPAGATION to REQUIRES_NEW, it works?
Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.
Thanks
The straight forward approach:
this.dataGridView1.DefaultCellStyle.Font = new Font("Tahoma", 15);
I modified the code as follow:
ViewModel
using System.Collections.Generic;
using ContosoUniversity.Models;
namespace ContosoUniversity.ViewModels
{
public class InstructorIndexData
{
public PagedList.IPagedList<Instructor> Instructors { get; set; }
public PagedList.IPagedList<Course> Courses { get; set; }
public PagedList.IPagedList<Enrollment> Enrollments { get; set; }
}
}
Controller
public ActionResult Index(int? id, int? courseID,int? InstructorPage,int? CoursePage,int? EnrollmentPage)
{
int instructPageNumber = (InstructorPage?? 1);
int CoursePageNumber = (CoursePage?? 1);
int EnrollmentPageNumber = (EnrollmentPage?? 1);
var viewModel = new InstructorIndexData();
viewModel.Instructors = db.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.Courses.Select(c => c.Department))
.OrderBy(i => i.LastName).ToPagedList(instructPageNumber,5);
if (id != null)
{
ViewBag.InstructorID = id.Value;
viewModel.Courses = viewModel.Instructors.Where(
i => i.ID == id.Value).Single().Courses.ToPagedList(CoursePageNumber,5);
}
if (courseID != null)
{
ViewBag.CourseID = courseID.Value;
viewModel.Enrollments = viewModel.Courses.Where(
x => x.CourseID == courseID).Single().Enrollments.ToPagedList(EnrollmentPageNumber,5);
}
return View(viewModel);
}
View
<div>
Page @(Model.Instructors.PageCount < Model.Instructors.PageNumber ? 0 : Model.Instructors.PageNumber) of @Model.Instructors.PageCount
@Html.PagedListPager(Model.Instructors, page => Url.Action("Index", new {InstructorPage=page}))
</div>
I hope this would help you!!
set /a countfiles-=%countfiles%
This will set countfiles to 0. I think you want to decrease it by 1, so use this instead:
set /a countfiles-=1
I'm not sure if the for loop will work, better try something like this:
:loop
cscript /nologo c:\deletefile.vbs %BACKUPDIR%
set /a countfiles-=1
if %countfiles% GTR 21 goto loop
I had the same error turns out the only thing i did wrong was to name my 'templates' folder,'template' without 's'. After changing that it worked fine,dont know why its a thing but it is.
ID VALUE1 VALUE2
===================
1 1 2
1 2 2
2 3 4
2 4 5
select ID, (coalesce(VALUE1 ,0) + coalesce(VALUE2 ,0) as Total from TableName
Use NSNumber *aNumber = [NSNumber numberWithDouble:number]; instead of NSNumber *aNumber = [NSNumber numberWithFloat:number];
+(NSString *)roundToNearestValue:(double)number
{
NSNumber *aNumber = [NSNumber numberWithDouble:number];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setUsesGroupingSeparator:NO];
[numberFormatter setMaximumFractionDigits:2];
[numberFormatter setMinimumFractionDigits:0];
NSString *string = [numberFormatter stringFromNumber:aNumber];
return string;
}
For Mac users who only have Command Line Tools instead of Xcode, check the /Library/Developer/CommandLineTools
directory, for example::
"configurations": [{
"name": "Mac",
"includePath": [
"/usr/local/include",
// others, e.g.: "/usr/local/opt/ncurses/include",
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include",
"${workspaceFolder}/**"
]
}]
You probably need to adjust the path if you have different version of Command Line Tools installed.
Note: You can also open/generate the
c_cpp_properties.json
file via theC/Cpp: Edit Configurations
command from the Command Palette (??P).
We can create multidimensional array dynamically as follows,
Create 2 variables to read x and y from standard input:
print("Enter the value of x: ")
x=int(input())
print("Enter the value of y: ")
y=int(input())
Create an array of list with initial values filled with 0 or anything using the following code
z=[[0 for row in range(0,x)] for col in range(0,y)]
creates number of rows and columns for your array data.
Read data from standard input:
for i in range(x):
for j in range(y):
z[i][j]=input()
Display the Result:
for i in range(x):
for j in range(y):
print(z[i][j],end=' ')
print("\n")
or use another way to display above dynamically created array is,
for row in z:
print(row)
Based on all the good answers of this thread, I wrote a library to fetch the output of each layer. It abstracts all the complexity and has been designed to be as user-friendly as possible:
https://github.com/philipperemy/keract
It handles almost all the edge cases
Hope it helps!
You could return to the previous page by using ViewBag.ReturnUrl
property.
You can also increase it via the VM arguments in your IDE. In my case, I am using Tomcat v7.0 which is running on Eclipse. To do this, double click on your server (Tomcat v7.0). Click the 'Open launch configuration' link. Go to the 'Arguments' tab. Add -XX:MaxPermSize=512m to the VM arguments list. Click 'Apply' and then 'OK'. Restart your server.
It's too late, but my answer is for those who search for a solution with a recent version of Django.
models.py
:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
extra_Field_1 = models.CharField(max_length=25, blank=True)
extra_Field_2 = models.CharField(max_length=25, blank=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
you can use it in templates like this:
<h2>{{ user.get_full_name }}</h2>
<ul>
<li>Username: {{ user.username }}</li>
<li>Location: {{ user.profile.extra_Field_1 }}</li>
<li>Birth Date: {{ user.profile.extra_Field_2 }}</li>
</ul>
and in views.py
like this:
def update_profile(request, user_id):
user = User.objects.get(pk=user_id)
user.profile.extra_Field_1 = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit...'
user.save()
This is for <object>
SVG and className is .svgClass
<object class="svgClass" type="image/svg+xml" data="image.svg"></object>
So JavaScript code is like this:
// change to red
document.querySelector(".svgClass").getSVGDocument().getElementById("svgInternalID").setAttribute("fill", "red")
To change svgInternalID you have to open SVG file which is plain .txt (ie image.svg) and edit it
<path id="svgInternalID"
I'm newbie, so sorry if is a bad practice. Based on the chosen answer, I did this function:
function x_apply(selector, variable, value) {
var scope = angular.element( $(selector) ).scope();
scope.$apply(function(){
scope[variable] = value;
});
}
I'm using it this way:
x_apply('#fileuploader', 'thereisfiles', true);
By the way, sorry for my english
You have to set to element_blank()
in theme()
elements you need to remove
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
<button style="position: absolute; left: 20%; right: 20%; bottom: 5%;"> Button </button>
You need to escape the backslash \
:
println yourString.replace("\\", "/")
When Python2.x sees a == b
, it tries the following.
type(b)
is a new-style class, and type(b)
is a subclass of type(a)
, and type(b)
has overridden __eq__
, then the result is b.__eq__(a)
.type(a)
has overridden __eq__
(that is, type(a).__eq__
isn't object.__eq__
), then the result is a.__eq__(b)
.type(b)
has overridden __eq__
, then the result is b.__eq__(a)
.__cmp__
. If it exists, the objects are equal iff it returns zero
.object.__eq__(a, b)
, which is True
iff a
and b
are the same object.If any of the special methods return NotImplemented
, Python acts as though the method didn't exist.
Note that last step carefully: if neither a
nor b
overloads ==
, then a == b
is the same as a is b
.
Switch to AppCompatActivity and add a 25 dp paddingTop on the toolbar and turn on
<item name="android:windowTranslucentStatus">true</item>
Then, the will toolbar go up top the top
If it's available to you, then it's difficult to think of a reason not to use the Java 5 executor framework. Calling:
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
will give you a ScheduledExecutorService
with similar functionality to Timer
(i.e. it will be single-threaded) but whose access may be slightly more scalable (under the hood, it uses concurrent structures rather than complete synchronization as with the Timer
class). Using a ScheduledExecutorService
also gives you advantages such as:
newScheduledThreadPoolExecutor()
or the ScheduledThreadPoolExecutor
class)About the only reasons for sticking to Timer
I can think of are:
For some reason, you're re-instantiating the form after you check is_valid()
. Forms only get a cleaned_data
attribute when is_valid()
has been called, and you haven't called it on this new, second instance.
Just get rid of the second form = SearchForm(request.POST)
and all should be well.
I would recommend using the visual designer built into VS2008, as updating the dbml also updates the code that is generated for you. Modifying the dbml outside of the visual designer would result in the underlying code being out of sync.
You must reload your TableView in main thread only. Otherwise your app will be crashed or will be updated after some time. For every UI update it is recommended to use main thread.
//To update UI only this below code is enough
//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
//Update UI
self.tableView.reloadData()//Your tableView here
})
//Perform some task and update UI immediately.
DispatchQueue.global(qos: .userInitiated).async {
// Call your function here
DispatchQueue.main.async {
// Update UI
self.tableView.reloadData()
}
}
//To call or execute function after some time and update UI
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
//Here call your function
//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
//Update UI
self.tableView.reloadData()
})
}
If you're using AVD manager add a hardware property Keyboard support and set it to false.
That should disable the shown keyboard, and show the virtual one.
In my case I had to add the public key to my repo (at Bitbucket) AND use git clone once via ssh to answer yes to the "known host" question the first time.
I am using API level 27 and found a best solution after struggling for around two days. If you want to read a xml file from a class which doesn't derive from Activity or Application then do the following.
Put the testdata.xml file inside the assets directory.
Write the following code to get the testdata document parsed.
InputStream inputStream = this.getClass().getResourceAsStream("/assets/testdata.xml");
// create a new DocumentBuilderFactory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// use the factory to create a documentbuilder
DocumentBuilder builder = factory.newDocumentBuilder();
// create a new document from input stream
Document doc = builder.parse(inputStream);
I jumped here looking for the very same thing, but none worked for me.
There are instances where regardless what you do, and depending on the system (Oracle Designer: Oracle 11g - PL/SQL), divs will always go to the next line, in which case you should use the span tag instead.
This worked wonders for me.
<span float: left; white-space: nowrap; overflow: hidden; onmouseover="rollOverImageSectionFiveThreeOne(this)">
<input type="radio" id="radio4" name="p_verify_type" value="SomeValue" />
</span>
Just Your Text ||
<span id="headerFiveThreeOneHelpText" float: left; white-space: nowrap; overflow: hidden;></span>
dynamic myDynamic = new { PropertyOne = true, PropertyTwo = false};
With negative lookahead, regular expression can match something not contains specific pattern. This is answered and explained by Bart Kiers. Great explanation!
However, with Bart Kiers' answer, the lookahead part will test 1 to 4 characters ahead while matching any single character. We can avoid this and let the lookahead part check out the whole text, ensure there is no 'hede', and then the normal part (.*) can eat the whole text all at one time.
Here is the improved regex:
/^(?!.*?hede).*$/
Note the (*?) lazy quantifier in the negative lookahead part is optional, you can use (*) greedy quantifier instead, depending on your data: if 'hede' does present and in the beginning half of the text, the lazy quantifier can be faster; otherwise, the greedy quantifier be faster. However if 'hede' does not present, both would be equal slow.
Here is the demo code.
For more information about lookahead, please check out the great article: Mastering Lookahead and Lookbehind.
Also, please check out RegexGen.js, a JavaScript Regular Expression Generator that helps to construct complex regular expressions. With RegexGen.js, you can construct the regex in a more readable way:
var _ = regexGen;
var regex = _(
_.startOfLine(),
_.anything().notContains( // match anything that not contains:
_.anything().lazy(), 'hede' // zero or more chars that followed by 'hede',
// i.e., anything contains 'hede'
),
_.endOfLine()
);
you have to pass values with the single quotes
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: '145'}), //variables should be pass like this
success: function(data){
console.log(data);
}
});
$.ajax({
url:'ajax.php',
data:"",
dataType:'json',
success:function(data1){
var y1=data1;
console.log(data1);
}
});
});
});
try it it may work.......
Bump...
I just had the same error. I noticed that I was invoking super.doPost(request, response);
when overriding the doPost()
method as well as explicitly invoking the superclass constructor
public ScheduleServlet() {
super();
// TODO Auto-generated constructor stub
}
As soon as I commented out the super.doPost(request, response);
from within doPost()
statement it worked perfectly...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//super.doPost(request, response);
// More code here...
}
Needless to say, I need to re-read on super()
best practices :p
Add
<form target="_blank" ...></form>
or
form.setAttribute("target", "_blank");
to your form's definition.
Use the matplotlib savefig
function with the keyword argument transparent=True
to save the image as a png file.
In [30]: x = np.linspace(0,6,31)
In [31]: y = np.exp(-0.5*x) * np.sin(x)
In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]
In [33]: savefig('demo.png', transparent=True)
Result:
Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display
command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.
I struggled with the same issue when trying to feed floats to the classifiers. I wanted to keep floats and not integers for accuracy. Try using regressor algorithms. For example:
import numpy as np
from sklearn import linear_model
from sklearn import svm
classifiers = [
svm.SVR(),
linear_model.SGDRegressor(),
linear_model.BayesianRidge(),
linear_model.LassoLars(),
linear_model.ARDRegression(),
linear_model.PassiveAggressiveRegressor(),
linear_model.TheilSenRegressor(),
linear_model.LinearRegression()]
trainingData = np.array([ [2.3, 4.3, 2.5], [1.3, 5.2, 5.2], [3.3, 2.9, 0.8], [3.1, 4.3, 4.0] ])
trainingScores = np.array( [3.4, 7.5, 4.5, 1.6] )
predictionData = np.array([ [2.5, 2.4, 2.7], [2.7, 3.2, 1.2] ])
for item in classifiers:
print(item)
clf = item
clf.fit(trainingData, trainingScores)
print(clf.predict(predictionData),'\n')
Problem
No, Media Queries cannot be used in this way
<span style="@media (...) { ... }"></span>
Solution
But if you want provided a specific behavior usable on the fly AND responsive, you can use the style
markup and not the attribute.
e.i.
<style scoped>
.on-the-fly-behavior {
background-image: url('particular_ad.png');
}
@media (max-width: 300px) {
.on-the-fly-behavior {
background-image: url('particular_ad_small.png');
}
}
</style>
<span class="on-the-fly-behavior"></span>
See the code working in live on CodePen
In my Blog for example, I inject a <style>
markup in <head>
just after <link>
declaration for CSS and it's contain the content of a textarea provided beside of real content textarea for create extra-class on the fly when I wrote an artitle.
Note : the scoped
attribute is a part of HTML5 specification. If you do not use it, the validator will blame you but browsers currently not support the real purpose : scoped the content of <style>
only on immediatly parent element and that element's child elements. Scoped is not mandatory if the <style>
element is in <head>
markup.
UPDATE: I advice to always use rules in the mobile first way so previous code should be:
<style scoped>
/* 0 to 299 */
.on-the-fly-behavior {
background-image: url('particular_ad_small.png');
}
/* 300 to X */
@media (min-width: 300px) { /* or 301 if you want really the same as previously. */
.on-the-fly-behavior {
background-image: url('particular_ad.png');
}
}
</style>
<span class="on-the-fly-behavior"></span>
Thanks for all answers above, but for me, I can not find Base64Encoder class, so I sort out my way anyway.
public static void main(String[] args) {
try {
DefaultHttpClient Client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("https://httpbin.org/basic-auth/user/passwd");
String encoding = DatatypeConverter.printBase64Binary("user:passwd".getBytes("UTF-8"));
httpGet.setHeader("Authorization", "Basic " + encoding);
HttpResponse response = Client.execute(httpGet);
System.out.println("response = " + response);
BufferedReader breader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder responseString = new StringBuilder();
String line = "";
while ((line = breader.readLine()) != null) {
responseString.append(line);
}
breader.close();
String repsonseStr = responseString.toString();
System.out.println("repsonseStr = " + repsonseStr);
} catch (IOException e) {
e.printStackTrace();
}
}
One more thing, I also tried
Base64.encodeBase64String("user:passwd".getBytes());
It does NOT work due to it return a string almost same with
DatatypeConverter.printBase64Binary()
but end with "\r\n", then server will return "bad request".
Also following code is working as well, actually I sort out this first, but for some reason, it does NOT work in some cloud environment (sae.sina.com.cn if you want to know, it is a chinese cloud service). so have to use the http header instead of HttpClient credentials.
public static void main(String[] args) {
try {
DefaultHttpClient Client = new DefaultHttpClient();
Client.getCredentialsProvider().setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("user", "passwd")
);
HttpGet httpGet = new HttpGet("https://httpbin.org/basic-auth/user/passwd");
HttpResponse response = Client.execute(httpGet);
System.out.println("response = " + response);
BufferedReader breader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder responseString = new StringBuilder();
String line = "";
while ((line = breader.readLine()) != null) {
responseString.append(line);
}
breader.close();
String responseStr = responseString.toString();
System.out.println("responseStr = " + responseStr);
} catch (IOException e) {
e.printStackTrace();
}
}
Thanks for the idea of breaking down a formula Werner!
Using Alt+Enter allows one to put each bit of a complex substitute formula on separate lines: they become easier to follow and automatically line themselves up when Enter is pressed.
Just make sure you have enough end statements to match the number of substitute(
lines either side of the cell reference.
As in this example:
=
substitute(
substitute(
substitute(
substitute(
B11
,"(","")
,")","")
,"[","")
,"]","")
becomes:
=
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE(B12,"(",""),")",""),"[",""),"]","")
which works fine as is, but one can always delete the extra paragraphs manually:
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(B12,"(",""),")",""),"[",""),"]","")
Name > substitute()
[American Samoa] > American Samoa
With Spark 2.4+, if you want to load a csv from a local directory, then you can use 2 sessions and load that into hive. The first session should be created with master() config as "local[*]" and the second session with "yarn" and Hive enabled.
The below one worked for me.
import org.apache.log4j.{Level, Logger}
import org.apache.spark._
import org.apache.spark.rdd._
import org.apache.spark.sql._
object testCSV {
def main(args: Array[String]) {
Logger.getLogger("org").setLevel(Level.ERROR)
val spark_local = SparkSession.builder().appName("CSV local files reader").master("local[*]").getOrCreate()
import spark_local.implicits._
spark_local.sql("SET").show(100,false)
val local_path="/tmp/data/spend_diversity.csv" // Local file
val df_local = spark_local.read.format("csv").option("inferSchema","true").load("file://"+local_path) // "file://" is mandatory
df_local.show(false)
val spark = SparkSession.builder().appName("CSV HDFS").config("spark.sql.warehouse.dir", "/apps/hive/warehouse").enableHiveSupport().getOrCreate()
import spark.implicits._
spark.sql("SET").show(100,false)
val df = df_local
df.createOrReplaceTempView("lcsv")
spark.sql(" drop table if exists work.local_csv ")
spark.sql(" create table work.local_csv as select * from lcsv ")
}
When ran with spark2-submit --master "yarn" --conf spark.ui.enabled=false testCSV.jar
it went fine and created the table in hive.
The easiest way would be using Substring
string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);
Using the overload with one int
as I put would get the substring
of a string
, starting from the index int
. In your case being str.Length - 3
, since you want to get the last three chars.
In my case I had two issues...
1) no listener at all because of running app from another entry file and this run script was deleted from package.json "scripts"
2) Case sensitive problem with 'Sequelize' instead of 'sequelize'
Maybe powershell -Command "Get-AppLockerFileInformation....."
Take a look at powershell /?
If Character.isLetter(ch)
looks a bit wordy/ugly you can use a static import.
import static java.lang.Character.*;
if(isLetter(ch)) {
} else if(isDigit(ch)) {
}
- Can someone give a simple definition of what
Record
is?
A Record<K, T>
is an object type whose property keys are K
and whose property values are T
. That is, keyof Record<K, T>
is equivalent to K
, and Record<K, T>[K]
is (basically) equivalent to T
.
- Is
Record<K,T>
merely a way of saying "all properties on this object will have typeT
"? Probably not all objects, sinceK
has some purpose...
As you note, K
has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>
, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }
.
- Does the
K
generic forbid additional keys on the object that are notK
, or does it allow them and just indicate that their properties are not transformed toT
?
It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:
declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'
and it would treat them as excess properties which are sometimes rejected:
declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties
and sometimes accepted:
const y = {a: "hey", b: "you"};
acceptR(y); // okay
With the given example:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
Is it exactly the same as this?:
type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
Yes!
Hope that helps. Good luck!
Your /home/gnu/bin/c++
seem to require additional flag to link things properly and CMake doesn't know about that.
To use /usr/bin/c++
as your compiler run cmake
with -DCMAKE_CXX_COMPILER=/usr/bin/c++
.
Also, CMAKE_PREFIX_PATH
variable sets destination dir where your project' files should be installed. It has nothing to do with CMake installation prefix and CMake itself already know this.
<view
android:id="@+id/blackLine"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#000000"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
_x000D_
app:layout_constraintStart_toStartOf="parent"/>
I just tried SMTPop and it worked.
smtpop.dll
reference to my C# .NET projectWrote the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmtPop;
namespace SMT_POP3 {
class Program {
static void Main(string[] args) {
SmtPop.POP3Client pop = new SmtPop.POP3Client();
pop.Open("<hostURL>", 110, "<username>", "<password>");
// Get message list from POP server
SmtPop.POPMessageId[] messages = pop.GetMailList();
if (messages != null) {
// Walk attachment list
foreach(SmtPop.POPMessageId id in messages) {
SmtPop.POPReader reader= pop.GetMailReader(id);
SmtPop.MimeMessage msg = new SmtPop.MimeMessage();
// Read message
msg.Read(reader);
if (msg.AddressFrom != null) {
String from= msg.AddressFrom[0].Name;
Console.WriteLine("from: " + from);
}
if (msg.Subject != null) {
String subject = msg.Subject;
Console.WriteLine("subject: "+ subject);
}
if (msg.Body != null) {
String body = msg.Body;
Console.WriteLine("body: " + body);
}
if (msg.Attachments != null && false) {
// Do something with first attachment
SmtPop.MimeAttachment attach = msg.Attachments[0];
if (attach.Filename == "data") {
// Read data from attachment
Byte[] b = Convert.FromBase64String(attach.Body);
System.IO.MemoryStream mem = new System.IO.MemoryStream(b, false);
//BinaryFormatter f = new BinaryFormatter();
// DataClass data= (DataClass)f.Deserialize(mem);
mem.Close();
}
// Delete message
// pop.Dele(id.Id);
}
}
}
pop.Quit();
}
}
}
This post already has a checked answer, but the answer doesn't filter for null values. The correct answer should prevent null values by using the Object::nonNull function as a predicate.
BigDecimal result = invoiceList.stream()
.map(Invoice::total)
.filter(Objects::nonNull)
.filter(i -> (i.getUnit_price() != null) && (i.getQuantity != null))
.reduce(BigDecimal.ZERO, BigDecimal::add);
This prevents null values from attempting to be summed as we reduce.
For putting a whole pdf in your file and not just 1 page, use:
\usepackage{pdfpages}
\includepdf[pages=-]{myfile.pdf}
$('#id-submit').click(function () {
$("input").val(function(i,val) {
return val.toUpperCase();
});
});
For simplicity, If you need to default to some value if nil you can use:
@something.nil? = "No" || "Yes"
Note that usage of a SerialPort.DataReceived
event is optional. You can set proper timeout using SerialPort.ReadTimeout
and continuously call SerialPort.Read()
after you wrote something to a port until you get a full response.
Moreover you can use SerialPort.BaseStream
property to extract an underlying Stream
instance. The benefit of using a Stream
is that you can easily utilize various decorators with it:
var port = new SerialPort();
// LoggingStream inherits Stream, implements IDisposable, needen abstract methods and
// overrides needen virtual methods.
Stream portStream = new LoggingStream(port.BaseStream);
portStream.Write(...); // Logs write buffer.
portStream.Read(...); // Logs read buffer.
For more information check:
Another solution is to use stat_count()
when dealing with discrete variables (and stat_bin()
with continuous ones).
ggplot(data = df, aes(x = x)) +
geom_bar(stat = "count") +
stat_count(geom = "text", colour = "white", size = 3.5,
aes(label = ..count..),position=position_stack(vjust=0.5))
Had the same problem when running the nodemon command so i reduced the name of files open in sublime text and the error dissappeared.
If you want to get a sub list including the last element, you leave blank after colon:
>>> ll=range(10)
>>> ll
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ll[5:]
[5, 6, 7, 8, 9]
>>> ll[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Why not just use NSMutableAttributedString?
let attributedString = NSMutableAttributedString(string: "Want to learn iOS? Just visit developer.apple.com!")
attributedString.addAttribute(.link, value: "https://developer.apple.com", range: NSRange(location: 30, length: 50))
myView.attributedText = attributedString
You can find more details here
myDate.ToString("yyyy-MM-dd HH:mm:ss")
the capital HH is for 24 hours format as you specified
I came across the same problem but no forum could help me, after some minutes I came out with an idea:
match(ColumnHeader,Table1[#Headers],0)
This will return you the number.
The reduce function also works
import operator
h=['a','b','c','d']
reduce(operator.add, h)
'abcd'
The problem here is in your explode statement
//$item['date'] presumably = 20120514. Do a print of this
$eventDate = trim($item['date']);
//This explodes on , but there is no , in $eventDate
//You also have a limit of 2 set in the below explode statement
$myarray = (explode(',', $eventDate, 2));
//$myarray is currently = to '20'
foreach ($myarray as $value) {
//Now you are iterating through a string
echo $value;
}
Try changing your initial $item['date'] to be 2012,04,30 if that's what you're trying to do. Otherwise I'm not entirely sure what you're trying to print.
I just add this line at the ViewDidLoad function and problem fixed.
tableView.tableFooterView = [[UIView alloc] init];
If multiple criteria use countifs
=countifs(A1:A10,">""",B1:B10,">""")
The " >"" "
looks at the greater than being empty. This formula looks for two criteria and neither column can be empty on the same row for it to count. If just counting one column do this with the one criteria (i.e. Use everything before B1:B10
not including the comma)
I used below code to change Navigation drawer text color in my app.
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setItemTextColor(ColorStateList.valueOf(Color.WHITE));
Cited from Technical Q&A QA1886:
Swift app crashes when trying to reference Swift library libswiftCore.dylib.
Q: What can I do about the libswiftCore.dylib loading error in my device's console that happens when I try to run my Swift language app?
A: To correct this problem, you will need to sign your app using code signing certificates with the Subject Organizational Unit (OU) set to your Team ID. All Enterprise and standard iOS developer certificates that are created after iOS 8 was released have the new Team ID field in the proper place to allow Swift language apps to run.
Usually this error appears in the device's console log with a message similar to one of the following: [....] [deny-mmap] mapped file has no team identifier and is not a platform binary: /private/var/mobile/Containers/Bundle/Application/5D8FB2F7-1083-4564-94B2-0CB7DC75C9D1/YourAppNameHere.app/Frameworks/libswiftCore.dylib
Dyld Error Message:
Library not loaded: @rpath/libswiftCore.dylib
Exception Type: EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x0000000120021088
Triggered by Thread: 0
Referenced from: /private/var/mobile/Containers/Bundle/Application/C3DCD586-2A40-4C7C-AA2B-64EDAE8339E2/TestApp.app/TestApp
Reason: no suitable image found. Did find:
/private/var/mobile/Containers/Bundle/Application/C3DCD586-2A40-4C7C-AA2B-64EDAE8339E2/TestApp.app/Frameworks/libswiftCore.dylib: mmap() error 1 at address=0x1001D8000, size=0x00194000 segment=__TEXT in Segment::map() mapping /private/var/mobile/Containers/Bundle/Application/C3DCD586-2A40-4C7C-AA2B-64EDAE8339E2/TestApp.app/Frameworks/libswiftCore.dylib
Dyld Version: 353.5
The new certificates are needed when building an archive and packaging your app. Even if you have one of the new certificates, just resigning an existing swift app archive won’t work. If it was built with a pre-iOS 8 certificate, you will need to build another archive.
Important: Please use caution if you need to revoke and setup up a new Enterprise Distribution certificate. If you are an in-house Enterprise developer you will need to be careful that you do not revoke a distribution certificate that was used to sign an app any one of your Enterprise employees is still using as any apps that were signed with that enterprise distribution certificate will stop working immediately. The above only applies to Enterprise Distribution certificates. Development certs are safe to revoke for enterprise/standard iOS developers.
As the AirSign guys state the problem roots from the missing OU attribute in the subject field of the In-House certificate.
Subject: UID=269J2W3P2L, CN=iPhone Distribution: Company Name, OU=269J2W3P2L, O=Company Name, C=FR
I have an enterprise development certificate, creating a new one solved the issue.
I guess it would be best to fix the database startup script itself. But as a work around, you can add that line to /etc/rc.local
, which is executed about last in init phase.
This is what a constant expression in Java looks like:
package com.mycompany.mypackage;
public class MyLinks {
// constant expression
public static final String GUESTBOOK_URL = "/guestbook";
}
You can use it with annotations as following:
import com.mycompany.mypackage.MyLinks;
@WebServlet(urlPatterns = {MyLinks.GUESTBOOK_URL})
public class GuestbookServlet extends HttpServlet {
// ...
}
Also see here
@FXML
private void mnuUserLevel_onClick(ActionEvent event) {
FXMLLoader loader = new FXMLLoader(getClass().getResource("DBedit.fxml"));
loader.setController(new DBeditEntityUserlevel());
try {
Node n = (Node)loader.load();
AnchorPane.setTopAnchor(n, 0.0);
AnchorPane.setRightAnchor(n, 0.0);
AnchorPane.setLeftAnchor(n, 0.0);
AnchorPane.setBottomAnchor(n, 0.0);
mainContent.getChildren().setAll(n);
} catch (IOException e){
System.out.println(e.getMessage());
}
}
The scenario is to load a child fxml into parent AnchorPane. To make the child to stretch in accords to its parent use AnChorPane.setxxxAnchor command.
pls refer this https://stackoverflow.com/a/1972404/951045
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
mngr.getDeviceId();
add READ_PHONE_STATE
permission to AndroidManifest.xml
Roman Samoylenko's answer was correct except the function has changed. The correct answer is
Glide.with(context)
.load(yourImage)
.apply(RequestOptions.circleCropTransform())
.into(imageView);
Error handling and making your code reusable is key. I added string to int validation and it is possible to add other types if needed. Solving this problem with a more reusable solution could be this:
public class Sample
{
public Sample(object inputToInt)
{
_intField = objectToInt(inputToInt);
}
public int IntProperty => _intField;
private readonly int _intField;
}
public static int objectToInt(object inputToInt)
{
switch (inputToInt)
{
case int inputInt:
return inputInt;
break;
case string inputString:
if (!int.TryParse(inputString, out int parsedInt))
{
throw new InvalidParameterException($"The input {inputString} could not be parsed to int");
}
return parsedInt;
default:
throw new InvalidParameterException($"Constructor do not support {inputToInt.GetType().Name}");
break;
}
}
Instead of using the pyodbc library, use the pypyodbc library... This worked for me.
import pypyodbc
conn = pypyodbc.connect("DRIVER={SQL Server};"
"SERVER=server;"
"DATABASE=database;"
"Trusted_Connection=yes;")
cursor = conn.cursor()
cursor.execute('SELECT * FROM [table]')
for row in cursor:
print('row = %r' % (row,))
This is done by event delegation. Event will get bind on wrapper-class element but will be delegated to selector-class element. This is how it works.
$('.wrapper-class').on("click", '.selector-class', function() {
// Your code here
});
And HTML
<div class="wrapper-class">
<button class="selector-class">
Click Me!
</button>
</div>
#Note:
wrapper-class element can be anything ex. document, body or your wrapper. Wrapper should already exist. However, selector
doesn't necessarily needs to be presented at page loading time. It may come later and the event will bind on selector
without fail.
Use:
pip install -r requirements.txt
For further details, please check the help option:
pip install --help
We can find the option '-r' -
-r, --requirement Install from the given requirements file. This option can be used multiple times.
Further information on some commonly used pip install options (this is the help option on the pip install command):
Also the above is the complete set of options. Please use pip install --help
for the complete list of options.
Java 13 added a method which does this: String#translateEscapes
.
It was a preview feature in Java 13 and 14, but was promoted to a full feature in Java 15.
Some how the group(1) didnt work for me. I used group(0) to find the url version.
Pattern urlVersionPattern = Pattern.compile("\\/v[0-9][a-z]{0,1}\\/");
Matcher m = urlVersionPattern.matcher(url);
if (m.find()) {
return StringUtils.substringBetween(m.group(0), "/", "/");
}
return "v0";
cls
$exactadminfile = "C:\temp\files\admin" #First folder to check the file
$userfile = "C:\temp\files\user" #Second folder to check the file
$filenames=Get-Content "C:\temp\files\files-to-watch.txt" #Reading the names of the files to test the existance in one of the above locations
foreach ($filename in $filenames) {
if (!(Test-Path $exactadminfile\$filename) -and !(Test-Path $userfile\$filename)) { #if the file is not there in either of the folder
Write-Warning "$filename absent from both locations"
} else {
Write-Host " $filename File is there in one or both Locations" #if file exists there at both locations or at least in one location
}
}
In modern browsers with modern javascript (>= 2015) you can add type="module"
to your script tag, and everything inside that script will execute after whole page loads. e.g:
<script type="module">
alert("runs after") // Whole page loads before this line execute
</script>
<script>
alert("runs before")
</script>
also older browsers will understand nomodule
attribute. Something like this:
<script nomodule>
alert("tuns after")
</script>
For more information you can visit javascript.info.
Actually, you can use two phases to translate your texts in Swift projects:
1) The first phase is using the old way to create all your translatable strings:
NSLocalisedString("Text to translate", comment: "Comment to comment")
1.1) Then you should use genstrings to generate Localizable.strings:
$ genstrings *swift
2) Afterwards, you should use this answer.
2.1) Use your XCode "Find and Replace" option based on the regular expression. As for the given example (if you have no comments) the regular expression will be:
NSLocalizedString\((.*)\, comment:\ \"\"\)
and replace it with
$1.localized
or (if you have comments)
NSLocalizedString\((.*)\, comment:\ (.*)\)
and replace it with
$1.localizedWithComment(comment: $2)
You are free to play with regex and different extension combinations as you wish. The general way is splitting the whole process in two phases. Hope that helps.
I had this issue occurring with mailto:
and tel:
links inside an iframe (in Chrome, not a webview). Clicking the links would show the grey "page not found" page and inspecting the page showed it had a ERR_UNKNOWN_URL_SCHEME error.
Adding target="_blank"
, as suggested by this discussion of the issue fixed the problem for me.
This works for me in PowerShell:
docker run --rm -v ${PWD}:/data alpine ls /data
also you can use this code (pure python by 3 byte of header file):
full_path = os.path.join(MEDIA_ROOT, pathfile)
try:
image_data = open(full_path, "rb").read()
except IOError:
return "Incorrect Request :( !!!"
header_byte = image_data[0:3].encode("hex").lower()
if header_byte == '474946':
return "image/gif"
elif header_byte == '89504e':
return "image/png"
elif header_byte == 'ffd8ff':
return "image/jpeg"
else:
return "binary file"
without any package install [and update version]
Here is what I wrote based on info found on this forum:
This is part of a MyDebugNamespace, Debug is apparently reserved and won't do as namespace name.
var DEBUG = true;
...
if (true == DEBUG && !test)
{
var sAlert = "Assertion failed! ";
if (null != message)
sAlert += "\n" + message;
if (null != err)
sAlert += "\n" + "File: " + err.fileName + "\n" + "Line: " + err.lineNumber;
alert(sAlert);
}
...
How to call:
MyDebugNamespace.Assert(new Error(""), (null != someVar), "Something is wrong!")
I included two functions with variable number of arguments calling this base code in my namespace so as to optionally omit message or error in calls.
This works fine with Firefox, IE6 and Chrome report the fileName and lineNumber as undefined.
we an use handy tools like ssh to accomplish this easily.
I was using ubuntu host and ubuntu based docker image.
when a new port is needed to be mapped out,
inside the docker run the following command
ssh -R8888:localhost:8888 <username>@172.17.0.1
172.17.0.1 was the ip of the docker interface
(you can get this by running
ifconfig docker0 | grep "inet addr" | cut -f2 -d":" | cut -f1 -d" "
on the host).
here I had local 8888 port mapped back to the hosts 8888. you can change the port as needed.
if you need one more port, you can kill the ssh and add one more line of -R to it with the new port.
I have tested this with netcat.
Android has all the tools you need to parse json built-in. Example follows, no need for GSON or anything like that.
Get your JSON:
Assume you have a json string
String result = "{\"someKey\":\"someValue\"}";
Create a JSONObject:
JSONObject jObject = new JSONObject(result);
If your json string is an array, e.g.:
String result = "[{\"someKey\":\"someValue\"}]"
then you should use JSONArray
as demonstrated below and not JSONObject
To get a specific string
String aJsonString = jObject.getString("STRINGNAME");
To get a specific boolean
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");
To get a specific integer
int aJsonInteger = jObject.getInt("INTEGERNAME");
To get a specific long
long aJsonLong = jObject.getLong("LONGNAME");
To get a specific double
double aJsonDouble = jObject.getDouble("DOUBLENAME");
To get a specific JSONArray:
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
To get the items from the array
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
} catch (JSONException e) {
// Oops
}
}
declare @cur cursor
declare @idx int
declare @Approval_No varchar(50)
declare @ReqNo varchar(100)
declare @M_Id varchar(100)
declare @Mail_ID varchar(100)
declare @temp table
(
val varchar(100)
)
declare @temp2 table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)
declare @slice varchar(8000)
declare @String varchar(100)
--set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
set @String = '20131'
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(',',@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
--select @slice
insert into @temp values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
-- select distinct(val) from @temp
SET @cur = CURSOR FOR select distinct(val) from @temp
--open cursor
OPEN @cur
--fetchng id into variable
FETCH NEXT
FROM @cur into @Approval_No
--
--loop still the end
while @@FETCH_STATUS = 0
BEGIN
select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=@Approval_No
insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)
FETCH NEXT
FROM @cur into @Approval_No
end
--close cursor
CLOSE @cur
select * from @tem
Assuming lengths of portfolio and index are the same:
matrix = []
for i in range(len(portfolio)):
matrix.append([portfolio[i], index[i]])
Or a one-liner using list comprehension:
matrix2 = [[portfolio[i], index[i]] for i in range(len(portfolio))]
Following the idea posted by Andrew Seaford, this is done using sshfs:
echo "SuperHardToGuessPass:P" | sshfs -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no [email protected]:/mypath/ /mnt/source-tmp/ -o workaround=rename -o password_stdin
rsync -a /mnt/source-tmp/ /media/destination/
umount /mnt/source-tmp
I don't know that much about batch files but couldn't you have a pre-made batch file copied from the home directory to the path you have that would return a list of the names of the files then use that name?
Here is a link I think might be helpful in making the pre-made batch file.
You appear to have a heredoc
containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc
:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF
or if BUILDING
is $2
in your script:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF
If your file.sql
had an exit
at the end then it would be even simpler as you wouldn't need the heredoc
:
sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2
In your SQL you can then refer to the position parameters using substitution variables:
...
}',SEM_Models('&1'),NULL,
...
The &1
will be replaced with the first value passed to the SQL script, BUILDING
; because that is a string it still needs to be enclosed in quotes. You might want to set verify off
to stop if showing you the substitutions in the output.
You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1
, the second is &2
, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF
or:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF
If total_count
is being passed to your shell script then just use its positional parameter, $4
or whatever. And your SQL would then be:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:
define MY_ALIAS = &1
define MY_MODEL = &2
SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
From your separate question, maybe you just wanted:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
... so the alias will be the same value you're querying on (the value in $2
, or BUILDING
in the original part of the answer). You can refer to a substitution variable as many times as you want.
That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:
select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT
If you set pages 0
and set heading off
, your repeated calls might appear in a neat list. You might also need to set tab off
and possibly use rpad('&1', 20)
or similar to make that column always the same width. Or get the results as CSV with:
select '&1' ||','|| COUNT(*)
Depends what you're using the results for...
Xcopy exit code 4 means "Initialization error occurred. There is not enough memory or disk space, or you entered an invalid drive name or invalid syntax on the command line."
It looks like Visual Studio is supplying invalid arguments to xcopy. Check your post-build event command via Project > Right Click > Properties > Build Events > Post Build Event
.
Note that if the $(ProjectDir)
or similar macro terms have spaces in the resulting paths when expanded, then they will need to be wrapped in double quotes. For example:
xcopy "$(ProjectDir)Library\dsoframer.ocx" "$(TargetDir)" /Y /E /D1
Assuming you already have a JFrame to call this from:
JOptionPane.showMessageDialog(frame, "thank you for using java");
First delete the constraint "fk_comments_projects1" and also its index. After that recreate it.
Checking the Options Over Write Database worked for me :)
They would start by hiding the defining a structure that would hold members necessary for the implementation. Then providing a group of functions that would manipulate the contents of the structure.
Something like this:
typedef struct vec
{
unsigned char* _mem;
unsigned long _elems;
unsigned long _elemsize;
unsigned long _capelems;
unsigned long _reserve;
};
vec* vec_new(unsigned long elemsize)
{
vec* pvec = (vec*)malloc(sizeof(vec));
pvec->_reserve = 10;
pvec->_capelems = pvec->_reserve;
pvec->_elemsize = elemsize;
pvec->_elems = 0;
pvec->_mem = (unsigned char*)malloc(pvec->_capelems * pvec->_elemsize);
return pvec;
}
void vec_delete(vec* pvec)
{
free(pvec->_mem);
free(pvec);
}
void vec_grow(vec* pvec)
{
unsigned char* mem = (unsigned char*)malloc((pvec->_capelems + pvec->_reserve) * pvec->_elemsize);
memcpy(mem, pvec->_mem, pvec->_elems * pvec->_elemsize);
free(pvec->_mem);
pvec->_mem = mem;
pvec->_capelems += pvec->_reserve;
}
void vec_push_back(vec* pvec, void* data, unsigned long elemsize)
{
assert(elemsize == pvec->_elemsize);
if (pvec->_elems == pvec->_capelems) {
vec_grow(pvec);
}
memcpy(pvec->_mem + (pvec->_elems * pvec->_elemsize), (unsigned char*)data, pvec->_elemsize);
pvec->_elems++;
}
unsigned long vec_length(vec* pvec)
{
return pvec->_elems;
}
void* vec_get(vec* pvec, unsigned long index)
{
assert(index < pvec->_elems);
return (void*)(pvec->_mem + (index * pvec->_elemsize));
}
void vec_copy_item(vec* pvec, void* dest, unsigned long index)
{
memcpy(dest, vec_get(pvec, index), pvec->_elemsize);
}
void playwithvec()
{
vec* pvec = vec_new(sizeof(int));
for (int val = 0; val < 1000; val += 10) {
vec_push_back(pvec, &val, sizeof(val));
}
for (unsigned long index = (int)vec_length(pvec) - 1; (int)index >= 0; index--) {
int val;
vec_copy_item(pvec, &val, index);
printf("vec(%d) = %d\n", index, val);
}
vec_delete(pvec);
}
Further to this they would achieve encapsulation by using void* in the place of vec* for the function group, and actually hide the structure definition from the user by defining it within the C module containing the group of functions rather than the header. Also they would hide the functions that you would consider to be private, by leaving them out from the header and simply prototyping them only in the C module.
use this in the command line
c:\Program Files\Java\jdk1.6.25\bin>keytool -list -v -keystore c:\you_key_here.key
In PHP, you can just put an extra $
in front of a variable to make it a dynamic variable :
$$variableName = $value;
While I wouldn't recommend it, you could even chain this behavior :
$$$$$$$$DoNotTryThisAtHomeKids = $value;
You can but are not forced to put $variableName
between {}
:
${$variableName} = $value;
Using {}
is only mandatory when the name of your variable is itself a composition of multiple values, like this :
${$variableNamePart1 . $variableNamePart2} = $value;
It is nevertheless recommended to always use {}
, because it's more readable.
Another reason to always use {}
, is that PHP5 and PHP7 have a slightly different way of dealing with dynamic variables, which results in a different outcome in some cases.
In PHP7, dynamic variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the mix of special cases in PHP5. The examples below show how the order of evaluation has changed.
$$foo['bar']['baz']
${$foo['bar']['baz']}
${$foo}['bar']['baz']
$foo->$bar['baz']
$foo->{$bar['baz']}
$foo->{$bar}['baz']
$foo->$bar['baz']()
$foo->{$bar['baz']}()
$foo->{$bar}['baz']()
Foo::$bar['baz']()
Foo::{$bar['baz']}()
Foo::{$bar}['baz']()
For someone who wants to understand this simple and fast:
First of all, this is not a syntax only to react. this is a syntax from ES6 called Spread syntax which iterate(merge, add..etc) array and object. read more about here
So answer to the question: let's imagine you have this tag:
<UserTag name="Supun" age="66" gender="male" />
and You do this:
const user = {
"name"=>"Joe",
"age"=>"50"
"test"=>"test-val"
};
<UserTag name="Supun" gender="male" {...user} age="66" />
then the tag will equal this:
<UserTag name="Joe" gender="male" test="test-val" age="66" />
So what happened was when you use Spread syntax in a react tag it takes tag's attribute as object attributes which merge(replace if it exists) with the given object user
. also, you might have noticed one thing that it only replaces before attribute, not after attributes. so in this example age remains as it is.
Hopes this helps :)
The default is: no prompt.
You can enable it with -Confirm
or disable it with -Confirm:$false
However, it will still prompt, when the target:
-Recurse
parameter is not specified.-Force
is required to also remove hidden and read-only items etc.
To sum it up:
Remove-Item -Recurse -Force -Confirm:$false
...should cover all scenarios.
When building a GET
request, there is no body to the request, but rather everything goes on the URL. To build a URL (and properly percent escaping it), you can also use URLComponents
.
var url = URLComponents(string: "https://www.google.com/search/")!
url.queryItems = [
URLQueryItem(name: "q", value: "War & Peace")
]
The only trick is that most web services need +
character percent escaped (because they'll interpret that as a space character as dictated by the application/x-www-form-urlencoded
specification). But URLComponents
will not percent escape it. Apple contends that +
is a valid character in a query and therefore shouldn't be escaped. Technically, they are correct, that it is allowed in a query of a URI, but it has a special meaning in application/x-www-form-urlencoded
requests and really should not be passed unescaped.
Apple acknowledges that we have to percent escaping the +
characters, but advises that we do it manually:
var url = URLComponents(string: "https://www.wolframalpha.com/input/")!
url.queryItems = [
URLQueryItem(name: "i", value: "1+2")
]
url.percentEncodedQuery = url.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
This is an inelegant work-around, but it works, and is what Apple advises if your queries may include a +
character and you have a server that interprets them as spaces.
So, combining that with your sendRequest
routine, you end up with something like:
func sendRequest(_ url: String, parameters: [String: String], completion: @escaping ([String: Any]?, Error?) -> Void) {
var components = URLComponents(string: url)!
components.queryItems = parameters.map { (key, value) in
URLQueryItem(name: key, value: value)
}
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
let request = URLRequest(url: components.url!)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, // is there data
let response = response as? HTTPURLResponse, // is there HTTP response
(200 ..< 300) ~= response.statusCode, // is statusCode 2XX
error == nil else { // was there no error, otherwise ...
completion(nil, error)
return
}
let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
completion(responseObject, nil)
}
task.resume()
}
And you'd call it like:
sendRequest("someurl", parameters: ["foo": "bar"]) { responseObject, error in
guard let responseObject = responseObject, error == nil else {
print(error ?? "Unknown error")
return
}
// use `responseObject` here
}
Personally, I'd use JSONDecoder
nowadays and return a custom struct
rather than a dictionary, but that's not really relevant here. Hopefully this illustrates the basic idea of how to percent encode the parameters into the URL of a GET request.
See previous revision of this answer for Swift 2 and manual percent escaping renditions.
import time
import random
import socket
import hashlib
def guid( *args ):
"""
Generates a universally unique ID.
Any arguments only create more randomness.
"""
t = long( time.time() * 1000 )
r = long( random.random()*100000000000000000L )
try:
a = socket.gethostbyname( socket.gethostname() )
except:
# if we can't get a network address, just imagine one
a = random.random()*100000000000000000L
data = str(t)+' '+str(r)+' '+str(a)+' '+str(args)
data = hashlib.md5(data).hexdigest()
return data
Use the -o
option.
git commit -o path/to/myfile -m "the message"
-o, --only commit only specified files
As suggested in an earlier answer, we need to include two additional files - jquery.fileupload-process.js
and then jquery.fileupload-validate.js
However as I need to perform some additional ajax calls while adding a file, I am subscribing to the fileuploadadd
event to perform those calls. Regarding such a usage the author of this plugin suggested the following
Please have a look here: https://github.com/blueimp/jQuery-File-Upload/wiki/Options#wiki-callback-options
Adding additional event listeners via bind (or on method with jQuery 1.7+) method is the preferred option to preserve callback settings by the jQuery File Upload UI version.
Alternatively, you can also simply start the processing in your own callback, like this: https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.fileupload-process.js#L50
Using the combination of the two suggested options, the following code works perfectly for me
$fileInput.fileupload({
url: 'upload_url',
type: 'POST',
dataType: 'json',
autoUpload: false,
disableValidation: false,
maxFileSize: 1024 * 1024,
messages: {
maxFileSize: 'File exceeds maximum allowed size of 1MB',
}
});
$fileInput.on('fileuploadadd', function(evt, data) {
var $this = $(this);
var validation = data.process(function () {
return $this.fileupload('process', data);
});
validation.done(function() {
makeAjaxCall('some_other_url', { fileName: data.files[0].name, fileSizeInBytes: data.files[0].size })
.done(function(resp) {
data.formData = data.formData || {};
data.formData.someData = resp.SomeData;
data.submit();
});
});
validation.fail(function(data) {
console.log('Upload error: ' + data.files[0].error);
});
});
You can use this following code. work just on chrome browser.
function failed(e) {_x000D_
// video playback failed - show a message saying why_x000D_
switch (e.target.error.code) {_x000D_
case e.target.error.MEDIA_ERR_ABORTED:_x000D_
alert('You aborted the video playback.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_NETWORK:_x000D_
alert('A network error caused the video download to fail part-way.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_DECODE:_x000D_
alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:_x000D_
alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');_x000D_
break;_x000D_
default:_x000D_
alert('An unknown error occurred.');_x000D_
break;_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">_x000D_
_x000D_
<head>_x000D_
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />_x000D_
<meta name="author" content="Amin Developer!" />_x000D_
_x000D_
<title>Untitled 1</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<p><video src="http://jell.yfish.us/media/Jellyfish-3-Mbps.mkv" type='video/x-matroska; codecs="theora, vorbis"' autoplay controls onerror="failed(event)" ></video></p>_x000D_
<p><a href="YOU mkv FILE LINK GOES HERE TO DOWNLOAD">Download the video file</a>.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Maybe this is what you're looking for?
string = "line #1"\
"line #2"\
"line #3"
p string # => "line #1line #2line #3"
Based on a previous answer, I have created a function that can also handle brackets. But no dots inside them due to the split.
function get(obj, str) {
return str.split(/\.|\[/g).map(function(crumb) {
return crumb.replace(/\]$/, '').trim().replace(/^(["'])((?:(?!\1)[^\\]|\\.)*?)\1$/, (match, quote, str) => str.replace(/\\(\\)?/g, "$1"));
}).reduce(function(obj, prop) {
return obj ? obj[prop] : undefined;
}, obj);
}
You can create the required headers in a filter too.
@WebFilter(urlPatterns="/rest/*")
public class AllowAccessFilter implements Filter {
@Override
public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException {
System.out.println("in AllowAccessFilter.doFilter");
HttpServletRequest request = (HttpServletRequest)sRequest;
HttpServletResponse response = (HttpServletResponse)sResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(request, response);
}
...
}
Everything in Java is passed by value. In case of an array (which is nothing but an Object), the array reference is passed by value (just like an object reference is passed by value).
When you pass an array to other method, actually the reference to that array is copied.
See this post: Is Java "pass-by-reference" or "pass-by-value"?
See this working example:
public static void changeContent(int[] arr) {
// If we change the content of arr.
arr[0] = 10; // Will change the content of array in main()
}
public static void changeRef(int[] arr) {
// If we change the reference
arr = new int[2]; // Will not change the array in main()
arr[0] = 15;
}
public static void main(String[] args) {
int [] arr = new int[2];
arr[0] = 4;
arr[1] = 5;
changeContent(arr);
System.out.println(arr[0]); // Will print 10..
changeRef(arr);
System.out.println(arr[0]); // Will still print 10..
// Change the reference doesn't reflect change here..
}
Actually you get promise
on $http.get
.
Try to use followed flow:
<li ng-repeat="document in documents" ng-class="IsFiltered(document.Filtered)">
<span><input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" /></span>
<span>{{document.Name}}</span>
</li>
Where documents
is your array.
$scope.documents = [];
$http.get('/Documents/DocumentsList/' + caseId).then(function(result) {
result.data.forEach(function(val, i) {
$scope.documents.push(/* put data here*/);
});
}, function(error) {
alert(error.message);
});
In General:
An example of an easy way to post XML data and get the response (as a string) would be the following function:
public string postXMLData(string destinationUrl, string requestXml)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
return responseStr;
}
return null;
}
In your specific situation:
Instead of:
request.ContentType = "application/x-www-form-urlencoded";
use:
request.ContentType = "text/xml; encoding='utf-8'";
Also, remove:
string postData = "XMLData=" + Sendingxml;
And replace:
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
with:
byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());
rysnc can be useful to run on slow and unreliable connections. So if your download aborts in the middle of a large file rysnc will be able to continue from where it left off when invoked again.
Use rsync -vP username@host:/path/to/file .
The -P option preserves partially downloaded files and also shows progress.
As usual check man rsync
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
var locations = ["http://webPage1.com", "http://webPage2.com"];
var len = locations.length;
var iframe = $('#frame');
var i = 0;
setInterval(function () {
iframe.attr('src', locations[++i % len]);
}, 30000);
});
</script>
</head>
<body>
<iframe id="frame"></iframe>
</body>
</html>
When you join the new thread in the main thread, it will wait until the thread finishes, so the GUI will block even though you are using multithreading.
If you want to place the logic portion in a different class, you can subclass Thread directly, and then start a new object of this class when you press the button. The constructor of this subclass of Thread can receive a Queue object and then you will be able to communicate it with the GUI part. So my suggestion is:
Then you have to solve the problem of what happens if the user clicks two times the same button (it will spawn a new thread with each click), but you can fix it by disabling the start button and enabling it again after you call self.prog_bar.stop()
.
import Queue
class GUI:
# ...
def tb_click(self):
self.progress()
self.prog_bar.start()
self.queue = Queue.Queue()
ThreadedTask(self.queue).start()
self.master.after(100, self.process_queue)
def process_queue(self):
try:
msg = self.queue.get(0)
# Show result of the task if needed
self.prog_bar.stop()
except Queue.Empty:
self.master.after(100, self.process_queue)
class ThreadedTask(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
time.sleep(5) # Simulate long running process
self.queue.put("Task finished")
In my case deleting href attribute solve problem as long there is a click function assign to a.
Try square braces with your $_COOKIE
, not parenthesis. Like this:
<?php
if ($_COOKIE['CaptchaResponseValue'] == "false")
{
header('Location: index.php');
return;
}
?>
I also corrected your location header call a little too.
(answer suitable for a subset of users)
If you're on (any recent) macOS, and even if you're away from your Time Machine disk, the OS will have saved hourly backups, called local snapshots.
Enter Time Machine and navigate to the file you lost. The OS will then ask you:
The location to which you're restoring "file.ext" already contains an
item with the same name. Do you want to replace it with the one you're
restoring?
You should be able to recover the file(s) you lost.
Cannot be done. MsgBox buttons can only have specific values.
You'll have to roll your own form for this.
To create a MsgBox with two options (Yes/No):
MsgBox("Some Text", vbYesNo)
To add to the above answer (do steps 1-5).