Use EmailMultiAlternatives and render_to_string to make use of two alternative templates (one in plain text and one in html):
from django.core.mail import EmailMultiAlternatives
from django.template import Context
from django.template.loader import render_to_string
c = Context({'username': username})
text_content = render_to_string('mail/email.txt', c)
html_content = render_to_string('mail/email.html', c)
email = EmailMultiAlternatives('Subject', text_content)
email.attach_alternative(html_content, "text/html")
email.to = ['[email protected]']
email.send()
In the model, do not pass the value:
timezone.now()
Rather, remove the parenthesis, and pass:
timezone.now
If you continue to get a runtime error warning, consider changing the model field from DateTimeField to DateField.
.navbar-nav {
float: left;
margin: 0;
margin-left: 40%;
}
.navbar-nav.navbar-right:last-child {
margin-right: -15px;
margin-left: 0;
}
Since You Have used the float
property we don't have many options except to adjust it manually.
Note that starting git1.8.4 (July 2013), you wouldn't have to go back to the root directory anymore.
cd ~/.janus/snipmate-snippets
git submodule add <git@github ...> snippets
(Bouke Versteegh comments that you don't have to use /.
, as in snippets/.
: snippets
is enough)
See commit 091a6eb0feed820a43663ca63dc2bc0bb247bbae:
submodule: drop the top-level requirement
Use the new
rev-parse --prefix
option to process all paths given to the submodule command, dropping the requirement that it be run from the top-level of the repository.Since the interpretation of a relative submodule URL depends on whether or not "
remote.origin.url
" is configured, explicitly block relative URLs in "git submodule add
" when not at the top level of the working tree.Signed-off-by: John Keeping
Depends on commit 12b9d32790b40bf3ea49134095619700191abf1f
This makes '
git rev-parse
' behave as if it were invoked from the specified subdirectory of a repository, with the difference that any file paths which it prints are prefixed with the full path from the top of the working tree.This is useful for shell scripts where we may want to
cd
to the top of the working tree but need to handle relative paths given by the user on the command line.
I tried sed 's/^M$//' file.txt on OSX as well as several other methods (http://www.thingy-ma-jig.co.uk/blog/25-11-2010/fixing-dos-line-endings or http://hintsforums.macworld.com/archive/index.php/t-125.html). None worked, the file remained unchanged (btw Ctrl-v Enter was needed to reproduce ^M). In the end I used TextWrangler. Its not strictly command line but it works and it doesn't complain.
I had a similar issue, my error was:
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: java.lang.ClassNotFoundException:org.glassfish.jersey.servlet.ServletContainer from [Module "deployment.RESTful_Services_CRUD.war:main" from Service Module Loader]
I use jboss
and glassfish
so I changed the web.xml
to the following:
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
Instead of:
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
Hope this work for you.
Cd to the environment path, go to the bin folder. At this point when you use ls command, you should see the "activate" file.
now type
source activate
Imagine what happens if x[l] is neither 0 nor 1 in the loop. In that case a and b will never be assigned to and have an undefined value. You must initialize them both with some value, for example 0.
HTML:
<div id="container" class="blog-pager">
<div id="left">Left</div>
<div id="right">Right</div>
<div id="center">Center</div>
</div>
CSS:
#container{width:98%; }
#left{float:left;}
#center{text-align:center;}
#right{float:right;}
text-align:center;
gives perfect centre align.
Or you can do the same using sql query:
Click on SQL present along side Structure
TRUNCATE tablename; //offers better performance, but used only when all entries need to be cleared
or
DELETE FROM tablename; //returns the number of rows deleted
I'm guessing here, based on issues I've had in the past which I did solve:
I ended up with two solutions. My original solution was based on using rsh. Since then, most of our servers have had ssh installed, which has made this easier.
Using rsh, I put together a table of machines vs OS vs custom options which would guide this process in perl. Bourne shell wasn't sufficient, and we don't have bash on Sun or HP machines (and didn't have bash on AIX at the time - AIX 5L wasn't out yet). Korn shell wasn't much of an option, either, since most of our Linux boxes don't have pdksh installed. But, if you don't face these limitations, you can implement the idea in ksh or bash, I think.
Anyway, I would basically run 'rsh $machine -l $user "$cmd"' where $machine, of course, was the machine I was logging in to, $user, similarly obvious (though when I was going in as "root" this had some variance as we have multiple roots on some machines for reasons I don't fully understand), and $cmd was basically "DISPLAY=$DISPLAY xterm", though if I were launching konsole, for example, $cmd would be "konsole --display=$DISPLAY". Since $DISPLAY was being evaluated locally (where it's set properly), and not being passed literally across rsh, the display would always be set correctly.
I also had to make sure that no one did anything silly like reset DISPLAY if it was already set.
Now, I just use ssh, make sure that X11Forwarding is set to yes on the server (sshd_config), and then I can just ssh to the machine, let X commands go across the wire encrypted, and it'll always go back to the right place.
I had the same issue but found resolve in a different way.
-
What I did was, I opened Advanced Settings for the Application Pool in IIS Manager.
There I set Enable 32-Bit Applications to True.
from abc import ABCMeta, abstractmethod
#Abstract class and abstract method declaration
class Jungle(metaclass=ABCMeta):
#constructor with default values
def __init__(self, name="Unknown"):
self.visitorName = name
def welcomeMessage(self):
print("Hello %s , Welcome to the Jungle" % self.visitorName)
# abstract method is compulsory to defined in child-class
@abstractmethod
def scarySound(self):
pass
If any of you is using the Angular-ui / ui-router, use:$state.go('yourstate')
instead of $location
. It did the trick for me.
If suppose you spotted this error after removing certain node modules, ideally should not be present the library under build.gradle(Module:app) . It can be removed manually and sync the project again.
Here is a very recent answer to this question from the file: 07reader.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
date_default_timezone_set('Europe/London');
/** Include PHPExcel_IOFactory */
require_once '../Classes/PHPExcel/IOFactory.php';
if (!file_exists("05featuredemo.xlsx")) {
exit("Please run 05featuredemo.php first." . EOL);
}
echo date('H:i:s') , " Load from Excel2007 file" , EOL;
$callStartTime = microtime(true);
$objPHPExcel = PHPExcel_IOFactory::load("05featuredemo.xlsx");
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
echo 'Call time to read Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
// Echo memory usage
echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
echo date('H:i:s') , " Write to Excel2007 format" , EOL;
$callStartTime = microtime(true);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
// Echo memory usage
echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
// Echo memory peak usage
echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
// Echo done
echo date('H:i:s') , " Done writing file" , EOL;
echo 'File has been created in ' , getcwd() , EOL;
Another example if you are using Titanium Alloy:
collection.fetch({
data: {
where : JSON.stringify({
page: 1
})
}
});
There's built-in solution for your problem: ModelChoiceField.
Generally, it's always worth trying to use ModelForm
when you need to create/change database objects. Works in 95% of the cases and it's much cleaner than creating your own implementation.
I would recommend you to have another class called File.
public class File
{
private string filename;
public File(string filename)
{
this.filename= filename;
}
public void download()
{
// download code using filename
}
}
And in your thread creation code, you instantiate a new file:
string filename = "my_file_name";
myFile = new File(filename);
ThreadStart threadDelegate = new ThreadStart(myFile.download);
Thread newThread = new Thread(threadDelegate);
I had a similar problem. I needed to get the last version of page content translation, in other words - to get that specific record which has highest number in version column. So I select all records ordered by version and then take the first row from result (by using LIMIT clause).
SELECT *
FROM `page_contents_translations`
ORDER BY version DESC
LIMIT 1
It could have formed a linked list, indeed. It's just that Map
contract requires it to replace the entry:
V put(K key, V value)
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)
http://docs.oracle.com/javase/6/docs/api/java/util/Map.html
For a map to store lists of values, it'd need to be a Multimap
. Here's Google's: http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html
A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.
Edit: Collision resolution
That's a bit different. A collision happens when two different keys happen to have the same hash code, or two keys with different hash codes happen to map into the same bucket in the underlying array.
Consider HashMap
's source (bits and pieces removed):
public V put(K key, V value) {
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
// i is the index where we want to insert the new element
addEntry(hash, key, value, i);
return null;
}
void addEntry(int hash, K key, V value, int bucketIndex) {
// take the entry that's already in that bucket
Entry<K,V> e = table[bucketIndex];
// and create a new one that points to the old one = linked list
table[bucketIndex] = new Entry<>(hash, key, value, e);
}
For those who are curious how the Entry
class in HashMap
comes to behave like a list, it turns out that HashMap
defines its own static Entry
class which implements Map.Entry
. You can see for yourself by viewing the source code:
var assemblyPath = Assembly.GetExecutingAssembly().CodeBase;
Tables work differently; sometimes counter-intuitively.
The solution is to use width
on the table cells instead of max-width
.
Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.
I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.
table {_x000D_
width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
border: 0;_x000D_
border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
min-width: 10px;_x000D_
width: 20px;_x000D_
max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
min-width: 40px;_x000D_
width: 45px;_x000D_
max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
<tr>_x000D_
<td class="a">A</td>_x000D_
<td class="b">B</td>_x000D_
<td class="c">C</td>_x000D_
</tr>_x000D_
</table>
_x000D_
I struggled a bit with coming up with a bash function that wraps Peter Tillemans' answer but here's what I came up with:
function regex { perl -n -e "/$1/ && printf \"%s\n\", "'$1' }
I found this worked better than opsb's awk-based bash function for the following regular expression argument, because I do not want the "ms" to be printed.
'([0-9]*)ms$'
wmic is a very complete tool
wmic diskdrive list
provide a (too much) detailed list, for instance
for less info
wmic diskdrive list brief
Sebastian Godelet mentions in the comments:
In C:
system("wmic diskdrive list");
As commented, you can also call the WinAPI, but... as shown in "How to obtain data from WMI using a C Application?", this is quite complex (and generally done with C++, not C).
Or with PowerShell:
Get-WmiObject Win32_DiskDrive
I had trouble with SQLite3, nStore and Alfred.
What works for me is node-dirty:
path = "#{__dirname}/data/messages.json"
messages = db path
message = 'text': 'Lorem ipsum dolor sit...'
messages.on "load", ->
messages.set 'my-unique-key', message, ->
console.log messages.get('my-unique-key').text
messages.forEach (key, value) ->
console.log "Found key: #{key}, val: %j", value
messages.on "drain", ->
console.log "Saved to #{path}"
The easiest way to use a non-static method/field within a a static method or vice versa is...
(To work this there must be at least one instance of this class)
This type of situation is very common in android app development eg:- An Activity has at-least one instance.
public class ParentClass{
private static ParentClass mParentInstance = null;
ParentClass(){
mParentInstance = ParentClass.this;
}
void instanceMethod1(){
}
static void staticMethod1(){
mParentInstance.instanceMethod1();
}
public static class InnerClass{
void innerClassMethod1(){
mParentInstance.staticMethod1();
mParentInstance.instanceMethod1();
}
}
}
Note:- This cannot be used as a builder method like this one.....
String.valueOf(100);
Many of the previous answers used backtracking. This is the asymptotically optimal way O(n*n!) of generating permutations after initial sorting
class Permutation {
/* runtime -O(n) for generating nextPermutaion
* and O(n*n!) for generating all n! permutations with increasing sorted array as start
* return true, if there exists next lexicographical sequence
* e.g [a,b,c],3-> true, modifies array to [a,c,b]
* e.g [c,b,a],3-> false, as it is largest lexicographic possible */
public static boolean nextPermutation(char[] seq, int len) {
// 1
if (len <= 1)
return false;// no more perm
// 2: Find last j such that seq[j] <= seq[j+1]. Terminate if no such j exists
int j = len - 2;
while (j >= 0 && seq[j] >= seq[j + 1]) {
--j;
}
if (j == -1)
return false;// no more perm
// 3: Find last l such that seq[j] <= seq[l], then exchange elements j and l
int l = len - 1;
while (seq[j] >= seq[l]) {
--l;
}
swap(seq, j, l);
// 4: Reverse elements j+1 ... count-1:
reverseSubArray(seq, j + 1, len - 1);
// return seq, add store next perm
return true;
}
private static void swap(char[] a, int i, int j) {
char temp = a[i];
a[i] = a[j];
a[j] = temp;
}
private static void reverseSubArray(char[] a, int lo, int hi) {
while (lo < hi) {
swap(a, lo, hi);
++lo;
--hi;
}
}
public static void main(String[] args) {
String str = "abcdefg";
char[] array = str.toCharArray();
Arrays.sort(array);
int cnt=0;
do {
System.out.println(new String(array));
cnt++;
}while(nextPermutation(array, array.length));
System.out.println(cnt);//5040=7!
}
//if we use "bab"-> "abb", "bab", "bba", 3(#permutations)
}
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
just set layout params in that layout like
create param variable
android.widget.LinearLayout.LayoutParams params = new android.widget.LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1f);
1f is weight variable
set your widget or layout like
TextView text = (TextView) findViewById(R.id.text);
text.setLayoutParams(params);
You try to instantiate an object of the Friends
class like this:
Friends f = new Friends(friendsName, friendsAge);
The class does not have a constructor that takes parameters. You should either add the constructor, or create the object using the constructor that does exist and then use the set-methods. For example, instead of the above:
Friends f = new Friends();
f.setName(friendsName);
f.setAge(friendsAge);
All other answers here depends on adding code the the notebook(!)
In my opinion is bad practice to hardcode a specific path into the notebook code, or otherwise depend on the location, since this makes it really hard to refactor you code later on. Instead I would recommend you to add the root project folder to PYTHONPATH when starting up your Jupyter notebook server, either directly from the project folder like so
env PYTHONPATH=`pwd` jupyter notebook
or if you are starting it up from somewhere else, use the absolute path like so
env PYTHONPATH=/Users/foo/bar/project/ jupyter notebook
The input may be string or integer.
num = 1000 #or num = '1000'
sum(map(lambda x: x[1]*(2**x[0]), enumerate(map(int, str(num))[::-1])))
# 8
Following line worked for me:
lbTabRes.Text += num + " x " + i + " = " + (num * i).ToString() + "<br/> \n";
In my case the element that generated the Exception was a button belonging to a form. I replaced
WebElement btnLogin = driver.findElement(By.cssSelector("button"));
btnLogin.click();
with
btnLogin.submit();
My environment was chromedriver windows 10
$data = DB::table('borrowers')
->join('loans', 'borrowers.id', '=', 'loans.borrower_id')
->select('borrowers.*', 'loans.*')
->where('loan_officers', 'like', '%' . $officerId . '%')
->where('loans.maturity_date', '<', date("Y-m-d"))
->get();
For question #1, let's break it into two parts. First, increment any document that has "items.item_name" equal to "my_item_two". For this you'll have to use the positional "$" operator. Something like:
db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } ,
{$inc : {"items.$.price" : 1} } ,
false ,
true);
Note that this will only increment the first matched subdocument in any array (so if you have another document in the array with "item_name" equal to "my_item_two", it won't get incremented). But this might be what you want.
The second part is trickier. We can push a new item to an array without a "my_item_two" as follows:
db.bar.update( {user_id : 123456, "items.item_name" : {$ne : "my_item_two" }} ,
{$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
false ,
true);
For your question #2, the answer is easier. To increment the total and the price of item_three in any document that contains "my_item_three," you can use the $inc operator on multiple fields at the same time. Something like:
db.bar.update( {"items.item_name" : {$ne : "my_item_three" }} ,
{$inc : {total : 1 , "items.$.price" : 1}} ,
false ,
true);
I know this post is old, but i ran in the same problem, and i solved it by simply changing my configuration from Java 11 down to Java 8.
IANAL but as I see it....
While you can combine GPL and MIT code, the GPL is tainting. Which means the package as a whole gets the limitations of the GPL. As that is more restrictive you can no longer use it in commercial (or rather closed source) software. Which also means if you have a MIT/BSD/ASL project you will not want to add dependencies to GPL code.
Adding a GPL dependency does not change the license of your code but it will limit what people can do with the artifact of your project. This is also why the ASF does not allow dependencies to GPL code for their projects.
I solved this problem in a simple way...
I added after oncreate
StrictMode.enableDefaults();
and solved this.
Or
use Service
or AsyncTask
to solve this
Note:
Do not change SDK version
Do not use a separate thread
For more, check this.
This is a bit old, but I ran into a similar issue. You can do this if you use a pointer:
#include <stdio.h>
typedef struct foo_t {
int a; int b; int c;
} foo_t;
static const foo_t s_FooInit = { .a=1, .b=2, .c=3 };
// or a pointer
static const foo_t *const s_pFooInit = (&(const foo_t){ .a=2, .b=4, .c=6 });
int main (int argc, char **argv) {
const foo_t *const f1 = &s_FooInit;
const foo_t *const f2 = s_pFooInit;
printf("Foo1 = %d, %d, %d\n", f1->a, f1->b, f1->c);
printf("Foo2 = %d, %d, %d\n", f2->a, f2->b, f2->c);
return 0;
}
Check the character set being emitted by your mirrored server. There appears to be a difference from that to the main server -- the live site appears to be outputting Unicode, where the mirror is not. Also, it's usually a good idea to scrub Unicode characters in your incoming content and replace them with their appropriate HTML entities.
Your specific issue regards "smart quotes," "em dashes" and "en dashes." I know you can replace em dashes with —
and n-dashes with –
(which should be done on the input side of your database); I don't know what the correct replacement for the smart quotes would be. (I usually just replace all curly single quotes with ' and all curly double quotes with " ... Typography geeks may feel free to shoot me on sight.)
I should note that some browsers are more forgiving than others with this issue -- Internet Explorer on Windows tends to auto-magically detect and "fix" this; Firefox and most other browsers display the question marks.
Here is the official FAQ on installing Python Modules: http://docs.python.org/install/index.html
There are some tips which might help you.
Your method needs to return a ActionResult
type:
public ActionResult Index()
{
//All we want to do is redirect to the class selection page
return RedirectToAction("SelectClasses", "Registration");
}
What for? You need to clarify: Do you need a pointer to the first element of an array, or an array?
If you're calling an API function that expects the former, you can do do_something(&v[0], v.size())
, where v
is a vector of double
s. The elements of a vector are contiguous.
Otherwise, you just have to copy each element:
double arr[100];
std::copy(v.begin(), v.end(), arr);
Ensure not only thar arr
is big enough, but that arr
gets filled up, or you have uninitialized values.
If you have set a width you may use:
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
text-align: center;
A simple as that :
<a href="#" class="btn btn-success" role="button">link</a>
Just add "class="btn btn-success" & role=button
You can use the "export" solution just like what other guys have suggested. I'd like to provide you with another solution for permanent convenience: you can use any path as GOPATH when running Go commands.
Firstly, you need to download a small tool named gost
: https://github.com/byte16/gost/releases . If you use ubuntu, you can download the linux version(https://github.com/byte16/gost/releases/download/v0.1.0/gost_linux_amd64.tar.gz).
Then you need to run the commands below to unpack it :
$ cd /path/to/your/download/directory
$ tar -xvf gost_linux_amd64.tar.gz
You would get an executable gost
. You can move it to /usr/local/bin
for convenient use:
$ sudo mv gost /usr/local/bin
Run the command below to add the path you want to use as GOPATH into the pathspace gost
maintains. It is required to give the path a name which you would use later.
$ gost add foo /home/foobar/bar # 'foo' is the name and '/home/foobar/bar' is the path
Run any Go command you want in the format:
gost goCommand [-p {pathName}] -- [goFlags...] [goArgs...]
For example, you want to run go get github.com/go-sql-driver/mysql
with /home/foobar/bar
as the GOPATH, just do it as below:
$ gost get -p foo -- github.com/go-sql-driver/mysql # 'foo' is the name you give to the path above.
It would help you to set the GOPATH and run the command. But remember that you have added the path into gost
's pathspace. If you are under any level of subdirectories of /home/foobar/bar
, you can even just run the command below which would do the same thing for short :
$ gost get -- github.com/go-sql-driver/mysql
gost
is a Simple Tool of Go which can help you to manage GOPATHs and run Go commands. For more details about how to use it to run other Go commands, you can just run gost help goCmdName
. For example you want to know more about install
, just type words below in:
$ gost help install
You can also find more details in the README of the project: https://github.com/byte16/gost/blob/master/README.md
It looks like they are also using pypi.org now. I added the following to %appdata%\pip\pip.ini and was able to download my packages from behind an HTTPS-intercepting proxy:
trusted-host = pypi.python.org files.pythonhosted.org pypi.org
You can add these style's and it works just as expected.
.btn {
white-space:normal !important;
word-wrap: break-word;
word-break: normal;
}
You can use MarkerWithLabel with SVG icons.
Update: The Google Maps Javascript API v3 now natively supports multiple characters in the MarkerLabel
proof of concept fiddle (you didn't provide your icon, so I made one up)
Note: there is an issue with labels on overlapping markers that is addressed by this fix, credit to robd who brought it up in the comments.
code snippet:
function initMap() {_x000D_
var latLng = new google.maps.LatLng(49.47805, -123.84716);_x000D_
var homeLatLng = new google.maps.LatLng(49.47805, -123.84716);_x000D_
_x000D_
var map = new google.maps.Map(document.getElementById('map_canvas'), {_x000D_
zoom: 12,_x000D_
center: latLng,_x000D_
mapTypeId: google.maps.MapTypeId.ROADMAP_x000D_
});_x000D_
_x000D_
var marker = new MarkerWithLabel({_x000D_
position: homeLatLng,_x000D_
map: map,_x000D_
draggable: true,_x000D_
raiseOnDrag: true,_x000D_
labelContent: "ABCD",_x000D_
labelAnchor: new google.maps.Point(15, 65),_x000D_
labelClass: "labels", // the CSS class for the label_x000D_
labelInBackground: false,_x000D_
icon: pinSymbol('red')_x000D_
});_x000D_
_x000D_
var iw = new google.maps.InfoWindow({_x000D_
content: "Home For Sale"_x000D_
});_x000D_
google.maps.event.addListener(marker, "click", function(e) {_x000D_
iw.open(map, this);_x000D_
});_x000D_
}_x000D_
_x000D_
function pinSymbol(color) {_x000D_
return {_x000D_
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',_x000D_
fillColor: color,_x000D_
fillOpacity: 1,_x000D_
strokeColor: '#000',_x000D_
strokeWeight: 2,_x000D_
scale: 2_x000D_
};_x000D_
}_x000D_
google.maps.event.addDomListener(window, 'load', initMap);
_x000D_
html,_x000D_
body,_x000D_
#map_canvas {_x000D_
height: 500px;_x000D_
width: 500px;_x000D_
margin: 0px;_x000D_
padding: 0px_x000D_
}_x000D_
.labels {_x000D_
color: white;_x000D_
background-color: red;_x000D_
font-family: "Lucida Grande", "Arial", sans-serif;_x000D_
font-size: 10px;_x000D_
text-align: center;_x000D_
width: 30px;_x000D_
white-space: nowrap;_x000D_
}
_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>_x000D_
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerwithlabel/src/markerwithlabel.js"></script>_x000D_
<div id="map_canvas" style="height: 400px; width: 100%;"></div>
_x000D_
You can use a LEFT JOIN with a "VALUES ('f',1),('p',2),('a',3),('i',4)" and use the second column in your order-by expression. Postgres will use a Hash Join which will be much faster than a huge CASE if you have a lot of values. And it is easier to autogenerate.
If this ordering information is fixed, then it should have its own table.
Another option is to create a shortcut with the following properties:
Target should be:
"%SYSTEMDRIVE%\Program Files (x86)\Git\bin\sh.exe" --login
Start in is the folder you wish your Git Bash prompt to launch into.
You cannot safely do what you want since the default hashCode() may not return the address, and has been mentioned, multiple objects with the same hashCode are possible. The only way to accomplish what you want, is to actually override the hashCode() method for the objects in question and guarantee that they all provide unique values. Whether this is feasible in your situation is another question.
For the record, I have experienced multiple objects with the same default hashcode in an IBM VM running in a WAS server. We had a defect where objects being put into a remote cache would get overwritten because of this. That was an eye opener for me at that point since I assumed the default hashcode was the objects memory address as well.
Well, null
is not an instance of any type. Rather, it is an invalid reference.
However, System.DbNull.Value
, is a valid reference to an instance of System.DbNull
(System.DbNull
is a singleton and System.DbNull.Value
gives you a reference to the single instance of that class) that represents nonexistent* values in the database.
*We would normally say null
, but I don't want to confound the issue.
So, there's a big conceptual difference between the two. The keyword null
represents an invalid reference. The class System.DbNull
represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null
) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).
Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull
is an example of.
This Worked for me
There are 2 options
in github - HTTPS/SSH
I had selected SSH
by mistake due to which the error was occuring -_-
Switch it to HTTPS and then copy the url again and try :)
You can do that like this:
INSERT INTO myTable (colum1, column2)
SELECT column1, column2 FROM OtherTable;
Just make sure the columns are matching, both in number as in datatype.
Better to support all the browsers:
img.lessOpacity {
opacity: 0.4;
filter: alpha(opacity=40);
zoom: 1; /* needed to trigger "hasLayout" in IE if no width or height is set */
}
I tried with this method and it significantly reduced my database insert execution time.
List<string> toinsert = new List<string>();
StringBuilder insertCmd = new StringBuilder("INSERT INTO tabblename (col1, col2, col3) VALUES ");
foreach (var row in rows)
{
// the point here is to keep values quoted and avoid SQL injection
var first = row.First.Replace("'", "''")
var second = row.Second.Replace("'", "''")
var third = row.Third.Replace("'", "''")
toinsert.Add(string.Format("( '{0}', '{1}', '{2}' )", first, second, third));
}
if (toinsert.Count != 0)
{
insertCmd.Append(string.Join(",", toinsert));
insertCmd.Append(";");
}
using (MySqlCommand myCmd = new MySqlCommand(insertCmd.ToString(), SQLconnectionObject))
{
myCmd.CommandType = CommandType.Text;
myCmd.ExecuteNonQuery();
}
*Create SQL connection object and replace it where I have written SQLconnectionObject.
C# does have a preprocessor. It works just slightly differently than that of C++ and C.
Here is a MSDN links - the section on all preprocessor directives.
document.getElementById('Id').value='new value';
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
This worked for me. But it gives only the main menu name. That is if user has opened Settings --> Bluetooth --> Device Name screen, RunningAppProcessInfo calls it as just Settings. Not able to drill down furthur
ActivityManager activityManager = (ActivityManager) context.getSystemService( Context.ACTIVITY_SERVICE );
PackageManager pm = context.getPackageManager();
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for(RunningAppProcessInfo appProcess : appProcesses) {
if(appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(appProcess.processName, PackageManager.GET_META_DATA));
Log.i("Foreground App", "package: " + appProcess.processName + " App: " + c.toString());
}
}
I finally was able to figure out a simple solution without the @Query
annotation.
List<People> findDistinctByNameNotIn(List<String> names);
Of course, I got the people object instead of only Strings. I can then do the change in java.
with Apache PDFBox it goes like this:
PDDocument document = PDDocument.load(new File("test.pdf"));
if (!document.isEncrypted()) {
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
System.out.println("Text:" + text);
}
document.close();
It is easy. C++11 provides an easy way to sum up elements of a vector.
sum = 0;
vector<int> vec = {1,2,3,4,5,....}
for(auto i:vec)
sum+=i;
cout<<" The sum is :: "<<sum<<endl;
Add XAttribute
in the constructor of the XElement
, like
new XElement("Conn", new XAttribute("Server", comboBox1.Text));
You can also add multiple attributes or elements via the constructor
new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));
or you can use the Add-Method of the XElement
to add attributes
XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);
You'd better create some class for each item instead of using anonymous objects. And in object you're serializing you should have array of those items. E.g.:
public class Item
{
public string name { get; set; }
public string index { get; set; }
public string optional { get; set; }
}
public class RootObject
{
public List<Item> items { get; set; }
}
Usage:
var objectToSerialize = new RootObject();
objectToSerialize.items = new List<Item>
{
new Item { name = "test1", index = "index1" },
new Item { name = "test2", index = "index2" }
};
And in the result you won't have to change things several times if you need to change data-structure.
p.s. Here's very nice tool for complex json
s
From one of my other posts, getting a unixtimestamp:
$unixTimestamp = time();
Converting to mysql datetime format:
$mysqlTimestamp = date("Y-m-d H:i:s", $unixTimestamp);
Getting some mysql timestamp:
$mysqlTimestamp = '2013-01-10 12:13:37';
Converting it to a unixtimestamp:
$unixTimestamp = strtotime('2010-05-17 19:13:37');
...comparing it with one or a range of times, to see if the user entered a realistic time:
if($unixTimestamp > strtotime("1999-12-15") && $unixTimestamp < strtotime("2025-12-15"))
{...}
Unix timestamps are safer too. You can do the following to check if a url passed variable is valid, before checking (for example) the previous range check:
if(ctype_digit($_GET["UpdateTimestamp"]))
{...}
As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:
<?php
$world = _("World");
$str = <<<EOF
<p>Hello</p>
<p>$world</p>
EOF;
echo $str;
?>
a workaround idea that comes to mind is building a class with a magic getter method.
You would declare a class like this:
class Translator
{
public function __get($name) {
return _($name); // Does the gettext lookup
}
}
Initialize an object of the class at some point:
$translate = new Translator();
You can then use the following syntax to do a gettext lookup inside a HEREDOC block:
$str = <<<EOF
<p>Hello</p>
<p>{$translate->World}</p>
EOF;
echo $str;
?>
$translate->World
will automatically be translated to the gettext lookup thanks to the magic getter method.
To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!
, you will have to use the following notation:
$translate->{"Hello World!!!!!!"}
This is all untested but should work.
Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.
If you do this a lot, NumPy is the way to go.
If for some reason you can't use NumPy:
>>> map(lambda x:sum(x)/float(len(x)), zip(*a))
[45.0, 10.5]
For setting row height there is separate method:
For Swift 3
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100.0;//Choose your custom row height
}
Older Swift uses
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100.0;//Choose your custom row height
}
Otherwise you can set row height using:
self.tableView.rowHeight = 44.0
In ViewDidLoad.
The problem is the OS can’t find Pip. Pip helps you install packages MODIFIED SOME GREAT ANSWERS TO BE BETTER
cd C:\Users\Username\AppData\Local\Programs\Python\Python37-32
In this directory, search pip with python -m pip then install package
python -m pip install ipywidgets
-m module-name Searches sys.path for the named module and runs the corresponding .py file as a script.
GO TO scripts from CMD. This is where Pip stays :)
cd C:\Users\User name\AppData\Local\Programs\Python\Python37-32\Scripts>
Then
pip install anypackage
One needs to be somewhat careful, since the Windows batch command:
for /f "delims=" %%a in ('command') do @set theValue=%%a
does not have the same semantics as the Unix shell statement:
theValue=`command`
Consider the case where the command fails, causing an error.
In the Unix shell version, the assignment to "theValue" still occurs, any previous value being replaced with an empty value.
In the Windows batch version, it's the "for" command which handles the error, and the "do" clause is never reached -- so any previous value of "theValue" will be retained.
To get more Unix-like semantics in Windows batch script, you must ensure that assignment takes place:
set theValue=
for /f "delims=" %%a in ('command') do @set theValue=%%a
Failing to clear the variable's value when converting a Unix script to Windows batch can be a cause of subtle errors.
You can create a new file, setenv.sh (or setenv.bat) inside tomcats bin directory and add following line there
export CLASSPATH=$CLASSPATH:/XX/xx/PATH_TO_DIR
At least some versions of SQL (Oracle, Informix, DB2, ISO Standard) support:
WHERE MOD(value, 2) = 1
MySQL supports '%' as the modulus operator:
WHERE value % 2 = 1
If you are using PHP: On a PDO object you can simple invoke the lastInsertId method after your insert.
Otherwise with a LAST_INSERT_ID you can get the value like this: SELECT LAST_INSERT_ID();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['iUserId'=>SORT_ASC]]
]);
Those solutions mentioned change how your program work.
You can off course put #if DEBUG
and #endif
around the Console calls, but if you really want to prevent the window from closing only on your dev machine under Visual Studio or if VS isn't running only if you explicitly configure it, and you don't want the annoying 'Press any key to exit...'
when running from the command line, the way to go is to use the System.Diagnostics.Debugger
API's.
If you only want that to work in DEBUG
, simply wrap this code in a [Conditional("DEBUG")] void BreakConditional()
method.
// Test some configuration option or another
bool launch;
var env = Environment.GetEnvironmentVariable("LAUNCH_DEBUGGER_IF_NOT_ATTACHED");
if (!bool.TryParse(env, out launch))
launch = false;
// Break either if a debugger is already attached, or if configured to launch
if (launch || Debugger.IsAttached) {
if (Debugger.IsAttached || Debugger.Launch())
Debugger.Break();
}
This also works to debug programs that need elevated privileges, or that need to be able to elevate themselves.
You cannot add methods to an existing type unless the existing type is marked as partial, you can only add methods that appear to be a member of the existing type through extension methods. Since this is the case you cannot add static methods to the type itself since extension methods use instances of that type.
There is nothing stopping you from creating your own static helper method like this:
static class DateTimeHelper
{
public static DateTime Tomorrow
{
get { return DateTime.Now.AddDays(1); }
}
}
Which you would use like this:
DateTime tomorrow = DateTimeHelper.Tomorrow;
void myfunc(void)
{
char* text = "Hello World";
char aLetter = 'C';
printf("%s\n", text);
printf("%c\n", aLetter);
}
Here in LoicTheAztec's answer is shown how to retrieve this information.
Only for WooCommerce v3.0+
Basically, you can call
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
This will return an array to the billing order data, including billing and shipping properties. Explore it by var_dump-ing it.
Here's an example:
$order_billing_data = array(
"first_name" => $order_data['billing']['first_name'],
"last_name" => $order_data['billing']['last_name'],
"company" => $order_data['billing']['company'],
"address_1" => $order_data['billing']['address_1'],
"address_2" => $order_data['billing']['address_2'],
"city" => $order_data['billing']['city'],
"state" => $order_data['billing']['state'],
"postcode" => $order_data['billing']['postcode'],
"country" => $order_data['billing']['country'],
"email" => $order_data['billing']['email'],
"phone" => $order_data['billing']['phone'],
);
I'm surprised I couldn't find a worthwhile solution here late 2018. I went ahead and figured it out a Bootstrap 3 solution myself using flexbox.
Clean and simple example:
HTML
<div class="row row-equal">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 col-equal">
<p>Text</p>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 col-equal">
<img src="//placehold.it/200x200">
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 col-equal">
<p>Text</p>
</div>
</div>
CSS
img {
width: 100%;
}
p {
padding: 2em;
}
@media (min-width: 768px) {
.row-equal {
display: flex;
flex-wrap: wrap;
}
.col-equal {
margin: auto;
}
}
View working demo: http://jsfiddle.net/5kmtfrny/
From ?read.table
: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.
So, perhaps your data file isn't clean. Being more specific will help the data import:
d = read.table("foobar.txt",
sep="\t",
col.names=c("id", "name"),
fill=FALSE,
strip.white=TRUE)
will specify exact columns and fill=FALSE
will force a two column data frame.
The first backslash in your string is being interpreted as a special character, in fact because it's followed by a "U" it's being interpreted as the start of a unicode code point.
To fix this you need to escape the backslashes in the string. I don't know Python specifically but I'd guess you do it by doubling the backslashes:
data = open("C:\\Users\\miche\\Documents\\school\\jaar2\\MIK\\2.6\\vektis_agb_zorgverlener")
You need to use WITH ROLLBACK IMMEDIATE
to boot other conections out with no regards to what or who is is already using it.
Or use WITH NO_WAIT
to not hang and not kill existing connections. See http://www.blackwasp.co.uk/SQLOffline.aspx for details
Although I didn't use this exact function I got this same error.
In my case I just had to remove the protocol.
Instead of $uri = "http://api.hostip.info/?ip=$ip&position=true";
Use $uri = "api.hostip.info/?ip=$ip&position=true";
And it worked fine afterwards
People already suggested methods that will try to determine if the program is being compiled in 32-bit
or 64-bit
.
And I want to add that you can use the c++11 feature static_assert
to make sure that the architecture is what you think it is ("to relax").
So in the place where you define the macros:
#if ...
# define IS32BIT
static_assert(sizeof(void *) == 4, "Error: The Arch is not what I think it is")
#elif ...
# define IS64BIT
static_assert(sizeof(void *) == 8, "Error: The Arch is not what I think it is")
#else
# error "Cannot determine the Arch"
#endif
Compare date only instead of date + time (NOW) with:
CURDATE()
Here's another way I implemented (didn't test it with an unwind segue but it probably wouldn't differentiate, as others have stated in regards to other solutions on this page) to have the parent view controller perform actions before the child VC it pushed gets popped off the view stack (I used this a couple levels down from the original UINavigationController). This could also be used to perform actions before the childVC gets pushed, too. This has the added advantage of working with the iOS system back button, instead of having to create a custom UIBarButtonItem or UIButton.
Have your parent VC adopt the UINavigationControllerDelegate
protocol and register for delegate messages:
MyParentViewController : UIViewController <UINavigationControllerDelegate>
-(void)viewDidLoad {
self.navigationcontroller.delegate = self;
}
Implement this UINavigationControllerDelegate
instance method in MyParentViewController
:
- (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC {
// Test if operation is a pop; can also test for a push (i.e., do something before the ChildVC is pushed
if (operation == UINavigationControllerOperationPop) {
// Make sure it's the child class you're looking for
if ([fromVC isKindOfClass:[ChildViewController class]]) {
// Can handle logic here or send to another method; can also access all properties of child VC at this time
return [self didPressBackButtonOnChildViewControllerVC:fromVC];
}
}
// If you don't want to specify a nav controller transition
return nil;
}
If you specify a specific callback function in the above UINavigationControllerDelegate
instance method
-(id <UIViewControllerAnimatedTransitioning>)didPressBackButtonOnAddSearchRegionsVC:(UIViewController *)fromVC {
ChildViewController *childVC = ChildViewController.new;
childVC = (ChildViewController *)fromVC;
// childVC.propertiesIWantToAccess go here
// If you don't want to specify a nav controller transition
return nil;
}
The following can be used to retreive an environment parameter:
println System.getenv("MY_PARAM")
Each tablespace has one or more datafiles that it uses to store data.
The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.
To find out if the actual limit is 32gb, run the following:
select value from v$parameter where name = 'db_block_size';
Compare the result you get with the first column below, and that will indicate what your max datafile size is.
I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).
Block Sz Max Datafile Sz (Gb) Max DB Sz (Tb)
-------- -------------------- --------------
2,048 8,192 524,264
4,096 16,384 1,048,528
8,192 32,768 2,097,056
16,384 65,536 4,194,112
32,768 131,072 8,388,224
You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):
select bytes/1024/1024 as mb_size,
maxbytes/1024/1024 as maxsize_set,
x.*
from dba_data_files x
MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).
If your datafile has a low max size or autoextend is not on you could simply run:
alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;
However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:
alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;
php.js ( http://www.phpjs.org/ ) has a isset()
function: http://phpjs.org/functions/isset:454
Are you parsing that string as ObjectId
?
Here in my application, what I do is:
ObjectId.fromString( myObjectIdString );
; always_populate_raw_post_data = -1 in php.init remove comment of this line .. always_populate_raw_post_data = -1
You can achieve almost everything in PROCESS_NUM
with this one-liner:
[ `pgrep $1` ] && return 1 || return 0
if you're looking for a partial match, i.e. program is named foobar and you want your $1
to be just foo you can add the -f switch
to pgrep:
[[ `pgrep -f $1` ]] && return 1 || return 0
Putting it all together your script could be reworked like this:
#!/bin/bash
check_process() {
echo "$ts: checking $1"
[ "$1" = "" ] && return 0
[ `pgrep -n $1` ] && return 1 || return 0
}
while [ 1 ]; do
# timestamp
ts=`date +%T`
echo "$ts: begin checking..."
check_process "dropbox"
[ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
sleep 5
done
Running it would look like this:
# SHELL #1
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox
# SHELL #2
$ dropbox stop
Dropbox daemon stopped.
# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: not running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox
Hope this helps!
A trick that works is to position box #2 with position: absolute
instead of position: relative
. We usually put a position: relative
on an outer box (here box #2) when we want an inner box (here box #3) with position: absolute
to be positioned relative to the outer box. But remember: for box #3 to be positioned relative to box #2, box #2 just need to be positioned. With this change, we get:
And here is the full code with this change:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">
/* Positioning */
#box1 { overflow: hidden }
#box2 { position: absolute }
#box3 { position: absolute; top: 10px }
/* Styling */
#box1 { background: #efe; padding: 5px; width: 125px }
#box2 { background: #fee; padding: 2px; width: 100px; height: 100px }
#box3 { background: #eef; padding: 2px; width: 75px; height: 150px }
</style>
</head>
<body>
<br/><br/><br/>
<div id="box1">
<div id="box2">
<div id="box3"/>
</div>
</div>
</body>
</html>
Try redirecting the output to Out-Null. Like so,
$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose | out-null
Fastest approach is the traditional for loop. Here is a more comprehensive performance comparison.
https://gists.cwidanage.com/2019/11/how-to-iterate-over-javascript-arrays.html
It's an old question. But for those who come across this question...
The white background behind the rounded corners is not actually the container. That is the canvas color of the app.
TO FIX: Change the canvas color of your app to Colors.transparent
Example:
return new MaterialApp(
title: 'My App',
theme: new ThemeData(
primarySwatch: Colors.green,
canvasColor: Colors.transparent, //----Change to this------------
accentColor: Colors.blue,
),
home: new HomeScreen(),
);
var str = "";
for(var k in obj)
if (obj.hasOwnProperty(k)) //omit this test if you want to see built-in properties
str += k + " = " + obj[k] + "\n";
alert(str);
You need INDIRECT
function:
=INDIRECT("'"&A5&"'!G7")
For anyone who has this issue with an already running container, and they don't necessarily want to rebuild, the following command connects to a running container with root privileges:
docker exec -ti -u root container_name bash
You can also connect using its ID, rather than its name, by finding it with:
docker ps -l
To save your changes so that they are still there when you next launch the container (or docker-compose cluster):
docker commit container_id image_name
To roll back to a previous image version (warning: this deletes history rather than appends to the end, so to keep a reference to the current image, tag it first using the optional step):
docker history image_name
docker tag latest_image_id my_descriptive_tag_name # optional
docker tag desired_history_image_id image_name
To start a container that isn't running and connect as root:
docker run -ti -u root --entrypoint=/bin/bash image_id_or_name -s
To copy from a running container:
docker cp <containerId>:/file/path/within/container /host/path/target
To export a copy of the image:
docker save container | gzip > /dir/file.tar.gz
Which you can restore to another Docker install using:
gzcat /dir/file.tar.gz | docker load
It is much quicker but takes more space to not compress, using:
docker save container | dir/file.tar
And:
cat dir/file.tar | docker load
The answer is "mostly".
We've hit a problem using it where the EF generates code that uses the CROSS and OUTER APPLY operators. This link shows that MS knows its a problem with SQL Server previous to 2005 however, they forget to mention that these operators are not supported by Oracle either.
If you insist on using ForEach-Object, then I would suggest adding a "break condition" like this:
$Break = $False;
1,2,3,4 | Where-Object { $Break -Eq $False } | ForEach-Object {
$Break = $_ -Eq 3;
Write-Host "Current number is $_";
}
The above code must output 1,2,3 and then skip (break before) 4. Expected output:
Current number is 1
Current number is 2
Current number is 3
I haven't figured out yet why this occurs, but I had classes that were in my App_Code
folder that were calling methods in each other, and were fine in doing this when I built a .NET 4.5.2 project, but then I had to revert it to 4.0 as the target server wasn't getting upgraded. That's when I found this problem (after fixing the langversion
in my web.config from 6 to 5... another story)....
One of my methods kept having an error like:
The type X.Y conflicts with the imported type X.Y in MyProject.DLL
All of my classes were already set to "Compile" in their properties, as suggested on the accepted answer here, and each had a common namespace that was the same, and each had using MyNamespace;
at the top of each class.
I found that if I just moved the offending classes that had to call methods in each other to another, standard folder named something other than "App_Code", they stopped having this conflict issue.
Note: If you create a standard folder called "AppCode", move your classes into it, delete the "App_Code" folder, then rename "AppCode" to "App_Code", your problems will return. It doesn't matter if you use the "New Folder" or "Add ASP .NET Folder" option to create "App_Code" - it seems to key in on the name.
Maybe this is just a .NET 4.0 (and possibly earlier) issue... I was just fine in 4.5.2 before having to revert!
Oneliner:
do_X() if len(your_list) > your_index else do_something_else()
Full example:
In [10]: def do_X():
...: print(1)
...:
In [11]: def do_something_else():
...: print(2)
...:
In [12]: your_index = 2
In [13]: your_list = [1,2,3]
In [14]: do_X() if len(your_list) > your_index else do_something_else()
1
Just for info. Imho, try ... except IndexError
is better solution.
Destroy the datepicker's instance when you don't want it and create new instance whenever necessary.
I know this is ugly but only this seems to be working...
$("#ddlSearchType").change(function () {
if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") {
$("#txtSearch").datepicker();
}
else {
$("#txtSearch").datepicker("destroy");
}
});
I got this error when I tried assigning a component property to a state property during instantiation
export default {
props: ['value1'],
data() {
return {
value2: this.value1 // throws the error
}
},
created(){
this.value2 = this.value1 // safe
}
}
int titleId = getResources().getIdentifier("action_bar_title", "id",
"android");
TextView yourTextView = (TextView) findViewById(titleId);
yourTextView.setTextColor(getResources().getColor(R.color.black));
yourTextView.setTypeface(face);
For me reinstalling and then upgrading the pip worked.
Reinstall pip by using below command or following link How do I install pip on macOS or OS X?
curl https://bootstrap.pypa.io/get-pip.py -o - | python
Upgrade pip after it's installed
pip install -U pip
I solved this issue by creating a bean for my service in SpringConfig.java file. Please check the below code,
@Configuration
public class SpringConfig {
@Bean
public TransactionService transactionService() {
return new TransactionServiceImpl();
}
}
The path of this file is shown in the below image, Spring boot application folder structure
Just for fine tuning. If you want to set only one of the boundaries of the axis and let the other boundary unchanged, you can choose one or more of the following statements
plt.xlim(right=xmax) #xmax is your value
plt.xlim(left=xmin) #xmin is your value
plt.ylim(top=ymax) #ymax is your value
plt.ylim(bottom=ymin) #ymin is your value
list()
is inherently slower than []
, because
there is symbol lookup (no way for python to know in advance if you did not just redefine list to be something else!),
there is function invocation,
then it has to check if there was iterable argument passed (so it can create list with elements from it) ps. none in our case but there is "if" check
In most cases the speed difference won't make any practical difference though.
I was given access to a database, but not the table where my query was being stored in.
Inspired by @marc_s answer, I had a look at HeidiSQL which is a Windows program that can deal with MySQL, SQL Server, and PostgreSQL.
I found that it can also search a database for a string.
It will search each table and give you how many times it found the string per table!
The /Date(ms + timezone)/
is a ASP.NET syntax for JSON dates. You might want to use a library like momentjs for parsing such dates. It would come in handy if you need to manipulate or print the dates any time later.
use test
go
alter proc restore_mdf_ldf_main (@database varchar(100), @mdf varchar(100),@ldf varchar(100),@filename varchar(200))
as
begin
begin try
RESTORE DATABASE @database FROM DISK = @FileName
with norecovery,
MOVE @mdf TO 'D:\sql samples\sample.mdf',
MOVE @ldf TO 'D:\sql samples\sample.ldf'
end try
begin catch
SELECT ERROR_MESSAGE() AS ErrorMessage;
print 'Restoring of the database ' + @database + ' failed';
end catch
end
exec restore_mdf_ldf_main product,product,product_log,'c:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\product.bak'
This will be used to change the Html content inside the span
$('#abc span').html('goes inside the span');
if you want to change the text inside the span, you can use:
$('#abc span').text('goes inside the span');
Your string is invalid, but assuming it was valid, you'd have to do:
var finalData = str.replace(/\\/g, "");
When you want to replace all the occurences with .replace
, the first parameter must be a regex, if you supply a string, only the first occurrence will be replaced, that's why your replace wouldn't work.
Cheers
Just remove activation section, I don't know why -Pdev1 doesn't override default false activation. But if you omit this:
<activation>
<activeByDefault>false</activeByDefault>
</activation>
then your profile will be activated only after explicit declaration as -Pdev1
Simplest of them all is to use the "Flash Fill" option under the "Data" tab.
Keep the original input column on the left (say column A) and just add a blank column on the right of it (say column B, this new column will be treated as output).
Just fill in a couple of cells of Column B with actual expected output. In this case:
[email protected],
[email protected],
Then select the column range where you want the output along with the first couple of cells you filled manually ... then do the magic...click on "Flash Fill".
It basically understands the output pattern corresponding to the input and fills the empty cells.
On Windows:
Go to Win -> Control Panel -> Credential Manager -> Windows Credentials
Search for github address and remove it.
Then try to execute:
git push -u origin master
Windows will ask for your git credentials again, put the right ones and that's it.
It actually means that class is already declared in the page and you are trying to recreate it.
A simple technique is as follow.
I solved the issue with the following. Hope this will help you a bit.
if(!class_exists("testClassIfExist"))
{
require_once("testClassIfExist.php");
}
For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:
"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="MySheet1" sheetId="1" r:id="rId1" />
<sheet name="MySheet2" sheetId="2" r:id="rId2" />
</sheets>
</workbook>
The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" ?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1">
<c r="A1">
<v>100</v>
</c>
</row>
</sheetData>
</worksheet>
"
Detection of cell encodings:
Just to keep a default value of the variable. Press Enter to use default from the recent run of your .bat:
@echo off
set /p Var1=<Var1.txt
set /p Var1="Enter new value ("%Var1%") "
echo %Var1%> Var1.txt
rem YourApp %Var1%
In the first run just ignore the message about lack of file with the initial value of the variable (or do create the Var1.txt manually).
The equivalent command in svn is:
svn log --diff -r revision
jScrollPane is a good solution to cross browser scrollbars and degrades nicely.
You can use list.sort
with its optional key
parameter and a lambda
expression:
>>> lst = [
... ['John',2],
... ['Jim',9],
... ['Jason',1]
... ]
>>> lst.sort(key=lambda x:x[1])
>>> lst
[['Jason', 1], ['John', 2], ['Jim', 9]]
>>>
This will sort the list in-place.
Note that for large lists, it will be faster to use operator.itemgetter
instead of a lambda
:
>>> from operator import itemgetter
>>> lst = [
... ['John',2],
... ['Jim',9],
... ['Jason',1]
... ]
>>> lst.sort(key=itemgetter(1))
>>> lst
[['Jason', 1], ['John', 2], ['Jim', 9]]
>>>
Your code is
urlpatterns = [
url(r'^$', 'myapp.views.home'),
url(r'^contact/$', 'myapp.views.contact'),
url(r'^login/$', 'django.contrib.auth.views.login'),
]
change it to following as you're importing include()
function :
urlpatterns = [
url(r'^$', views.home),
url(r'^contact/$', views.contact),
url(r'^login/$', views.login),
]
In my case ,
//app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
//{
// HotModuleReplacement = true
//});
i commented it in startup.cs
If your textbox is a Required field and have some regex pattern to match and has minlength and maxlength
TestBox code
<input type="text" name="myfieldname" ng-pattern="/^[ A-Za-z0-9_@./#&+-]*$/" ng-minlength="3" ng-maxlength="50" class="classname" ng-model="model.myfieldmodel">
Ng-Class to Add
ng-class="{ 'err' : myform.myfieldname.$invalid || (myform.myfieldname.$touched && !model.myfieldmodel.length) }"
I'm surprised nobody has mentioned the simplest version:
\d
This will match any digit. If your regular expression engine is Unicode-aware, this means it will match anything that's defined as a digit in any language, not just the Arabic numerals 0-9.
There's no need to put it in [
square brackets]
to define it as a character class, as one of the other answers did; \d
works fine by itself.
Since it's not anchored with ^
or $
, it will match any subset of the string, so if the string contains at least one digit, this will match.
And there's no need for the added complexity of +
, since the goal is just to determine whether there's at least one digit. If there's at least one digit, this will match; and it will do so with a minimum of overhead.
If you are using express you need to allow serving of static content by adding something like: var server = express(); server.use(express.static('./public')); // where public is the app root folder, with the fonts contained therein, at any level, i.e. public/fonts or public/dist/fonts... // If you are using connect, google for a similar configuration.
You may try this example:
<form>_x000D_
<h1>Hello! I'm duke! What's you name?</h1>_x000D_
<input type="text" name="user">_x000D_
<br>_x000D_
<br>_x000D_
<input type="submit" value="submit"> _x000D_
<input type="reset">_x000D_
</form>_x000D_
<h1>Hello ${param.user}</h1> _x000D_
<!-- its Expression Language -->
_x000D_
$(function(){
if($.browser.msie && $.browser.version <= 9){
$("[placeholder]").focus(function(){
if($(this).val()==$(this).attr("placeholder")) $(this).val("");
}).blur(function(){
if($(this).val()=="") $(this).val($(this).attr("placeholder"));
}).blur();
$("[placeholder]").parents("form").submit(function() {
$(this).find('[placeholder]').each(function() {
if ($(this).val() == $(this).attr("placeholder")) {
$(this).val("");
}
})
});
}
});
try this
You can download code here.
Step 1:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:id="@+id/btnCustomToast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Custom Toast" />
</RelativeLayout>
Step 2:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/custom_toast_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/custom_toast_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My custom Toast Example Text" />
</LinearLayout>
Step 3:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button btnCustomToast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCustomToast= (Button) findViewById(R.id.btnCustomToast);
btnCustomToast.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Find custom toast example layout file
View layoutValue = LayoutInflater.from(MainActivity.this).inflate(R.layout.android_custom_toast_example, null);
// Creating the Toast object
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
// gravity, xOffset, yOffset
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setView(layoutValue);//setting the view of custom toast layout
toast.show();
}
});
}
}
You would use the read.csv
function; for example:
dat = read.csv("spam.csv", header = TRUE)
You can also reference this tutorial for more details.
Note: make sure the .csv
file to read is in your working directory (using getwd()
) or specify the right path to file. If you want, you can set the current directory using setwd
.
To solve the problem zabbix server is not running you have to :
First - Check that all of the database parameters in zabbix.conf.php ( /etc/zabbix/web/zabbix.conf.php) and zabbix_server.conf ( /etc/zabbix/zabbix_server.conf) to be the same. Including:
• DBHost
• DBName
• DBUser
• DBPassword
Second- Change SElinux parameters:
#setsebool -P httpd_can_network_connect on
#setsebool -P httpd_can_connect_zabbix 1
#setsebool -P zabbix_can_network 1
After all, restart all services:
#service zabbix-server restart
#service httpd restart
worth a try.
They say it right there in the documentation for the FPDF constructor:
FPDF([string orientation [, string unit [, mixed size]]])
This is the class constructor. It allows to set up the page size, the orientation and the unit of measure used in all methods (except for font sizes). Parameters ...
size
The size used for pages. It can be either one of the following values (case insensitive):
A3 A4 A5 Letter Legal
or an array containing the width and the height (expressed in the unit given by unit).
They even give an example with custom size:
Example with a custom 100x150 mm page size:
$pdf = new FPDF('P','mm',array(100,150));
"Which editor/IDE for ...?" is a longstanding way to start a "My dog is too prettier than yours!" slapfest. Nowadays most editors from vim
upwards can be used, there are multiple good alternatives, and even IDEs that started as C or Java tools work pretty well with Python and other dynamic languages.
That said, having tried a bunch of IDEs (Eclipse, NetBeans, XCode, Komodo, PyCharm, ...), I am a fan of ActiveState's Komodo IDE. I use it on Mac OS X primarily, though I've used it for years on Windows as well. The one license follows you to any platform.
Komodo is well-integrated with popular ActiveState builds of the languages themselves (esp. for Windows), works well with the fabulous (and Pythonic) Mercurial change management system (among others), and has good-to-excellent abilities for core tasks like code editing, syntax coloring, code completion, real-time syntax checking, and visual debugging. It is a little weak when it comes to pre-integrated refactoring and code-check tools (e.g. rope, pylint), but it is extensible and has a good facility for integrating external and custom tools.
Some of the things I like about Komodo go beyond the write-run-debug loop. ActiveState has long supported the development community (e.g. with free language builds, package repositories, a recipes site, ...), since before dynamic languages were the trend. The base Komodo Edit editor is free and open source, an extension of Mozilla's Firefox technologies. And Komodo is multi-lingual. I never end up doing just Python, just Perl, or just whatever. Komodo works with the core language (Python, Perl, Ruby, PHP, JavaScript) alongside supporting languages (XML, XSLT, SQL, X/HTML, CSS), non-dynamic languages (Java, C, etc.), and helpers (Makefiles, INI and config files, shell scripts, custom little languages, etc.) Others can do that too, but Komodo puts them all in once place, ready to go. It's a Swiss Army Knife for dynamic languages. (This is contra PyCharm, e.g., which is great itself, but I'd need like a half-dozen of JetBrains' individual IDEs to cover all the things I do).
Komodo IDE is by no means perfect, and editors/IDEs are the ultimate YMMV choice. But I am regularly delighted to use it, and every year I re-up my support subscription quite happily. Indeed, I just remembered! That's coming up this month. Credit card: Out. I have no commercial connection to ActiveState--just a happy customer.
Use Long.parseLong()
Long.parseLong("0", 10) // returns 0L
Long.parseLong("473", 10) // returns 473L
Long.parseLong("-0", 10) // returns 0L
Long.parseLong("-FF", 16) // returns -255L
Long.parseLong("1100110", 2) // returns 102L
Long.parseLong("99", 8) // throws a NumberFormatException
Long.parseLong("Hazelnut", 10) // throws a NumberFormatException
Long.parseLong("Hazelnut", 36) // returns 1356099454469L
Long.parseLong("999") // returns 999L
sp_spaceused
Place this dependency, and dont forget to select : Include dependencies with "provided" scope
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
\S
matches anything but a whitespace, according to this reference.
After trying a lot of things, I found working solutions that nuked the autofilled fields and replaced them with duplicated. Not to loose attached events, i came up with another (a bit lengthy) solution.
At each "input" event it swiftly attaches "change" events to all involved inputs. It tests if they have been autofilled. If yes, then dispatch a new text event that will trick the browser to think that the value has been changed by the user, thus allowing to remove the yellow background.
var initialFocusedElement = null
, $inputs = $('input[type="text"]');
var removeAutofillStyle = function() {
if($(this).is(':-webkit-autofill')) {
var val = this.value;
// Remove change event, we won't need it until next "input" event.
$(this).off('change');
// Dispatch a text event on the input field to trick the browser
this.focus();
event = document.createEvent('TextEvent');
event.initTextEvent('textInput', true, true, window, '*');
this.dispatchEvent(event);
// Now the value has an asterisk appended, so restore it to the original
this.value = val;
// Always turn focus back to the element that received
// input that caused autofill
initialFocusedElement.focus();
}
};
var onChange = function() {
// Testing if element has been autofilled doesn't
// work directly on change event.
var self = this;
setTimeout(function() {
removeAutofillStyle.call(self);
}, 1);
};
$inputs.on('input', function() {
if(this === document.activeElement) {
initialFocusedElement = this;
// Autofilling will cause "change" event to be
// fired, so look for it
$inputs.on('change', onChange);
}
});
Basically copying and pasting from Bjarne Stroustrup's "The C++ Programming Language 4th Edition":
List initialization does not allow narrowing (§iso.8.5.4). That is:
Example:
void fun(double val, int val2) {
int x2 = val; // if val == 7.9, x2 becomes 7 (bad)
char c2 = val2; // if val2 == 1025, c2 becomes 1 (bad)
int x3 {val}; // error: possible truncation (good)
char c3 {val2}; // error: possible narrowing (good)
char c4 {24}; // OK: 24 can be represented exactly as a char (good)
char c5 {264}; // error (assuming 8-bit chars): 264 cannot be
// represented as a char (good)
int x4 {2.0}; // error: no double to int value conversion (good)
}
The only situation where = is preferred over {} is when using auto
keyword to get the type determined by the initializer.
Example:
auto z1 {99}; // z1 is an int
auto z2 = {99}; // z2 is std::initializer_list<int>
auto z3 = 99; // z3 is an int
Prefer {} initialization over alternatives unless you have a strong reason not to.
The M2_HOME
environment variable for the global one. See Settings Reference:
The
settings
element in thesettings.xml
file contains elements used to define values which configure Maven execution in various ways, like thepom.xml
, but should not be bundled to any specific project, or distributed to an audience. These include values such as the local repository location, alternate remote repository servers, and authentication information. There are two locations where a settings.xml file may live:
- The Maven install:
$M2_HOME/conf/settings.xml
- A user's install:
${user.home}/.m2/settings.xml
envsubst
seems exactly like something I wanted to use, but -v
option surprised me a bit.
While envsubst < template.txt
was working fine, the same with option -v
was not working:
$ cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.1 (Maipo)
$ envsubst -V
envsubst (GNU gettext-runtime) 0.18.2
Copyright (C) 2003-2007 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Bruno Haible.
As I wrote, this was not working:
$ envsubst -v < template.txt
envsubst: missing arguments
$ cat template.txt | envsubst -v
envsubst: missing arguments
I had to do this to make it work:
TEXT=`cat template.txt`; envsubst -v "$TEXT"
Maybe it helps someone.
two of the best options are
$(this).parent("div:first")
$(this).parent().closest('div')
and of course you can find the class attr by
$(this).parent("div:first").attr("class")
$(this).parent().closest('div').attr("class")
You could use the Array.reduce
method:
const myData = [_x000D_
['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],_x000D_
['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], _x000D_
['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], _x000D_
['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]_x000D_
];_x000D_
const sum = myData_x000D_
.map( v => v[1] ) _x000D_
.reduce( (sum, current) => sum + current, 0 );_x000D_
_x000D_
console.log(sum);
_x000D_
See MDN
Edit the .csproj or vbproj file. Find and replace these entries
<UseIIS>true</UseIIS> by <UseIIS>false</UseIIS>
<UseIISExpress>true</UseIISExpress> by <UseIISExpress>false</UseIISExpress>
A good resource start off point would be MSDN as your looking into a microsoft product
You can use the function RESHAPE:
B = reshape(A.',1,[]);
For java 11+ you can use Objects.nonNull(Object obj)
if(nonNull(foo)){
//
}
Math.floor((Date.now() - Date.parse(new Date().getFullYear(), 0, 0)) / 86400000)
this is my solution
This should work!
[HttpPost]
public ActionResult RedirectToImages(int id)
{
return RedirectToAction("Index", "ProductImageManeger", new { id = id });
}
[HttpGet]
public ViewResult Index(int id)
{
return View(_db.ProductImages.Where(rs => rs.ProductId == id).ToList());
}
Notice that you don't have to pass the name of view if you are returning the same view as implemented by the action.
Your view should inherit the model as this:
@model <Your class name>
You can then access your model in view as:
@Model.<property_name>
In Skype:
Go to Tools ? Options ? Advanced ? Connections
and uncheck the box use port 80 and 443 as alternative
. This should help.
As Salman Quader said: In the updated skype(8.x), there is no menu option to change the port. This means this answer is no longer valid.
Okay, I'd like to just add my class only because there might be some dev out there in the future that wants to connect to a Netbackup server (or something similar) and do stuff from Java while ignoring the SSL cert. This worked for me and we use windows active directory for auth to the Netbackup server.
public static void main(String[] args) throws Exception {
SSLContext sslcontext = null;
try {
sslcontext = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
try {
sslcontext.init(null, new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@Override
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}}, new java.security.SecureRandom());
} catch (KeyManagementException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
//HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder().credentials(username, password).build();
ClientConfig clientConfig = new ClientConfig();
//clientConfig.register(feature);
Client client = ClientBuilder.newBuilder().withConfig(clientConfig)
.sslContext(sslcontext)
.hostnameVerifier((s1, s2) -> true)
.build();
//String the_url = "https://the_server:1556/netbackup/security/cacert";
String the_token;
{
String the_url = "https://the_server:1556/netbackup/login";
WebTarget webTarget = client.target(the_url);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
String jsonString = new JSONObject()
.put("domainType", "NT")
.put("domainName", "XX")
.put("userName", "the username")
.put("password", "the password").toString();
System.out.println(jsonString);
Response response = invocationBuilder.post(Entity.json(jsonString));
String data = response.readEntity(String.class);
JSONObject jo = new JSONObject(data);
the_token = jo.getString("token");
System.out.println("token is:" + the_token);
}
{
String the_url = "https://the_server:1556/netbackup/admin/jobs/1122012"; //job id 1122012 is an example
WebTarget webTarget = client.target(the_url);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, the_token).header(HttpHeaders.ACCEPT, "application/vnd.netbackup+json;version=1.0");
Response response = invocationBuilder.get();
System.out.println("response status:" + response.getStatus());
String data = response.readEntity(String.class);
//JSONObject jo = new JSONObject(data);
System.out.println(data);
}
}
I know it can be considered off-topic, but I bet the dev that tries to connect to a Netbackup server will probably end up here. By the way many thanks to all the answers in this question! The spec I'm talking about is here and their code samples are (currently) missing a Java example.
***This is of course unsafe since we ignore the cert!
You can also do something like this...
<input @input="myHandler('foo', 'bar', ...arguments)">
Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.
@Theo
The LINQ translator is smart enough to execute:
.Where(r => r.UserName !="XXXX" && r.UsernName !="YYYY")
I've test this in LinqPad ==> YES, Linq translator is smart enough :))
Using Postman for Chrome, selecting CODE you get this... And works
<?php_x000D_
_x000D_
$curl = curl_init();_x000D_
_x000D_
curl_setopt_array($curl, array(_x000D_
CURLOPT_URL => "https://blablabla.com/comorl",_x000D_
CURLOPT_RETURNTRANSFER => true,_x000D_
CURLOPT_ENCODING => "",_x000D_
CURLOPT_MAXREDIRS => 10,_x000D_
CURLOPT_TIMEOUT => 30,_x000D_
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,_x000D_
CURLOPT_CUSTOMREQUEST => "PUT",_x000D_
CURLOPT_POSTFIELDS => "{\n \"customer\" : \"con\",\n \"customerID\" : \"5108\",\n \"customerEmail\" : \"[email protected]\",\n \"Phone\" : \"34600000000\",\n \"Active\" : false,\n \"AudioWelcome\" : \"https://audio.com/welcome-defecto-es.mp3\"\n\n}",_x000D_
CURLOPT_HTTPHEADER => array(_x000D_
"cache-control: no-cache",_x000D_
"content-type: application/json",_x000D_
"x-api-key: whateveriyouneedinyourheader"_x000D_
),_x000D_
));_x000D_
_x000D_
$response = curl_exec($curl);_x000D_
$err = curl_error($curl);_x000D_
_x000D_
curl_close($curl);_x000D_
_x000D_
if ($err) {_x000D_
echo "cURL Error #:" . $err;_x000D_
} else {_x000D_
echo $response;_x000D_
}_x000D_
_x000D_
?>
_x000D_
Use the arc4random_uniform(upper_bound)
function to generate a random number within a range. The following will generate a number between 0 and 73 inclusive.
arc4random_uniform(74)
arc4random_uniform(upper_bound)
avoids modulo bias as described in the man page:
arc4random_uniform() will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.
Here are different method of doing this. And i found your code is even working fine.
Your code: http://jsfiddle.net/NKC2j/
Jquery toggle class demo: http://jsfiddle.net/NKC2j/2/
Jquery fade toggle: http://jsfiddle.net/NKC2j/3/
Jquery slide toggle: http://jsfiddle.net/NKC2j/4/
And you can do this with CSS as answered by Sandeep
In addition to Gaby aka's method, we can find elements inside htmlObject
in this way -
htmlObj.find("#box").html();
Fiddle is available here - http://jsfiddle.net/ashwyn/76gL3/
Please find the require.js module that I wrote for Offline.
define(['offline'], function (Offline) {
//Tested with Chrome and IE11 Latest Versions as of 20140412
//Offline.js - http://github.hubspot.com/offline/
//Offline.js is a library to automatically alert your users
//when they've lost internet connectivity, like Gmail.
//It captures AJAX requests which were made while the connection
//was down, and remakes them when it's back up, so your app
//reacts perfectly.
//It has a number of beautiful themes and requires no configuration.
//Object that will be exposed to the outside world. (Revealing Module Pattern)
var OfflineDetector = {};
//Flag indicating current network status.
var isOffline = false;
//Configuration Options for Offline.js
Offline.options = {
checks: {
xhr: {
//By default Offline.js queries favicon.ico.
//Change this to hit a service that simply returns a 204.
url: 'favicon.ico'
}
},
checkOnLoad: true,
interceptRequests: true,
reconnect: true,
requests: true,
game: false
};
//Offline.js raises the 'up' event when it is able to reach
//the server indicating that connection is up.
Offline.on('up', function () {
isOffline = false;
});
//Offline.js raises the 'down' event when it is unable to reach
//the server indicating that connection is down.
Offline.on('down', function () {
isOffline = true;
});
//Expose Offline.js instance for outside world!
OfflineDetector.Offline = Offline;
//OfflineDetector.isOffline() method returns the current status.
OfflineDetector.isOffline = function () {
return isOffline;
};
//start() method contains functionality to repeatedly
//invoke check() method of Offline.js.
//This repeated call helps in detecting the status.
OfflineDetector.start = function () {
var checkOfflineStatus = function () {
Offline.check();
};
setInterval(checkOfflineStatus, 3000);
};
//Start OfflineDetector
OfflineDetector.start();
return OfflineDetector;
});
Please read this blog post and let me know your thoughts. http://zen-and-art-of-programming.blogspot.com/2014/04/html-5-offline-application-development.html It contains a code sample using offline.js to detect when the client is offline.
Here is a way to center content both vertically and horizontally in any situation, which is useful when you do not know the width or height or both:
CSS
#container {
display: table;
width: 300px; /* not required, just for example */
height: 400px; /* not required, just for example */
}
#update {
display: table-cell;
vertical-align: middle;
text-align: center;
}
HTML
<div id="container">
<a id="update" href="#">
<i class="icon-refresh"></i>
</a>
</div>
Note that the width and height values are just for demonstration here, you can change them to anything you want (or remove them entirely) and it will still work because the vertical centering here is a product of the way the table-cell
display property works.
Suppose your query is "select id,name from users where rollNo = 1001".
Here query will return a object with id and name column. Your Response class is like bellow:
public class UserObject{
int id;
String name;
String rollNo;
public UserObject(Object[] columns) {
this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
this.name = (String) columns[1];
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
}
here UserObject
constructor will get a Object Array and set data with object.
public UserObject(Object[] columns) {
this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
this.name = (String) columns[1];
}
Your query executing function is like bellow :
public UserObject getUserByRoll(EntityManager entityManager,String rollNo) {
String queryStr = "select id,name from users where rollNo = ?1";
try {
Query query = entityManager.createNativeQuery(queryStr);
query.setParameter(1, rollNo);
return new UserObject((Object[]) query.getSingleResult());
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
Here you have to import bellow packages:
import javax.persistence.Query;
import javax.persistence.EntityManager;
Now your main class, you have to call this function.
First you have to get EntityManager and call this getUserByRoll(EntityManager entityManager,String rollNo)
function. Calling procedure is given bellow:
@PersistenceContext
private EntityManager entityManager;
UserObject userObject = getUserByRoll(entityManager,"1001");
Now you have data in this userObject.
Here is Imports
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
Note:
query.getSingleResult() return a array. You have to maintain the column position and data type.
select id,name from users where rollNo = ?1
query return a array and it's [0] --> id and [1] -> name
.
For more info, visit this Answer
Thanks :)
Just compare the string with itself reversed:
string input;
cout << "Please enter a string: ";
cin >> input;
if (input == string(input.rbegin(), input.rend())) {
cout << input << " is a palindrome";
}
This constructor of string
takes a beginning and ending iterator and creates the string from the characters between those two iterators. Since rbegin()
is the end of the string and incrementing it goes backwards through the string, the string we create will have the characters of input
added to it in reverse, reversing the string.
Then you just compare it to input
and if they are equal, it is a palindrome.
This does not take into account capitalisation or spaces, so you'll have to improve on it yourself.
You should be checking the root directory and not the app directory.
Look in $ROOT/storage/laravel.log
not app/storage/laravel.log
, where root is the top directory of the project.
a = ["A", "B", "C", "B", "A"]
a.each_with_object(Hash.new(0)) {|i,hash| hash[i] += 1}.select{|_, count| count > 1}.keys
This is a O(n)
procedure.
Alternatively you can do either of the following lines. Also O(n) but only one iteration
a.each_with_object(Hash.new(0).merge dup: []){|x,h| h[:dup] << x if (h[x] += 1) == 2}[:dup]
a.inject(Hash.new(0).merge dup: []){|h,x| h[:dup] << x if (h[x] += 1) == 2;h}[:dup]
Yes, like in plain sql you could specify what kind of properties you want to select:
SELECT i.firstProperty, i.secondProperty FROM ObjectName i WHERE i.id=10
Executing this query will return a list of Object[], where each array contains the selected properties of one object.
Another way is to wrap the selected properties in a custom object and execute it in a TypedQuery:
String query = "SELECT NEW CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=10";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();
Examples can be found in this article.
UPDATE 29.03.2018:
@Krish:
@PatrickLeitermann for me its giving "Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate class ***" exception . how to solve this ?
I guess you’re using JPA in the context of a Spring application, don't you? Some other people had exactly the same problem and their solution was adding the fully qualified name (e. g. com.example.CustomObject) after the SELECT NEW keywords.
Maybe the internal implementation of the Spring data framework only recognizes classes annotated with @Entity or registered in a specific orm file by their simple name, which causes using this workaround.
I found the answer :)
I've set the Theme's editText style to:
<item name="android:editTextStyle">@style/myEditText</item>
Then I've used the following drawable to set the cursor:
`
<style name="myEditText" parent="@android:style/Widget.Holo.Light.EditText">
<item name="android:background">@android:drawable/editbox_background_normal</item>
<item name="android:textCursorDrawable">@android:drawable/my_cursor_drawable</item>
<item name="android:height">40sp</item>
</style>
`
android:textCursorDrawable is the key here.
if you use Windows 10, this is the directory:
C:\Users<UserName>\AppData\Local\
+
<ProjectName.exe_Url_somedata>\1.0.0.0<filename.config>
I managed to do this with the following code:
ALTER TABLE `table_name`
CHANGE COLUMN `colum_name` `colum_name` INT(11) NOT NULL AUTO_INCREMENT FIRST;
This is the only way I could make a column auto increment.
INT(11) shows that the maximum int length is 11, you can skip it if you want.
Web.config file
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS; Initial Catalog=YourDatabaseName;Integrated Security=True;"/>
</connectionStrings>
.cs file
System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
I know this has been said earlier, but jQuery Autocomplete will do exactly what you need. You should check out the docs as the autocomplete is very customizable. If you are familiar with javascript then you should be able to work this out. If not I can give you a few pointers, as I have done this once before, but beware I am not well versed in javascript myself either, so bear with me on this.
I think the first thing you should do is just get a simple autocomplete text field working on your page, and then you can customize it from there.
The autocomplete widget accepts JSON data as it's 'source:' option. So you should set-up your app to produce the 20 top level categories, and subcategories in JSON format.
The next thing to know is that when the user types into your textfield, the autocomplete widget will send the typed values in a parameter called "term".
So let's say you first set-up your site to deliver the JSON data from a URL like this:
/categories.json
Then your autocomplete source: option would be 'source: /categories.json'.
When a user types into the textfield, such as 'first-cata...' the autocomplete widget will start sending the value in the 'term' parameter like this:
/categories.json?term=first-cata
This will return JSON data back to the widget filtered by anything that matches 'first-cata', and this is displayed as an autocomplete suggestion.
I am not sure what you are programming in, but you can specify how the 'term' parameter finds a match. So you can customize this, so that the term finds a match in the middle of a word if you want. Example, if the user types 'or' you code could make a match on 'sports'.
Lastly, you made a comment that you want to be able to select a category name but have the autocomplete widget submit the category ID not the name.
This can easily be done with a hidden field. This is what is shown in the jQuery autocomplete docs.
When a user selects a category, your JavaScript should update a hidden field with the ID.
I know this answer is not very detailed, but that is mainly because I am not sure what you are programming in, but the above should point you in the right direction. The thing to know is that you can do practically any customizing you want with this widget, if you are willing to spend the time to learn it.
These are the broad strokes, but you can look here for some notes I made when I implemented something similar to what you want in a Rails app.
Hope this helped.
I think you might need to use the full path:
export EDITOR=/usr/bin/vim
The WebSocket connection starts its life with an HTTP or HTTPS handshake. When the page is accessed through HTTP, you can use WS or WSS (WebSocket secure: WS over TLS) . However, when your page is loaded through HTTPS, you can only use WSS - browsers don't allow to "downgrade" security.
You could use replicate
or sapply
:
R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL)))
replicate
is a wrapper for the common use of sapply
for repeated evaluation of an expression (which will usually involve random number generation).
If you're coding for the kind of clarity that would be understood by someone who is just starting out with Perl, the traditional this construct says what it means, with a high degree of clarity and legibility:
$string = join ', ', @array;
print "$string\n";
This construct is documented in perldoc -f
join
.
However, I've always liked how simple $,
makes it. The special variable $"
is for interpolation, and the special variable $,
is for lists. Combine either one with dynamic scope-constraining 'local
' to avoid having ripple effects throughout the script:
use 5.012_002;
use strict;
use warnings;
my @array = qw/ 1 2 3 4 5 /;
{
local $" = ', ';
print "@array\n"; # Interpolation.
}
OR with $,:
use feature q(say);
use strict;
use warnings;
my @array = qw/ 1 2 3 4 5 /;
{
local $, = ', ';
say @array; # List
}
The special variables $,
and $"
are documented in perlvar. The local
keyword, and how it can be used to constrain the effects of altering a global punctuation variable's value is probably best described in perlsub.
Enjoy!
A more elegant way I found to achieve this behaviour is simply:
<div id="{{ 'object-' + myScopeObject.index }}"></div>
For my implementation I wanted each input element in a ng-repeat to each have a unique id to associate the label with. So for an array of objects contained inside myScopeObjects one could do this:
<div ng-repeat="object in myScopeObject">
<input id="{{object.name + 'Checkbox'}}" type="checkbox">
<label for="{{object.name + 'Checkbox'}}">{{object.name}}</label>
</div>
Being able to generate unique ids on the fly can be pretty useful when dynamically adding content like this.
Don't think anyone has mentioned it yet, but if you are sure the data won't change underneath you, you may want to also apply the NoLock hint to ensure it is not blocked when reading.
SELECT CASE WHEN EXISTS (SELECT 1
FROM dbo.[YourTable] WITH (NOLOCK)
WHERE [YourColumn] = [YourValue])
THEN CAST (1 AS BIT)
ELSE CAST (0 AS BIT) END
You are missing ,
EXEC proc_name 'paramValue1','paramValue2'
As others have mentioned, you can't extract the type of a variable at runtime. However, you could construct your own "object" and store the type along with it. Then you would be able to check it at runtime:
typedef struct {
int type; // or this could be an enumeration
union {
double d;
int i;
} u;
} CheesyObject;
Then set the type as needed in the code:
CheesyObject o;
o.type = 1; // or better as some define, enum value...
o.u.d = 3.14159;
It worked - To change in Eclipse, go to Window -> Preferences -> Java -> Installed JREs. Select the checked JRE/JDK and click edit.
Default VM Arguments = -Xms128m -Xmx1024m
It's not possible with Notepad but HERE'S THE EASY SOLUTION:
You will need the freeware Expresso v3.1 http://www.ultrapico.com/ExpressoDownload.htm
I resorted to another piece of free software: Expresso by Ultrapico.
Paste your whole text to be searched into the "Sample text" pane of Expresso,
Press the "Run match" button. Right click in the "Search results pane" and "Export to..." or "Copy matched text to clipboard".
N.B.: The original author is @Andreas Jansson but it is hidden in a comment, so since this page is high ranked in Google Search I leave it here for others.
Offering a quick answer for people using Ionic. I need to show a tooltip only once so I used the $localStorage to achieve this. This is for playing a track, so when they push play, it shows the tooltip once.
$scope.storage = $localStorage; //connects an object to $localstorage
$scope.storage.hasSeenPopup = "false"; // they haven't seen it
$scope.showPopup = function() { // popup to tell people to turn sound on
$scope.data = {}
// An elaborate, custom popup
var myPopup = $ionicPopup.show({
template: '<p class="popuptext">Turn Sound On!</p>',
cssClass: 'popup'
});
$timeout(function() {
myPopup.close(); //close the popup after 3 seconds for some reason
}, 2000);
$scope.storage.hasSeenPopup = "true"; // they've now seen it
};
$scope.playStream = function(show) {
PlayerService.play(show);
$scope.audioObject = audioObject; // this allow for styling the play/pause icons
if ($scope.storage.hasSeenPopup === "false"){ //only show if they haven't seen it.
$scope.showPopup();
}
}
SQLite can use text, real, or integer data types to store dates.
Even more, whenever you perform a query, the results are shown using format %Y-%m-%d %H:%M:%S
.
Now, if you insert/update date/time values using SQLite date/time functions, you can actually store milliseconds as well.
If that's the case, the results are shown using format %Y-%m-%d %H:%M:%f
.
For example:
sqlite> create table test_table(col1 text, col2 real, col3 integer);
sqlite> insert into test_table values (
strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.123'),
strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.123'),
strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.123')
);
sqlite> insert into test_table values (
strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.126'),
strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.126'),
strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.126')
);
sqlite> select * from test_table;
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123
2014-03-01 13:01:01.126|2014-03-01 13:01:01.126|2014-03-01 13:01:01.126
Now, doing some queries to verify if we are actually able to compare times:
sqlite> select * from test_table /* using col1 */
where col1 between
strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.121') and
strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.125');
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123
You can check the same SELECT
using col2
and col3
and you will get the same results.
As you can see, the second row (126 milliseconds) is not returned.
Note that BETWEEN
is inclusive, therefore...
sqlite> select * from test_table
where col1 between
/* Note that we are using 123 milliseconds down _here_ */
strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.123') and
strftime('%Y-%m-%d %H:%M:%f', '2014-03-01 13:01:01.125');
... will return the same set.
Try playing around with different date/time ranges and everything will behave as expected.
What about without strftime
function?
sqlite> select * from test_table /* using col1 */
where col1 between
'2014-03-01 13:01:01.121' and
'2014-03-01 13:01:01.125';
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123
What about without strftime
function and no milliseconds?
sqlite> select * from test_table /* using col1 */
where col1 between
'2014-03-01 13:01:01' and
'2014-03-01 13:01:02';
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123
2014-03-01 13:01:01.126|2014-03-01 13:01:01.126|2014-03-01 13:01:01.126
What about ORDER BY
?
sqlite> select * from test_table order by 1 desc;
2014-03-01 13:01:01.126|2014-03-01 13:01:01.126|2014-03-01 13:01:01.126
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123
sqlite> select * from test_table order by 1 asc;
2014-03-01 13:01:01.123|2014-03-01 13:01:01.123|2014-03-01 13:01:01.123
2014-03-01 13:01:01.126|2014-03-01 13:01:01.126|2014-03-01 13:01:01.126
Works just fine.
Finally, when dealing with actual operations within a program (without using the sqlite executable...)
BTW: I'm using JDBC (not sure about other languages)... the sqlite-jdbc driver v3.7.2 from xerial - maybe newer revisions change the behavior explained below...
If you are developing in Android, you don't need a jdbc-driver. All SQL operations can be submitted using the SQLiteOpenHelper
.
JDBC has different methods to get actual date/time values from a database: java.sql.Date
, java.sql.Time
, and java.sql.Timestamp
.
The related methods in java.sql.ResultSet
are (obviously) getDate(..)
, getTime(..)
, and getTimestamp()
respectively.
For example:
Statement stmt = ... // Get statement from connection
ResultSet rs = stmt.executeQuery("SELECT * FROM TEST_TABLE");
while (rs.next()) {
System.out.println("COL1 : "+rs.getDate("COL1"));
System.out.println("COL1 : "+rs.getTime("COL1"));
System.out.println("COL1 : "+rs.getTimestamp("COL1"));
System.out.println("COL2 : "+rs.getDate("COL2"));
System.out.println("COL2 : "+rs.getTime("COL2"));
System.out.println("COL2 : "+rs.getTimestamp("COL2"));
System.out.println("COL3 : "+rs.getDate("COL3"));
System.out.println("COL3 : "+rs.getTime("COL3"));
System.out.println("COL3 : "+rs.getTimestamp("COL3"));
}
// close rs and stmt.
Since SQLite doesn't have an actual DATE/TIME/TIMESTAMP data type all these 3 methods return values as if the objects were initialized with 0:
new java.sql.Date(0)
new java.sql.Time(0)
new java.sql.Timestamp(0)
So, the question is: how can we actually select, insert, or update Date/Time/Timestamp objects? There's no easy answer. You can try different combinations, but they will force you to embed SQLite functions in all the SQL statements. It's far easier to define an utility class to transform text to Date objects inside your Java program. But always remember that SQLite transforms any date value to UTC+0000.
In summary, despite the general rule to always use the correct data type, or, even integers denoting Unix time (milliseconds since epoch), I find much easier using the default SQLite format ('%Y-%m-%d %H:%M:%f'
or in Java 'yyyy-MM-dd HH:mm:ss.SSS'
) rather to complicate all your SQL statements with SQLite functions. The former approach is much easier to maintain.
TODO: I will check the results when using getDate/getTime/getTimestamp inside Android (API15 or better)... maybe the internal driver is different from sqlite-jdbc...
In a nutshell answer.
As others said, libreoffice
can convert xls files to csv. The problem for me was the sheet selection.
This libreoffice Python script does a fine job at converting a single sheet to CSV.
Usage is:
./libreconverter.py File.xls:"Sheet Name" output.csv
The only downside (on my end) is that --headless
doesn't seem to work. I have a LO window that shows up for a second and then quits.
That's OK with me, it's the only tool that does the job rapidly.
Html:
<div class="outerDiv">
<div class="innerDiv">Content</div>
</div>
CSS:
.outerDiv{
background: #000;
padding: 10px;
}
.innerDiv{
border: 2px dashed #fff;
min-height: 200px; //adding min-height as there is no content inside
}
The .css()
function doesn't queue behind running animations, it's instantaneous.
To match the behaviour that you're after, you'd need to do the following:
$(document).ready(function() {
$("button").mouseover(function() {
var p = $("p#44.test").css("background-color", "yellow");
p.hide(1500).show(1500);
p.queue(function() {
p.css("background-color", "red");
});
});
});
The .queue()
function waits for running animations to run out and then fires whatever's in the supplied function.
From https://api.jquery.com/change/:
The change
event is sent to an element when its value changes. This event is limited to <input>
elements, <textarea>
boxes and <select>
elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.
__construct simply initiates a class. Suppose you have the following code;
Class Person {
function __construct() {
echo 'Hello';
}
}
$person = new Person();
//the result 'Hello' will be shown.
We did not create another function to echo the word 'Hello'. It simply shows that the keyword __construct is quite useful in initiating a class or an object.
The sqlite answer is
update TABLE set mydatetime = datetime('now');
in case someone else was looking for it.
Type history
in your terminal.
It's not technically git, but I think it is what you want.
SGML parsers (or XML parsers in the case of XHTML) can handle —
without having to process the DTD (which doesn't matter to browsers as they just slurp tag soup), while —
is easier for humans to read and write in the source code.
Personally, I would stick to a literal em-dash and ensure that my character encoding settings were consistent.
You can use iconSize
like this:
floatingActionButton: FloatingActionButton(
onPressed: () {
// Add your onPressed code here
},
child: IconButton(
icon: isPlaying
? Icon(
Icons.pause_circle_outline,
)
: Icon(
Icons.play_circle_outline,
),
iconSize: 40,
onPressed: () {
setState(() {
isPlaying = !isPlaying;
});
},
),
),
Don't think you're allowed to do that: http://www.w3.org/TR/html5/forms.html#the-placeholder-attribute
The relevant content (emphasis mine):
The placeholder attribute represents a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. A hint could be a sample value or a brief description of the expected format. The attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.
Right click your project > Run As > Run Configuration... > Java Application (in left side panel) - double click on it. That will create new configuration. click on search button under Main Class section and select your main class from it.
With :after and :before you can do that.
HTML:
<div class="a"> </div>
<div class="b"> </div>
<div class="c"> </div>
CSS:
div {
height: 100px;
position: relative;
}
.a {
background: #9C9E9F;
}
.b {
background: linear-gradient(to right, #9c9e9f, #f6f6f6);
}
.a:after, .c:before, .c:after {
content: '';
width: 50%;
height: 100%;
top: 0;
right: 0;
display: block;
position: absolute;
}
.a:after {
background: #f6f6f6;
}
.c:before {
background: #9c9e9f;
left: 0;
}
.c:after {
background: #33CCFF;
right: 0;
height: 80%;
}
And a demo.