Right click in console and click Terminate/Disconnect All option.
OR
Click on 'Display selected console' icon on top right corner of the console window and, choose and terminate the console which holds the port still.
Your application is not able to connect to activemq. Check that your activemq is running and listening on localhost 61616.
You can try using: netstat -a
to check if the activemq process has started. Or try check if you can access your actvemq using admin page: localhost:8161/admin/queues.jsp
On mac you will start your activemq using:
$ACTMQ_HOME/bin/activemq start
Or if your config file (activemq.xml ) if located in another location you can use:
$ACTMQ_HOME/bin/activemq start xbean:file:${location_of_your_config_file}
In your case the executable is under: bin/macosx/activemq
so you need to use: $ACTMQ_HOME/bin/macosx/activemq start
<a href="#" (click)="onGoToPage2()">Go to page 2</a>
The question mentions Windows, and the accepted answer also works for Ubuntu, but for those who found this question coming from a Redhat flavor of Linux, this did the trick:
sudo yum install -y python-setuptools
Instead of typing command just press:
CLTRL + L
to clear chrome console
You can use the FromStr
trait's from_str
method, which is implemented for i32
:
let my_num = i32::from_str("9").unwrap_or(0);
20190907
OS: Win 10
I'm making an exe in c++, for some reason usting START make my program fail.
So, just use quotes:
"c:\folder\program.exe"
Add the css for .card
.card {
margin: 0 auto; /* Added */
float: none; /* Added */
margin-bottom: 10px; /* Added */
}
here is the pen
UPDATE:
You can use the class .mx-auto
available in bootstrap 4 to center cards.
A timestamp is a point in time. Typically this can be represented by a number of milliseconds past an epoc (the Unix Epoc of Jan 1 1970 12AM UTC). The format of that point in time depends on the time zone. While it is the same point in time, the "hours value" is not the same among time zones and one must take into account the offset from the UTC.
Here's some code to illustrate. A point is time is captured in three different ways.
var moment = require( 'moment' );
var localDate = new Date();
var localMoment = moment();
var utcMoment = moment.utc();
var utcDate = new Date( utcMoment.format() );
//These are all the same
console.log( 'localData unix = ' + localDate.valueOf() );
console.log( 'localMoment unix = ' + localMoment.valueOf() );
console.log( 'utcMoment unix = ' + utcMoment.valueOf() );
//These formats are different
console.log( 'localDate = ' + localDate );
console.log( 'localMoment string = ' + localMoment.format() );
console.log( 'utcMoment string = ' + utcMoment.format() );
console.log( 'utcDate = ' + utcDate );
//One to show conversion
console.log( 'localDate as UTC format = ' + moment.utc( localDate ).format() );
console.log( 'localDate as UTC unix = ' + moment.utc( localDate ).valueOf() );
Which outputs this:
localData unix = 1415806206570
localMoment unix = 1415806206570
utcMoment unix = 1415806206570
localDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localMoment string = 2014-11-12T10:30:06-05:00
utcMoment string = 2014-11-12T15:30:06+00:00
utcDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localDate as UTC format = 2014-11-12T15:30:06+00:00
localDate as UTC unix = 1415806206570
In terms of milliseconds, each are the same. It is the exact same point in time (though in some runs, the later millisecond is one higher).
As far as format, each can be represented in a particular timezone. And the formatting of that timezone'd string looks different, for the exact same point in time!
Are you going to compare these time values? Just convert to milliseconds. One value of milliseconds is always less than, equal to or greater than another millisecond value.
Do you want to compare specific 'hour' or 'day' values and worried they "came from" different timezones? Convert to UTC first using moment.utc( existingDate )
, and then do operations. Examples of those conversions, when coming out of the DB, are the last console.log
calls in the example.
newdf = df.query('closing_price.mean() <= closing_price <= closing_price.std()')
or
mean = closing_price.mean()
std = closing_price.std()
newdf = df.query('@mean <= closing_price <= @std')
Strong pattern matching — This is the method that I use here at Perishable Press. Using strong pattern matching, this technique prevents external access to any file containing “.hta”, “.HTA”, or any case-insensitive combination thereof. To illustrate, this code will prevent access through any of the following requests:
..etc., etc. Clearly, this method is highly effective at securing your site’s HTAccess files. Further, this technique also includes the fortifying “Satisfy All” directive. Note that this code should be placed in your domain’s root HTAccess file:
# STRONG HTACCESS PROTECTION
<Files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>
Strongly typed var don't seem to be available, I have to do the following in order to get access to them:
String MyVar = Dts.Variables["MyVarName"].Value.ToString();
If your are not in a session you can just nextval('you_sequence_name') and it's just fine.
A date-time object is supposed to store the information about the date, time, timezone etc., not about the formatting. You can format a date-time object into a String
with the pattern of your choice using date-time formatting API.
java.time.format
e.g. java.time.format.DateTimeFormatter
, java.time.format.DateTimeFormatterBuilder
etc.java.text
e.g. java.text.SimpleDateFormat
, java.text.DateFormat
etc.Demo using modern API:
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = ZonedDateTime.of(LocalDate.of(2012, Month.DECEMBER, 1).atStartOfDay(),
ZoneId.of("Europe/London"));
// Default format returned by Date#toString
System.out.println(zdt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = dtf.format(zdt);
System.out.println(formattedDate);
}
}
Output:
2012-12-01T00:00Z[Europe/London]
2012-12-01
Learn about the modern date-time API from Trail: Date Time.
Demo using legacy API:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTimeInMillis(0);
calendar.set(Calendar.YEAR, 2012);
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date date = calendar.getTime();
// Default format returned by Date#toString
System.out.println(date);
// Custom format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
Output:
Sat Dec 01 00:00:00 GMT 2012
2012-12-01
Some more important points:
java.util.Date
object is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from the Epoch of January 1, 1970
. When you print an object of java.util.Date
, its toString
method returns the date-time calculated from this milliseconds value. Since java.util.Date
does not have timezone information, it applies the timezone of your JVM and displays the same. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFomrat
and obtain the formatted string from it.java.util
and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
You can do like
HTML in PHP :
<?php
echo "<table>";
echo "<tr>";
echo "<td>Name</td>";
echo "<td>".$name."</td>";
echo "</tr>";
echo "</table>";
?>
Or You can write like.
PHP in HTML :
<?php /*Do some PHP calculation or something*/ ?>
<table>
<tr>
<td>Name</td>
<td><?php echo $name;?></td>
</tr>
</table>
<?php /*Do some PHP calculation or something*/ ?>
Means:
You can open a PHP tag with <?php
, now add your PHP code, then close the tag with ?>
and then write your html code. When needed to add more PHP, just open another PHP tag with <?php
.
You could write a generic Pair<A, B> class and use this in an array or list. Yes, you have to write a class, but you can reuse the same class for all types, so you only have to do it once.
Here's how you can do it by using loops.
public static int[][] makeCopy(int[][] array){
b=new int[array.length][];
for(int row=0; row<array.length; ++row){
b[row]=new int[array[row].length];
for(int col=0; col<b[row].length; ++col){
b[row][col]=array[row][col];
}
}
return b;
}
Create some nice new 10 year certificates and install them. The procedure is fairly easy.
Start at (1B) Generate your own CA (Certificate Authority) on this web page: Creating Certificate Authorities and self-signed SSL certificates and generate your CA Certificate and Key. Once you have these, generate your Server Certificate and Key. Create a Certificate Signing Request (CSR) and then sign the Server Key with the CA Certificate. Now install your Server Certificate and Key on the web server as usual, and import the CA Certificate into Internet Explorer's Trusted Root Certification Authority Store (used by the Flex uploader and Chrome as well) and into Firefox's Certificate Manager Authorities Store on each workstation that needs to access the server using the self-signed, CA-signed server key/certificate pair.
You now should not see any warning about using self-signed Certificates as the browsers will find the CA certificate in the Trust Store and verify the server key has been signed by this trusted certificate. Also in e-commerce applications like Magento, the Flex image uploader will now function in Firefox without the dreaded "Self-signed certificate" error message.
Do you mean "A" (a string
) or 'A' (a char
)?
int unicode = 65;
char character = (char) unicode;
string text = character.ToString();
Note that I've referred to Unicode rather than ASCII as that's C#'s native character encoding; essentially each char
is a UTF-16 code point.
We can iterate loop like as C programming.
#!/bin/bash
for ((i=1; i<=20; i=i+1))
do
echo $i
done
int pow( int base, int exponent)
{ // Does not work for negative exponents. (But that would be leaving the range of int)
if (exponent == 0) return 1; // base case;
int temp = pow(base, exponent/2);
if (exponent % 2 == 0)
return temp * temp;
else
return (base * temp * temp);
}
You could also use Three20 Library that contains a styleable PageControl and dozens of other helpful UI Controls and Abstractions.
import json
myDict = {'dict': [{'a': 'none', 'b': 'none', 'c': 'none'}]}
test = json.dumps(myDict)
print(test)
{"dict": [{"a": "none", "b": "none", "c": "none"}]}
myDict['dict'].append(({'a': 'aaaa', 'b': 'aaaa', 'c': 'aaaa'}))
test = json.dumps(myDict)
print(test)
{"dict": [{"a": "none", "b": "none", "c": "none"}, {"a": "aaaa", "b": "aaaa", "c": "aaaa"}]}
Use this:
mysqli_query($this->db_link, $query) or die(mysqli_error($this->db_link));
# mysqli_query($link,$query) returns 0 if there's an error.
# mysqli_error($link) returns a string with the last error message
You can also use this to print the error code.
echo mysqli_errno($this->db_link);
In UWP:
await Launcher.LaunchUriAsync(new Uri("http://google.com"));
var text = "" &<>";
text = text.replaceHtmlEntites();
String.prototype.replaceHtmlEntites = function() {
var s = this;
var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
var translate = {"nbsp": " ","amp" : "&","quot": "\"","lt" : "<","gt" : ">"};
return ( s.replace(translate_re, function(match, entity) {
return translate[entity];
}) );
};
try this.....this worked for me
Here is an ES2017+ way to get the counts for all array items in O(N):
const arr = [1, 2, 3, 5, 2, 8, 9, 2];
const counts = {};
arr.forEach((el) => {
counts[el] = counts[el] ? (counts[el] += 1) : 1;
});
You can also optionally sort the output:
const countsSorted = Object.entries(counts).sort(([_, a], [__, b]) => a - b);
console.log(countsSorted) for your example array:
[
[ '2', 3 ],
[ '1', 1 ],
[ '3', 1 ],
[ '5', 1 ],
[ '8', 1 ],
[ '9', 1 ]
]
I ran to a similar problem and that was just because of the extra spaces:
<uses-permission android:name="android.permission.INTERNET "/>
which when removed works fine:
<uses-permission android:name="android.permission.INTERNET"/>
Any possible option is to use custom file wrapper for simulating variables as files. You can achieve it by using this:
1) First of all, register your wrapper (only once in file, use it like session_start()):
stream_wrapper_register('var', VarWrapper);
2) Then define your wrapper class (it is really fast written, not completely correct, but it works):
class VarWrapper {
protected $pos = 0;
protected $content;
public function stream_open($path, $mode, $options, &$opened_path) {
$varname = substr($path, 6);
global $$varname;
$this->content = $$varname;
return true;
}
public function stream_read($count) {
$s = substr($this->content, $this->pos, $count);
$this->pos += $count;
return $s;
}
public function stream_stat() {
$f = fopen(__file__, 'rb');
$a = fstat($f);
fclose($f);
if (isset($a[7])) $a[7] = strlen($this->content);
return $a;
}
}
3) Then use any file function with your wrapper on var:// protocol (you can use it for include, require etc. too):
global $__myVar;
$__myVar = 'Enter tags here';
$data = php_strip_whitespace('var://__myVar');
Note: Don't forget to have your variable in global scope (like global $__myVar)
First, keep in mind that, in its precise definition, a module is an object in the memory of a Python interpreter, often created by reading one or more files from disk. While we may informally call a disk file such as a/b/c.py
a "module," it doesn't actually become one until it's combined with information from several other sources (such as sys.path
) to create the module object.
(Note, for example, that two modules with different names can be loaded from the same file, depending on sys.path
and other settings. This is exactly what happens with python -m my.module
followed by an import my.module
in the interpreter; there will be two module objects, __main__
and my.module
, both created from the same file on disk, my/module.py
.)
A package is a module that may have submodules (including subpackages). Not all modules can do this. As an example, create a small module hierarchy:
$ mkdir -p a/b
$ touch a/b/c.py
Ensure that there are no other files under a
. Start a Python 3.4 or later interpreter (e.g., with python3 -i
) and examine the results of the following statements:
import a
a ? <module 'a' (namespace)>
a.b ? AttributeError: module 'a' has no attribute 'b'
import a.b.c
a.b ? <module 'a.b' (namespace)>
a.b.c ? <module 'a.b.c' from '/home/cjs/a/b/c.py'>
Modules a
and a.b
are packages (in fact, a certain kind of package called a "namespace package," though we wont' worry about that here). However, module a.b.c
is not a package. We can demonstrate this by adding another file, a/b.py
to the directory structure above and starting a fresh interpreter:
import a.b.c
? ImportError: No module named 'a.b.c'; 'a.b' is not a package
import a.b
a ? <module 'a' (namespace)>
a.__path__ ? _NamespacePath(['/.../a'])
a.b ? <module 'a.b' from '/home/cjs/tmp/a/b.py'>
a.b.__path__ ? AttributeError: 'module' object has no attribute '__path__'
Python ensures that all parent modules are loaded before a child module is loaded. Above it finds that a/
is a directory, and so creates a namespace package a
, and that a/b.py
is a Python source file which it loads and uses to create a (non-package) module a.b
. At this point you cannot have a module a.b.c
because a.b
is not a package, and thus cannot have submodules.
You can also see here that the package module a
has a __path__
attribute (packages must have this) but the non-package module a.b
does not.
Here's mine:
git remote --verbose | grep origin | grep fetch | cut -f2 | cut -d' ' -f1
no better than the others, but I made it a bash function so I can drop in the remote name if it isn't origin.
grurl () {
xx_remote=$1
[ -z "$xx_remote" ] && xx_remote=origin
git remote --verbose | grep "$1" | grep fetch | cut -f2 | cut -d' ' -f1
unset xx_remote
}
./main.go (in package main)
./a/a.go (in package a)
./a/b.go (in package a)
in this case:
main.go import "./a"
It can call the function in the a.go and b.go,that with first letter caps on.
I found a different way to handle this error. (the variables is according to the original question)
JsonNode parsedNodes = mapper.readValue(jsonMessage , JsonNode.class);
Response response = xmlMapper.enable(ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,ACCEPT_SINGLE_VALUE_AS_ARRAY )
.disable(FAIL_ON_UNKNOWN_PROPERTIES, FAIL_ON_IGNORED_PROPERTIES)
.convertValue(parsedNodes, Response.class);
In addition, you need the "AllowOverride Options" directive for this to work. (Apache 2.2.15)
I have studied a number of Go projects and there is a fair bit of variation. You can kind of tell who is coming from C and who is coming from Java, as the former dump just about everything in the projects root directory in a main
package, and the latter tend to put everything in a src
directory. Neither is optimal however. Each have consequences because they affect import paths and how others can reuse them.
To get the best results I have worked out the following approach.
myproj/
main/
mypack.go
mypack.go
Where mypack.go
is package mypack
and main/mypack.go
is (obviously) package main
.
If you need additional support files you have two choices. Either keep them all in the root directory, or put private support files in a lib
subdirectory. E.g.
myproj/
main/
mypack.go
myextras/
someextra.go
mypack.go
mysupport.go
Or
myproj.org/
lib/
mysupport.go
myextras/
someextra.go
main/
mypack.go
mypage.go
Only put the files in a lib
directory if they are not intended to be imported by another project. In other words, if they are private support files. That's the idea behind having lib
--to separate public from private interfaces.
Doing things this way will give you a nice import path, myproj.org/mypack
to reuse the code in other projects. If you use lib
then internal support files will have an import path that is indicative of that, myproj.org/lib/mysupport
.
When building the project, use main/mypack
, e.g. go build main/mypack
. If you have more than one executable you can also separate those under main
without having to create separate projects. e.g. main/myfoo/myfoo.go
and main/mybar/mybar.go
.
To enable use bind()
method
$("#id").bind("click",eventhandler);
call this handler
function eventhandler(){
alert("Bind click")
}
To disable click useunbind()
$("#id").unbind("click");
One more possibility, if you don't want to use ArgumentCaptor
(for example, because you're also using stubbing), is to use Hamcrest Matchers in combination with Mockito.
import org.mockito.Mockito
import org.hamcrest.Matchers
...
Mockito.verify(mockedObject).someMethodOnMockedObject(MockitoHamcrest.argThat(
Matchers.<SomeObjectAsArgument>hasProperty("propertyName", desiredValue)));
It was making me crazy also until I realized that the paragraph where the key must be is [mysqld] not [mysql]
So, for 10.3.22-MariaDB-1ubuntu1, my solution is, in /etc/mysql/conf.d/mysql.cnf
[mysqld]
sql_mode = "ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
In Windows 10, I fix this by comment like this
;extension=php_sockets.dll
You can do it without dealing with encoding by using BlockCopy:
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
string str = new string(chars);
With:
FILES = $(shell ls)
indented underneath all
like that, it's a build command. So this expands $(shell ls)
, then tries to run the command FILES ...
.
If FILES
is supposed to be a make
variable, these variables need to be assigned outside the recipe portion, e.g.:
FILES = $(shell ls)
all:
echo $(FILES)
Of course, that means that FILES
will be set to "output from ls
" before running any of the commands that create the .tgz files. (Though as Kaz notes the variable is re-expanded each time, so eventually it will include the .tgz files; some make variants have FILES := ...
to avoid this, for efficiency and/or correctness.1)
If FILES
is supposed to be a shell variable, you can set it but you need to do it in shell-ese, with no spaces, and quoted:
all:
FILES="$(shell ls)"
However, each line is run by a separate shell, so this variable will not survive to the next line, so you must then use it immediately:
FILES="$(shell ls)"; echo $$FILES
This is all a bit silly since the shell will expand *
(and other shell glob expressions) for you in the first place, so you can just:
echo *
as your shell command.
Finally, as a general rule (not really applicable to this example): as esperanto notes in comments, using the output from ls
is not completely reliable (some details depend on file names and sometimes even the version of ls
; some versions of ls
attempt to sanitize output in some cases). Thus, as l0b0 and idelic note, if you're using GNU make you can use $(wildcard)
and $(subst ...)
to accomplish everything inside make
itself (avoiding any "weird characters in file name" issues). (In sh
scripts, including the recipe portion of makefiles, another method is to use find ... -print0 | xargs -0
to avoid tripping over blanks, newlines, control characters, and so on.)
1The GNU Make documentation notes further that POSIX make added ::=
assignment in 2012. I have not found a quick reference link to a POSIX document for this, nor do I know off-hand which make
variants support ::=
assignment, although GNU make does today, with the same meaning as :=
, i.e., do the assignment right now with expansion.
Note that VAR := $(shell command args...)
can also be spelled VAR != command args...
in several make
variants, including all modern GNU and BSD variants as far as I know. These other variants do not have $(shell)
so using VAR != command args...
is superior in both being shorter and working in more variants.
$a = array(1, '', '', '', 2, '', 3, 4);
$b = array_values(array_filter($a));
print_r($b)
Open a newline above Ctrl + Enter
Open a newline below Ctrl + Shift + Enter
you can try this exapmple
START TRANSACTION;
SET foreign_key_checks = 0;
ALTER TABLE `job_definers` ADD CONSTRAINT `job_cities_foreign` FOREIGN KEY
(`job_cities`) REFERENCES `drop_down_lists`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
SET foreign_key_checks = 1;
COMMIT;
Note : if you are using phpmyadmin just uncheck Enable foreign key checks
hope this soloution fix your problem :)
If you will never need to serialize your objects to byte array and send/store them, then you don't need to worry about it. If you do, then you must consider your serialVersionUID since the deserializer of the object will match it to the version of object its classloader has. Read more about it in the Java Language Specification.
import java.util.*;
import java.lang.*;
import java.io.*;
class hari
{
public static void main (String[] args) throws Exception
{ Scanner s=new Scanner(System.in);
int i=0;
int b=0;
HashSet<Integer> h=new HashSet<Integer>();
try{
for(i=0;i<1000;i++)
{ b=s.nextInt();
h.add(b);
}
}
catch(Exception e){
System.out.println(h+","+h.size());
}
}}
Swift 4, Autolayout version
func showActivityIndicator(on parentView: UIView) {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicator.startAnimating()
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
parentView.addSubview(activityIndicator)
NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: parentView.centerXAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: parentView.centerYAnchor),
])
}
~mypage.aspx?strID=x&strName=y&strDate=z
I'd call the column "gender".
Data Type Bytes Taken Number/Range of Values
------------------------------------------------
TinyINT 1 255 (zero to 255)
INT 4 - 2,147,483,648 to 2,147,483,647
BIT 1 (2 if 9+ columns) 2 (0 and 1)
CHAR(1) 1 26 if case insensitive, 52 otherwise
The BIT data type can be ruled out because it only supports two possible genders which is inadequate. While INT supports more than two options, it takes 4 bytes -- performance will be better with a smaller/more narrow data type.
CHAR(1)
has the edge over TinyINT - both take the same number of bytes, but CHAR provides a more narrow number of values. Using CHAR(1)
would make using "m", "f",etc natural keys, vs the use of numeric data which are referred to as surrogate/artificial keys. CHAR(1)
is also supported on any database, should there be a need to port.
I would use Option 2: CHAR(1).
An index on the gender column likely would not help because there's no value in an index on a low cardinality column. Meaning, there's not enough variety in the values for the index to provide any value.
For example we have:
example.com/list/search?q=Somethink
And you need use variable url like this by window.location.href:
example.com/list/edit
From url:
example.com/list/search?q=Somethink
example.com/list/
var url = (window.location.href);
url = url.split('/search')[0];
url = (url + '/edit');
This is simple solution:-)
The biggest difference between Task.Delay
and Thread.Sleep
is that Task.Delay
is intended to run asynchronously. It does not make sense to use Task.Delay
in synchronous code. It is a VERY bad idea to use Thread.Sleep
in asynchronous code.
Normally you will call Task.Delay()
with the await
keyword:
await Task.Delay(5000);
or, if you want to run some code before the delay:
var sw = new Stopwatch();
sw.Start();
Task delay = Task.Delay(5000);
Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
await delay;
Guess what this will print? Running for 0.0070048 seconds.
If we move the await delay
above the Console.WriteLine
instead, it will print Running for 5.0020168 seconds.
Let's look at the difference with Thread.Sleep
:
class Program
{
static void Main(string[] args)
{
Task delay = asyncTask();
syncCode();
delay.Wait();
Console.ReadLine();
}
static async Task asyncTask()
{
var sw = new Stopwatch();
sw.Start();
Console.WriteLine("async: Starting");
Task delay = Task.Delay(5000);
Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
await delay;
Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
Console.WriteLine("async: Done");
}
static void syncCode()
{
var sw = new Stopwatch();
sw.Start();
Console.WriteLine("sync: Starting");
Thread.Sleep(5000);
Console.WriteLine("sync: Running for {0} seconds", sw.Elapsed.TotalSeconds);
Console.WriteLine("sync: Done");
}
}
Try to predict what this will print...
async: Starting
async: Running for 0.0070048 seconds
sync: Starting
async: Running for 5.0119008 seconds
async: Done
sync: Running for 5.0020168 seconds
sync: Done
Also, it is interesting to notice that Thread.Sleep
is far more accurate, ms accuracy is not really a problem, while Task.Delay
can take 15-30ms minimal. The overhead on both functions is minimal compared to the ms accuracy they have (use Stopwatch
Class if you need something more accurate). Thread.Sleep
still ties up your Thread, Task.Delay
release it to do other work while you wait.
I don't know why you think there's no constructor. See the API.
You can use this:
function sanitize(string) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
"/": '/',
};
const reg = /[&<>"'/]/ig;
return string.replace(reg, (match)=>(map[match]));
}
Also see OWASP XSS Prevention Cheat Sheet.
Your query looks fine, and your data and query work for me using this JsonPath parser. Also see the example queries on that page for more predicate examples.
The testing tool that you're using seems faulty. Even the examples from the JsonPath site are returning incorrect results:
e.g., given:
{
"store":
{
"book":
[
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle":
{
"color": "red",
"price": 19.95
}
}
}
And the expression: $.store.book[?(@.length-1)].title
, the tool returns a list of all titles.
I'm adding this answer because after arriving here (with the same question), none of the answers really describe all the required steps needed to go from nothing to a fully usable remote (bare) repo.
Note: this example uses local paths for the location of the bare repo, but other git protocols (like SSH indicated by the OP) should work just fine.
I've tried to add some notes along the way for those less familiar with git.
1. Initialise the bare repo...
> git init --bare /path/to/bare/repo.git
Initialised empty Git repository in /path/to/bare/repo.git/
This creates a folder (repo.git) and populates it with git files representing a git repo. As it stands, this repo is useless - it has no commits and more importantly, no branches. Although you can clone this repo, you cannot pull from it.
Next, we need to create a working folder. There are a couple of ways of doing this, depending upon whether you have existing files.
2a. Create a new working folder (no existing files) by cloning the empty repo
git clone /path/to/bare/repo.git /path/to/work
Cloning into '/path/to/work'...
warning: You appear to have cloned an empty repository.
done.
This command will only work if /path/to/work
does not exist or is an empty folder.
Take note of the warning - at this stage, you still don't have anything useful. If you cd /path/to/work
and run git status
, you'll get something like:
On branch master
Initial commit
nothing to commit (create/copy files and use "git add" to track)
but this is a lie. You are not really on branch master
(because git branch
returns nothing) and so far, there are no commits.
Next, copy/move/create some files in the working folder, add them to git and create the first commit.
> cd /path/to/work
> echo 123 > afile.txt
> git add .
> git config --local user.name adelphus
> git config --local user.email [email protected]
> git commit -m "added afile"
[master (root-commit) 614ab02] added afile
1 file changed, 1 insertion(+)
create mode 100644 afile.txt
The git config
commands are only needed if you haven't already told git who you are. Note that if you now run git branch
, you'll now see the master
branch listed. Now run git status
:
On branch master
Your branch is based on 'origin/master', but the upstream is gone.
(use "git branch --unset-upstream" to fixup)
nothing to commit, working directory clean
This is also misleading - upstream has not "gone", it just hasn't been created yet and git branch --unset-upstream
will not help. But that's OK, now that we have our first commit, we can push and master will be created on the bare repo.
> git push origin master
Counting objects: 3, done.
Writing objects: 100% (3/3), 207 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To /path/to/bare/repo.git
* [new branch] master -> master
At this point, we have a fully functional bare repo which can be cloned elsewhere on a master branch as well as a local working copy which can pull and push.
> git pull
Already up-to-date.
> git push origin master
Everything up-to-date
2b. Create a working folder from existing files If you already have a folder with files in it (so you cannot clone into it), you can initialise a new git repo, add a first commit and then link it to the bare repo afterwards.
> cd /path/to/work_with_stuff
> git init
Initialised empty Git repository in /path/to/work_with_stuff
> git add .
# add git config stuff if needed
> git commit -m "added stuff"
[master (root-commit) 614ab02] added stuff
20 files changed, 1431 insertions(+)
create mode 100644 stuff.txt
...
At this point we have our first commit and a local master branch which we need to turn into a remote-tracked upstream branch.
> git remote add origin /path/to/bare/repo.git
> git push -u origin master
Counting objects: 31, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (31/31), done.
Writing objects: 100% (31/31), 43.23 KiB | 0 bytes/s, done.
Total 31 (delta 11), reused 0 (delta 0)
To /path/to/bare/repo.git
* [new branch] master -> master
Branch master set up to track remote branch master from origin.
Note the -u
flag on git push to set the (new) tracked upstream branch.
Just as before, we now have a fully functional bare repo which can be cloned elsewhere on a master branch as well as a local working copy which can pull and push.
All this may seem obvious to some, but git confuses me at the best of times (it's error and status messages really need some rework) - hopefully, this will help others.
Just substitute "user", "pass", "SSHD_IP". And create a file called known_hosts.txt with the content of the server's ~/.ssh/known_hosts. You will get a shell.
public class Known_Hosts {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
jsch.setKnownHosts("known_hosts.txt");
Session session = jsch.getSession("user", "SSHD_IP", 22);
session.setPassword("pass");
session.connect();
Channel channel = session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
} catch (Exception e) {
System.out.println(e);
}
}
}
Assuming that I
is your input image and F
is its Fourier Transform (i.e. F = fft2(I)
)
You can use this code:
F = fftshift(F); % Center FFT
F = abs(F); % Get the magnitude
F = log(F+1); % Use log, for perceptual scaling, and +1 since log(0) is undefined
F = mat2gray(F); % Use mat2gray to scale the image between 0 and 1
imshow(F,[]); % Display the result
SQL Server requires subqueries that you SELECT FROM
or JOIN
to have an alias.
Add an alias to your subquery (in this case x
):
select COUNT(*) from
(
select m.Company_id
from Monitor as m
inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
group by m.Company_id
having COUNT(m.Monitor_id)>=5) x
Try this. Create a shortcut in startup folder and iuput
PowerShell "&.'PathToFile\script.ps1'"
This is the easiest way.
You really need to post a more complete example, so we can see what you're trying to do. From what you have posted, here's what I can see. First, there is no built-in round()
method. You need to either call Math.round(n)
, or statically import Math.round
, and then call it like you have.
For iterations using a selector doesn't seem to make any sense though:
var some = $( '...' );
for( i = some.length -1; i>=0; --i )
{
// Have to transform in a jquery object again:
//
var item = $( some[ i ] );
// use item at will
// ...
}
Both setInterval
and setTimeout
can work for you (as @Doug Neiner and @John Boker wrote both now point to setInterval
).
See here for some more explanation about both to see which suites you most and how to stop each of them.
my solution: org.springframework.boot 2.0.5.RELEASE
Rather: org.springframework.boot 2.1.0.RELEASE
For those wondering, @edward-coast
If you want to set the keep alive for the server, add this to /etc/ssh/sshd_config
:
ClientAliveInterval 60
ClientAliveCountMax 2
ClientAliveInterval: Sets a timeout interval in seconds after which if no data has been received from the client, sshd(8) will send a message through the encrypted channel to request a response from the client.
ClientAliveCountMax: Sets the number of client alive messages (see below) which may be sent without sshd(8) receiving any messages back from the client. If this threshold is reached while client alive messages are being sent, sshd will disconnect the client, terminating the session.
dynamic np = Py.Import("numpy")
dynamic
when applying numerical operators on them. This provides type safety and avoids limitations of generics. This is in essence *duck typing:T y = x * (dynamic)x
, where typeof(x) is T
subprocess.call
will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e.
import subprocess
subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])
Putting this code at the end of your body
tag will focus the first visible, non-hidden enabled element on the screen automatically. It will handle most cases I can come up with on short notice.
<script>
(function(){
var forms = document.forms || [];
for(var i = 0; i < forms.length; i++){
for(var j = 0; j < forms[i].length; j++){
if(!forms[i][j].readonly != undefined && forms[i][j].type != "hidden" && forms[i][j].disabled != true && forms[i][j].style.display != 'none'){
forms[i][j].focus();
return;
}
}
}
})();
</script>
Actually, I think you may have discovered a bug in the week(...)
function, or at least an error in the documentation. Hopefully someone will jump in and explain why I am wrong.
Looking at the code:
library(lubridate)
> week
function (x)
yday(x)%/%7 + 1
<environment: namespace:lubridate>
The documentation states:
Weeks is the number of complete seven day periods that have occured between the date and January 1st, plus one.
But since Jan 1 is the first day of the year (not the zeroth), the first "week" will be a six day period. The code should (??) be
(yday(x)-1)%/%7 + 1
NB: You are using week(...)
in the data.table
package, which is the same code as lubridate::week
except it coerces everything to integer rather than numeric for efficiency. So this function has the same problem (??).
How do I check a variable if it's
null
orundefined
...
Is the variable null
:
if (a === null)
// or
if (a == null) // but see note below
...but note the latter will also be true if a
is undefined
.
Is it undefined
:
if (typeof a === "undefined")
// or
if (a === undefined)
// or
if (a == undefined) // but see note below
...but again, note that the last one is vague; it will also be true if a
is null
.
Now, despite the above, the usual way to check for those is to use the fact that they're falsey:
if (!a) {
// `a` is falsey, which includes `undefined` and `null`
// (and `""`, and `0`, and `NaN`, and [of course] `false`)
}
This is defined by ToBoolean in the spec.
...and what is the difference between the
null
andundefined
?
They're both values usually used to indicate the absence of something. undefined
is the more generic one, used as the default value of variables until they're assigned some other value, as the value of function arguments that weren't provided when the function was called, and as the value you get when you ask an object for a property it doesn't have. But it can also be explicitly used in all of those situations. (There's a difference between an object not having a property, and having the property with the value undefined
; there's a difference between calling a function with the value undefined
for an argument, and leaving that argument off entirely.)
null
is slightly more specific than undefined
: It's a blank object reference. JavaScript is loosely typed, of course, but not all of the things JavaScript interacts with are loosely typed. If an API like the DOM in browsers needs an object reference that's blank, we use null
, not undefined
. And similarly, the DOM's getElementById
operation returns an object reference — either a valid one (if it found the DOM element), or null
(if it didn't).
Interestingly (or not), they're their own types. Which is to say, null
is the only value in the Null type, and undefined
is the only value in the Undefined type.
What is the difference between "==" and "==="
The only difference between them is that ==
will do type coercion to try to get the values to match, and ===
won't. So for instance "1" == 1
is true, because "1"
coerces to 1
. But "1" === 1
is false, because the types don't match. ("1" !== 1
is true.) The first (real) step of ===
is "Are the types of the operands the same?" and if the answer is "no", the result is false
. If the types are the same, it does exactly what ==
does.
Type coercion uses quite complex rules and can have surprising results (for instance, "" == 0
is true).
More in the spec:
==
, also called "loose" equality)===
)You should define the struct out of the class like this:
#include <iostream>
using namespace std;
struct X
{
int v;
};
class E
{
public:
X var;
};
int main(){
E object;
object.var.v=10;
return 0;
}
The mozilla docs for setDate() don't indicate that it will handle end of month scenarios. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
setDate()
That is why I use setTime() when I need to add days.
$('element[name="element_name"]').click(function(){
//do stuff
});
in your case:
$('input[name="btnName"]').click(function(){
//do stuff
});
In plain node.js:
const http = require('http')
const fs = require('fs')
const path = require('path')
process.on('uncaughtException', err => console.error('uncaughtException', err))
process.on('unhandledRejection', err => console.error('unhandledRejection', err))
const publicFolder = process.argv.length > 2 ? process.argv[2] : '.'
const port = process.argv.length > 3 ? process.argv[3] : 8080
const mediaTypes = {
zip: 'application/zip',
jpg: 'image/jpeg',
html: 'text/html',
/* add more media types */
}
const server = http.createServer(function(request, response) {
console.log(request.method + ' ' + request.url)
const filepath = path.join(publicFolder, request.url)
fs.readFile(filepath, function(err, data) {
if (err) {
response.statusCode = 404
return response.end('File not found or you made an invalid request.')
}
let mediaType = 'text/html'
const ext = path.extname(filepath)
if (ext.length > 0 && mediaTypes.hasOwnProperty(ext.slice(1))) {
mediaType = mediaTypes[ext.slice(1)]
}
response.setHeader('Content-Type', mediaType)
response.end(data)
})
})
server.on('clientError', function onClientError(err, socket) {
console.log('clientError', err)
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')
})
server.listen(port, '127.0.0.1', function() {
console.log('? Development server is online.')
})
This is a simple node.js server that only serves requested files in a certain directory.
Usage:
node server.js folder port
folder
may be absolute or relative depending on the server.js
location. The default value is .
which is the directory you execute node server.js
command.
port
is 8080 by default but you can specify any port available in your OS.
In your case, I would do:
cd D:\Folder
node server.js
You can browse the files under D:\Folder
from a browser by typing http://127.0.0.1:8080/somefolder/somefile.html
After try several code, and still not working, I go to official documentation of select2.js. here the link: https://select2.org/programmatic-control/add-select-clear-items
from that the way to clear selection select2 js is:
$('#mySelect2').val(null).trigger('change');
This worked for me:
<a onClick={this.openPopupbox} style={{cursor: 'pointer'}}>
<a name='fb_share' type='button_count' href='http://www.facebook.com/sharer.php?appId={YOUR APP ID}&link=<?php the_permalink() ?>' rel='nofollow'>Share</a><script src='http://static.ak.fbcdn.net/connect.php/js/FB.Share' type='text/javascript'></script>
/// <summary>
/// map properties
/// </summary>
/// <param name="sourceObj"></param>
/// <param name="targetObj"></param>
private void MapProp(object sourceObj, object targetObj)
{
Type T1 = sourceObj.GetType();
Type T2 = targetObj.GetType();
PropertyInfo[] sourceProprties = T1.GetProperties(BindingFlags.Instance | BindingFlags.Public);
PropertyInfo[] targetProprties = T2.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var sourceProp in sourceProprties)
{
object osourceVal = sourceProp.GetValue(sourceObj, null);
int entIndex = Array.IndexOf(targetProprties, sourceProp);
if (entIndex >= 0)
{
var targetProp = targetProprties[entIndex];
targetProp.SetValue(targetObj, osourceVal);
}
}
}
Interesting observation using Java 11 and switching off loop unrolling with the following VM option:
-XX:LoopUnrollLimit=0
The loop with the 2 * (i * i)
expression results in more compact native code1:
L0001: add eax,r11d
inc r8d
mov r11d,r8d
imul r11d,r8d
shl r11d,1h
cmp r8d,r10d
jl L0001
in comparison with the 2 * i * i
version:
L0001: add eax,r11d
mov r11d,r8d
shl r11d,1h
add r11d,2h
inc r8d
imul r11d,r8d
cmp r8d,r10d
jl L0001
Java version:
java version "11" 2018-09-25
Java(TM) SE Runtime Environment 18.9 (build 11+28)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11+28, mixed mode)
Benchmark results:
Benchmark (size) Mode Cnt Score Error Units
LoopTest.fast 1000000000 avgt 5 694,868 ± 36,470 ms/op
LoopTest.slow 1000000000 avgt 5 769,840 ± 135,006 ms/op
Benchmark source code:
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS)
@State(Scope.Thread)
@Fork(1)
public class LoopTest {
@Param("1000000000") private int size;
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(LoopTest.class.getSimpleName())
.jvmArgs("-XX:LoopUnrollLimit=0")
.build();
new Runner(opt).run();
}
@Benchmark
public int slow() {
int n = 0;
for (int i = 0; i < size; i++)
n += 2 * i * i;
return n;
}
@Benchmark
public int fast() {
int n = 0;
for (int i = 0; i < size; i++)
n += 2 * (i * i);
return n;
}
}
1 - VM options used: -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly -XX:LoopUnrollLimit=0
import java.util.*;
imports everything within java.util including the Date class.
import java.util.Date;
just imports the Date class.
Doing either of these could not make any difference.
Clean the solution and then right click on the project and select Package
Here increment the Assembly
and Assembly file
version and rebuild.
If that does not work,
1 - Open the solution in file Explorer.
2 - Close Visual Studio.
3 - Remove all bin
and obj
folders.
4 - Reopen the project and build it.
Problem: My component does not appear after I have added it to the container.
You need to invoke revalidate and repaint after adding a component before it will show up in your container.
Source: http://docs.oracle.com/javase/tutorial/uiswing/layout/problems.html
Use DateFormat. (Sorry, but the brevity of the question does not warrant a longer or more detailed answer.)
There is one rule that is set by font-awesome.css
, which you need to override.
You should set overrides in your CSS files rather than inline, but essentially, the icon-ok class is being set to vertical-align: baseline;
by default and which I've corrected here:
<button id="whatever" class="btn btn-large btn-primary" name="Continue" type="submit">
<span>Continue</span>
<i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>
Example here: http://jsfiddle.net/fPXFY/4/ and the output of which is:
I've downsized the font-size of the icon above in this instance to 30px
, as it feels too big at 40px
for the size of the button, but this is purely a personal viewpoint. You could increase the padding on the button to compensate if required:
<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">
<span>Continue</span>
<i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>
Producing: http://jsfiddle.net/fPXFY/5/ the output of which is:
I found one way to access the shared folder without giving the username and password.
We need to change the share folder protect settings in the machine where the folder has been shared.
Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.
By doing the above settings we can access the shared folder without any username/password.
I had the same problem.
After checking Lint warnings I saw the warning The resource R.string.app_name appears to be unused
..., so I deleted R.string.app_name
.
This resource is required in AndroidManifest.xml
although Lint warned me about an unused resource. I added "unused resource" to the manifest and everything went back to normal.
I hope this helps to someone.
Json.Net prefers to use the default (parameterless) constructor on an object if there is one. If there are multiple constructors and you want Json.Net to use a non-default one, then you can add the [JsonConstructor]
attribute to the constructor that you want Json.Net to call.
[JsonConstructor]
public Result(int? code, string format, Dictionary<string, string> details = null)
{
...
}
It is important that the constructor parameter names match the corresponding property names of the JSON object (ignoring case) for this to work correctly. You do not necessarily have to have a constructor parameter for every property of the object, however. For those JSON object properties that are not covered by the constructor parameters, Json.Net will try to use the public property accessors (or properties/fields marked with [JsonProperty]
) to populate the object after constructing it.
If you do not want to add attributes to your class or don't otherwise control the source code for the class you are trying to deserialize, then another alternative is to create a custom JsonConverter to instantiate and populate your object. For example:
class ResultConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(Result));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Load the JSON for the Result into a JObject
JObject jo = JObject.Load(reader);
// Read the properties which will be used as constructor parameters
int? code = (int?)jo["Code"];
string format = (string)jo["Format"];
// Construct the Result object using the non-default constructor
Result result = new Result(code, format);
// (If anything else needs to be populated on the result object, do that here)
// Return the result
return result;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Then, add the converter to your serializer settings, and use the settings when you deserialize:
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new ResultConverter());
Result result = JsonConvert.DeserializeObject<Result>(jsontext, settings);
One use of the internal keyword is to limit access to concrete implementations from the user of your assembly.
If you have a factory or some other central location for constructing objects the user of your assembly need only deal with the public interface or abstract base class.
Also, internal constructors allow you to control where and when an otherwise public class is instantiated.
If the size of the list if fixed, then you can use an AtomicReferenceArray. This would allow you to perform indexed updates to a slot. You could write a List view if needed.
The project can be removed from the "recent project" list but it will still remain in the project directory. To remove from the project list:
To completely remove the project:
For the case that you wish to revert a recently installed package that made several changes to dependencies (such as tensorflow), you can "roll back" to an earlier installation state via the following method:
conda list --revisions
conda install --revision [revision number]
The first command shows previous installation revisions (with dependencies) and the second reverts to whichever revision number
you specify.
Note that if you wish to (re)install a later revision, you may have to sequentially reinstall all intermediate versions. If you had been at revision 23, reinstalled revision 20 and wish to return, you may have to run each:
conda install --revision 21
conda install --revision 22
conda install --revision 23
Close cmd and services window if opened, then start cmd again by right clicking and selecting run as administrator. If sc delete serviceName
does not work or anything does not work.
Sometimes the "Bundle Identifier" in Xcode is changing due to some things that you made. Make sure the Bundle Identifier you defined in your Apple Developer account is exactly the same as the one in Xcode.
Most of the time, if you are very sure you imported the library in question, Visual Studio will guide you with IntelliSense.
Here is what worked for me:
Make sure that #include "stdafx.h"
is declared first, that is, at the top of all of your includes.
Is there any specific reason you would want your buttons in an item template.You can alternatively do it the following way , there by giving you the full power of the grid row editing event.You are also given a bonus of wiring easily the cancel and delete functionality.
Mark up
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="EditImageButton" runat="server" CommandName="Edit"
ImageUrl="~/images/Edit.png" Style="height: 16px" ToolTip="Edit"
CausesValidation="False" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" runat="server" CommandName="Update"
Text="Update" Visible="true" ImageUrl="~/images/saveHS.png"
/>
<asp:LinkButton ID="btnCancel" runat="server" CommandName="Cancel"
ImageUrl="~/images/Edit_UndoHS.png" />
<asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete"
ImageUrl="~/images/delete.png" />
</EditItemTemplate>
<ControlStyle BackColor="Transparent" BorderStyle="None" />
<FooterStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
Code behind
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
TextBox txtledName = (TextBox) GridView1.Rows[e.NewEditIndex].FindControl("txtAccountName");
//then do something with the retrieved textbox's text.
}
Another approach (especially useful if you need to make a decision to exclude a field at runtime) is to register a TypeAdapter with your gson instance. Example below:
Gson gson = new GsonBuilder()
.registerTypeAdapter(BloodPressurePost.class, new BloodPressurePostSerializer())
In the case below, the server would expect one of two values but since they were both ints then gson would serialize them both. My goal was to omit any value that is zero (or less) from the json that is posted to the server.
public class BloodPressurePostSerializer implements JsonSerializer<BloodPressurePost> {
@Override
public JsonElement serialize(BloodPressurePost src, Type typeOfSrc, JsonSerializationContext context) {
final JsonObject jsonObject = new JsonObject();
if (src.systolic > 0) {
jsonObject.addProperty("systolic", src.systolic);
}
if (src.diastolic > 0) {
jsonObject.addProperty("diastolic", src.diastolic);
}
jsonObject.addProperty("units", src.units);
return jsonObject;
}
}
select group_id,
listagg(name, ',') within group (order by name) as names
over (partition by group_id)
from demotable
group by group_id
Different people who come to this question mean different things by a popup box. I highly recommend reading the Temporary Views documentation. My answer is largely a summary of this and other related documentation.
Alerts display a title and an optional message. The user must acknowledge it (a one-button alert) or make a simple choice (a two-button alert) before going on. You create an alert with a UIAlertController
.
It is worth quoting the documentation's warning and advice about creating unnecessary alerts.
Notes:
UIAlertView
was deprecated. You should use UIAlertController
to create alerts now.Action Sheets give the user a list of choices. They appear either at the bottom of the screen or in a popover depending on the size and orientation of the device. As with alerts, a UIAlertController
is used to make an action sheet. Before iOS 8, UIActionSheet
was used, but now the documentation says:
Important:
UIActionSheet
is deprecated in iOS 8. (Note thatUIActionSheetDelegate
is also deprecated.) To create and manage action sheets in iOS 8 and later, instead useUIAlertController
with apreferredStyle
ofUIAlertControllerStyleActionSheet
.
A modal view is a self-contained view that has everything it needs to complete a task. It may or may not take up the full screen. To create a modal view, use a UIPresentationController
with one of the Modal Presentation Styles.
See also
A Popover is a view that appears when a user taps on something and disappears when tapping off it. It has an arrow showing the control or location from where the tap was made. The content can be just about anything you can put in a View Controller. You make a popover with a UIPopoverPresentationController
. (Before iOS 8, UIPopoverController
was the recommended method.)
In the past popovers were only available on the iPad, but starting with iOS 8 you can also get them on an iPhone (see here, here, and here).
See also
Notifications are sounds/vibrations, alerts/banners, or badges that notify the user of something even when the app is not running in the foreground.
See also
In Android, a Toast is a short message that displays on the screen for a short amount of time and then disappears automatically without disrupting user interaction with the app.
People coming from an Android background want to know what the iOS version of a Toast is. Some examples of these questions can he found here, here, here, and here. The answer is that there is no equivalent to a Toast in iOS. Various workarounds that have been presented include:
UIView
However, my advice is to stick with the standard UI options that already come with iOS. Don't try to make your app look and behave exactly the same as the Android version. Think about how to repackage it so that it looks and feels like an iOS app.
If you do android native code development using NDK, give Visual Studio a try. (Not a typo!!!) Check out: http://ian-ni-lewis.blogspot.com/2011/01/its-like-coming-home-again.html
One possible answer to OP-s question ("I wanted to find out the total by adding each digit, for eg, 110. 1 + 1 + 0 = 2. How do I do that?") is to use built-in function divmod()
num = int(input('Enter a number: ')
nums_sum = 0
while num:
num, reminder = divmod(num, 10)
nums_sum += reminder
Works pretty well, in command line, all arguments are required, -W is for password
psql -h localhost -U user -W -d database_name -f path/to/file.sql
No. Standard CSS does not provide the kind of thing you're looking for.
However, you might want to look into LESS and SASS.
These are two projects which aim to extend default CSS syntax by introducing additional features, including variables, nested rules, and other enhancements.
They allow you to write much more structured CSS code, and either of them will almost certainly solve your particular use case.
Of course, none of the browsers support their extended syntax (especially since the two projects each have different syntax and features), but what they do is provide a "compiler" which converts your LESS or SASS code into standard CSS, which you can then deploy on your site.
Typically, you can read the declaration of the variable from right to left. Therefore in the case of int *ptr;
, it means that you have a Pointer *
to an Integer variable int
. Also when it's declared int **ptr2;
, it is a Pointer variable *
to a Pointer variable *
pointing to an Integer variable int
, which is the same as "(int *)* ptr2;"
Now, following the syntax by declaring int*& rPtr;
, we say it's a Reference &
to a Pointer *
that points to a variable of type int
. Finally, you can apply again this approach also for int**& rPtr2;
concluding that it signifies a Reference &
to a Pointer *
to a Pointer *
to an Integer int
.
Got a bit confused from the top answers so I've wrote a small gist with examples for better understanding.
Option #1 - socket.settimeout()
Will raise an exception in case the sock.recv()
waits for more than the defined timeout.
import socket
sock = socket.create_connection(('neverssl.com', 80))
timeout_seconds = 2
sock.settimeout(timeout_seconds)
sock.send(b'GET / HTTP/1.1\r\nHost: neverssl.com\r\n\r\n')
data = sock.recv(4096)
data = sock.recv(4096) # <- will raise a socket.timeout exception here
Option #2 - select.select()
Waits until data is sent until the timeout is reached. I've tweaked Daniel's answer so it will raise an exception
import select
import socket
def recv_timeout(sock, bytes_to_read, timeout_seconds):
sock.setblocking(0)
ready = select.select([sock], [], [], timeout_seconds)
if ready[0]:
return sock.recv(bytes_to_read)
raise socket.timeout()
sock = socket.create_connection(('neverssl.com', 80))
timeout_seconds = 2
sock.send(b'GET / HTTP/1.1\r\nHost: neverssl.com\r\n\r\n')
data = recv_timeout(sock, 4096, timeout_seconds)
data = recv_timeout(sock, 4096, timeout_seconds) # <- will raise a socket.timeout exception here
Since you are in a controller, the action method is given a Request
parameter.
You can access all POST data with $request->request->all();
.
This returns a key-value pair array.
When using GET requests you access data using $request->query->all();
if you build an MVC project, its included by default. otherwise, what Nick said.
Disabling/enabling an html input button with JavaScript:
(And React with refs. Replace "elementRef.current" with element selection if not using React)
elementRef.current.setAttribute('disabled', 'disabled');
Enable:
elementRef.current.removeAttribute('disabled');
The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:
RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);
There, &rect
is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.
The code should create a dynamic variable:
RectInvoice *rect = new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);
There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.
Cheers
These four commands work for me.
git reset --hard HEAD
git checkout origin/master
git branch -D master
git checkout -b master
To check/pull after executing these commands
git pull origin master
I tried a lot but finally got success with these commands.
This is a working example.
HTML Form :
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
PHP Code :
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<p>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
This is my working code for express 4.0.
express 4.0 is very different from 3.0 and others.
4.0 you have /bin/www file, which you are going to add https here.
"npm start" is standard way you start express 4.0 server.
readFileSync() function should use __dirname get current directory
while require() use ./ refer to current directory.
First you put private.key and public.cert file under /bin folder, It is same folder as WWW file.
I had a similar issue, no videos would play in Chrome. Tried installing beta 64bit, going back to Chrome 32bit release.
The only thing that worked for me was updating my video drivers.
I have the NVIDIA GTS 240. Downloaded, installed the drivers and restarted and Chrome 38.0.2125.77 beta-m (64-bit) starting playing HTML5 videos again on youtube, vimeo and others. Hope this helps anyone else.
This works:
$a = array(1 => 1, 2 => 2, 3 => 3);
$b = array(4 => 4, 5 => 5, 6 => 6);
$c = $a + $b;
print_r($c);
To quickly and safely compare any two files:
if cmp --silent -- "$FILE1" "$FILE2"; then
echo "files contents are identical"
else
echo "files differ"
fi
It's readable, efficient, and works for any file names including "` $()
You can use instance_of?
e.g
@some_var.instance_of?(Hash)
Temporarily changing dirs works well for importing:
cwd = os.getcwd()
os.chdir(<module_path>)
import <module>
os.chdir(cwd)
GET will send the data as a querystring, but POST will not. Rather it will send it in the body of the request.
You are not copying the map, but the reference to the map. Your delete
thus modifies the values in both your original map and the super map. To copy a map, you have to use a for
loop like this:
for k,v := range originalMap {
newMap[k] = v
}
Here's an example from the now-retired SO documentation:
// Create the original map
originalMap := make(map[string]int)
originalMap["one"] = 1
originalMap["two"] = 2
// Create the target map
targetMap := make(map[string]int)
// Copy from the original map to the target map
for key, value := range originalMap {
targetMap[key] = value
}
Excerpted from Maps - Copy a Map. The original author was JepZ. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 and may be found in the Documentation archive. Reference topic ID: 732 and example ID: 9834.
I had the same issue. The problem for me was that one button had two Action methods. What I did was create a first action method for my button and then deleted it in the view controller, but forgot to disconnect the connection in the main storyboard in the connection inspector. So when I added a second action method, there were now two action methods for one button, which caused the error.
You can convert all elements of id to str
using apply
df.id.apply(str)
0 123
1 512
2 zhub1
3 12354.3
4 129
5 753
6 295
7 610
Edit by OP:
I think the issue was related to the Python version (2.7.), this worked:
df['id'].astype(basestring)
0 123
1 512
2 zhub1
3 12354.3
4 129
5 753
6 295
7 610
Name: id, dtype: object
[1-9]\.\d{1,2}|0\.((0?[1-9])|([1-9]0?)){1,2}\b
A simple method of creating the service, adding headers and reading the JSON response,
private static void WebRequest()
{
const string WEBSERVICE_URL = "<<Web Service URL>>";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "GET";
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
webRequest.Headers.Add("Authorization", "Basic dcmGV25hZFzc3VudDM6cGzdCdvQ=");
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
Console.WriteLine(String.Format("Response: {0}", jsonResponse));
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
The most efficient way is by ID.
$("#foo").val(); //by id
You can read more here:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficient_CSS
https://developers.google.com/speed/docs/best-practices/rendering?hl=it#UseEfficientCSSSelectors
I've been trying to get this working. Here's what works:
Example:
mod.mjs
export const STR = 'Hello World'
test.mjs
import {STR} from './mod.mjs'
console.log(STR)
Run: node test.mjs
You should see "Hello World".
Create an empty list of Character and then make a loop to get every character from the array and put them in the list one by one.
List<Character> characterList = new ArrayList<Character>();
char arrayChar[] = abc.toCharArray();
for (char aChar : arrayChar)
{
characterList.add(aChar); // autoboxing
}
We also had this problem. My colleague found a solution. It turned up to be a redefinition of "main" in a third party library header:
#define main SDL_main
So the solution was to add:
#undef main
before our main function.
This is clearly a stupidity!
Try upgrading your node to latest version.
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
version 0.4 may not work properly.
Go to Build Gradle (Module:app) Change the following. In my case, I choose 25.0.3
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.example.cesarhcq.viisolutions"
minSdkVersion 15
targetSdkVersion 25
After that, it works fine!
With .Net 4.x you can use Task-based Asynchronous Pattern (TAP) to achieve this:
// .NET 4.x async-await
using UnityEngine;
using System.Threading.Tasks;
public class AsyncAwaitExample : MonoBehaviour
{
private async void Start()
{
Debug.Log("Wait.");
await WaitOneSecondAsync();
DoMoreStuff(); // Will not execute until WaitOneSecond has completed
}
private async Task WaitOneSecondAsync()
{
await Task.Delay(TimeSpan.FromSeconds(1));
Debug.Log("Finished waiting.");
}
}
this is a feature to use .Net 4.x with Unity please see this link for description about it
and this link for sample project and compare it with coroutine
But becareful as documentation says that This is not fully replacement with coroutine
Ok, solved my problem, if anyone is passing by here is the answer:
Just had to add left: 0,
and top: 0,
to the styles, and yes, I'm tired.
position: 'absolute',
left: 0,
top: 0,
In PowerShell v5.1 this is slightly different compared to v5. According to MS documentation, it has to have a -Path
parameter to specify the archive file path.
Expand-Archive -Path Draft.Zip -DestinationPath C:\Reference
Or else, this can be an actual path:
Expand-Archive -Path c:\Download\Draft.Zip -DestinationPath C:\Reference
You may want trigger action to execute once after the client executes a statement that modifies a million rows (statement-level trigger). Or, you may want to trigger the action once for every row that is modified (row-level trigger).
EXAMPLE: Let's say you have a trigger that will make sure all high school seniors graduate. That is, when a senior's grade is 12, and we increase it to 13, we want to set the grade to NULL
.
For a statement level trigger, you'd say, after the increase-grade statement runs, check the whole table once to update any nows with grade 13 to NULL
.
For a row-level trigger, you'd say, after every row that is updated, update the new row's grade to NULL
if it is 13.
A statement-level trigger would look like this:
create trigger stmt_level_trigger
after update on Highschooler
begin
update Highschooler
set grade = NULL
where grade = 13;
end;
and a row-level trigger would look like this:
create trigger row_level_trigger
after update on Highschooler
for each row
when New.grade = 13
begin
update Highschooler
set grade = NULL
where New.ID = Highschooler.ID;
end;
Note that SQLite doesn't support statement-level triggers, so in SQLite, the FOR EACH ROW
is optional.
you might use
a.view(1,5)
Out:
1 2 3 4 5
[torch.FloatTensor of size 1x5]
I'm using NetBeans and needed a solution for this also. After googleling around and starting from Christopher's answer i managed to build a script that helps you easily do this in NetBeans. I'm putting the instructions here in case someone else will need them.
What you have to do is download one-jar. You can use the link from here: http://one-jar.sourceforge.net/index.php?page=getting-started&file=ant Extract the jar archive and look for one-jar\dist folder that contains one-jar-ant-task-.jar, one-jar-ant-task.xml and one-jar-boot-.jar. Extract them or copy them to a path that we will add to the script below, as the value of the property one-jar.dist.dir.
Just copy the following script at the end of your build.xml script (from your NetBeans project), just before /project tag, replace the value for one-jar.dist.dir with the correct path and run one-jar target.
For those of you that are unfamiliar with running targets, this tutorial might help: http://www.oracle.com/technetwork/articles/javase/index-139904.html . It also shows you how to place sources into one jar, but they are exploded, not compressed into jars.
<property name="one-jar.dist.dir" value="path\to\one-jar-ant"/>
<import file="${one-jar.dist.dir}/one-jar-ant-task.xml" optional="true" />
<target name="one-jar" depends="jar">
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.6"/>
<property name="source" value="1.6"/>
<property name="src.dir" value="src"/>
<property name="bin.dir" value="bin"/>
<property name="build.dir" value="build"/>
<property name="dist.dir" value="dist"/>
<property name="external.lib.dir" value="${dist.dir}/lib"/>
<property name="classes.dir" value="${build.dir}/classes"/>
<property name="jar.target.dir" value="${build.dir}/jars"/>
<property name="final.jar" value="${dist.dir}/${ant.project.name}.jar"/>
<property name="main.class" value="${main.class}"/>
<path id="project.classpath">
<fileset dir="${external.lib.dir}">
<include name="*.jar"/>
</fileset>
</path>
<mkdir dir="${bin.dir}"/>
<!-- <mkdir dir="${build.dir}"/> -->
<!-- <mkdir dir="${classes.dir}"/> -->
<mkdir dir="${jar.target.dir}"/>
<copy includeemptydirs="false" todir="${classes.dir}">
<fileset dir="${src.dir}">
<exclude name="**/*.launch"/>
<exclude name="**/*.java"/>
</fileset>
</copy>
<!-- <echo message="${ant.project.name}: ${ant.file}"/> -->
<javac debug="true" debuglevel="${debuglevel}" destdir="${classes.dir}" source="${source}" target="${target}">
<src path="${src.dir}"/>
<classpath refid="project.classpath"/>
</javac>
<delete file="${final.jar}" />
<one-jar destfile="${final.jar}" onejarmainclass="${main.class}">
<main>
<fileset dir="${classes.dir}"/>
</main>
<lib>
<fileset dir="${external.lib.dir}" />
</lib>
</one-jar>
<delete dir="${jar.target.dir}"/>
<delete dir="${bin.dir}"/>
<delete dir="${external.lib.dir}"/>
</target>
Best of luck and don't forget to vote up if it helped you.
SELECT ...
SELECT SLEEP(5);
SELECT ...
But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?
We can also set the vertical alignment with using this way
$style_cell = array(
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
)
);
with this cell set the vertically aligned into the middle.
Buffers are always of fixed size, there is no built in way to resize them dynamically, so your approach of copying it to a larger Buffer is the only way.
However, to be more efficient, you could make the Buffer larger than the original contents, so it contains some "free" space where you can add data without reallocating the Buffer. That way you don't need to create a new Buffer and copy the contents on each append operation.
if any(t < 0 for t in x):
# do something
Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory:
if True in (t < 0 for t in x):
As Tim Williams suggested, using Application.VLookup
will not throw an error if the lookup value is not found (unlike Application.WorksheetFunction.VLookup
).
If you want the lookup to return a default value when it fails to find a match, and to avoid hard-coding the column number -- an equivalent of IFERROR(VLOOKUP(what, where, COLUMNS(where), FALSE), default)
in formulas, you could use the following function:
Private Function VLookupVBA(what As Variant, lookupRng As Range, defaultValue As Variant) As Variant
Dim rv As Variant: rv = Application.VLookup(what, lookupRng, lookupRng.Columns.Count, False)
If IsError(rv) Then
VLookupVBA = defaultValue
Else
VLookupVBA = rv
End If
End Function
Public Sub UsageExample()
MsgBox VLookupVBA("ValueToFind", ThisWorkbook.Sheets("ReferenceSheet").Range("A:D"), "Not found!")
End Sub
Sorry, you can't view or download this file at this time is an error message that you may get when you try to download files on Google Drive.
Bandwidth limits
Limit Per hour Per day
Download via web client 750 MB 1250 MB
Upload via web client 300 MB 500 MB
The explanation for the error message is simple: while users are free to share files publicly, or with a large number of users, quotas are in effect that limit availability.
If too many users view or download a file, it may be locked for a 24 hour period before the quota is reset. The period that a file is locked may be shorter according to Google.
If a file is particularly popular, it may take days or even longer before you manage to download it to your computer or place it on your Drive storage.
It could be a solution:
Locate the "uc" part of the address, and replace it with "open", so that the beginning of the URL reads * https:// drive.google.com/open?*
Load the address again once you have replaced uc with open in the address.
This loads a new screen with controls at the top.
Click on the "add to my drive" icon at the top right.
Click on "add to my drive" again to open your Google Drive storage in a new tab in the browser.
You should see the locked file on your drive now.
Select it with a right-click, and then the "make a copy" option from the menu.
8.Select the copy of the file with a right-click, and there download to download the file to your local system.
Basically, what this does is create a copy of the file on your own Drive account. Since you are the owner of the copied file, you may download it to your local system this way.
Please note that this works only if you are signed in to a Google Account. Also note that you are the owner of the copied file and will be held responsible for policy violations or other issues linked to the file.
Another option is: Any public folder in Drive can host files and provide direct links to the files.
How to create the hosting URL: https:// googledrive.com/host/FolderID (your id file)
This will provide a folder that will give direct links to files inside the folder. Note: hosting view will not display files created in Google Docs.
My solution:
I had the same problem, so I made a JSON file in Google Drive but the URL file (.mp3) is in Dropbox. It is working fantastic even though I have 40,000 active user. I used this solution because I did not have time to search too much! I wrote you the Dropbox Limits anyway but I did not get problems with it
Traffic limits DROPBOX
Links and file requests are automatically banned if they generate unusually large amounts of traffic.
Dropbox Basic (free) accounts:
20 GB per day: The total amount of traffic that all of your links and file requests combined can generate without getting banned 100,000 downloads per day: The total number of downloads that all of your links combined can generate
Dropbox Plus and Business accounts: About 200 GB per day: The total amount of traffic that all of your links and file requests combined can generate without getting banned There's no daily limit to the number of downloads that your links can generate If your account hits our limit, we'll send a message to the email address registered to your account. Your links will be temporarily disabled, and anyone who tries to access them will see an error page instead of your files.
P.S. If you need more information about my files and how did it and How to make the URL File from Dropbox, I hope help to the people is reading this! (I posted it before but Someone deleted my last post)!
127.0.0.1
is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1
for connections will only receive local connections on that socket.
"localhost" is normally the hostname for the 127.0.0.1
IP address. It's usually set in /etc/hosts
(or the Windows equivalent named "hosts" somewhere under %WINDIR%
). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1
.
0.0.0.0
has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0
that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1
from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0
will accept connections on that interface too.
That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000
is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1
There is an api in Express.
res.sendFile
app.get('/report/:chart_id/:user_id', function (req, res) {
// res.sendFile(filepath);
});
Maybe this simple solution can help:
<input type="text" id="myInput" value="No War"/><button onclick="document.getElementById('myInput').value = ''" title="Clear">X</button></input>
_x000D_
Prerequisite:
Your APK needs to be signed by system as correctly pointed out earlier. One way to achieve that is building the AOSP image yourself and adding the source code into the build.
Code:
Once installed as a system app, you can use the package manager methods to install and uninstall an APK as following:
Install:
public boolean install(final String apkPath, final Context context) {
Log.d(TAG, "Installing apk at " + apkPath);
try {
final Uri apkUri = Uri.fromFile(new File(apkPath));
final String installerPackageName = "MyInstaller";
context.getPackageManager().installPackage(apkUri, installObserver, PackageManager.INSTALL_REPLACE_EXISTING, installerPackageName);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Uninstall:
public boolean uninstall(final String packageName, final Context context) {
Log.d(TAG, "Uninstalling package " + packageName);
try {
context.getPackageManager().deletePackage(packageName, deleteObserver, PackageManager.DELETE_ALL_USERS);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
To have a callback once your APK is installed/uninstalled you can use this:
/**
* Callback after a package was installed be it success or failure.
*/
private class InstallObserver implements IPackageInstallObserver {
@Override
public void packageInstalled(String packageName, int returnCode) throws RemoteException {
if (packageName != null) {
Log.d(TAG, "Successfully installed package " + packageName);
callback.onAppInstalled(true, packageName);
} else {
Log.e(TAG, "Failed to install package.");
callback.onAppInstalled(false, null);
}
}
@Override
public IBinder asBinder() {
return null;
}
}
/**
* Callback after a package was deleted be it success or failure.
*/
private class DeleteObserver implements IPackageDeleteObserver {
@Override
public void packageDeleted(String packageName, int returnCode) throws RemoteException {
if (packageName != null) {
Log.d(TAG, "Successfully uninstalled package " + packageName);
callback.onAppUninstalled(true, packageName);
} else {
Log.e(TAG, "Failed to uninstall package.");
callback.onAppUninstalled(false, null);
}
}
@Override
public IBinder asBinder() {
return null;
}
}
/**
* Callback to give the flow back to the calling class.
*/
public interface InstallerCallback {
void onAppInstalled(final boolean success, final String packageName);
void onAppUninstalled(final boolean success, final String packageName);
}
Here is the PHP code to check if 'id' parameter exists in the URL or not:
if(isset($_GET['id']))
{
$slide = $_GET['id'] // Getting parameter value inside PHP variable
}
I hope it will help you.
A polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively.
I am sorry, but I must disagree with many of the other answers. I would like to stop this muddled misunderstanding of the definition of declarative programming.
Definition
Referential transparency (RT) of the sub-expressions is the only required attribute of a declarative programming expression, because it is the only attribute which is not shared with imperative programming.
Other cited attributes of declarative programming, derive from this RT. Please click the hyperlink above for the detailed explanation.
Spreadsheet example
Two answers mentioned spreadsheet programming. In the cases where the spreadsheet programming (a.k.a. formulas) does not access mutable global state, then it is declarative programming. This is because the mutable cell values are the monolithic input and output of the main()
(the entire program). The new values are not written to the cells after each formula is executed, thus they are not mutable for the life of the declarative program (execution of all the formulas in the spreadsheet). Thus relative to each other, the formulas view these mutable cells as immutable. An RT function is allowed to access immutable global state (and also mutable local state).
Thus the ability to mutate the values in the cells when the program terminates (as an output from main()
), does not make them mutable stored values in the context of the rules. The key distinction is the cell values are not updated after each spreadsheet formula is performed, thus the order of performing the formulas does not matter. The cell values are updated after all the declarative formulas have been performed.
Another simple Vanilla solution based on the A1rPun answer (see his fiddle for the jQuery solution, and both are in this one).
It seems that to NOT trigger a single-click handler when the user double-clicks, the single-click handler is necessarily triggered after a delay...
var single = function(e){console.log('single')},
double = function(e){console.log('double')};
var makeDoubleClick = function(e) {
var clicks = 0,
timeout;
return function (e) {
clicks++;
if (clicks == 1) {
timeout = setTimeout(function () {
single(e);
clicks = 0;
}, 250);
} else {
clearTimeout(timeout);
double(e);
clicks = 0;
}
};
}
document.getElementById('btnVanilla').addEventListener('click', makeDoubleClick(), false);
A simple alternative solution:
Paste the URL into a json to csv converter
Open the CSV file in either Excel or Open Office
Use the spreadsheet tools to parse the data
I do something like this where I just give each table a string name to identify it in column A, and a count for column. Then I union them all so they stack. The result is pretty in my opinion - not sure how efficient it is compared to other options but it got me what I needed.
select 'table1', count (*) from table1
union select 'table2', count (*) from table2
union select 'table3', count (*) from table3
union select 'table4', count (*) from table4
union select 'table5', count (*) from table5
union select 'table6', count (*) from table6
union select 'table7', count (*) from table7;
Result:
-------------------
| String | Count |
-------------------
| table1 | 123 |
| table2 | 234 |
| table3 | 345 |
| table4 | 456 |
| table5 | 567 |
-------------------
In short:
Explanation:
Prebuilt OpenJDK (or distribution) — binaries, built from http://hg.openjdk.java.net/, provided as an archive or installer, offered for various platforms, with a possible support contract.
OpenJDK, the source repository (also called OpenJDK project) - is a Mercurial-based open source repository, hosted at http://hg.openjdk.java.net. The Java source code. The vast majority of Java features (from the VM and the core libraries to the compiler) are based solely on this source repository. Oracle have an alternate fork of this.
OpenJDK, the distribution (see the list of providers below) - is free as in beer and kind of free as in speech, but, you do not get to call Oracle if you have problems with it. There is no support contract. Furthermore, Oracle will only release updates to any OpenJDK (the distribution) version if that release is the most recent Java release, including LTS (long-term support) releases. The day Oracle releases OpenJDK (the distribution) version 12.0, even if there's a security issue with OpenJDK (the distribution) version 11.0, Oracle will not release an update for 11.0. Maintained solely by Oracle.
Some OpenJDK projects - such as OpenJDK 8 and OpenJDK 11 - are maintained by the OpenJDK community and provide releases for some OpenJDK versions for some platforms. The community members have taken responsibility for releasing fixes for security vulnerabilities in these OpenJDK versions.
AdoptOpenJDK, the distribution is very similar to Oracle's OpenJDK distribution (in that it is free, and it is a build produced by compiling the sources from the OpenJDK source repository). AdoptOpenJDK as an entity will not be backporting patches, i.e. there won't be an AdoptOpenJDK 'fork/version' that is materially different from upstream (except for some build script patches for things like Win32 support). Meaning, if members of the community (Oracle or others, but not AdoptOpenJDK as an entity) backport security fixes to updates of OpenJDK LTS versions, then AdoptOpenJDK will provide builds for those. Maintained by OpenJDK community.
OracleJDK - is yet another distribution. Starting with JDK12 there will be no free version of OracleJDK. Oracle's JDK distribution offering is intended for commercial support. You pay for this, but then you get to rely on Oracle for support. Unlike Oracle's OpenJDK offering, OracleJDK comes with longer support for LTS versions. As a developer you can get a free license for personal/development use only of this particular JDK, but that's mostly a red herring, as 'just the binary' is basically the same as the OpenJDK binary. I guess it means you can download security-patched versions of LTS JDKs from Oracle's websites as long as you promise not to use them commercially.
Note. It may be best to call the OpenJDK builds by Oracle the "Oracle OpenJDK builds".
Donald Smith, Java product manager at Oracle writes:
Ideally, we would simply refer to all Oracle JDK builds as the "Oracle JDK", either under the GPL or the commercial license, depending on your situation. However, for historical reasons, while the small remaining differences exist, we will refer to them separately as Oracle’s OpenJDK builds and the Oracle JDK.
---------------------------------------------------------------------------------------- | Provider | Free Builds | Free Binary | Extended | Commercial | Permissive | | | from Source | Distributions | Updates | Support | License | |--------------------------------------------------------------------------------------| | AdoptOpenJDK | Yes | Yes | Yes | No | Yes | | Amazon – Corretto | Yes | Yes | Yes | No | Yes | | Azul Zulu | No | Yes | Yes | Yes | Yes | | BellSoft Liberica | No | Yes | Yes | Yes | Yes | | IBM | No | No | Yes | Yes | Yes | | jClarity | No | No | Yes | Yes | Yes | | OpenJDK | Yes | Yes | Yes | No | Yes | | Oracle JDK | No | Yes | No** | Yes | No | | Oracle OpenJDK | Yes | Yes | No | No | Yes | | ojdkbuild | Yes | Yes | No | No | Yes | | RedHat | Yes | Yes | Yes | Yes | Yes | | SapMachine | Yes | Yes | Yes | Yes | Yes | ----------------------------------------------------------------------------------------
Free Builds from Source - the distribution source code is publicly available and one can assemble its own build
Free Binary Distributions - the distribution binaries are publicly available for download and usage
Extended Updates - aka LTS (long-term support) - Public Updates beyond the 6-month release lifecycle
Commercial Support - some providers offer extended updates and customer support to paying customers, e.g. Oracle JDK (support details)
Permissive License - the distribution license is non-protective, e.g. Apache 2.0
In the Sun/Oracle days, it was usually Sun/Oracle producing the proprietary downstream JDK distributions based on OpenJDK sources. Recently, Oracle had decided to do their own proprietary builds only with the commercial support attached. They graciously publish the OpenJDK builds as well on their https://jdk.java.net/ site.
What is happening starting JDK 11 is the shift from single-vendor (Oracle) mindset to the mindset where you select a provider that gives you a distribution for the product, under the conditions you like: platforms they build for, frequency and promptness of releases, how support is structured, etc. If you don't trust any of existing vendors, you can even build OpenJDK yourself.
Each build of OpenJDK is usually made from the same original upstream source repository (OpenJDK “the project”). However each build is quite unique - $free or commercial, branded or unbranded, pure or bundled (e.g., BellSoft Liberica JDK offers bundled JavaFX, which was removed from Oracle builds starting JDK 11).
If no environment (e.g., Linux) and/or license requirement defines specific distribution and if you want the most standard JDK build, then probably the best option is to use OpenJDK by Oracle or AdoptOpenJDK.
Additional information
Time to look beyond Oracle's JDK by Stephen Colebourne
Java Is Still Free by Java Champions community (published on September 17, 2018)
Java is Still Free 2.0.0 by Java Champions community (published on March 3, 2019)
Aleksey Shipilev about JDK updates interview by Opsian (published on June 27, 2019)
In the System.Windows.Forms
class, you can find more on the MSDN page for this here. Among other things you can control the message box text, title, default button, and icons. Since you didn't specify, if you are trying to do this in a webpage you should look at triggering the javascript alert("my message");
or confirm("my question");
functions.
Here is a query, you can run it in SQL Developer (or SQL*Plus):
SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
FROM DBA_SEGMENTS DS
WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
GROUP BY DS.TABLESPACE_NAME,
SEGMENT_NAME;
I would simply do this, which literally follows what your desired logic was:
df.groupby(['org']).mean().groupby(['cluster']).mean()
Somebody asked this again (duplicate) which made me go a little deeper on this issue.
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
ArrayList<String> aList = new ArrayList<String>();
aList.add("a");
aList.add("b");
}
If we use a bytecode viewer (I used http://asm.ow2.org/eclipse/index.html) well see the following (only list initialization and assignment) for our list snippet:
L0
LINENUMBER 9 L0
NEW ArrayList
DUP
INVOKESPECIAL ArrayList.<init> () : void
ASTORE 1
L1
LINENUMBER 10 L1
ALOAD 1: list
LDC "a"
INVOKEINTERFACE List.add (Object) : boolean
POP
L2
LINENUMBER 11 L2
ALOAD 1: list
LDC "b"
INVOKEINTERFACE List.add (Object) : boolean
POP
and for alist:
L3
LINENUMBER 13 L3
NEW java/util/ArrayList
DUP
INVOKESPECIAL java/util/ArrayList.<init> ()V
ASTORE 2
L4
LINENUMBER 14 L4
ALOAD 2
LDC "a"
INVOKEVIRTUAL java/util/ArrayList.add (Ljava/lang/Object;)Z
POP
L5
LINENUMBER 15 L5
ALOAD 2
LDC "b"
INVOKEVIRTUAL java/util/ArrayList.add (Ljava/lang/Object;)Z
POP
The difference is list ends up calling INVOKEINTERFACE whereas aList calls INVOKEVIRTUAL. Accoding to the Bycode Outline Plugin reference,
invokeinterface is used to invoke a method declared within a Java interface
while invokevirtual
invokes all methods except interface methods (which use invokeinterface), static methods (which use invokestatic), and the few special cases handled by invokespecial.
In summary, invokevirtual pops objectref off the stack while for invokeinterface
the interpreter pops 'n' items off the operand stack, where 'n' is an 8-bit unsigned integer parameter taken from the bytecode. The first of these items is objectref, a reference to the object whose method is being called.
If I understand this correctly, the difference is basically how each way retrieves objectref.
"+" does not mutate the list
.append() mutates the old list
<script type="text/javascript">
function showml(divId,inhtmText)
{
var x = document.getElementById(divId).style.display;
if(x=="block")
{
document.getElementById(divId).style.display = "none";
document.getElementById(inhtmText).innerHTML="Show More...";
}
if(x=="none")
{
document.getElementById(divId).style.display = "block";
document.getElementById(inhtmText).innerHTML="Show Less";
}
}
</script>
<p id="show_more1" onclick="showml('content1','show_more1')" onmouseover="this.style.cursor='pointer'">Show More...</p>
<div id="content1" style="display: none; padding: 16px 20px 4px; margin-bottom: 15px; background-color: rgb(239, 239, 239);">
</div>
if more div use like this change only 1 to 2
<p id="show_more2" onclick="showml('content2','show_more2')" onmouseover="this.style.cursor='pointer'">Show More...</p>
<div id="content2" style="display: none; padding: 16px 20px 4px; margin-bottom: 15px; background-color: rgb(239, 239, 239);">
</div>
demo jsfiddle
For python, you need to use
Class pg8000.types.Bytea (str) Bytea is a str-derived class that is mapped to a PostgreSQL byte array.
or
Pg8000.Binary (value) Construct an object holding binary data.
If you have a clear button, the accepted answer won't work for you. We should also guard against Apple changing things in the future by calling super
.
So, to make sure the text doesn't overlap the clear button, let's get the 'default' value from super
first, then adjust as necessary.
This code will add a 10px insets on the top, left and bottom of the text field:
@interface InsetTextField : UITextField
@end
@implementation InsetTextField
// Placeholder position
- (CGRect)textRectForBounds:(CGRect)bounds {
CGRect rect = [super textRectForBounds:bounds];
UIEdgeInsets insets = UIEdgeInsetsMake(10, 10, 10, 0);
return UIEdgeInsetsInsetRect(rect, insets);
}
// Text position
- (CGRect)editingRectForBounds:(CGRect)bounds {
CGRect rect = [super editingRectForBounds:bounds];
UIEdgeInsets insets = UIEdgeInsetsMake(10, 10, 10, 0);
return UIEdgeInsetsInsetRect(rect, insets);
}
// Clear button position
- (CGRect)clearButtonRectForBounds:(CGRect)bounds {
CGRect rect = [super clearButtonRectForBounds:bounds];
return CGRectOffset(rect, -5, 0);
}
@end
Note: UIEdgeInsetsMake takes parameters in the order: top, left, bottom, right.
You can simply do this:
user.js
class User {
//...
}
module.exports = User
server.js
const User = require('./user.js')
// Instantiate User:
let user = new User()
This is called CommonJS module.
Sometimes it could be useful to export more than one value. For example it could be classes, functions or constants. This is an alternative version of the same functionality:
user.js
class User {}
exports.User = User // Spot the difference
server.js
const {User} = require('./user.js') // Destructure on import
// Instantiate User:
let user = new User()
Since Node.js version 14 it's possible to use ES Modules with CommonJS. Read more about it in the ESM documentation.
?? Don't use globals, it creates potential conflicts with the future code.
Why not using Pandas?
import pandas as pd
l = ['a', 'b', 'c', 'd', 'a', 'd', 'a']
# converting the list to a Series and counting the values
my_count = pd.Series(l).value_counts()
my_count
Output:
a 3
d 2
b 1
c 1
dtype: int64
If you are looking for a count of a particular element, say a, try:
my_count['a']
Output:
3
The one you include last will be the one that is used. Note however that if any rules has !important in the first stylesheet they will take priority.
On modern browsers, you can use the input
event:
$("#textbox").on('input',function() {alert("Change detected!");});
Put from before where, and order_by on last:
$this->db->select('*');
$this->db->from('courses');
$this->db->where('tennant_id',$tennant_id);
$this->db->order_by("UPPER(course_name)","desc");
Or try BINARY:
ORDER BY BINARY course_name DESC;
You should add manually on codeigniter for binary sorting.
And set "course_name" character column.
If sorting is used on a character type column, normally the sort is conducted in a case-insensitive fashion.
What type of structure data in courses table?
If you frustrated you can put into array and return using PHP:
Use natcasesort for order in "natural order": (Reference: http://php.net/manual/en/function.natcasesort.php)
Your array from database as example: $array_db = $result_from_db
:
$final_result = natcasesort($array_db);
print_r($final_result);
set ROOT=c:\programs
set SRC_ROOT=%ROOT%\System\Source
I had a similar problem. As I got a Character from my XML child I had to convert it first to a String (or Integer, if you expect one). The following shows how I solved the problem.
foreach($xml->children() as $newInstr){
$iInstrument = new Instrument($newInstr['id'],$newInstr->Naam,$newInstr->Key);
$arrInstruments->offsetSet((String)$iInstrument->getID(), $iInstrument);
}
Browser > Inspect > Element >
<.app-root _nghost-hey-c0="" ng-version="8.2.11">
In terminal
:> ng version
:> ng --version
:> ng -v
Use this:
<link onclick='doWithThisElement(this.attributes["id"].value)' />
In the context of the onclick JavaScript, this refers to the current element (which in this case is the whole HTML element link).
Keep in mind this overwrites any ID that the element already has:
$(".element").attr("id","SomeID");
The reason why addClass
exists is because an element can have multiple classes, so you wouldn't want to necessarily overwrite the classes already set. But with most attributes, there is only one value allowed at any given time.
@Column
is not the appropriate annotation. You don't want to store a whole User or Question in a column. You want to create an association between the entities. Start by renaming Questions
to Question
, since an instance represents a single question, and not several ones. Then create the association:
@Entity
@Table(name = "UserAnswer")
public class UserAnswer {
// this entity needs an ID:
@Id
@Column(name="useranswer_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "question_id")
private Question question;
@Column(name = "response")
private String response;
//getter and setter
}
The Hibernate documentation explains that. Read it. And also read the javadoc of the annotations.
Okay: weird syntax!
var el: HTMLElement = document.getElementById('content');
fixes the problem. I wonder why the example didn't do this in the first place?
complete code:
class Greeter {
element: HTMLElement;
span: HTMLElement;
timerToken: number;
constructor (element: HTMLElement) {
this.element = element;
this.element.innerText += "The time is: ";
this.span = document.createElement('span');
this.element.appendChild(this.span);
this.span.innerText = new Date().toUTCString();
}
start() {
this.timerToken = setInterval(() => this.span.innerText = new Date().toUTCString(), 500);
}
stop() {
clearTimeout(this.timerToken);
}
}
window.onload = () => {
var el: HTMLElement = document.getElementById('content');
var greeter = new Greeter(el);
greeter.start();
};
The downloads have moved, it says that on that very page:
You should to use: ConfigurableApplicationContext instead of for ApplicationContext
I realized following line was missing in settings.gradle file
include ':app'
make sure you include ":app" module
T-SQL is not asynchronous, so you really have no choice but to wait until SP2 ends. Luckily, that's what you want.
CREATE PROCEDURE SP1 AS
EXEC SP2
PRINT 'Done'
By using ng-focus you can achieve your goal. you need to provide ng-focus in your input field. And while writing your ng-show derivatives you have to write a logic not equal too. Like the below code:
<input type="text" class="form-control" name="inputPhone" ng-model="demo.phoneNumber" required ng-focus>
<div ng-show="demoForm.inputPhone.$dirty && demoForm.inputPhone.$invalid && !demoForm.inputPhone.$focused"></div>
This is the sort of thing that sed
is really good at: $ sed 's/[ \t]*$//'
. Be aware the you will probably need to literally type a TAB character instead of \t
for this to work.
After carefully searching, I figured out the best approach to accomplish this.
private HttpResponseMessage response;
[SetUp]
public void Setup()
{
var handlerMock = new Mock<HttpMessageHandler>();
handlerMock
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
// This line will let you to change the response in each test method
.ReturnsAsync(() => response);
_httpClient = new HttpClient(handlerMock.Object);
yourClinet = new YourClient( _httpClient);
}
As you noticed I have used Moq and Moq.Protected packages.
Here's an example that uses 3 different types of parameters.
def func(required_arg, *args, **kwargs):
# required_arg is a positional-only parameter.
print required_arg
# args is a tuple of positional arguments,
# because the parameter name has * prepended.
if args: # If args is not empty.
print args
# kwargs is a dictionary of keyword arguments,
# because the parameter name has ** prepended.
if kwargs: # If kwargs is not empty.
print kwargs
>>> func()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func() takes at least 1 argument (0 given)
>>> func("required argument")
required argument
>>> func("required argument", 1, 2, '3')
required argument
(1, 2, '3')
>>> func("required argument", 1, 2, '3', keyword1=4, keyword2="foo")
required argument
(1, 2, '3')
{'keyword2': 'foo', 'keyword1': 4}
As per your description, things don't add up. If aSourceDictionary
is a dictionary, then your for loop has to work properly.
>>> source = {'a': [1, 2], 'b': [2, 3]}
>>> target = {}
>>> for key in source:
... target[key] = []
... target[key].extend(source[key])
...
>>> target
{'a': [1, 2], 'b': [2, 3]}
>>>
These are properties of 'window' object in JavaScript, just like document is one of a property of window object which holds DOM objects.
Session Storage property maintains a separate storage area for each given origin that's available for the duration of the page session i.e as long as the browser is open, including page reloads and restores.
Local Storage does the same thing, but persists even when the browser is closed and reopened.
You can set and retrieve stored data as follows:
sessionStorage.setItem('key', 'value');
var data = sessionStorage.getItem('key');
Similarly for localStorage.
You can do it like this.
String to byte array
String stringToConvert = "This String is 76 characters long and will be converted to an array of bytes";
byte[] theByteArray = stringToConvert.getBytes();
http://www.javadb.com/convert-string-to-byte-array
Byte array to String
byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
String value = new String(byteArray);
Your first problem is that you are passing -3 to the 2nd parameter of Columns.Add. It needs to be -2 for it to auto-size the column. Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columns.aspx (look at the comments on the code example at the bottom)
private void initListView()
{
// Add columns
lvRegAnimals.Columns.Add("Id", -2,HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);
}
You can also use the other overload, Add(string). E.g:
lvRegAnimals.Columns.Add("Id");
lvRegAnimals.Columns.Add("Name");
lvRegAnimals.Columns.Add("Age");
Reference for more overloads: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columnheadercollection.aspx
Second, to add items to the ListView, you need to create instances of ListViewItem and add them to the listView's Items collection. You will need to use the string[] constructor.
var item1 = new ListViewItem(new[] {"id123", "Tom", "24"});
var item2 = new ListViewItem(new[] {person.Id, person.Name, person.Age});
lvRegAnimals.Items.Add(item1);
lvRegAnimals.Items.Add(item2);
You can also store objects in the item's Tag property.
item2.Tag = person;
And then you can extract it
var person = item2.Tag as Person;
Let me know if you have any questions and I hope this helps!
axios.delete
does support a request body. It accepts two parameters: url
and optional config. You can use config.data
to set the request body and headers as follows:
axios.delete(url, { data: { foo: "bar" }, headers: { "Authorization": "***" } });
See here - https://github.com/axios/axios/issues/897
Exotic Windows Solution
import subprocess
subprocess.run("powershell Invoke-WebRequest {} -OutFile {}".format(your_url, filename), shell=True)
moment has updated the js lib as of 06/2018.
var newYork = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london = newYork.clone().tz("Europe/London");
newYork.format(); // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format(); // 2014-06-01T17:00:00+01:00
if you have freedom to use Angular5+, then better use datePipe feature there than the timezone function here. I have to use moment.js because my project limits to Angular2 only.
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration. -- jQuery.each() | jQuery API Documentation
All tags must have enclosing tags. In my case, the hr and input elements weren't closed properly.
Parent Error was: JSX element 'div' has no corresponding closing tag, due to code below:
<hr class="my-4">
<input
type="password"
id="inputPassword"
class="form-control"
placeholder="Password"
required
>
Fix:
<hr class="my-4"/>
<input
type="password"
id="inputPassword"
class="form-control"
placeholder="Password"
required
/>
The parent elements will show errors due to child element errors. Therefore, start investigating from most inner elements up to the parent ones.
Consider this addition to your example
a = "Dog"
b = "eats"
c = "treats"
print (a,b,c)
#Dog eats treats
d = a + " " + b + " " + c
print (a)
#Dog
print (d)
#Dog eats treats
One of the more precise explanations I found in a blog is:
In Python, (almost) everything is an object. What we commonly refer to as "variables" in Python are more properly called names. Likewise, "assignment" is really the binding of a name to an object. Each binding has a scope that defines its visibility, usually the block in which the name originates.
Eg:
some_guy = 'Fred'
# ...
some_guy = 'George'
When we later say some_guy = 'George', the string object containing 'Fred' is unaffected. We've just changed the binding of the name some_guy. We haven't, however, changed either the 'Fred' or 'George' string objects. As far as we're concerned, they may live on indefinitely.
Link to blog: https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/
DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
Here's a function that will calculate how many pixels you need to add - using the given stroke - to the top, right, bottom and left, all based on the browser:
var getStrokeOffsets = function(stroke){
var strokeFloor = Math.floor(stroke / 2), // max offset
strokeCeil = Math.ceil(stroke / 2); // min offset
if($.browser.mozilla){ // Mozilla offsets
return {
bottom: strokeFloor,
left: strokeFloor,
top: strokeCeil,
right: strokeCeil
};
}else if($.browser.webkit){ // WebKit offsets
return {
bottom: strokeCeil,
left: strokeFloor,
top: strokeFloor,
right: strokeCeil
};
}else{ // default offsets
return {
bottom: strokeCeil,
left: strokeCeil,
top: strokeCeil,
right: strokeCeil
};
}
};
If you want to force Keras to use CPU
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = ""
before Keras / Tensorflow is imported.
Run your script as
$ CUDA_VISIBLE_DEVICES="" ./your_keras_code.py
See also
$today = date('Y-m-d');//Y-m-d H:i:s
$expireDate = new DateTime($row->expireDate);// From db
$date1=date_create($today);
$date2=date_create($expireDate->format('Y-m-d'));
$diff=date_diff($date1,$date2);
//echo $timeDiff;
if($diff->days >= 30){
echo "Expired.";
}else{
echo "Not expired.";
}
It works fine for me: http://jsfiddle.net/qwertynl/htb9h/
My javascript:
var app = angular.module("myApp", [])
app.controller("MyCtrl", ['$scope', function($scope) {
$scope.telephone = []; // << remember to set this
}]);
For me, I had set my project to run on the latest version of .Net Framework (a change from .Net Framework 4.6.1 to 4.7.2).
Everything worked, no errors and published without issue, and it was only by chance that I came across the System.Net.Http error message, shown in a small, hard-to-notice, but quite important API request over the website I'm working on.
I rolled back to 4.6.1 and everything is fine again.
Iterating over the generator expression or the list comprehension will do the same thing. However, the list comprehension will create the entire list in memory first while the generator expression will create the items on the fly, so you are able to use it for very large (and also infinite!) sequences.
to make it as globally reuse function using jquery
HTML
<select class="select_location">
<option value="http://localhost.com/app/page1.html">Page 1</option>
<option value="http://localhost.com/app/page2.html">Page 2</option>
<option value="http://localhost.com/app/page3.html">Page 3</option>
</select>
Javascript using jquery
$('.select_location').on('change', function(){
window.location = $(this).val();
});
now you will able to reuse this function by adding .select_location class to any Select element class
It happens sometimes for the files downloaded with "wget" command. Just 10 minutes ago, I was trying to install something to server from the command screen and the same thing happened. As a solution, I just downloaded the .tar.gz file to my machine from the web then uploaded it to the server via FTP. After that, the "tar" command worked as it was expected.
Just set css property of container div 'pointer-events' as none i.e. 'pointer-events:none;'