Yes, using DateFormat.getDateInstance(int style, Locale aLocale) This displays the current date in a locale-specific way.
So, for example:
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, yourLocale);
String formattedDate = df.format(yourDate);
See the docs for the exact meaning of the style parameter (SHORT
, MEDIUM
, etc)
If you wanted to stay with a class level selector then you could do something like this (using the same jfiddle from Mahn)
$("div.fetch_results input:text").each(function() {
this.value = "testing";
})?
This will select only the text input boxes within the div with a fetch_results class.
As with any jQuery this is just one way to do it. Ask 10 jQuery people this question and you will get 12 answers.
Try this:
-1 * numeric_limits<double>::max()
Reference: numeric_limits
This class is specialized for each of the fundamental types, with its members returning or set to the different values that define the properties that type has in the specific platform in which it compiles.
If you have longer query and you like to use psql then put your query to a file and use the following command:
psql -d my_db_name -t -A -F";" -f input-file.sql -o output-file.csv
http://developer.android.com/reference/android/content/Context.html#BIND_ABOVE_CLIENT
public static final int BIND_ABOVE_CLIENT -- Added in API level 14
Flag for bindService(Intent, ServiceConnection, int)
: indicates that the client application binding to this service considers the service to be more important than the app itself. When set, the platform will try to have the out of memory killer kill the app before it kills the service it is bound to, though this is not guaranteed to be the case.
Other flags of the same group are: BIND_ADJUST_WITH_ACTIVITY, BIND_AUTO_CREATE, BIND_IMPORTANT, BIND_NOT_FOREGROUND, BIND_WAIVE_PRIORITY.
Note that the meaning of BIND_AUTO_CREATE has changed in ICS, and
old applications that don't specify BIND_AUTO_CREATE
will automatically have the flags BIND_WAIVE_PRIORITY
and BIND_ADJUST_WITH_ACTIVITY
set for them.
solve boundary date problem (2020, 01, 01) -> 2019, 12, 31
var now = new Date();
return new Date(now.getMonth() - 1 === 0 ? now.getFullYear() - 1 : now.getFullYear(),
now.getDate() - 1 === 0 ? now.getMonth() - 1: now.getMonth(),
now.getDate() - 1);
You can use replace
go mod init example.com/my/foo
foo/go.mod
module example.com/my/foo
go 1.14
replace example.com/my/bar => /path/to/bar
require example.com/my/bar v1.0.0
foo/main.go
package main
import "example.com/bar"
func main() {
bar.MyFunc()
}
bar/go.mod
module github.com/my/bar
go 1.14
bar/fn.go
package github.com/my/bar
import "fmt"
func MyFunc() {
fmt.Printf("hello")
}
Importing a local package is just like importing an external pacakge
except inside the go.mod file you replace that external package name with a local folder.
The path to the folder can be full or relative /path/to/bar
or ../bar
This solution gives correct results over the entire range [0,UINT_MAX] without requiring digits to be buffered.
It also works for wider types or signed types (with positive values) with appropriate type changes.
This kind of approach is particularly useful on tiny environments (e.g. Arduino bootloader) because it doesn't end up pulling in all the printf() bloat (when printf() isn't used for demo output) and uses very little RAM. You can get a look at value just by blinking a single led :)
#include <limits.h>
#include <stdio.h>
int
main (void)
{
unsigned int score = 42; // Works for score in [0, UINT_MAX]
printf ("score via printf: %u\n", score); // For validation
printf ("score digit by digit: ");
unsigned int div = 1;
unsigned int digit_count = 1;
while ( div <= score / 10 ) {
digit_count++;
div *= 10;
}
while ( digit_count > 0 ) {
printf ("%d", score / div);
score %= div;
div /= 10;
digit_count--;
}
printf ("\n");
return 0;
}
Here is what I have that helps you and others about markdown checkbox table. Enjoy!
| Projects | Operating Systems | Programming Languages | CAM/CAD Programs | Microcontrollers and Processors |
|---------------------------------- |---------------|---------------|----------------|-----------|
| <ul><li>[ ] Blog </li></ul> | <ul><li>[ ] CentOS</li></ul> | <ul><li>[ ] Python </li></ul> | <ul><li>[ ] AutoCAD Electrical </li></ul> | <ul><li>[ ] Arduino </li></ul> |
| <ul><li>[ ] PyGame</li></ul> | <ul><li>[ ] Fedora </li></ul> | <ul><li>[ ] C</li></ul> | <ul><li>[ ] 3DsMax </li></ul> |<ul><li>[ ] Raspberry Pi </li></ul> |
| <ul><li>[ ] Server Info Display</li></ul>| <ul><li>[ ] Ubuntu</li></ul> | <ul><li>[ ] C++ </li></ul> | <ul><li>[ ] Adobe AfterEffects </li></ul> |<ul><li>[ ] </li></ul> |
| <ul><li>[ ] Twitter Subs Bot </li></ul> | <ul><li>[ ] ROS </li></ul> | <ul><li>[ ] C# </li></ul> | <ul><li>[ ] Adobe Illustrator </li></ul> |<ul><li>[ ] </li></ul> |
Yes, you can do ajax request to server with your data in request parameters, like this (very simple):
Note that the following code uses jQuery
jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
and your_functions_address.php like this:
<?php
header('Content-Type: application/json');
$aResult = array();
if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }
if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }
if( !isset($aResult['error']) ) {
switch($_POST['functionname']) {
case 'add':
if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) {
$aResult['error'] = 'Error in arguments!';
}
else {
$aResult['result'] = add(floatval($_POST['arguments'][0]), floatval($_POST['arguments'][1]));
}
break;
default:
$aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
break;
}
}
echo json_encode($aResult);
?>
You appear to have upper and lowercase back to front. A-Z would be upper, a-z would be lower. While not exactly efficient - with the inverted case exception, I think it should output correctly.
You can add super privilege using phpmyadmin
:
Go to PHPMYADMIN > privileges > Edit User > Under Administrator tab Click SUPER. > Go
If you want to do it through Console
, do like this:
mysql> GRANT SUPER ON *.* TO user@'localhost' IDENTIFIED BY 'password';
After executing above code, end it with:
mysql> FLUSH PRIVILEGES;
You should do in on *.*
because SUPER is not the privilege that applies just to one database, it's global.
Just 2 simple steps to solve your issue
First of all check AppendDataBoundItems property and make it assign false
Secondly clear all the items using property .clear()
{
ddl1.Items.Clear();
ddl1.datasource = sql1;
ddl1.DataBind();
}
Pure4J supports what you are after, in two ways.
First, it provides an @ImmutableValue
annotation, so that you can annotate a class to say that it is immutable. There is a maven plugin to allow you to check that your code actually is immutable (use of final
etc.).
Second, it provides the persistent collections from Clojure, (with added generics) and ensures that elements added to the collections are immutable. Performance of these is apparently pretty good. Collections are all immutable, but implement java collections interfaces (and generics) for inspection. Mutation returns new collections.
Disclaimer: I'm the developer of this
I think this is what the OP really wants:
array = -1:0.1:10
for i=1:numel(array)
disp(array(i))
end
Adding one of the blocks below works for me to use KDiff3 for my Windows and Linux development environments. It makes for a nice consistent cross-platform diff and merge tool.
[difftool "kdiff3"]
path = /usr/bin/kdiff3
trustExitCode = false
[difftool]
prompt = false
[diff]
tool = kdiff3
[mergetool "kdiff3"]
path = /usr/bin/kdiff3
trustExitCode = false
[mergetool]
keepBackup = false
[merge]
tool = kdiff3
[difftool "kdiff3"]
path = C:/Progra~1/KDiff3/kdiff3.exe
trustExitCode = false
[difftool]
prompt = false
[diff]
tool = kdiff3
[mergetool "kdiff3"]
path = C:/Progra~1/KDiff3/kdiff3.exe
trustExitCode = false
[mergetool]
keepBackup = false
[merge]
tool = kdiff3
Maybe this can help
string input = "hello123world";
bool isDigitPresent = input.Any(c => char.IsDigit(c));
answer from msdn.
You may write your "main.py" like this:
#!/usr/bin/env python
__all__=["somevar", "do_something"]
somevar=""
def do_something():
pass #blahblah
if __name__=="__main__":
do_something()
That meta tag basically specifies which character set a website is written with.
Here is a definition of UTF-8:
UTF-8 (U from Universal Character Set + Transformation Format—8-bit) is a character encoding capable of encoding all possible characters (called code points) in Unicode. The encoding is variable-length and uses 8-bit code units.
From my test (spring 3.0.5), @RequestMapping(value={"", "/"})
- only "/"
works, ""
does not. However I found out this works: @RequestMapping(value={"/", " * "})
, the " * "
matches anything, so it will be the default handler in case no others.
Here is a solution using INDIRECT, which if you drag the formula, it will pick up different cells from the target sheet accordingly. It uses R1C1 notation and is not limited to working only on columns A-Z.
=INDIRECT("'"&$A$5&"'!R"&ROW()&"C"&COLUMN(),FALSE)
This version picks up the value from the target cell corresponding to the cell where the formula is placed. For example, if you place the formula in 'Summary'!B5 then it will pick up the value from 'SERVER-ONE'!B5, not 'SERVER-ONE'!G7 as specified in the original question. But you could easily add in offsets to the row and column to achieve the desired mapping in any case.
you can set the environment variable JAVA_TOOL_OPTS like as follows, which will be picked by JVM for any application.
set JAVA_TOOL_OPTS=-Djava.net.preferIPv4Stack=true
You can set this from the command prompt or set in system environment variables, based on your need. Note that this will reflect into all the java applications that run in your machine, even if it's a java interpreter that you have in a private setup.
On the side bar of the PHP 7 alpha download page, it does say this:
VC9, VC11 & VC14 More recent versions of PHP are built with VC9, VC11 or VC14 (Visual Studio 2008, 2012 or 2015 compiler respectively) and include improvements in performance and stability.
The VC9 builds require you to have the Visual C++ Redistributable for Visual Studio 2008 SP1 x86 or x64 installed
The VC11 builds require to have the Visual C++ Redistributable for Visual Studio 2012 x86 or x64 installed
The VC14 builds require to have the Visual C++ Redistributable for Visual Studio 2015 x86 or x64 installed
There's been a problem with some of those links, so the files are also available from Softpedia.
In the case of the PHP 7 alpha, it's the last option that's required.
I think that the placement of this information is poor, as it's kind of marginalized (i.e.: it's basically literally in the margin!) whereas it's actually critical for the software to run.
I documented my experiences of getting PHP 7 alpha up and running on Windows 8.1 in PHP: getting PHP7 alpha running on Windows 8.1, and it covers some more symptoms that might crop up. They're out of scope for this question but might help other people.
Other symptom of this issue:
php7apache2_4.dll
is missing despite it definitely being in place, and offering nothing else in any log.php-cgi.exe - The FastCGI process exited unexpectedly
(as per @ftexperts's comment below)Attempted solution:
php7apache2_4.dll
file from an earlier PHP 7 dev build. This did not work.(I include those for googleability.)
Use ==
:
pip install django_modeltranslation==0.4.0-beta2
You can find information relating to setting up a device over WiFi over by the Android ADB Docs.
For devices running Android 11+ see instructions.
For devices running Android 10- see instructions
Since nobody else has mentioned it, I found that the xdebug debugger dramatically increased the time. I served a basic "Hello World, the time is 2020-01-01T01:01:01.010101" dynamic page and used this in my httpd.conf to time the request:
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" **%T/%D**" combined
%T is the serve time in seconds, %D is the time in microseconds. With this in my php.ini:
[XDebug]
xdebug.remote_autostart = 1
xdebug.remote_enable = 1
I was getting around 770ms response times, but with both of those set to 0 to disable them, it jumped to 160ms instantly. Running both of these brought it down to 120ms:
php artisan route:cache
php artisan config:cache
The downside being that if I made config or route changes, I would need to re-cache them, which is annoying.
As a sidenote, oddly, moving the site from my SSD to a spinning HDD provided no performance benefits, which is super odd to me, but I suppose it's maybe cached, I'm on Windows 10 with XAMPP.
You can access the same environment variables from groovy using the same names (e.g. JOB_NAME
or env.JOB_NAME
).
From the documentation:
Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):
env.MYTOOL_VERSION = '1.33' node { sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start' }
These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.
For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job
You can use git checkout.
I tried the accepted solution but got an error, warning: refname '<tagname>' is ambiguous'
But as the answer states, tags do behave like a pointer to a commit, so as you would with a commit hash, you can just checkout the tag. The only difference is you preface it with tags/
:
git checkout tags/<tagname>
return "default" if x is None else x
try the above.
If you use your web server, you ca use Header
On Apache
<VirtualHost>
or in an .htaccess
file.
Header set Access-Control-Allow-Origin 'origin-list'
On Nginx
add_header 'Access-Control-Allow-Origin' 'origin-list'
This is one-liner for parsing query from current URL into array:
parse_str($_SERVER['QUERY_STRING'], $query);
My Spring Data JPA-based answer: I simply added a @Transactional
annotation to my outer method.
The child entity was immediately becoming detached because there was no active Hibernate Session context. Providing a Spring (Data JPA) transaction ensures a Hibernate Session is present.
https://vladmihalcea.com/a-beginners-guide-to-jpa-hibernate-entity-state-transitions/
$('#thisElement').find('.classToSelect')
will find any descendents of #thisElement
with class classToSelect
.
Also, you can use shelljs
plugin.
It's easy and it's cross-platform.
Install command:
npm install [-g] shelljs
What is shellJS
ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts!
An example of how it works:
var shell = require('shelljs');
if (!shell.which('git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');
// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
shell.echo('Error: Git commit failed');
shell.exit(1);
}
Also, you can use from the command line:
$ shx mkdir -p foo
$ shx touch foo/bar.txt
$ shx rm -rf foo
You can use window.scroll()
with behavior: smooth
and top
set to the anchor tag's offset top which ensures that the anchor tag will be at the top of the viewport.
document.querySelectorAll('a[href^="#"]').forEach(a => {
a.addEventListener('click', function (e) {
e.preventDefault();
var href = this.getAttribute("href");
var elem = document.querySelector(href)||document.querySelector("a[name="+href.substring(1, href.length)+"]");
//gets Element with an id of the link's href
//or an anchor tag with a name attribute of the href of the link without the #
window.scroll({
top: elem.offsetTop,
left: 0,
behavior: 'smooth'
});
//if you want to add the hash to window.location.hash
//you will need to use setTimeout to prevent losing the smooth scrolling behavior
//the following code will work for that purpose
/*setTimeout(function(){
window.location.hash = this.hash;
}, 2000); */
});
});
Demo:
a, a:visited{_x000D_
color: blue;_x000D_
}_x000D_
_x000D_
section{_x000D_
margin: 500px 0px; _x000D_
text-align: center;_x000D_
}
_x000D_
<a href="#section1">Section 1</a>_x000D_
<br/>_x000D_
<a href="#section2">Section 2</a>_x000D_
<br/>_x000D_
<a href="#section3">Section 3</a>_x000D_
<br/>_x000D_
<a href="#section4">Section 4</a>_x000D_
<section id="section1">_x000D_
<b style="font-size: 2em;">Section 1</b>_x000D_
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea._x000D_
_x000D_
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram._x000D_
_x000D_
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his._x000D_
_x000D_
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat._x000D_
_x000D_
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.<p/>_x000D_
<section>_x000D_
<section id="section2">_x000D_
<b style="font-size: 2em;">Section 2</b>_x000D_
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea._x000D_
_x000D_
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram._x000D_
_x000D_
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his._x000D_
_x000D_
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat._x000D_
_x000D_
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>_x000D_
<section>_x000D_
<section id="section3">_x000D_
<b style="font-size: 2em;">Section 3</b>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea._x000D_
_x000D_
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram._x000D_
_x000D_
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his._x000D_
_x000D_
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat._x000D_
_x000D_
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>_x000D_
<section>_x000D_
<a style="margin: 500px 0px; color: initial;" name="section4">_x000D_
<b style="font-size: 2em;">Section 4 <i>(this is an anchor tag, not a section)</i></b>_x000D_
</a>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea._x000D_
_x000D_
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram._x000D_
_x000D_
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his._x000D_
_x000D_
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat._x000D_
_x000D_
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>_x000D_
<script>_x000D_
document.querySelectorAll('a[href^="#"]').forEach(a => {_x000D_
a.addEventListener('click', function (e) {_x000D_
e.preventDefault();_x000D_
var href = this.getAttribute("href");_x000D_
var elem = document.querySelector(href)||document.querySelector("a[name="+href.substring(1, href.length)+"]");_x000D_
window.scroll({_x000D_
top: elem.offsetTop, _x000D_
left: 0, _x000D_
behavior: 'smooth' _x000D_
});_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
You can just set the CSS property scroll-behavior
to smooth
(which most modern browsers support) which obviates the need for Javascript.
html, body{_x000D_
scroll-behavior: smooth;_x000D_
}_x000D_
a, a:visited{_x000D_
color: blue;_x000D_
}_x000D_
_x000D_
section{_x000D_
margin: 500px 0px; _x000D_
text-align: center;_x000D_
}
_x000D_
<a href="#section1">Section 1</a>_x000D_
<br/>_x000D_
<a href="#section2">Section 2</a>_x000D_
<br/>_x000D_
<a href="#section3">Section 3</a>_x000D_
<br/>_x000D_
<a href="#section4">Section 4</a>_x000D_
<section id="section1">_x000D_
<b style="font-size: 2em;">Section 1</b>_x000D_
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea._x000D_
_x000D_
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram._x000D_
_x000D_
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his._x000D_
_x000D_
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat._x000D_
_x000D_
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.<p/>_x000D_
<section>_x000D_
<section id="section2">_x000D_
<b style="font-size: 2em;">Section 2</b>_x000D_
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea._x000D_
_x000D_
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram._x000D_
_x000D_
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his._x000D_
_x000D_
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat._x000D_
_x000D_
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>_x000D_
<section>_x000D_
<section id="section3">_x000D_
<b style="font-size: 2em;">Section 3</b>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea._x000D_
_x000D_
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram._x000D_
_x000D_
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his._x000D_
_x000D_
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat._x000D_
_x000D_
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>_x000D_
<section>_x000D_
<a style="margin: 500px 0px; color: initial;" name="section4">_x000D_
<b style="font-size: 2em;">Section 4 <i>(this is an anchor tag, not a section)</i></b>_x000D_
</a>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea._x000D_
_x000D_
Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram._x000D_
_x000D_
Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his._x000D_
_x000D_
Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat._x000D_
_x000D_
Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
_x000D_
Here's another fun solution. This takes advantage of the locals()
dict of a comprehension, i.e. local variables generated inside the list comprehension scope:
>>> [locals().setdefault(i, (elem + locals().get(i-1, 0))) for i, elem
in enumerate(time_interval)]
[4, 10, 22]
Here's what the locals()
looks for each iteration:
>>> [[locals().setdefault(i, (elem + locals().get(i-1, 0))), locals().copy()][1]
for i, elem in enumerate(time_interval)]
[{'.0': <enumerate at 0x21f21f7fc80>, 'i': 0, 'elem': 4, 0: 4},
{'.0': <enumerate at 0x21f21f7fc80>, 'i': 1, 'elem': 6, 0: 4, 1: 10},
{'.0': <enumerate at 0x21f21f7fc80>, 'i': 2, 'elem': 12, 0: 4, 1: 10, 2: 22}]
Performance is not terrible for small lists:
>>> %timeit list(accumulate([4, 6, 12]))
387 ns ± 7.53 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> %timeit np.cumsum([4, 6, 12])
5.31 µs ± 67.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>> %timeit [locals().setdefault(i, (e + locals().get(i-1,0))) for i,e in enumerate(time_interval)]
1.57 µs ± 12 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
And obviously falls flat for larger lists.
>>> l = list(range(1_000_000))
>>> %timeit list(accumulate(l))
95.1 ms ± 5.22 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
>>> %timeit np.cumsum(l)
79.3 ms ± 1.07 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
>>> %timeit np.cumsum(l).tolist()
120 ms ± 1.23 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
>>> %timeit [locals().setdefault(i, (e + locals().get(i-1, 0))) for i, e in enumerate(l)]
660 ms ± 5.14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Even though the method is ugly and not practical, it sure is fun.
This is an old thread, but I'm responding because it still appears high in the list of search results. Now that the future has arrived, you can use the :nth-child pseudo-selector.
p:nth-child(1) { color: blue; }
p.myclass1:nth-child(1) { color: red; }
p.myclass2:nth-child(1) { color: green; }
The :nth-child pseudo-selector is powerful - the parentheses accept formulas as well as numbers.
More here: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
I think that the idea of setting the Auto Return values as described above by Kevin is a bit strange!
Say, for example, that you have a number of websites that use the same PayPal account to handle your payments, or say that you have a number of sections in one website that perform different purchasing tasks, and require different return-addresses when the payment is completed. If I put a button on my page as described above in the 'Sample form using PHP for direct payments' section, you can see that there is a line there:
input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php"
where you set the individual return value. Why does it have to be set generally, in the profile section as well?!?!
Also, because you can only set one value in the Profile Section, it means (AFAIK) that you cannot use the Auto Return on a site with multiple actions.
Comments please??
You want to wrap each number into Math.abs()
. e.g.
System.out.println(Math.abs(-1));
prints out "1".
If you want to avoid writing the Math.
-part, you can include the Math util statically. Just write
import static java.lang.Math.abs;
along with your imports, and you can refer to the abs()
-function just by writing
System.out.println(abs(-1));
public static final String YOUR_STRING_CONSTANT = "";
By specifying the option --user and --ask-password wget will ask for the credentials. Below is an example. Change the username and download link to your needs.
wget --user=username --ask-password https://xyz.com/changelog-6.40.txt
just add them within the main bracket of the if statement like
if ((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')) {
PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}
Logically this can be rewritten in a better way too! This has exactly the same meaning
if (Type == 2 && (PageCount == 0 || PageCount == '')) {
From any class you can't set its value to null. This is not allowed and doesn't make sense also -
public void Delete()
{
this = null; <-- NOT ALLOWED
}
You need an instance of class to call Delete()
method so why not set that instance to null itself once you are done with it.
Car car = new Car();
// Use car objects and once done set back to null
car = null;
Anyhow what you are trying to achieve is not possible in C#. I suspect from your question that you want this because there are memory leaks present in your current design which doesn't let the Car instance to go away. I would suggest you better profile your application and identify the areas which is stopping GC to collect car instance and work on improving that area.
On some OS you get .
..
and .DS_Store
, Well we can't use them so let's us hide them.
First start get all information about the files, using scandir()
// Folder where you want to get all files names from
$dir = "uploads/";
/* Hide this */
$hideName = array('.','..','.DS_Store');
// Sort in ascending order - this is default
$files = scandir($dir);
/* While this to there no more files are */
foreach($files as $filename) {
if(!in_array($filename, $hideName)){
/* echo the name of the files */
echo "$filename<br>";
}
}
In Azure Devops browser(pipeline yaml editor),
Ctrl + K + C Comment Block
Ctrl + K + U Uncomment Block
There also a 'Toggle Block Comment' option but this did not work for me.
There are other 'wierd' ways too: right click to see 'Command Palette' or F1
Now it is just a matter of #
or even smarter [Ctrl + k] + [Ctrl + c]
I find using the pipe character with some top and bottom padding works well. Using a div with a border will require more CSS to vertically align it and get the horizontal spacing even with the other elements.
.divider-vertical {
padding-top: 14px;
padding-bottom: 14px;
}
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li class="divider-vertical">|</li>
<li><a href="#">Faq</a></li>
<li class="divider-vertical">|</li>
<li><a href="#">News</a></li>
<li class="divider-vertical">|</li>
<li><a href="#">Contact</a></li>
</ul>
Did they add a runtime List<> and/or Map<> type class to typepad 1.0
No, providing a runtime is not the focus of the TypeScript team.
is there a solid library out there someone wrote that provides this functionality?
I wrote (really just ported over buckets to typescript): https://github.com/basarat/typescript-collections
JavaScript / TypeScript now support this natively and you can enable them with lib.d.ts
: https://basarat.gitbooks.io/typescript/docs/types/lib.d.ts.html along with a polyfill if you want
INSERT INTO def (field_1, field_2, field3)
VALUES
('$field_1', (SELECT id_user from user_table where name = 'jhon'), '$field3')
false != 'false'
For good measures, put the result of validate into a variable to avoid double validation and use that in the IF statement. Like this:
var result = ValidateForm();
if(result == false) {
...
}
Look here, the operator used is !!
.
I.e. [1,2,3]!!1
gives you 2
, since lists are 0-indexed.
There are two important points to the Swift 2 error handling model: exhaustiveness and resiliency. Together, they boil down to your do
/catch
statement needing to catch every possible error, not just the ones you know you can throw.
Notice that you don't declare what types of errors a function can throw, only whether it throws at all. It's a zero-one-infinity sort of problem: as someone defining a function for others (including your future self) to use, you don't want to have to make every client of your function adapt to every change in the implementation of your function, including what errors it can throw. You want code that calls your function to be resilient to such change.
Because your function can't say what kind of errors it throws (or might throw in the future), the catch
blocks that catch it errors don't know what types of errors it might throw. So, in addition to handling the error types you know about, you need to handle the ones you don't with a universal catch
statement -- that way if your function changes the set of errors it throws in the future, callers will still catch its errors.
do {
let sandwich = try makeMeSandwich(kitchen)
print("i eat it \(sandwich)")
} catch SandwichError.NotMe {
print("Not me error")
} catch SandwichError.DoItYourself {
print("do it error")
} catch let error {
print(error.localizedDescription)
}
But let's not stop there. Think about this resilience idea some more. The way you've designed your sandwich, you have to describe errors in every place where you use them. That means that whenever you change the set of error cases, you have to change every place that uses them... not very fun.
The idea behind defining your own error types is to let you centralize things like that. You could define a description
method for your errors:
extension SandwichError: CustomStringConvertible {
var description: String {
switch self {
case NotMe: return "Not me error"
case DoItYourself: return "Try sudo"
}
}
}
And then your error handling code can ask your error type to describe itself -- now every place where you handle errors can use the same code, and handle possible future error cases, too.
do {
let sandwich = try makeMeSandwich(kitchen)
print("i eat it \(sandwich)")
} catch let error as SandwichError {
print(error.description)
} catch {
print("i dunno")
}
This also paves the way for error types (or extensions on them) to support other ways of reporting errors -- for example, you could have an extension on your error type that knows how to present a UIAlertController
for reporting the error to an iOS user.
Use iconv - see Best way to convert text files between character sets?
The simples way arround is to put -40dp margin at the buttom of the top imageview
You can't access the overflow flag from C/C++.
Some compilers allow you to insert trap instructions into the code. On GCC the option is -ftrapv
.
The only portable and compiler independent thing you can do is to check for overflows on your own. Just like you did in your example.
However, -ftrapv
seems to do nothing on x86 using the latest GCC. I guess it's a leftover from an old version or specific to some other architecture. I had expected the compiler to insert an INTO opcode after each addition. Unfortunately it does not do this.
"files" in *nix type systems are very much an abstract concept.
They can be areas on disk organized by a file system, but they could equally well be a network connection, a bit of shared memory, the buffer output from another process, a screen or a keyboard.
In order for perl to be really useful it mirrors this model very closely, and does not treat files by emulating a magnetic tape as many 4gls do.
So it tried an "IOCTL" operation 'open for write' on a file handle which does not allow write operations which is an inappropriate IOCTL operation for that device/file.
The easiest thing to do is stick an " or die 'Cannot open $myfile'
statement at the end of you open and you can choose your own meaningful message.
In your app or server.js file include this line:
app.use(express.static('public'));
In your index.ejs, following line will help you:
<link rel="stylesheet" type="text/css" href="/css/style.css" />
I hope this helps, it did for me!
In my case I was trying to install Flask. I wanted to run pip install Flask command. But when I open command prompt it I goes to C:\Users[user]>. If you give here it will say pip is not recognized. I did below steps
On your desktop right click Computer and select Properties
Select Advanced Systems Settings
In popup which you see select Advanced tab and then click Environment Variables
In popup double click PATH and from popup copy variable value for variable name PATH and paste the variable value in notepad or so and look for an entry for Python.
In my case it was C:\Users\[user]\AppData\Local\Programs\Python\Python36-32
Now in my command prompt i moved to above location and gave pip install Flask
Setting spring.datasource.tomcat.testOnBorrow=true
in application.properties didn't work.
Programmatically setting like below worked without any issues.
import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;
@Bean
public DataSource dataSource() {
PoolProperties poolProperties = new PoolProperties();
poolProperties.setUrl(this.properties.getDatabase().getUrl());
poolProperties.setUsername(this.properties.getDatabase().getUsername());
poolProperties.setPassword(this.properties.getDatabase().getPassword());
//here it is
poolProperties.setTestOnBorrow(true);
poolProperties.setValidationQuery("SELECT 1");
return new DataSource(poolProperties);
}
You can edit any number of the list using indexes
for example :
items[0] = 5;
items[5] = 100;
You should use copy all the time to declare NSString property
@property (nonatomic, copy) NSString* name;
You should read these for more information on whether it returns immutable string (in case mutable string was passed) or returns a retained string (in case immutable string was passed)
Implement NSCopying by retaining the original instead of creating a new copy when the class and its contents are immutable
So, for our immutable version, we can just do this:
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
vector.clear() is effectively the same as vector.erase( vector.begin(), vector.end() ).
If your problem is about calling delete
for each pointer contained in your vector, try this:
#include <algorithm>
template< typename T >
struct delete_pointer_element
{
void operator()( T element ) const
{
delete element;
}
};
// ...
std::for_each( vector.begin(), vector.end(), delete_pointer_element<int*>() );
Edit: Code rendered obsolete by C++11 range-for.
Run ---> Debug Configuration ---> YourConfiguration ---> Arguments tab
In my case It was totally different since I was not having activity to launch the service in Oreo.
Below are the steps which I used to resolve this foreground service issue -
public class SocketService extends Service {
private String TAG = this.getClass().getSimpleName();
@Override
public void onCreate() {
Log.d(TAG, "Inside onCreate() API");
if (Build.VERSION.SDK_INT >= 26) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.ic_launcher);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// notificationID allows you to update the notification later on.
mNotificationManager.notify(100, mBuilder.build());
startForeground(100, mBuilder.mNotification);
}
Toast.makeText(getApplicationContext(), "inside onCreate()", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent resultIntent, int resultCode, int startId) {
Log.d(TAG, "inside onStartCommand() API");
return startId;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "inside onDestroy() API");
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
And after that to initiate this service I triggered below cmd -
adb -s " + serial_id + " shell am startforegroundservice -n com.test.socket.sample/.SocketService
So this helps me to start service without activity on Oreo devices :)
gensim.utils.deaccent(text) from Gensim - topic modelling for humans:
'Sef chomutovskych komunistu dostal postou bily prasek'
Another solution is unidecode.
Note that the suggested solution with unicodedata typically removes accents only in some character (e.g. it turns 'l'
into ''
, rather than into 'l'
).
If you move from iframes, you may get lost in your page, best way to execute some jquery without issue (with selenimum/python/gecko):
# 1) Get back to the main body page
driver.switch_to.default_content()
# 2) Download jquery lib file to your current folder manually & set path here
with open('./_lib/jquery-3.3.1.min.js', 'r') as jquery_js:
# 3) Read the jquery from a file
jquery = jquery_js.read()
# 4) Load jquery lib
driver.execute_script(jquery)
# 5) Execute your command
driver.execute_script('$("#myId").click()')
It seems to me that the chief difference between the MIT license and GPL is that the MIT doesn't require modifications be open sourced whereas the GPL does.
True - in general. You don't have to open-source your changes if you're using GPL. You could modify it and use it for your own purpose as long as you're not distributing it. BUT... if you DO distribute it, then your entire project that is using the GPL code also becomes GPL automatically. Which means, it must be open-sourced, and the recipient gets all the same rights as you - meaning, they can turn around and distribute it, modify it, sell it, etc. And that would include your proprietary code which would then no longer be proprietary - it becomes open source.
The difference with MIT is that even if you actually distribute your proprietary code that is using the MIT licensed code, you do not have to make the code open source. You can distribute it as a closed app where the code is encrypted or is a binary. Including the MIT-licensed code can be encrypted, as long as it carries the MIT license notice.
is the GPL is more restrictive than the MIT license?
Yes, very much so.
this works with most types of elements:
$('selector').on('click',function(e){
log(e.currentTarget.id);
});
You want to use the onblur event.
<input type="text" name="name" value="value" onblur="alert(1);"/>
for bootstrap 4
add classes :
.full_modal-dialog {
width: 98% !important;
height: 92% !important;
min-width: 98% !important;
min-height: 92% !important;
max-width: 98% !important;
max-height: 92% !important;
padding: 0 !important;
}
.full_modal-content {
height: 99% !important;
min-height: 99% !important;
max-height: 99% !important;
}
and in HTML :
<div role="document" class="modal-dialog full_modal-dialog">
<div class="modal-content full_modal-content">
My guess is that you don't really want to GROUP BY
some_product.
The answer to: "Is there a way to GROUP BY
a column alias such as some_product in this case, or do I need to put this in a subquery and group on that?" is: You can not GROUP BY
a column alias.
The SELECT
clause, where column aliases are assigned, is not processed until after the GROUP BY
clause. An inline view or common table expression (CTE) could be used to make the results available for grouping.
Inline view:
select ...
from (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
from ...
group by col1, col2 ... ) T
group by some_product ...
CTE:
with T as (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
from ...
group by col1, col2 ... )
select ...
from T
group by some_product ...
I have a simpler vanilla js only solution:
For checkboxes:
document.getElementById("id").oninvalid = function () {
this.setCustomValidity(this.checked ? '' : 'My message');
};
For inputs:
document.getElementById("id").oninvalid = function () {
this.setCustomValidity(this.value ? '' : 'My message');
};
Here are few pointers/suggestions for investigation
vote
method which creates a fresh HTTP connection.HttpClient
instance to post to the server. This way it wont create too many connections from the client side. HttpClient
needs to be shut and hence call httpclient.getConnectionManager().shutdown();
to release the resources used by the connections. You can use the following two properties in "colors.xml"
<color name="colorControlNormal">#eeeeee</color>
<color name="colorControlActivated">#eeeeee</color>
colorControlNormal is for the normal view of checkbox, and colorControlActivated is for when the checkbox is checked.
if you are working in the java world - intelliJ idea has also extensive xml support, including xsd generation and samle xml from xsd generation, and with plugins you can get xslt debuggers. - especially nice if you plan to use tools such as jaxb afterwards.
If you use a full screen table you are maybe interested in setting th to display:fixed; and top:0; or try a very similar approach via css.
Update
Just quickly build up a working solution with iframes (html4.0). This example IS NOT standard conform, however you will easily be able to fix it:
outer.html
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Outer</title>
<body>
<iframe src="test.html" width="200" height="100"></iframe>
</body>
</html>
test.html
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Floating</title>
<style type="text/css">
.content{
position:relative;
}
thead{
background-color:red;
position:fixed;
top:0;
}
</style>
<body>
<div class="content">
<table>
<thead>
<tr class="top"><td>Title</td></tr>
</head>
<tbody>
<tr><td>a</td></tr>
<tr><td>b</td></tr>
<tr><td>c</td></tr>
<tr><td>d</td></tr>
<tr><td>e</td></tr>
<tr><td>e</td></tr>
<tr><td>e</td></tr>
<tr><td>e</td></tr>
<tr><td>e</td></tr>
<tr><td>e</td></tr>
</tbody>
</table>
</div>
</body>
</html>
Training Dataset: The sample of data used to fit the model.
Validation Dataset: The sample of data used to provide an unbiased evaluation of a model fit on the training dataset while tuning model hyperparameters. The evaluation becomes more biased as skill on the validation dataset is incorporated into the model configuration.
Test Dataset: The sample of data used to provide an unbiased evaluation of a final model fit on the training dataset.
This is because, in the constructor, you declared a local variable with the same name as an attribute.
To allocate an integer array which all elements are initialized to zero, write this in the constructor:
data = new int[3];
To allocate an integer array which has other initial values, put this code in the constructor:
int[] temp = {2, 3, 7};
data = temp;
or:
data = new int[] {2, 3, 7};
You are right that CSS positioning is the way to go. Here's a quick run down:
position: relative
will layout an element relative to itself. In other words, the elements is laid out in normal flow, then it is removed from normal flow and offset by whatever values you have specified (top, right, bottom, left). It's important to note that because it's removed from flow, other elements around it will not shift with it (use negative margins instead if you want this behaviour).
However, you're most likely interested in position: absolute
which will position an element relative to a container. By default, the container is the browser window, but if a parent element either has position: relative
or position: absolute
set on it, then it will act as the parent for positioning coordinates for its children.
To demonstrate:
#container {_x000D_
position: relative;_x000D_
border: 1px solid red;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
#box {_x000D_
position: absolute;_x000D_
top: 50px;_x000D_
left: 20px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="box">absolute</div>_x000D_
</div>
_x000D_
In that example, the top left corner of #box
would be 100px down and 50px left of the top left corner of #container
. If #container
did not have position: relative
set, the coordinates of #box
would be relative to the top left corner of the browser view port.
Since not all versions of jQuery are created equal, you may run into the same issue I did which means calling $("#item").removeClass(); does not actually remove the class. (Probably a bug)
A more reliable method is to simply use raw JavaScript and remove the class attribute altogether.
document.getElementById("item").removeAttribute("class");
scanf("%2000s %2000[^\n]", a, b);
You can try the following:
gitk --all
You can tell gitk
what to display using anything that git rev-list
understands, so if you just want a few branches, you can do:
gitk master origin/master origin/experiment
... or more exotic things like:
gitk --simplify-by-decoration --all
The 32-bit vs 64-bit difference does become more important when you are interfacing with native libraries. 64-bit Java will not be able to interface with a 32-bit non-Java dll (via JNI)
You will have to save the relationship on the server side. The value is the only part that is transmitted when the form is posted. You could do something nasty like...
<option value="2|Dog">Dog</option>
Then split the result apart if you really wanted to, but that is an ugly hack and a waste of bandwidth assuming the numbers are truly unique and have a one to one relationship with the text.
The best way would be to create an array, and loop over the array to create the HTML. Once the form is posted you can use the value to look up the text in that same array.
Using SSH
git remote add origin ssh://login@IP/path/to/repository
Using HTTP
git remote add origin http://IP/path/to/repository
However having a simple git pull
as a deployment process is usually a bad idea and should be avoided in favor of a real deployment script.
Both stored procedures and functions are named blocks that reside in the database and can be executed as and when required.
The major differences are:
A stored procedure can optionally return values using out parameters, but can also be written in a manner without returning a value. But, a function must return a value.
A stored procedure cannot be used in a SELECT statement whereas a function can be used in a SELECT statement.
Practically speaking, I would go for a stored procedure for a specific group of requirements and a function for a common requirement that could be shared across multiple scenarios. For example: comparing between two strings, or trimming them or taking the last portion, if we have a function for that, we could globally use it for any application that we have.
There is an official Microsoft answer to this question at the following knowledge base article:
Unfortunately, it doesn't appear to work, because the mscorlib.dll version in the 2.0 directory has a 2.0 version, and there is no mscorlib.dll version in either the 3.0 or 3.5 directories even though 3.5 SP1 is installed ... why would the official Microsoft answer be so misinformed?
So what will happen if two threads attack a volatile primitive variable at same time?
Usually each one can increment the value. However sometime, both will update the value at the same time and instead of incrementing by 2 total, both thread increment by 1 and only 1 is added.
Does this mean that whosoever takes lock on it, that will be setting its value first.
There is no lock. That is what synchronized
is for.
And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?
Yes,
What is the difference between Atomic and volatile keyword?
AtomicXxxx wraps a volatile so they are basically same, the difference is that it provides higher level operations such as CompareAndSwap which is used to implement increment.
AtomicXxxx also supports lazySet. This is like a volatile set, but doesn't stall the pipeline waiting for the write to complete. It can mean that if you read a value you just write you might see the old value, but you shouldn't be doing that anyway. The difference is that setting a volatile takes about 5 ns, bit lazySet takes about 0.5 ns.
You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.*
function are thin wrappers that basically do gca().*
.
plt.subplot
returns an axes
object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.
import matplotlib.pyplot as plt
ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])
ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])
and so on for as many axes as you want.
or better, wrap it all up in a loop:
import matplotlib.pyplot as plt
DATA_x = ([1, 2],
[2, 3],
[3, 4])
DATA_y = DATA_x[::-1]
XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3
for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
ax = plt.subplot(1, 3, j + 1)
ax.scatter(x, y)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
That's not really a question of aesthetics, but indeed a technical difference. The directory thinking of it is totally correct and pretty much explaining everything. Let's work it out:
You have a fixed directory structure on your web server and only static files like images, html and so on — no server side scripts or whatsoever.
A browser requests /index.htm
, it exists and is delivered to the client. Later you have lots of - let's say - DVD movies reviewed and a html page for each of them in the /dvd/
directory. Now someone requests /dvd/adams_apples.htm
and it is delivered because it is there.
At some day, someone just requests /dvd/
- which is a directory and the server is trying to figure out what to deliver. Besides access restrictions and so on there are two possibilities: Show the user the directory content (I bet you already have seen this somewhere) or show a default file (in Apache it is: DirectoryIndex: sets the file that Apache will serve if a directory is requested.
)
So far so good, this is the expected case. It already shows the difference in handling, so let's get into it:
(Which is by the way completely understandable.) So, you did something entirely wrong and instead of uploading /dvd/the_big_lebowski.htm
you uploaded that file as dvd
(with no extension) to /
.
Someone bookmarked your /dvd/
directory listing (of course you didn't want to create and always update that nifty index.htm
) and is visiting your web-site. Directory content is delivered - all fine.
Someone heard of your list and is typing /dvd
. And now it is screwed. Instead of your DVD directory listing the server finds a file with that name and is delivering your Big Lebowski file.
So, you delete that file and tell the guy to reload the page. Your server looks for the /dvd
file, but it is gone. Most servers will then notice that there is a directory with that name and tell the client that what it was looking for is indeed somewhere else. The response will most likely be be:
Status Code:301 Moved Permanently
with Location: http://[...]/dvd/
So, totally ignoring what you think about directories or files, the server only can handle such stuff and - unless told differently - decides for you about the meaning of "slash or not".
Finally after receiving this response, the client loads /dvd/
and everything is fine.
Is it fine? No.
You have some dynamic page where everything is passed to /index.php
and gets processed. Everything worked quite good until now, but that entire thing starts to feel slower and you investigate.
Soon, you'll notice that /dvd/list
is doing exactly the same: Redirecting to /dvd/list/
which is then internally translated into index.php?controller=dvd&action=list
. One additional request - but even worse! customer/login
redirects to customer/login/
which in turn redirects to the HTTPS URL of customer/login/
. You end up having tons of unnecessary HTTP redirects (= additional requests) that make the user experience slower.
Most likely you have a default directory index here, too: index.php?controller=dvd
with no action
simply internally loads index.php?controller=dvd&action=list
.
If it ends with /
it can never be a file. No server guessing.
Slash or no slash are entirely different meanings. There is a technical/resource difference between "slash or no slash", and you should be aware of it and use it accordingly. Just because the server most likely loads /dvd/index.htm
- or loads the correct script stuff - when you say /dvd
: It does it, but not because you made the right request. Which would have been /dvd/
.
Omitting the slash even if you indeed mean the slashed version gives you an additional HTTP request penalty. Which is always bad (think of mobile latency) and has more weight than a "pretty URL" - especially since crawlers are not as dumb as SEOs believe or want you to believe ;)
Open the project you want to add it.
Right click on the name.
Then select, add in the active project.
Then the cpp
file will get its link to cbp
.
public class Form1 : Form
{
public Form1()
{
InitializeComponents(); // or whatever that method is called :)
this.button.Click += new RoutedEventHandler(buttonClick);
}
private void buttonClick(object sender, EventArgs e)
{
this.Close();
}
}
This function creates a temporary form, then send data using jQuery :
function postToIframe(data,url,target){
$('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
$.each(data,function(n,v){
$('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
});
$('#postToIframe').submit().remove();
}
target is the 'name' attr of the target iFrame, and data is a JS object :
data={last_name:'Smith',first_name:'John'}
I'm developing cordova apps for 2 years and I spent weeks to solve related problems (eg: webview scrolls when keyboard open). Here's a tested and proven solution for both ios and android
P.S.: I'm using iScroll for scrolling content
Add below to config.xml (first ff after x is opacity)
<preference name="BackgroundColor" value="0xff088c90" />
Handle your scroll position yourself by adding focus events to input elements
iscrollObj.scrollToElement(elm, transitionduration ... etc)
For android, do the same but instead of cordova-plugin-webviewcolor, install cordova-plugin-statusbar and cordova-plugin-navigationbar-color
Here's a javascript code using those plugins to work on both ios and android:
function setStatusColor(colorCode) {
//colorCode is smtg like '#427309';
if (cordova.platformId == 'android') {
StatusBar.backgroundColorByHexString(colorCode);
NavigationBar.backgroundColorByHexString(colorCode);
} else if (cordova.platformId == 'ios') {
window.plugins.webviewcolor.change(colorCode);
}
}
I know this has already been answered, but if you end doing this a lot, regular expressions may be a better way to go:
>>> import re
>>> re.sub(r'\s', '', string).split(',')
['blah', 'lots', 'of', 'spaces', 'here']
The \s
matches any whitespace character, and we just replace it with an empty string ''
. You can find more info here: http://docs.python.org/library/re.html#re.sub
Generally there are two ways to do it, a converter class or a property in the Viewmodel that essentially converts the value for you.
I tend to use the property approach if it is a one off conversion. If you want to reuse it, use the converter. Below, find an example of the converter:
<ValueConversion(GetType(Boolean), GetType(Visibility))> _
Public Class BoolToVisibilityConverter
Implements IValueConverter
Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
If value IsNot Nothing Then
If value = True Then
Return Visibility.Visible
Else
Return Visibility.Collapsed
End If
Else
Return Visibility.Collapsed
End If
End Function
Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
Throw New NotImplementedException
End Function
End Class
A ViewModel property method would just check the boolean property value, and return a visibility based on that. Be sure to implement INotifyPropertyChanged and call it on both the Boolean and Visibility properties to updated properly.
\df+
in psql gives you the sourcecode.
i thing you shuold make this variant to previous query:
SELECT UserId, Value FROM Users U1 WHERE
Date = ( SELECT MAX(Date) FROM Users where UserId = U1.UserId)
We ejected from react-scripts
and so could not simply upgrade the package.json entry to fix this.
Instead, we did this:
1.) in a new directory, create a new project -> $> npx create-react-app foo-project
2.) and then eject it -> cd ./foo-project && npm run eject
3.) now copy the files from /foo-project/config into the config directory of our main app and fire up your dev server
hope this helps others in a similar bind.
Why not having something simpler?
Just call Request.Path
, it will return a String Separated by the "/"
and then you can use .Split('/')[1]
to get the Controller Name.
You need to use
<?php bloginfo('template_directory'); ?>
It returns the directory of the current WordPress theme.
Now for example, if your theme has some image named example.jpg
inside some folder name subfolder
folder in the images
folder.
themes
|-> your theme
|-> images
|->subfolder
|-> examples.jpg
You access it like this
<img class="article-image" src="<?php bloginfo('template_directory'); ?> /images/subfolder/example.jpg" border="0" alt="">
if you are on Windows
sqlplus / as sysdba
Now you are logged with SYS user and you can do anything you want (query DBA_USERS to find out your username, or change any user password). You can not see the old password, you can only change it.
The underlying XMLHttpRequest object used by jQuery will always silently follow redirects rather than return a 302 status code. Therefore, you can't use jQuery's AJAX request functionality to get the returned URL. Instead, you need to put all the data into a form and submit the form with the target
attribute set to the value of the name
attribute of the iframe:
$('#myIframe').attr('name', 'myIframe');
var form = $('<form method="POST" action="url.do"></form>').attr('target', 'myIframe');
$('<input type="hidden" />').attr({name: 'search', value: 'test'}).appendTo(form);
form.appendTo(document.body);
form.submit();
The server's url.do
page will be loaded in the iframe, but when its 302 status arrives, the iframe will be redirected to the final destination.
I can't believe that no one mentioned that MySQL doesn't support Common Table Expressions (CTE) / "with" statements. It's a pretty annoying difference.
For tomcat you can increase the permGem space by using
-XX:MaxPermSize=128m
For this you need to create (if not already exists) a file named setenv.sh in tomcat/bin folder and include following line in it
export JAVA_OPTS="-XX:MaxPermSize=128m"
Reference : http://wiki.razuna.com/display/ecp/Adjusting+Memory+Settings+for+Tomcat
For Ionic (Typescript) you have to double slash in order to scape the characters. For example (this is to match some special characters):
"^(?=.*[\\]\\[!¡\'=ªº\\-\\_ç@#$%^&*(),;\\.?\":{}|<>\+\\/])"
Pay attention to this ] [ - _ . /
characters. They have to be double slashed. If you don't do that, you are going to have a type error in your code.
From plt.imshow()
official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower', extent = [0, 10000, 0, 10], aspect = 1000)
Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.
plt.imshow(data, origin = 'lower', extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')
To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1]
and y_max - y_min = y_res * data.shape[0]
, where extent = [x_min, x_max, y_min, y_max]
. By default, aspect = 1
, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower', extent = [0, 5, 0, 5])
The aspect of color pixel is x_res / y_res
. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])
) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10], aspect = 1.5)
The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10], aspect = 1.2)
Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.
It's declaring the string as nvarchar
data type, rather than varchar
You may have seen Transact-SQL code that passes strings around using an N prefix. This denotes that the subsequent string is in Unicode (the N actually stands for National language character set). Which means that you are passing an NCHAR, NVARCHAR or NTEXT value, as opposed to CHAR, VARCHAR or TEXT.
To quote from Microsoft:
Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. This default code page may not recognize certain characters.
If you want to know the difference between these two data types, see this SO post:
DailyRollingFileAppender is what you exactly searching for.
<appender name="roll" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="application.log" />
<param name="DatePattern" value=".yyyy-MM-dd" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{yyyy-MMM-dd HH:mm:ss,SSS} [%t] %c %x%n %-5p %m%n"/>
</layout>
</appender>
There are lot of different Timers in the .NET BCL:
When to use which?
System.Timers.Timer
, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.System.Threading.Timer
, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.System.Windows.Forms.Timer
(.NET Framework only), a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.System.Web.UI.Timer
(.NET Framework only), an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.System.Windows.Threading.DispatcherTimer
, a timer that's integrated into the Dispatcher queue. This timer is processed with a specified priority at a specified time interval.Some of them needs explicit Start
call to begin ticking (for example System.Timers
, System.Windows.Forms
). And an explicit Stop
to finish ticking.
using TimersTimer = System.Timers.Timer;
static void Main(string[] args)
{
var timer = new TimersTimer(1000);
timer.Elapsed += (s, e) => Console.WriteLine("Beep");
Thread.Sleep(1000); //1 second delay
timer.Start();
Console.ReadLine();
timer.Stop();
}
While on the other hand there are some Timers (like: System.Threading
) where you don't need explicit Start
and Stop
calls. (The provided delegate will run a background thread.) Your timer will tick until you or the runtime dispose it.
So, the following two versions will work in the same way:
using ThreadingTimer = System.Threading.Timer;
static void Main(string[] args)
{
var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
Console.ReadLine();
}
using ThreadingTimer = System.Threading.Timer;
static void Main(string[] args)
{
StartTimer();
Console.ReadLine();
}
static void StartTimer()
{
var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}
But if your timer
disposed then it will stop ticking obviously.
using ThreadingTimer = System.Threading.Timer;
static void Main(string[] args)
{
StartTimer();
GC.Collect(0);
Console.ReadLine();
}
static void StartTimer()
{
var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}
If you use a navigation controller and set its delegate, then the view{Will,Did}{Appear,Disappear} methods are not invoked.
You need to use the navigation controller delegate methods instead:
navigationController:willShowViewController:animated:
navigationController:didShowViewController:animated:
UPDATE Table
SET DateColumn=GETDATE()
WHERE UserID=@UserID
If you're inserting into a table, and will always need to put the current date, I would recommend setting GETDATE()
as the default value for that column, and don't allow NULLs
You can use org.json.JSONObject and org.json.JSONTokener. you don't need any external libraries since these classes come with Android SDK
The solutions here are:
None
as your default value (or a nonce object
), and switch on that to create your values at runtime; orlambda
as your default parameter, and call it within a try block to get the default value (this is the sort of thing that lambda abstraction is for).The second option is nice because users of the function can pass in a callable, which may be already existing (such as a type
)
You probably finally realized this between posting this question and today, but the very nature of selectors makes it impossible to navigate through hierarchically unrelated HTML elements.
Or, to put it simply, since you said in your comment that
there are no uniform parent containers
... it's just not possible with selectors alone, without modifying the markup in some way as shown by the other answers.
You have to use the jQuery .eq()
solution.
The >>
redirection operator will append lines to the end of the specified file, where-as the single greater than >
will empty and overwrite the file.
echo "text" > 'Users/Name/Desktop/TheAccount.txt'
By using new version of jquery (1.8.2), I amend the current code like in this links http://jsfiddle.net/q5EXG/97/
By using the same code, I just change from jQuery to '$'
<a id="send-thoughts" href="">Click</a>
<textarea id="message"></textarea>
$('#send-thoughts').click(function()
{ var thought = $('#message').val();
alert(thought);
});
Configuring the CORS response headers on the server wasn't really an option. You should configure a proxy in client side.
Sample to Angular - So, I created a proxy.conf.json file to act as a proxy server. Below is my proxy.conf.json file:
{
"/api": {
"target": "http://localhost:49389",
"secure": true,
"pathRewrite": {
"^/api": "/api"
},
"changeOrigin": true
}
}
Put the file in the same directory the package.json then I modified the start command in the package.json file like below
"start": "ng serve --proxy-config proxy.conf.json"
now, the http call from the app component is as follows:
return this.http.get('/api/customers').map((res: Response) => res.json());
Lastly to run use npm start or ng serve --proxy-config proxy.conf.json
If you don't want to do it manually use Apache Commons - Codec library. The class you are looking at is: org.apache.commons.codec.net.URLCodec
String final url = "http://www.google.com?...."
String final urlSafe = org.apache.commons.codec.net.URLCodec.encode(url);
I tried the above solutions but it didn't work for me.
This is kind of hack, where you do not have to trigger change.
$("select").select2('destroy').val("").select2();
or
$("select").each(function () { //added a each loop here
$(this).select2('destroy').val("").select2();
});
Here is another work around can be controlled from the backend.
ASPX
<asp:CheckBox ID="Parts_Return_Yes" runat="server" AutoPostBack="false" />
In ASPX.CS
Parts_Return_Yes.InputAttributes["disabled"] = "disabled";
Parts_Return_Yes.InputAttributes["class"] = "disabled-checkbox";
Class is only added for style purposes.
I believe you are looking for -maxdepth 1
.
- (void)zoomMapViewToFitAnnotationsWithExtraZoomToAdjust:(double)extraZoom
{
if ([self.annotations count] == 0) return;
int i = 0;
MKMapPoint points[[self.annotations count]];
for (id<MKAnnotation> annotation in [self annotations])
{
points[i++] = MKMapPointForCoordinate(annotation.coordinate);
}
MKPolygon *poly = [MKPolygon polygonWithPoints:points count:i];
MKCoordinateRegion r = MKCoordinateRegionForMapRect([poly boundingMapRect]);
r.span.latitudeDelta += extraZoom;
r.span.longitudeDelta += extraZoom;
[self setRegion: r animated:YES];
}
Calculate the length of your text line and create a block which is the same size as the line of text. Center the block. If you have two lines you will need two blocks if they are different lengths. You could use a span tag and a br tag if you don't want extra spaces from the blocks. You can also use the pre tag to format inside a block.
And you can do this: style='text-align:center;'
For vertical see: http://www.w3schools.com/cssref/pr_pos_vertical-align.asp
Here is the best way for blocks and web page layouts, go here and learn flex the new standard which started in 2009. http://www.w3.org/TR/2014/WD-css-flexbox-1-20140325/#justify-content-property
Also w3schools has lots of flex examples.
If you are writing Metro app, you should use other code:
Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetTypeInfo().GetDeclaredProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType));
Note:
ship.GetType().GetTypeInfo().GetDeclaredProperty("Latitude");
instead of
ship.GetType().GetProperty("Latitude");
I know it might be out of context but linking a non existed file might cause this issue as it happened to me before.
<!-- bootstrap grid -->
<link rel="stylesheet" href="./css/bootstrap-grid.css" />
If this file does not exist you will face that issue.
Also: your process needs to be suspended for Eclipse to show variables. If it is running, Eclipse won't show any variable.
To suspend a thread, select a thread in the "debug" view, and hit "Suspend"
There are two different ways to clear the terminal in BlueJ. You can get BlueJ to automatically clear the terminal before every interactive method call. To do this, activate the 'Clear screen at method call' option in the 'Options' menu of the terminal. You can also clear the terminal programmatically from within your program. Printing a formfeed character (Unicode 000C) clears the BlueJ terminal, for example:
System.out.print('\u000C');
Somewhere you will need to set a fixed height, instead of using auto everywhere. You will find that if you set a fixed height on your content and/or container, then using auto for things inside it will work.
Also, your boxes will still expand height-wise with more content in, even though you have set a height for it - so don't worry about that :)
#container {
height:500px;
min-height:500px;
}
For those looking for the shortex mutex example:
#include <mutex>
int main() {
std::mutex m;
m.lock();
// do thread-safe stuff
m.unlock();
}
Generally, setting static field by object instance is a bad practice.
to avoid optional issues you can add synchronized
definition, and set it only if private static Logger logger;
@Autowired
public synchronized void setLogger(Logger logger)
{
if (MyClass.logger == null)
{
MyClass.logger = logger;
}
}
:
you have to use rewrite to pass params using proxy_pass here is example I did for angularjs app deployment to s3
S3 Static Website Hosting Route All Paths to Index.html
adopted to your needs would be something like
location /service/ {
rewrite ^\/service\/(.*) /$1 break;
proxy_pass http://apache;
}
if you want to end up in http://127.0.0.1:8080/query/params/
if you want to end up in http://127.0.0.1:8080/service/query/params/ you'll need something like
location /service/ {
rewrite ^\/(.*) /$1 break;
proxy_pass http://apache;
}
I had the same problem and even after turning the symbol loading off, the module loading in Visual Studio was terribly slow.
The solution was to turn off the antivirus software (in my case NOD32) or better yet, to add exceptions to it so that it ignores the paths from which your process is loading assemblies (in my case it is the GAC folder and the Temporary ASP.NET Files folder).
I had similar problem. I needed to write down csv file on driver while I was connect to cluster in client mode.
I wanted to reuse the same CSV parsing code as Apache Spark to avoid potential errors.
I checked spark-csv code and found code responsible for converting dataframe into raw csv RDD[String]
in com.databricks.spark.csv.CsvSchemaRDD
.
Sadly it is hardcoded with sc.textFile
and the end of relevant method.
I copy-pasted that code and removed last lines with sc.textFile
and returned RDD directly instead.
My code:
/*
This is copypasta from com.databricks.spark.csv.CsvSchemaRDD
Spark's code has perfect method converting Dataframe -> raw csv RDD[String]
But in last lines of that method it's hardcoded against writing as text file -
for our case we need RDD.
*/
object DataframeToRawCsvRDD {
val defaultCsvFormat = com.databricks.spark.csv.defaultCsvFormat
def apply(dataFrame: DataFrame, parameters: Map[String, String] = Map())
(implicit ctx: ExecutionContext): RDD[String] = {
val delimiter = parameters.getOrElse("delimiter", ",")
val delimiterChar = if (delimiter.length == 1) {
delimiter.charAt(0)
} else {
throw new Exception("Delimiter cannot be more than one character.")
}
val escape = parameters.getOrElse("escape", null)
val escapeChar: Character = if (escape == null) {
null
} else if (escape.length == 1) {
escape.charAt(0)
} else {
throw new Exception("Escape character cannot be more than one character.")
}
val quote = parameters.getOrElse("quote", "\"")
val quoteChar: Character = if (quote == null) {
null
} else if (quote.length == 1) {
quote.charAt(0)
} else {
throw new Exception("Quotation cannot be more than one character.")
}
val quoteModeString = parameters.getOrElse("quoteMode", "MINIMAL")
val quoteMode: QuoteMode = if (quoteModeString == null) {
null
} else {
QuoteMode.valueOf(quoteModeString.toUpperCase)
}
val nullValue = parameters.getOrElse("nullValue", "null")
val csvFormat = defaultCsvFormat
.withDelimiter(delimiterChar)
.withQuote(quoteChar)
.withEscape(escapeChar)
.withQuoteMode(quoteMode)
.withSkipHeaderRecord(false)
.withNullString(nullValue)
val generateHeader = parameters.getOrElse("header", "false").toBoolean
val headerRdd = if (generateHeader) {
ctx.sparkContext.parallelize(Seq(
csvFormat.format(dataFrame.columns.map(_.asInstanceOf[AnyRef]): _*)
))
} else {
ctx.sparkContext.emptyRDD[String]
}
val rowsRdd = dataFrame.rdd.map(row => {
csvFormat.format(row.toSeq.map(_.asInstanceOf[AnyRef]): _*)
})
headerRdd union rowsRdd
}
}
Here are all of the previous answers summarized:
The code should look like this:
import sys
def hello(a, b):
print "hello and that's your sum:"
sum = a+b
print sum
if __name__== "__main__":
hello(int(sys.argv[1]), int(sys.argv[2]))
Then run the code with this command:
python hello.py 1 1
Old thread, but maybe my answer will help someone. I resolved by executing the query first, then setting an errors variable, then checking if that errors variable array is empty. see simplified example:
$field1 = 'foo';
$field2 = 'bar';
$insert_QUERY = $db->prepare("INSERT INTO table bogus(field1, field2) VALUES (:field1, :field2)");
$insert_QUERY->bindParam(':field1', $field1);
$insert_QUERY->bindParam(':field2', $field2);
$insert_QUERY->execute();
$databaseErrors = $insert_QUERY->errorInfo();
if( !empty($databaseErrors) ){
$errorInfo = print_r($databaseErrors, true); # true flag returns val rather than print
$errorLogMsg = "error info: $errorInfo"; # do what you wish with this var, write to log file etc...
/*
$errorLogMsg will return something like:
error info:
Array(
[0] => 42000
[1] => 1064
[2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table bogus(field1, field2) VALUES ('bar', NULL)' at line 1
)
*/
} else {
# no SQL errors.
}
Here is simple overlay div without using any gif, This can be applied over another div.
<style>
.loader {
position: relative;
border: 16px solid #f3f3f3;
border-radius: 50%;
border-top: 16px solid #3498db;
width: 70px;
height: 70px;
left:50%;
top:50%;
-webkit-animation: spin 2s linear infinite; /* Safari */
animation: spin 2s linear infinite;
}
#overlay{
position: absolute;
top:0px;
left:0px;
width: 100%;
height: 100%;
background: black;
opacity: .5;
}
.container{
position:relative;
height: 300px;
width: 200px;
border:1px solid
}
/* Safari */
@-webkit-keyframes spin {
0% { -webkit-transform: rotate(0deg); }
100% { -webkit-transform: rotate(360deg); }
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
<h2>How To Create A Loader</h2>
<div class="container">
<h3>Overlay over this div</h3>
<div id="overlay">
<div class="loader"></div>
</div>
<div>
We just need to construct a new String
with the array: http://www.mkyong.com/java/how-do-convert-byte-array-to-string-in-java/
String s = new String(bytes);
The bytes of the resulting string differs depending on what charset you use. new String(bytes) and new String(bytes, Charset.forName("utf-8")) and new String(bytes, Charset.forName("utf-16")) will all have different byte arrays when you call String#getBytes() (depending on the default charset)
I know this is an old post but just for reference. Here is how to append without the special case check for an empty list, although at the expense of more complex looking code.
void Append(List * l, Node * n)
{
Node ** next = &list->Head;
while (*next != NULL) next = &(*next)->Next;
*next = n;
n->Next = NULL;
}
How about this?
=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))
The "3" at the end means for column C.
I solved this by have 2 Lists. One list I use for only the adapter, and I do all data changes/updates on the other list. This allows me to do updates on one list in a background thread, and then update the "adapter" list in the main/UI thread:
List<> data = new ArrayList<>();
List<> adapterData = new ArrayList();
...
adapter = new Adapter(adapterData);
listView.setAdapter(adapter);
// Whenever data needs to be updated, it can be done in a separate thread
void updateDataAsync()
{
new Thread(new Runnable()
{
@Override
public void run()
{
// Make updates the "data" list.
...
// Update your adapter.
refreshList();
}
}).start();
}
void refreshList()
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
adapterData.clear();
adapterData.addAll(data);
adapter.notifyDataSetChanged();
listView.invalidateViews();
}
});
}
Here's a great overview on MSDN that covers how to do this.
In your web.config, add a connection string entry:
<connectionStrings>
<add
name="MyConnectionString"
connectionString="Data Source=sergio-desktop\sqlexpress;Initial
Catalog=MyDatabase;User ID=userName;Password=password"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
Let's break down the component parts here:
Data Source is your server. In your case, a named SQL instance on sergio-desktop
.
Initial Catalog is the default database queries should be executed against. For normal uses, this will be the database name.
For the authentication, we have a few options.
User ID and Password means using SQL credentials, not Windows, but still very simple - just go into your Security section of your SQL Server and create a new Login. Give it a username and password, and give it rights to your database. All the basic dialogs are very self-explanatory.
You can also use integrated security, which means your .NET application will try to connect to SQL using the credentials of the worker process. Check here for more info on that.
Finally, in code, you can get to your connection string by using:
ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString
Be careful with the answers above. sqljdbc4.jar is not distributed with under a public license which is why it is difficult to include it in a jar for runtime and distribution. See my answer below for more details and a much better solution. Your life will become much easier as mine did once I found this answer.
The init(frame:)
version is the default initializer. You must call it only after initializing your instance variables. If this view is being reconstituted from a Nib then your custom initializer will not be called, and instead the init?(coder:)
version will be called. Since Swift now requires an implementation of the required init?(coder:)
, I have updated the example below and changed the let
variable declarations to var
and optional. In this case, you would initialize them in awakeFromNib()
or at some later time.
class TestView : UIView {
var s: String?
var i: Int?
init(s: String, i: Int) {
self.s = s
self.i = i
super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
If they're both strings you can just do:
#define STR3 STR1 STR2
This then expands to:
#define STR3 "s" "1"
and in the C language, separating two strings with space as in "s" "1"
is exactly equivalent to having a single string "s1"
.
here is mine
echo Math+
ECHO First num:
SET /P a=
ECHO Second num:
SET /P b=
set /a s=%a%+%b%
echo Result: %s%
You can use css or js for hiding a div. In else statement you can write it as:
else{
?>
<style type="text/css">#divId{
display:none;
}</style>
<?php
}
Or in jQuery
else{
?>
<script type="text/javascript">$('#divId').hide()</script>
<?php
}
Or in javascript
else{
?>
<script type="text/javascript">document.getElementById('divId').style.display = 'none';</script>
<?php
}
If using Angular Material Design, you can use the datepicker component there and this will work in Firefox, IE etc.
https://material.angularjs.org/latest/demo/datepicker
Fair warning though - personal experience is that there are problems with this, and seemingly it is being re-worked at present. See here:
In terminal run this command in the folder where the systlesheets are:
sass --watch style.scss:style.css
Source:
When ever it notices a change in the .scss
file it will update your .css
This only works when your .scss
is on your local machine. Try copying the code to a file and running it locally.
You could also use this existing solution. The demo is here. It looks like youtube loading bar. I just found it and added it to my own project.
do:
$("button").click(function() {
$('html,body').animate({
scrollTop: $(".second").offset().top},
'slow');
});
Updated Jsfiddle
The easiest way is to use fetcher
first, install fetcher with the following command:
npm install -g github-files-fetcher
then you can download file or folder with its URL:
fetcher --url=resource_url --out=output_directory
for example:
fetcher --url="https://github.com/Gyumeijie/github-files-fetcher/blob/master/CHANGELOG.md" --out=/tmp
No, you can't undo, rollback or reverse a commit.
(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE
or similar, not an rm -rf /data/directory
scenario).
If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate
so that no checkpoint is run on shutdown.
You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.
If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.
Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base
, pg_clog
, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog
etc. No part is unimportant.
Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.
If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT
or UPDATE
. Thus, the old versions of the UPDATE
d rows might still be lying around, present but inaccessible.
Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter
and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl
in immediate
mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.
Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.
You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.
I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOAST
ed data so it's of limited utility. Give it a try, if you're lucky it might work.
See: pg_dirtyread on GitHub.
I've removed what I'd written in this section as it's obsoleted by that tool.
See also PostgreSQL row storage fundamentals
See my blog entry Preventing PostgreSQL database corruption.
On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED
for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.
I bet you are retrieving data in non-utf8 encoding: try to put mysql_query('SET CHARACTER SET utf8')
before your SELECT
query.
This is a bit of a work around, but one way you can achieve this is by adding a breakpoint at the start of the javascript file or block you want to manipulate.
Then when you reload, the debugger will pause on that breakpoint, and you can make any changes you want to the source, save the file and then run the debugger through the modified code.
But as everyone has said, next reload the changes will be gone - at least it let's you run some slightly modified JS client side.
Modal Window using ExtJS approach.
In Main Window
<html>
<link rel="stylesheet" href="ext.css" type="text/css">
<head>
<script type="text/javascript" src="ext-all.js"></script>
function openModalDialog() {
Ext.onReady(function() {
Ext.create('Ext.window.Window', {
title: 'Hello',
height: Ext.getBody().getViewSize().height*0.8,
width: Ext.getBody().getViewSize().width*0.8,
minWidth:'730',
minHeight:'450',
layout: 'fit',
itemId : 'popUpWin',
modal:true,
shadow:false,
resizable:true,
constrainHeader:true,
items: [{
xtype: 'box',
autoEl: {
tag: 'iframe',
src: '2.html',
frameBorder:'0'
}
}]
}).show();
});
}
function closeExtWin(isSubmit) {
Ext.ComponentQuery.query('#popUpWin')[0].close();
if (isSubmit) {
document.forms[0].userAction.value = "refresh";
document.forms[0].submit();
}
}
</head>
<body>
<form action="abc.jsp">
<a href="javascript:openModalDialog()"> Click to open dialog </a>
</form>
</body>
</html>
In popupWindow 2.html
<html>
<head>
<script type="text\javascript">
function doSubmit(action) {
if (action == 'save') {
window.parent.closeExtWin(true);
} else {
window.parent.closeExtWin(false);
}
}
</script>
</head>
<body>
<a href="javascript:doSubmit('save');" title="Save">Save</a>
<a href="javascript:doSubmit('cancel');" title="Cancel">Cancel</a>
</body>
</html>
The following adds one line after SearchPattern
.
sed -i '/SearchPattern/aNew Text' SomeFile.txt
It inserts New Text
one line below each line that contains SearchPattern
.
To add two lines, you can use a \
and enter a newline while typing New Text
.
POSIX sed requires a \
and a newline after the a
sed function. [1]
Specifying the text to append without the newline is a GNU sed extension (as documented in the sed
info page), so its usage is not as portable.
[1] https://unix.stackexchange.com/questions/52131/sed-on-osx-insert-at-a-certain-line/
You could do:
sub("*\\.[0-9]", "", a)
or
library(stringr)
str_sub(a, start=1, end=-3)
When calling a function that is declared with throws
in Swift, you must annotate the function call site with try
or try!
. For example, given a throwing function:
func willOnlyThrowIfTrue(value: Bool) throws {
if value { throw someError }
}
this function can be called like:
func foo(value: Bool) throws {
try willOnlyThrowIfTrue(value)
}
Here we annotate the call with try
, which calls out to the reader that this function may throw an exception, and any following lines of code might not be executed. We also have to annotate this function with throws
, because this function could throw an exception (i.e., when willOnlyThrowIfTrue()
throws, then foo
will automatically rethrow the exception upwards.
If you want to call a function that is declared as possibly throwing, but which you know will not throw in your case because you're giving it correct input, you can use try!
.
func bar() {
try! willOnlyThrowIfTrue(false)
}
This way, when you guarantee that code won't throw, you don't have to put in extra boilerplate code to disable exception propagation.
try!
is enforced at runtime: if you use try!
and the function does end up throwing, then your program's execution will be terminated with a runtime error.
Most exception handling code should look like the above: either you simply propagate exceptions upward when they occur, or you set up conditions such that otherwise possible exceptions are ruled out. Any clean up of other resources in your code should occur via object destruction (i.e. deinit()
), or sometimes via defer
ed code.
func baz(value: Bool) throws {
var filePath = NSBundle.mainBundle().pathForResource("theFile", ofType:"txt")
var data = NSData(contentsOfFile:filePath)
try willOnlyThrowIfTrue(value)
// data and filePath automatically cleaned up, even when an exception occurs.
}
If for whatever reason you have clean up code that needs to run but isn't in a deinit()
function, you can use defer
.
func qux(value: Bool) throws {
defer {
print("this code runs when the function exits, even when it exits by an exception")
}
try willOnlyThrowIfTrue(value)
}
Most code that deals with exceptions simply has them propagate upward to callers, doing cleanup on the way via deinit()
or defer
. This is because most code doesn't know what to do with errors; it knows what went wrong, but it doesn't have enough information about what some higher level code is trying to do in order to know what to do about the error. It doesn't know if presenting a dialog to the user is appropriate, or if it should retry, or if something else is appropriate.
Higher level code, however, should know exactly what to do in the event of any error. So exceptions allow specific errors to bubble up from where they initially occur to the where they can be handled.
Handling exceptions is done via catch
statements.
func quux(value: Bool) {
do {
try willOnlyThrowIfTrue(value)
} catch {
// handle error
}
}
You can have multiple catch statements, each catching a different kind of exception.
do {
try someFunctionThatThowsDifferentExceptions()
} catch MyErrorType.errorA {
// handle errorA
} catch MyErrorType.errorB {
// handle errorB
} catch {
// handle other errors
}
For more details on best practices with exceptions, see http://exceptionsafecode.com/. It's specifically aimed at C++, but after examining the Swift exception model, I believe the basics apply to Swift as well.
For details on the Swift syntax and error handling model, see the book The Swift Programming Language (Swift 2 Prerelease).
var nums = [1,4,5,3,1,4,7,8,6,2,1,4];
nums.sort();
nums.reverse();
alert(nums[0]);
_x000D_
Simplest Way:
var nums = [1,4,5,3,1,4,7,8,6,2,1,4]; nums.sort(); nums.reverse(); alert(nums[0]);
Since your list is already in ascending order, we can simply reverse the list.
>>> timestamps.reverse()
>>> timestamps
['2010-04-20 10:25:38',
'2010-04-20 10:12:13',
'2010-04-20 10:12:13',
'2010-04-20 10:11:50',
'2010-04-20 10:10:58',
'2010-04-20 10:10:37',
'2010-04-20 10:09:46',
'2010-04-20 10:08:22',
'2010-04-20 10:08:22',
'2010-04-20 10:07:52',
'2010-04-20 10:07:38',
'2010-04-20 10:07:30']
I assume X
and Y
are arrays? If so, there's a very simple way to do this:
x = [1, 1, 2, 4]
y = [1, 2, 2, 2]
# intersection
x & y # => [1, 2]
# union
x | y # => [1, 2, 4]
# difference
x - y # => [4]
For security: Gives each user permission to access the database only through a small set of views that contain the specific data the user or group of users is authorized to see, restricting user access to other data.
Simplicity for queries and structure: A view can draw data from several tables and present a single table, simplifying the information and turning multi-table queries into single-table queries for a view and it give users a specific view of the database structure, presenting the database as a set of virtual tables specific to particular users or groups of users.
For create consistent database structure: Views present a consistent, unchanged image of the database structure, even if underlying source tables are changed.
This was the only reasonable thing I found to fade a background image.
<div id="foo">
<!-- some content here -->
</div>
Your CSS; now enhanced with CSS3 transition.
#foo {
background-image: url(a.jpg);
transition: background 1s linear;
}
Now swap out the background
document.getElementById("foo").style.backgroundImage = "url(b.jpg)";
Voilà, it fades!
Obvious disclaimer: if your browser doesn't support the CSS3 transition
property, this won't work. In which case, the image will change without a transition. Given <1%
of your users' browser don't support CSS3, that's probably fine. Don't kid yourself, it's fine.
You may also get this error if you add a reference to a different, unrelated project by mistake. Check if that applies to you.
Using CSS, you set the logo div to position absolute, and set the z-order to be above the second div.
#logo
{
position: absolute:
z-index: 2000;
left: 100px;
width: 100px;
height: 50px;
}
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int[] numbers=new int[5];
String x=null;
System.out.print("enter the number 10:"+"/n");
for(int i=0;i<5;i++){
numbers[i] = input.nextInt();
}
System.out.print("Numbers : count"+"\n");
int count=1;
Arrays.sort(numbers);
for(int z=0;z<5;z++){
for(int j=0;j<z;j++){
if(numbers[z]==numbers[j] & j!=z){
count=count+1;
}
}
System.out.print(numbers[z]+" - "+count+"\n");
count=1;
}
I know this post was posted 5 years ago, but I had this problem recently. It may be cause by corporate network limitations. So my solution is letting WebClient
go through proxy server to make the call. Here is the code which worked for me. Hope it helps.
using (WebClient client = new WebClient())
{
client.Encoding = Encoding.UTF8;
WebProxy proxy = new WebProxy("your proxy host IP", port);
client.Proxy = proxy;
string sourceUrl = "xxxxxx";
try
{
using (Stream stream = client.OpenRead(new Uri(noaaSourceUrl)))
{
//......
}
}
catch (Exception ex)
{
throw;
}
}
The biggest difference is their functionality. push_back
always puts a new element at the end of the vector
and insert
allows you to select new element's position. This impacts the performance. vector
elements are moved in the memory only when it's necessary to increase it's length because too little memory was allocated for it. On the other hand insert
forces to move all elements after the selected position of a new element. You simply have to make a place for it. This is why insert
might often be less efficient than push_back
.
You can do it for any Java char using the one liner here:
System.out.println( "\\u" + Integer.toHexString('÷' | 0x10000).substring(1) );
But it's only going to work for the Unicode characters up to Unicode 3.0, which is why I precised you could do it for any Java char.
Because Java was designed way before Unicode 3.1 came and hence Java's char primitive is inadequate to represent Unicode 3.1 and up: there's not a "one Unicode character to one Java char" mapping anymore (instead a monstrous hack is used).
So you really have to check your requirements here: do you need to support Java char or any possible Unicode character?
printf("\nmaximum of %d and %d is = %d",a,b,c);
According to this article on sqlserverstudymaterial;
Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).
If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.
If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including
You could also use PyAutoGui to send a virtual key presses.
Here's the documentation: https://pyautogui.readthedocs.org/en/latest/
import pyautogui
pyautogui.press('Any key combination')
You can also send keys like the shift key or enter key with:
import pyautogui
pyautogui.press('shift')
Pyautogui can also send straight text like so:
import pyautogui
pyautogui.typewrite('any text you want to type')
As for pressing the "A" key 1000 times, it would look something like this:
import pyautogui
for i in range(999):
pyautogui.press("a")
alt-tab or other tasks that require more than one key to be pressed at the same time:
import pyautogui
# Holds down the alt key
pyautogui.keyDown("alt")
# Presses the tab key once
pyautogui.press("tab")
# Lets go of the alt key
pyautogui.keyUp("alt")
In Android Studio v1.2, it tells you how to fix it:
players
is a list which needs to be indexed by integers. You seem to be using it like a dictionary. Maybe you could use unpacking -- Something like:
name, score = player
(if the player
list is always a constant length).
There's not much more advice we can give you without knowing what query
is and how it works.
It's worth pointing out that the entire code you posted doesn't make a whole lot of sense. There's an IndentationError
on the second line. Also, your function is looping over some iterable, but unconditionally returning during the first iteration which isn't usually what you actually want to do.
It looks like you are trying to connect using TLSv1.2, which isn't widely implemented on servers. Does your destination support tls1.2?
Here is some Java code that worked for me:
boolean liesOnSegment(Coordinate a, Coordinate b, Coordinate c) {
double dotProduct = (c.x - a.x) * (c.x - b.x) + (c.y - a.y) * (c.y - b.y);
return (dotProduct < 0);
}
If you want the last 5 rows, ordered in ascending order, you need a subquery:
SELECT *
FROM
( SELECT id, name, form_id, DATE(updated_at) AS updated_date, updated_at
FROM wp_frm_items
WHERE user_id = 11
AND form_id=9
ORDER BY updated_at DESC
LIMIT 5
) AS tmp
ORDER BY updated_at
After reading the question for 10th time, this may be (just maybe) what you want. Order by Date descending and then order by time (on same date) ascending:
SELECT id, name, form_id, DATE(updated_at) AS updated_date
FROM wp_frm_items
WHERE user_id = 11
AND form_id=9
ORDER BY DATE(updated_at) DESC
, updated_at ASC
Have you tried performing an svn cleanup?
print("sorted counting values:-")
from collections import Counter
fname = open(filename)
fname = fname.read()
fsplit = fname.split()
user = Counter(fsplit)
for i,v in sorted(user.items()):
print((v,i))
100% Working!
To send HTML contents in the body of the mail on the go with Sender and Recipient mail address in single line, you may try the below,
export EMAIL="[email protected]" && mutt -e "my_hdr Content-Type: text/html" -s "Test Mail" "[email protected]" < body_html.html
File: body_html.html
<HTML>
<HEAD> Test Mail </HEAD>
<BODY>
<p>This is a <strong><span style="color: #ff0000;">test mail!</span></strong></p>
</BODY>
</HTML>
Note: Tested in RHEL, CentOS, Ubuntu.
Summarizing the advices from this page, I finished up with the following:
keytool -genkeypair -keystore ~/.android/release.keystore -alias <my_alias> -storepass <my_cert_pass> -keyalg RSA
Then I got a set of questions regarding name, organization, location and password for my alias.
You can set the z-index in css
<div style="z-index: -1"></div>
The key is to keep the declarations of the variable in the header file and source file the same.
I use this trick
------sample.c------
#define sample_c
#include sample.h
(rest of sample .c)
------sample.h------
#ifdef sample_c
#define EXTERN
#else
#define EXTERN extern
#endif
EXTERN int x;
Sample.c is only compiled once and it defines the variables. Any file that includes sample.h is only given the "extern" of the variable; it does allocate space for that variable.
When you change the type of x, it will change for everybody. You won't need to remember to change it in the source file and the header file.
( child selector) was introduced in css2. div p{ } select all p elements decedent of div elements, whereas div > p selects only child p elements, not grand child, great grand child on so on.
<style>
div p{ color:red } /* match both p*/
div > p{ color:blue } /* match only first p*/
</style>
<div>
<p>para tag, child and decedent of p.</p>
<ul>
<li>
<p>para inside list. </p>
</li>
</ul>
</div>
For more information on CSS Ce[lectors and their use, check my blog, css selectors and css3 selectors
Lets go through basic definition of typedef. typedef use to define an alias to an existing data type either it is user defined or inbuilt.
typedef <data_type> <alias>;
for example
typedef int scores;
scores team1 = 99;
Confusion here is with the self referential structure, due to a member of same data type which is not define earlier. So In standard way you can write your code as :-
//View 1
typedef struct{ bool isParent; struct Cell* child;} Cell;
//View 2
typedef struct{
bool isParent;
struct Cell* child;
} Cell;
//Other Available ways, define stucture and create typedef
struct Cell {
bool isParent;
struct Cell* child;
};
typedef struct Cell Cell;
But last option increase some extra lines and words with usually we don't want to do (we are so lazy you know ;) ) . So prefer View 2.
This is an universal solution:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
Usage:
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
Display the date based on the client local setting:
date.toLocaleString();
You are getting an HTTP 400
(Bad Request) error because there is a space
in your URL. If you fix it (before the zoom
parameter), you will get an HTTP 400
error (Unauthorized).
Maybe you need some HTTP header to identify your download as a recognised browser (use the "User-Agent" header) or additional authentication parameter.
For the User-Agent example, then use the ImageIO.read(InputStream) using the connection inputstream:
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "xxxxxx");
Use whatever needed for xxxxxx
try this:
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
return false;
}
else {
return true;
}
}
if (verifyPwd()==true){
addNewUser();
}
else {
// passwords do not match
}
the correct syntax is -
with t1
as
(select * from tab1
where conditions...
),
t2
as
(select * from tab2
where conditions...
(you can access columns of t1 here as well)
)
select * from t1, t2
where t1.col1=t2.col2;
It is possible to debug by writing key word "debugger" to place where you want to debug and just press F5 key to debug JavaScript code.
1) First Insert JS file path in an index.html file :
<script src="assets/video.js" type="text/javascript"></script>
2) Import JS file and declare the variable in component.ts :
declare var RunPlayer: any;
NOTE: Variable name should be same as the name of a function in js file
3) Call the js method in the component
ngAfterViewInit(){
setTimeout(() => {
new RunPlayer();
});
}
Just as an empty Request body is in keeping with the original purpose of a GET request and empty response body is in keeping with the original purpose of a PUT request.
First, in Python, if your code is CPU-bound, multithreading won't help, because only one thread can hold the Global Interpreter Lock, and therefore run Python code, at a time. So, you need to use processes, not threads.
This is not true if your operation "takes forever to return" because it's IO-bound—that is, waiting on the network or disk copies or the like. I'll come back to that later.
Next, the way to process 5 or 10 or 100 items at once is to create a pool of 5 or 10 or 100 workers, and put the items into a queue that the workers service. Fortunately, the stdlib multiprocessing
and concurrent.futures
libraries both wraps up most of the details for you.
The former is more powerful and flexible for traditional programming; the latter is simpler if you need to compose future-waiting; for trivial cases, it really doesn't matter which you choose. (In this case, the most obvious implementation with each takes 3 lines with futures
, 4 lines with multiprocessing
.)
If you're using 2.6-2.7 or 3.0-3.1, futures
isn't built in, but you can install it from PyPI (pip install futures
).
Finally, it's usually a lot simpler to parallelize things if you can turn the entire loop iteration into a function call (something you could, e.g., pass to map
), so let's do that first:
def try_my_operation(item):
try:
api.my_operation(item)
except:
print('error with item')
Putting it all together:
executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_my_operation, item) for item in items]
concurrent.futures.wait(futures)
If you have lots of relatively small jobs, the overhead of multiprocessing might swamp the gains. The way to solve that is to batch up the work into larger jobs. For example (using grouper
from the itertools
recipes, which you can copy and paste into your code, or get from the more-itertools
project on PyPI):
def try_multiple_operations(items):
for item in items:
try:
api.my_operation(item)
except:
print('error with item')
executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_multiple_operations, group)
for group in grouper(5, items)]
concurrent.futures.wait(futures)
Finally, what if your code is IO bound? Then threads are just as good as processes, and with less overhead (and fewer limitations, but those limitations usually won't affect you in cases like this). Sometimes that "less overhead" is enough to mean you don't need batching with threads, but you do with processes, which is a nice win.
So, how do you use threads instead of processes? Just change ProcessPoolExecutor
to ThreadPoolExecutor
.
If you're not sure whether your code is CPU-bound or IO-bound, just try it both ways.
Can I do this for multiple functions in my python script? For example, if I had another for loop elsewhere in the code that I wanted to parallelize. Is it possible to do two multi threaded functions in the same script?
Yes. In fact, there are two different ways to do it.
First, you can share the same (thread or process) executor and use it from multiple places with no problem. The whole point of tasks and futures is that they're self-contained; you don't care where they run, just that you queue them up and eventually get the answer back.
Alternatively, you can have two executors in the same program with no problem. This has a performance cost—if you're using both executors at the same time, you'll end up trying to run (for example) 16 busy threads on 8 cores, which means there's going to be some context switching. But sometimes it's worth doing because, say, the two executors are rarely busy at the same time, and it makes your code a lot simpler. Or maybe one executor is running very large tasks that can take a while to complete, and the other is running very small tasks that need to complete as quickly as possible, because responsiveness is more important than throughput for part of your program.
If you don't know which is appropriate for your program, usually it's the first.
Best solution I have seen so far: jQuery: Smooth Scrolling Internal Anchor Links
HTML:
<a href="#comments" class="scroll">Scroll to comments</a>
Script:
jQuery(document).ready(function($) {
$(".scroll").click(function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});
});
%lld
is the standard C99 way, but that doesn't work on the compiler that I'm using (mingw32-gcc v4.6.0). The way to do it on this compiler is: %I64d
So try this:
if(e%n==0)printf("%15I64d -> %1.16I64d\n",e, 4*pi);
and
scanf("%I64d", &n);
The only way I know of for doing this in a completely portable way is to use the defines in <inttypes.h>
.
In your case, it would look like this:
scanf("%"SCNd64"", &n);
//...
if(e%n==0)printf("%15"PRId64" -> %1.16"PRId64"\n",e, 4*pi);
It really is very ugly... but at least it is portable.
SELECT CAST(GETDATE() AS DATE)
Returns the current date with the time part removed.
DATETIME
s are not "stored in the following format". They are stored in a binary format.
SELECT CAST(GETDATE() AS BINARY(8))
The display format in the question is independent of storage.
Formatting into a particular display format should be done by your application.
You can now also get to the Web properties by clicking the dropdown arrow next to the Run button!
You're all set!
PS: This works for me, I'm on version 16.5.5 of VS Professional 2019 :)
This can be done for a non-critical purpose by putting an overlay on top of your input element. Here's my example in pure HTML and CSS.
https://jsfiddle.net/1tL40L99/
<div id="container">
<input name="name" type="text" value="Text input here" />
<span id="overlay"></span>
</div>
<style>
#container {
width: 300px;
height: 50px;
position: relative;
}
#container input[type="text"] {
position: relative;
top: 15px;
z-index: 1;
width: 200px;
display: block;
margin: 0 auto;
}
#container #overlay {
width: 300px;
height: 50px;
position: absolute;
top: 0px;
left: 0px;
z-index: 2;
background: rgba(255,0,0, .5);
}
</style>
The @ symbol allows you to use reserved word. For example:
int @class = 15;
The above works, when the below wouldn't:
int class = 15;