There is a good stackoverflow answer here by Mark Rajcok:
AngularJS directive controllers requiring parent directive controllers?
with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/
<div ng-controller="MyCtrl">
<div screen>
<div component>
<div widget>
<button ng-click="widgetIt()">Woo Hoo</button>
</div>
</div>
</div>
</div>
JavaScript
var myApp = angular.module('myApp',[])
.directive('screen', function() {
return {
scope: true,
controller: function() {
this.doSomethingScreeny = function() {
alert("screeny!");
}
}
}
})
.directive('component', function() {
return {
scope: true,
require: '^screen',
controller: function($scope) {
this.componentFunction = function() {
$scope.screenCtrl.doSomethingScreeny();
}
},
link: function(scope, element, attrs, screenCtrl) {
scope.screenCtrl = screenCtrl
}
}
})
.directive('widget', function() {
return {
scope: true,
require: "^component",
link: function(scope, element, attrs, componentCtrl) {
scope.widgetIt = function() {
componentCtrl.componentFunction();
};
}
}
})
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Superhero';
}
I've gotten the following to work:
html {
background:
linear-gradient(rgba(0,184,255,0.45),rgba(0,184,255,0.45)),
url('bgimage.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
The above will produce a nice opaque blue overlay.
Having two primary keys at the same time, is not possible. But (assuming that you have not messed the case up with composite key), may be what you might need is to make one attribute unique.
CREATE t1(
c1 int NOT NULL,
c2 int NOT NULL UNIQUE,
...,
PRIMARY KEY (c1)
);
However note that in relational database a 'super key' is a subset of attributes which uniquely identify a tuple or row in a table. A 'key' is a 'super key' that has an additional property that removing any attribute from the key, makes that key no more a 'super key'(or simply a 'key' is a minimal super key). If there are more keys, all of them are candidate keys. We select one of the candidate keys as a primary key. That's why talking about multiple primary keys for a one relation or table is being a conflict.
There is a good point for using !
for function invocation marked on airbnb JavaScript guide
Generally idea for using this technique on separate files (aka modules) which later get concatenated. The caveat here is that files supposed to be concatenated by tools which put the new file at the new line (which is anyway common behavior for most of concat tools). In that case, using !
will help to avoid error in if previously concatenated module missed trailing semicolon, and yet that will give the flexibility to put them in any order with no worry.
!function abc(){}();
!function bca(){}();
Will work the same as
!function abc(){}();
(function bca(){})();
but saves one character and arbitrary looks better.
And by the way any of +
,-
,~
,void
operators have the same effect, in terms of invoking the function, for sure if you have to use something to return from that function they would act differently.
abcval = !function abc(){return true;}() // abcval equals false
bcaval = +function bca(){return true;}() // bcaval equals 1
zyxval = -function zyx(){return true;}() // zyxval equals -1
xyzval = ~function xyz(){return true;}() // your guess?
but if you using IIFE patterns for one file one module code separation and using concat tool for optimization (which makes one line one file job), then construction
!function abc(/*no returns*/) {}()
+function bca() {/*no returns*/}()
Will do safe code execution, same as a very first code sample.
This one will throw error cause JavaScript ASI will not be able to do its work.
!function abc(/*no returns*/) {}()
(function bca() {/*no returns*/})()
One note regarding unary operators, they would do similar work, but only in case, they used not in the first module. So they are not so safe if you do not have total control over the concatenation order.
This works:
!function abc(/*no returns*/) {}()
^function bca() {/*no returns*/}()
This not:
^function abc(/*no returns*/) {}()
!function bca() {/*no returns*/}()
This gives you just the revision.
git rev-parse HEAD
Just throwing this out there, but try retyping things manually. There's a chance that your quotation marks are the "wrong" ones as there's a similar unicode character which looks similar but is NOT a quotation mark.
If you copy/pasted the code snippits off a website, that might be your problem.
If you look in the source code for $.fn.bind
you will find that it's just an rewrite function for on
:
function (types, data, fn) {
return this.on(types, null, data, fn);
}
Just wanted to add that if you want to debug stuff, you should compile with debug information before you debug, otherwise the debugger won't work. So, in g++ you need to do g++ -g source.cpp
. The -g
flag means that the compiler will insert debugging information into your executable, so that you can run gdb on it.
There's a whole page of the Django documentation devoted to this, well indexed from the contents page.
As that page states, you need to do:
my_obj.categories.add(fragmentCategory.objects.get(id=1))
or
my_obj.categories.create(name='val1')
use sc.nextLine(); two time so that we can read the last line of string
sc.nextLine() sc.nextLine()
Checkout the .SaveAs()
method in Excel object.
wbWorkbook.SaveAs("c:\yourdesiredFilename.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV)
Or following:
public static void SaveAs()
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook wbWorkbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Sheets wsSheet = wbWorkbook.Worksheets;
Microsoft.Office.Interop.Excel.Worksheet CurSheet = (Microsoft.Office.Interop.Excel.Worksheet)wsSheet[1];
Microsoft.Office.Interop.Excel.Range thisCell = (Microsoft.Office.Interop.Excel.Range)CurSheet.Cells[1, 1];
thisCell.Value2 = "This is a test.";
wbWorkbook.SaveAs(@"c:\one.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wbWorkbook.SaveAs(@"c:\two.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wbWorkbook.Close(false, "", true);
}
I think you are looking for nested loops.
Example (based on your edit):
t1=[1,2,'Hello',(1,2),999,1.23]
t2=[1,'Hello',(1,2),999]
t3=[]
for it1, e1 in enumerate(t1):
for it2, e2 in enumerate(t2):
if e1==e2:
t3.append((it1,it2,e1))
# t3=[(0, 0, 1), (2, 1, 'Hello'), (3, 2, (1, 2)), (4, 3, 999)]
Which can be reduced to a single comprehension:
[(it1,it2,e1) for it1, e1 in enumerate(t1) for it2, e2 in enumerate(t2) if e1==e2]
But to find the common elements, you can just do:
print set(t1) & set(t2)
# set([(1, 2), 1, 'Hello', 999])
If your list contains non-hashable objects (like other lists, dicts) use a frozen set:
from collections import Iterable
s1=set(frozenset(e1) if isinstance(e1,Iterable) else e1 for e1 in t1)
s2=set(frozenset(e2) if isinstance(e2,Iterable) else e2 for e2 in t2)
print s1 & s2
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(aMethod:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(10.0, 100.0, 300.0, 20.0);
[self.view addSubview:button];
Yes. But you can't redefine built-in types. You have to subclass them:
class MyTuple(tuple): def __add__(self, other): if len(self) != len(other): raise ValueError("tuple lengths don't match") return MyTuple(x + y for (x, y) in zip(self, other))
.myDiv {
display: flex;
align-items: center;
}
.myDiv:before {
display: inline-block;
content: url(./dog.svg);
margin-right: 15px;
width: 10px;
}
Part One - Polyfill
For browsers that haven't implemented it, a polyfill for array.find
. Courtesy of MDN.
if (!Array.prototype.find) {
Array.prototype.find = function(predicate) {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};
}
Part Two - Interface
You need to extend the open Array interface to include the find
method.
interface Array<T> {
find(predicate: (search: T) => boolean) : T;
}
When this arrives in TypeScript, you'll get a warning from the compiler that will remind you to delete this.
Part Three - Use it
The variable x
will have the expected type... { id: number }
var x = [{ "id": 1 }, { "id": -2 }, { "id": 3 }].find(myObj => myObj.id < 0);
You can flip it horizontally with CSS...
a:visited {
-moz-transform: scaleX(-1);
-o-transform: scaleX(-1);
-webkit-transform: scaleX(-1);
transform: scaleX(-1);
filter: FlipH;
-ms-filter: "FlipH";
}
If you want to flip vertically instead...
a:visited {
-moz-transform: scaleY(-1);
-o-transform: scaleY(-1);
-webkit-transform: scaleY(-1);
transform: scaleY(-1);
filter: FlipV;
-ms-filter: "FlipV";
}
Your DOS command 2> nul
Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.
For python 3.5+ it is recommended that you use the run function from the subprocess module. This returns a CompletedProcess
object, from which you can easily obtain the output as well as return code.
from subprocess import PIPE, run
command = ['echo', 'hello']
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(result.returncode, result.stdout, result.stderr)
DDL is Data Definition Language : Specification notation for defining the database schema. It works on Schema level.
DDL commands are:
create,drop,alter,rename
For example:
create table account (
account_number char(10),
balance integer);
DML is Data Manipulation Language .It is used for accessing and manipulating the data.
DML commands are:
select,insert,delete,update,call
For example :
update account set balance = 1000 where account_number = 01;
does it matter? people are generally smart enough to interpret messages correctly, if they aren't you probably shouldn't let them access your repository anyway!
I assume you are using the caption feature of Word, that is, captions were not typed in as normal text, but were inserted using Insert > Caption (Word versions before 2007), or References > Insert Caption (in the ribbon of Word 2007 and up). If done correctly, the captions are really 'fields'. You'll know if it is a field if the caption's background turns grey when you put your cursor on them (or is permanently displayed grey).
Captions are fields - Unfortunately fields (like caption fields) are only updated on specific actions, like opening of the document, printing, switching from print view to normal view, etc. The easiest way to force updating of all (caption) fields when you want it is by doing the following:
Captions are normal text - If the caption number is not a field, I am afraid you'll have to edit the text manually.
Your merge stopped in the middle of the action. You should add your files, and then 'git commit':
git add file_1.php file_2.php file_3.php
git commit
Cheers
Split on commas, then map to integers:
map(int, example_string.split(','))
Or use a list comprehension:
[int(s) for s in example_string.split(',')]
The latter works better if you want a list result, or you can wrap the map()
call in list()
.
This works because int()
tolerates whitespace:
>>> example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
>>> list(map(int, example_string.split(','))) # Python 3, in Python 2 the list() call is redundant
[0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]
>>> [int(s) for s in example_string.split(',')]
[0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]
Splitting on just a comma also is more tolerant of variable input; it doesn't matter if 0, 1 or 10 spaces are used between values.
The answers here work to open the page in the same browser window/tab.
However, I wanted the page to open in a new window/tab when they click a button. (tab/window decision depends on the user's browser setting)
So here is how it worked to open the page in new tab/window:
<button type="button" onclick="window.open('http://www.example.com/', '_blank');">View Example Page</button>
It doesn't have to be a button, you can use anywhere. Notice the _blank that is used to open in new tab/window.
You can do an interactive rebase:
git rebase -i <commit>
This will bring up your default editor. Just delete the line containing the commit you want to remove to delete that commit.
You will, of course, need access to the remote repository to apply this change there too.
See this question: Git: removing selected commits from repository
let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let regexp = /[a-d]/gi;
console.log(str.match(regexp));
You can try writing into the Documents folder. Here is a "debug" function I did for the debugging needs of my project:
Private Sub writeDebug(ByVal x As String)
Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Dim FILE_NAME As String = path & "\mydebug.txt"
MsgBox(FILE_NAME)
If System.IO.File.Exists(FILE_NAME) = False Then
System.IO.File.Create(FILE_NAME).Dispose()
End If
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine(x)
objWriter.Close()
End Sub
There are more standard folders you can access through the "SpecialFolder" object.
Best explanation for X = aY + b
(in fact it f(x) = ax + b
)) is provided at https://math.stackexchange.com/a/906280/357701
A Simpler one by just adjusting lightness/luma/brightness for contrast as is below:
import cv2
img = cv2.imread('test.jpg')
cv2.imshow('test', img)
cv2.waitKey(1000)
imghsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
imghsv[:,:,2] = [[max(pixel - 25, 0) if pixel < 190 else min(pixel + 25, 255) for pixel in row] for row in imghsv[:,:,2]]
cv2.imshow('contrast', cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))
cv2.waitKey(1000)
raw_input()
I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.
//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
"ln": {c.ln},
"ip": {c.ip},
"ua": {c.ua}})
//okay, moving on...
if err != nil {
//handle postform error
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
//handle read response error
}
fmt.Printf("%s\n", string(body))
For MS IE 10 you'll probably find you need to do the following:
-ms-overflow-style: none
See the following:
https://msdn.microsoft.com/en-us/library/hh771902(v=vs.85).aspx
The scanner can also use delimiters other than whitespace.
Easy example from Scanner API:
String input = "1 fish 2 fish red fish blue fish";
// \\s* means 0 or more repetitions of any whitespace character
// fish is the pattern to find
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt()); // prints: 1
System.out.println(s.nextInt()); // prints: 2
System.out.println(s.next()); // prints: red
System.out.println(s.next()); // prints: blue
// don't forget to close the scanner!!
s.close();
The point is to understand the regular expressions (regex
) inside the Scanner::useDelimiter
. Find an useDelimiter
tutorial here.
To start with regular expressions here you can find a nice tutorial.
abc… Letters
123… Digits
\d Any Digit
\D Any Non-digit character
. Any Character
\. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanumeric character
\W Any Non-alphanumeric character
{m} m Repetitions
{m,n} m to n Repetitions
* Zero or more repetitions
+ One or more repetitions
? Optional character
\s Any Whitespace
\S Any Non-whitespace character
^…$ Starts and ends
(…) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(ab|cd) Matches ab or cd
I'm using simple BASH script for renaming.
Usage: ./rename.sh oldName newName
#!/bin/sh
OLDNAME=$1
NEWNAME=$2
export LC_CTYPE=C
export LANG=C
find . -type f ! -path ".*/.*" -exec sed -i '' -e "s/${OLDNAME}/${NEWNAME}/g" {} +
mv "${OLDNAME}.xcodeproj" "${NEWNAME}.xcodeproj"
mv "${OLDNAME}" "${NEWNAME}"
Notes:
.git
and .DS_Store
Check the javadocs for java.text.SimpleDateFormat
It describes everything you need.
Only solution that works was create a new conda env with the name you want (you will, unfortunately, delete the old one to keep the name). Then create a new env with a new python version and re-run your install.sh
script with the conda/pip installs (or the yaml file or whatever you use to keep your requirements):
conda remove --name original_name --all
conda create --name original_name python=3.8
sh install.sh # or whatever you usually do to install dependencies
doing conda install python=3.8
doesn't work for me. Also, why do you want 3.6? Move forward with the word ;)
If you want to update the conda version of your previous env what you can also do is the following (more complicated than it should be because you cannot rename envs in conda):
conda create --name temporary_env_name --clone original_env_name
conda deactivate
conda remove --name original_env_name --all # or its alias: `conda env remove --name original_env_name`
conda create --name original_env_name python=3.8 --clone temporary_env_name
From Equivalent of setInterval in python:
import threading
def setInterval(interval):
def decorator(function):
def wrapper(*args, **kwargs):
stopped = threading.Event()
def loop(): # executed in another thread
while not stopped.wait(interval): # until stopped
function(*args, **kwargs)
t = threading.Thread(target=loop)
t.daemon = True # stop if the program exits
t.start()
return stopped
return wrapper
return decorator
Usage:
@setInterval(.5)
def function():
"..."
stop = function() # start timer, the first call is in .5 seconds
stop.set() # stop the loop
stop = function() # start new timer
# ...
stop.set()
Or here's the same functionality but as a standalone function instead of a decorator:
cancel_future_calls = call_repeatedly(60, print, "Hello, World")
# ...
cancel_future_calls()
I personally prefer the +
operator than append
:
for i in range(0, n):
list1 += [[i]]
But this is creating a new list every time, so might not be the best if performance is critical.
In case you have a loop with an async request in each one and you want a certain time between each request you can use this code:
var startTimeout = function(timeout, i){
setTimeout(function() {
myAsyncFunc(i).then(function(data){
console.log(data);
})
}, timeout);
}
var myFunc = function(){
timeout = 0;
i = 0;
while(i < 10){
// By calling a function, the i-value is going to be 1.. 10 and not always 10
startTimeout(timeout, i);
// Increase timeout by 1 sec after each call
timeout += 1000;
i++;
}
}
This examples waits 1 second after each request before sending the next one.
After some searching I found this on a Google groups discussion:
docker currently inhibits this capability for enhanced safety.
That is because the ulimit settings of the host system apply to the docker container. It is regarded as a security risk that programs running in a container can change the ulimit settings for the host.
The good news is that you have two different solutions to choose from.
sys_resource
from lxc_template.go
and recompile docker. Then
you'll be able to set the ulimit as high as you like.or
I applied the second method:
sudo service docker stop;
changed the limits in /etc/security/limits.conf
reboot the machine
run my container
run ulimit -a
in the container to confirm the open files limit has been inherited.
See: https://groups.google.com/forum/#!searchin/docker-user/limits/docker-user/T45Kc9vD804/v8J_N4gLbacJ
I had run into the same issue while I was dealing with large dataset. One thing I've noticed was the NoSuchElementException
is thrown when the Scanner reaches the endOfFile
, where it is not going to affect our data.
Here, I've placed my code in try block
and catch block
handles the exception
. You can also leave it empty, if you don't want to perform any task.
For the above question, because you are using file.next()
both in the condition and in the while loop you can handle the exception as
while(!file.next().equals(treasure)){
try{
file.next(); //stack trace error here
}catch(NoSuchElementException e) { }
}
This worked perfectly for me, if there are any corner cases for my approach, do let me know through comments.
BalusC said:
Update: to clarify a conceptual misunderstanding, the sleep() is not required. It is just used for SSCCE/demonstration purposes. Just do your long running task right there in place of sleep().
But if you replace Thread.sleep(4000);
with for (int i = 0; i < 5E8; i++) {}
then it doesn't compile, because the empty loop doesn't throw an InterruptedException
.
And for the thread to be interruptible, it needs to throw an InterruptedException
.
This seems like a serious problem to me. I can't see how to adapt this answer to work with a general long-running task.
Edited to add: I reasked this as a new question: [ interrupting a thread after fixed time, does it have to throw InterruptedException? ]
VBScript does not have a method for sorting arrays so you've got two options:
Simple ---
I have created a Sheet 2 with 4 cells and Sheet 1 with a single Cell with a Formula:
=SUM(Sheet2!B3:E3)
Note, trying as you stated, it does not make sense to assign a Single Cell a value from a range. Send it to a Formula that uses a range to do something with it.
It's very simple. Git doesn't care about what's the name of its directory. It only cares what's inside. So you can simply do:
# copy the directory into newrepo dir that exists already (else create it)
$ cp -r gitrepo1 newrepo
# remove .git from old repo to delete all history and anything git from it
$ rm -rf gitrepo1/.git
Note that the copy is quite expensive if the repository is large and with a long history. You can avoid it easily too:
# move the directory instead
$ mv gitrepo1 newrepo
# make a copy of the latest version
# Either:
$ mkdir gitrepo1; cp -r newrepo/* gitrepo1/ # doesn't copy .gitignore (and other hidden files)
# Or:
$ git clone --depth 1 newrepo gitrepo1; rm -rf gitrepo1/.git
# Or (look further here: http://stackoverflow.com/q/1209999/912144)
$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -
Once you create newrepo
, the destination to put gitrepo1
could be anywhere, even inside newrepo
if you want it. It doesn't change the procedure, just the path you are writing gitrepo1
back.
You could simply do the following.
Let's say you have the JavaScript file named myscript.js
in your root folder. Add the reference to your javascript source file in your head tag of your html file.
<script src="~/myscript.js"></script>
JS file: (myscript.js
)
function awesomeClick(){
alert('awesome click triggered');
}
HTML
<button type="button" id="jstrigger" onclick="javascript:awesomeClick();">Submit</button>
./bilet.sh: line 6: [: 7]: integer expression expected
Be careful with " "
./bilet.sh: line 9: [: missing `]'
This is because you need to have space between brackets like:
if [ "$age" -le 7 ] -o [ "$age" -ge 65 ]
look: added space, and no " "
From the man page for time:
/usr/bin/time
You can provide a format string and one of the format options is elapsed time - e.g. %E
/usr/bin/time -f'%E' $CMD
Example:
$ /usr/bin/time -f'%E' ls /tmp/mako/
res.py res.pyc
0:00.01
a simple way would be to cast the dates into timestamps and take their difference and then extract the DAY part.
if you want real difference
select extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp);
if you want absolute difference
select abs(extract(day from 'DATE_A'::timestamp - 'DATE_B':timestamp));
It looks like the DOCTYPE is causing the image to display as an inline element. If I add display: block
to the image, problem solved.
Something I recently discovered for styling Radio Buttons AND Checkboxes. Before, I had to use jQuery and other things. But this is stupidly simple.
input[type=radio] {
padding-left:5px;
padding-right:5px;
border-radius:15px;
-webkit-appearance:button;
border: double 2px #00F;
background-color:#0b0095;
color:#FFF;
white-space: nowrap;
overflow:hidden;
width:15px;
height:15px;
}
input[type=radio]:checked {
background-color:#000;
border-left-color:#06F;
border-right-color:#06F;
}
input[type=radio]:hover {
box-shadow:0px 0px 10px #1300ff;
}
You can do the same for a checkbox, obviously change the input[type=radio]
to input[type=checkbox]
and change border-radius:15px;
to border-radius:4px;
.
Hope this is somewhat useful to you.
The powerful command installs and replaces the last package.
I had a similar problem. I fixed it.
npm install -g @angular/cli@latest
and
npm install --save-dev @angular/cli@latest
In the Gregorian calendar, three conditions are used to identify leap years:
This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years. source
def is_leap(year):
leap = False
if year % 4 == 0:
leap = True
if year % 4 == 0 and year % 100 == 0:
leap = False
if year % 400 == 0:
leap = True
return leap
year = int(input())
leap = is_leap(year)
if leap:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
$("ul > li a")
But you would need to set a class on the root ul if you specifically want to target the outermost ul:
<ul class="rootlist">
...
Then it's:
$("ul.rootlist > li a")....
Another way of making sure you only have the root li elements:
$("ul > li a").not("ul li ul a")
It looks kludgy, but it should do the trick
Another one with a different concept: http://www.klausbasan.de/misc/telnet/index.html
Map:
Map transformation.
The map works on a single Row at a time.
Map returns after each input Row.
The map doesn’t hold the output result in Memory.
Map no way to figure out then to end the service.
// map example
val dfList = (1 to 100) toList
val df = dfList.toDF()
val dfInt = df.map(x => x.getInt(0)+2)
display(dfInt)
MapPartition:
MapPartition transformation.
MapPartition works on a partition at a time.
MapPartition returns after processing all the rows in the partition.
MapPartition output is retained in memory, as it can return after processing all the rows in a particular partition.
MapPartition service can be shut down before returning.
// MapPartition example
Val dfList = (1 to 100) toList
Val df = dfList.toDF()
Val df1 = df.repartition(4).rdd.mapPartition((int) => Iterator(itr.length))
Df1.collec()
//display(df1.collect())
For more details, please refer to the Spark map vs mapPartitions transformation article.
Hope this is helpful!
Use bs3-upgrade library for spacings and text aligment...
https://github.com/studija/bs3-upgrade
col-xs-text-center col-sm-text-left
col-xs-text-center col-sm-text-right
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-6 col-xs-text-center col-sm-text-left">
<p>
© 2015 example.com. All rights reserved.
</p>
</div>
<div class="col-xs-12 col-sm-6 col-xs-text-center col-sm-text-right">
<p>
<a href="#"><i class="fa fa-facebook"></i></a>
<a href="#"><i class="fa fa-twitter"></i></a>
<a href="#"><i class="fa fa-google-plus"></i></a>
</p>
</div>
</div>
</div>
Let's look at the answer in a more abstract way:
Suppose we have this code in x.py
:
...
<Block A>
if __name__ == '__main__':
<Block B>
...
Blocks A and B are run when we are running x.py
.
But just block A (and not B) is run when we are running another module, y.py
for example, in which x.py
is imported and the code is run from there (like when a function in x.py
is called from y.py
).
A boilerplate is a unit of writing that can be reused over and over without change. By extension, the idea is sometimes applied to reusable programming, as in “boilerplate code
select *
from my_table
where length( Name ) = (
select max( length( Name ) )
from my_table
limit 1
);
It this involves two table scans, and so might not be very fast !
You can find it in your "Home" directory:
On Windows 7:
C:\Users\<YOUR_ACCOUNT>\.keystore
On Linux (Ubuntu):
/home/<YOUR_ACCOUNT>/.keystore
Use this one:
box-shadow: 0px 0px 0px 1px red;
For SQL Developer
You have to execute it manually
SET SERVEROUTPUT ON
After that if you execute any procedure with DBMS_OUTPUT.PUT_LINE('info'); or directly .
This will print the line
And please don't try to add this
SET SERVEROUTPUT ON
inside the definition of function and procedure, it will not compile and will not work.
Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
By the way - ASP.NET has nothing to do with it. Encodings are universal.
if($("#checkbox1").prop('checked') == false){
alert('checkbox is not checked');
//do something
}
else
{
alert('checkbox is checked');
}
info registers
shows all the registers; info registers eax
shows just the register eax
. The command can be abbreviated as i r
There are 2 jQuery functions that you'll want to use here.
1) click
. This will take an anonymous function as it's sole parameter, and will execute it when the element is clicked.
2) html
. This will take an html string as it's sole parameter, and will replace the contents of your element with the html provided.
So, in your case, you'll want to do the following:
$('#content-container a').click(function(e){
$(this).parent().html('<a href="#">I\'m a new link</a>');
e.preventDefault();
});
If you only want to add content to your div, rather than replacing everything in it, you should use append
:
$('#content-container a').click(function(e){
$(this).parent().append('<a href="#">I\'m a new link</a>');
e.preventDefault();
});
If you want the new added links to also add new content when clicked, you should use event delegation:
$('#content-container').on('click', 'a', function(e){
$(this).parent().append('<a href="#">I\'m a new link</a>');
e.preventDefault();
});
In my case my site on IIS was pointing to a different project than the one I was running on visual studio.
I prefer to hunt down and fix problems instead of suppressing logs whenever possible. After a couple days of observing this issue in my app, I realized I was setting listeners on the req.socket
in an Express middleware to catch socket io errors that kept popping up. At some point, I learned that that was not necessary, but I kept the listeners around anyway. I just removed them and the error you are experiencing went away. I verified it was the cause by running requests to my server with and without the following middleware:
socketEventsHandler(req, res, next) {
req.socket.on("error", function(err) {
console.error('------REQ ERROR')
console.error(err.stack)
});
res.socket.on("error", function(err) {
console.error('------RES ERROR')
console.error(err.stack)
});
next();
}
Removing that middleware stopped the warning you are seeing. I would look around your code and try to find anywhere you may be setting up listeners that you don't need.
Android comes with Apache's Commons Codec - or you add it as dependency. Then do:
String myHexHash = DigestUtils.shaHex(myFancyInput);
That is the old deprecated method you get with Android 4 by default. The new versions of DigestUtils bring all flavors of shaHex() methods like sha256Hex() and also overload the methods with different argument types.
In case you want to pass error strings, here is an example from Errors and Exceptions (Python 2.6)
>>> try:
... raise Exception('spam', 'eggs')
... except Exception as inst:
... print type(inst) # the exception instance
... print inst.args # arguments stored in .args
... print inst # __str__ allows args to printed directly
... x, y = inst # __getitem__ allows args to be unpacked directly
... print 'x =', x
... print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
Try this:
update MasterTbl M,
(select sum(X) as sX,
sum(Y) as sY,
sum(Z) as sZ,
MasterID
from DetailTbl
group by MasterID) A
set
M.TotalX=A.sX,
M.TotalY=A.sY,
M.TotalZ=A.sZ
where
M.ID=A.MasterID
If you created your project with Spring Initializr, everything should be configured correctly and all you need to do is run...
./gradlew clean test --info
--info
if you want to see test output.clean
if you want to re-run tests that have already passed since the last change.Dependencies required in build.gradle
for testing in Spring Boot...
dependencies {
compile('org.springframework.boot:spring-boot-starter')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
For some reason the test runner doesn't tell you this, but it produces an HTML report in build/reports/tests/test/index.html
.
* Very Easy Solution:
Go to IIS
Select your application from left Pane.
Double click on Directory Browsing in middle Pane.
Now go to right pane and under Action tab, Just click 'ENABLE'
That's all !!
People, try to understand the error: Config Error Cannot read configuration file due to insufficient permissions
Answer: From php 5.3 and >
, the var
keyword is equivalent to public
when declaring variables inside a class.
class myClass {
var $x;
}
is the same as (for php 5.3 and >
):
class myClass {
public $x;
}
History: It was previously the norm for declaring variables in classes, though later became depreciated, but later (PHP 5.3) it became un-depreciated.
A good place to start is the sample application provided on the developer docs.
Take a look at other IME's to see what you should be aiming for. Some (like the official one) are open source.
Apps can’t be deleted if they are part of a Game Center group, in an app bundle, or currently displayed on a store. You’ll want to remove the app from sale or from the group if you want to delete it.
Source: iTunes Connect Developer Guide - Transferring and Deleting Apps
Use the --force
(-f
) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.
For example:
mysql -u userName -p -f -D dbName < script.sql
why not just use export/import wizard in SSMS?
May I suggest that you initialize your "max and min so far" variables not to infinity, but to the first number in the array?
You can try like this:
var x= str== null
? string.Empty
: str.Substring(0, Math.Min(5, str.Length));
Perhaps $('#fruit').val();
is not returning an array and you need something like:
$("#fruit").val() || []
I know this questions has been answered, however the reason this is happening to you, was probably because you did not add your username to the docker group.
Here are the steps to do it:
Add the docker group if it doesn't already exist:
sudo groupadd docker
Add the connected user ${USER}
to the docker group. Change the user name to match your preferred user:
sudo gpasswd -a ${USER} docker
Restart the Docker daemon:
sudo service docker restart
If you are on Ubuntu 14.04-15.10* use docker.io instead:
sudo service docker.io restart
(If you are on Ubuntu 16.04 the service is named "docker" simply)
Either do a newgrp
docker or log out/in to activate the changes to groups.
m2e is only included in the Java developer version of Eclipse, as you can see on this page ("Maven" topic): http://www.eclipse.org/downloads/compare.php
However, an easy way to get m2e is through the Eclipse Marketplace:
Go to Help -> Eclipse Marketplace and look for m2e. Click "Maven Integration for Eclipse", then on Install (or drag and drop the install link to your running Eclipse workspace if you opened the marketplace in a browser), et voila!
Direct browser access: http://marketplace.eclipse.org/content/maven-integration-eclipse
I add my SMS method if it can help someone. Be careful with smsManager.sendTextMessage, If the text is too long, the message does not go away. You have to respect max length depending of encoding. More information here SMS Manager send mutlipart message when there is less than 160 characters
//TO USE EveryWhere
SMSUtils.sendSMS(context, phoneNumber, message);
//Manifest
<!-- SMS -->
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<receiver
android:name=".SMSUtils"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="SMS_SENT"/>
<action android:name="SMS_DELIVERED"/>
</intent-filter>
</receiver>
//JAVA
public class SMSUtils extends BroadcastReceiver {
public static final String SENT_SMS_ACTION_NAME = "SMS_SENT";
public static final String DELIVERED_SMS_ACTION_NAME = "SMS_DELIVERED";
@Override
public void onReceive(Context context, Intent intent) {
//Detect l'envoie de sms
if (intent.getAction().equals(SENT_SMS_ACTION_NAME)) {
switch (getResultCode()) {
case Activity.RESULT_OK: // Sms sent
Toast.makeText(context, context.getString(R.string.sms_send), Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE: // generic failure
Toast.makeText(context, context.getString(R.string.sms_not_send), Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE: // No service
Toast.makeText(context, context.getString(R.string.sms_not_send_no_service), Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU: // null pdu
Toast.makeText(context, context.getString(R.string.sms_not_send), Toast.LENGTH_LONG).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF: //Radio off
Toast.makeText(context, context.getString(R.string.sms_not_send_no_radio), Toast.LENGTH_LONG).show();
break;
}
}
//detect la reception d'un sms
else if (intent.getAction().equals(DELIVERED_SMS_ACTION_NAME)) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, context.getString(R.string.sms_receive), Toast.LENGTH_LONG).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(context, context.getString(R.string.sms_not_receive), Toast.LENGTH_LONG).show();
break;
}
}
}
/**
* Test if device can send SMS
* @param context
* @return
*/
public static boolean canSendSMS(Context context) {
return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
}
public static void sendSMS(final Context context, String phoneNumber, String message) {
if (!canSendSMS(context)) {
Toast.makeText(context, context.getString(R.string.cannot_send_sms), Toast.LENGTH_LONG).show();
return;
}
PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, new Intent(SENT_SMS_ACTION_NAME), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0, new Intent(DELIVERED_SMS_ACTION_NAME), 0);
final SMSUtils smsUtils = new SMSUtils();
//register for sending and delivery
context.registerReceiver(smsUtils, new IntentFilter(SMSUtils.SENT_SMS_ACTION_NAME));
context.registerReceiver(smsUtils, new IntentFilter(DELIVERED_SMS_ACTION_NAME));
SmsManager sms = SmsManager.getDefault();
ArrayList<String> parts = sms.divideMessage(message);
ArrayList<PendingIntent> sendList = new ArrayList<>();
sendList.add(sentPI);
ArrayList<PendingIntent> deliverList = new ArrayList<>();
deliverList.add(deliveredPI);
sms.sendMultipartTextMessage(phoneNumber, null, parts, sendList, deliverList);
//we unsubscribed in 10 seconds
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
context.unregisterReceiver(smsUtils);
}
}, 10000);
}
}
Use forward slashes to specify the UNC Path:
open('//HOST/share/path/to/file')
(if your Python client code is also running under Windows)
I would like just to add that if you want to use windows socket library you have to :
at the beginning : call WSAStartup()
at the end : call WSACleanup()
Regards;
Starting from Java 7:
Define a path and the String containing the line separator at the beginning:
Path p = Paths.get("C:\\Users\\first.last\\test.txt");
String s = System.lineSeparator() + "New Line!";
and then you can use one of the following approaches:
Using Files.write
(small files):
try {
Files.write(p, s.getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
System.err.println(e);
}
Using Files.newBufferedWriter
(text files):
try (BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.APPEND)) {
writer.write(s);
} catch (IOException ioe) {
System.err.format("IOException: %s%n", ioe);
}
Using Files.newOutputStream
(interoperable with java.io
APIs):
try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(p, StandardOpenOption.APPEND))) {
out.write(s.getBytes());
} catch (IOException e) {
System.err.println(e);
}
Using Files.newByteChannel
(random access files):
try (SeekableByteChannel sbc = Files.newByteChannel(p, StandardOpenOption.APPEND)) {
sbc.write(ByteBuffer.wrap(s.getBytes()));
} catch (IOException e) {
System.err.println(e);
}
Using FileChannel.open
(random access files):
try (FileChannel sbc = FileChannel.open(p, StandardOpenOption.APPEND)) {
sbc.write(ByteBuffer.wrap(s.getBytes()));
} catch (IOException e) {
System.err.println(e);
}
Details about these methods can be found in the Oracle's tutorial.
Eloquent Model:
class User extends Model
{
protected $table = 'users';
public $timestamps = false;
}
Or Simply try this
$users = new Users();
$users->timestamps = false;
$users->name = 'John Doe';
$users->email = '[email protected]';
$users->save();
You could use max() for getting the largest value, but it will return just a value without an according index of array. Then, you could use array_search() to find the according key.
$array = array("a"=>1,"b"=>2,"c"=>4,"d"=>5);
$maxValue = max($array);
$maxIndex = array_search(max($array), $array);
var_dump($maxValue, $maxIndex);
Output:
int 5
string 'd' (length=1)
If there are multiple elements with the same value, you'll have to loop through array to get all the keys.
It's difficult to suggest something good without knowing the problem. Why do you need it? What is the input, what is the desired output?
This looks like a behavior difference in the handling of \s
between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).
Note:
GNU grep 2.5.4
echo "foo bar" | grep "\s"
(doesn't match)
whereas
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Probably less trouble (as \s
is not documented):
Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
My advice is to avoid using \s
... use [ \t]*
or [[:space:]]
or something like it instead.
If you're feeling lazy, here's a terse method of handling conditions using ||
(or) and &&
(and) after the operation:
wget -q --tries=10 --timeout=20 --spider http://google.com || \
{ echo "Sorry you are Offline" && exit 1; }
You could use the "Shown" event: MSDN - Form.Shown
"The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this event."
First we need to understand how normal (without indexing) query runs. It basically traverse each rows one by one and when it finds the data it returns. Refer the following image. (This image has been taken from this video.)
So suppose query is to find 50 , it will have to read 49 records as a linear search.
Refer the following image. (This image has been taken from this video)
When we apply indexing, the query will quickly find out the data without reading each one of them just by eliminating half of the data in each traversal like a binary search. The mysql indexes are stored as B-tree where all the data are in leaf node.
In Python 3, you can use
"one" in d.values()
to test if "one"
is among the values of your dictionary.
In Python 2, it's more efficient to use
"one" in d.itervalues()
instead.
Note that this triggers a linear scan through the values of the dictionary, short-circuiting as soon as it is found, so this is a lot less efficient than checking whether a key is present.
Just use "Key" and "Value"
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a '.' and the token class.
One of the changes in JDK 5.0 is that the class java.lang.Class is generic, java.lang.Class Class<T>
, therefore:
Class<Print> p = Print.class;
References here:
https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html
http://docs.oracle.com/javase/tutorial/extra/generics/literals.html
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.8.2
You are setting the label text before the button is clicked to "txt". Instead when the button is clicked call setText()
on the label and pass it the text from the text field.
Example:
label1.setText(nameField.getText());
It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src
and the package file under $GOPATH/pkg/<architecture>
, for example: $GOPATH/pkg/windows_amd64
.
Use del
.
Example:
>>> text = 'lipsum'
>>> l = list(text)
>>> del l[3:]
>>> ''.join(l)
'sum'
You can use jQuery's hasData method.
http://api.jquery.com/jQuery.hasData/
The primary advantage of jQuery.hasData(element) is that it does not create and associate a data object with the element if none currently exists. In contrast, jQuery.data(element) always returns a data object to the caller, creating one if no data object previously existed.
This will only check for the existence of any data objects (or events) on your element, it won't be able to confirm if it specifically has a "timer" object.
You can create an alias in .bashrc file as follows
alias vg='valgrind --leak-check=full -v --track-origins=yes --log-file=vg_logfile.out'
So whenever you want to check memory leaks, just do simply
vg ./<name of your executable> <command line parameters to your executable>
This will generate a Valgrind log file in the current directory.
If a GPU device has, for example, 4 multiprocessing units, and they can run 768 threads each: then at a given moment no more than 4*768 threads will be really running in parallel (if you planned more threads, they will be waiting their turn).
threads are organized in blocks. A block is executed by a multiprocessing unit. The threads of a block can be indentified (indexed) using 1Dimension(x), 2Dimensions (x,y) or 3Dim indexes (x,y,z) but in any case xyz <= 768 for our example (other restrictions apply to x,y,z, see the guide and your device capability).
Obviously, if you need more than those 4*768 threads you need more than 4 blocks. Blocks may be also indexed 1D, 2D or 3D. There is a queue of blocks waiting to enter the GPU (because, in our example, the GPU has 4 multiprocessors and only 4 blocks are being executed simultaneously).
Suppose we want one thread to process one pixel (i,j).
We can use blocks of 64 threads each. Then we need 512*512/64 = 4096 blocks (so to have 512x512 threads = 4096*64)
It's common to organize (to make indexing the image easier) the threads in 2D blocks having blockDim = 8 x 8 (the 64 threads per block). I prefer to call it threadsPerBlock.
dim3 threadsPerBlock(8, 8); // 64 threads
and 2D gridDim = 64 x 64 blocks (the 4096 blocks needed). I prefer to call it numBlocks.
dim3 numBlocks(imageWidth/threadsPerBlock.x, /* for instance 512/8 = 64*/
imageHeight/threadsPerBlock.y);
The kernel is launched like this:
myKernel <<<numBlocks,threadsPerBlock>>>( /* params for the kernel function */ );
Finally: there will be something like "a queue of 4096 blocks", where a block is waiting to be assigned one of the multiprocessors of the GPU to get its 64 threads executed.
In the kernel the pixel (i,j) to be processed by a thread is calculated this way:
uint i = (blockIdx.x * blockDim.x) + threadIdx.x;
uint j = (blockIdx.y * blockDim.y) + threadIdx.y;
UPDATE will return the number of modified rows. If you use JDBC (Java), you can then check this value against 0 and, if no rows have been affected, fire INSERT instead. If you use some other programming language, maybe the number of the modified rows still can be obtained, check documentation.
This may not be as elegant but you have much simpler SQL that is more trivial to use from the calling code. Differently, if you write the ten line script in PL/PSQL, you probably should have a unit test of one or another kind just for it alone.
We can use Object.requireNonNull static method of Object class. Implementation is below
public void someMethod(SomeClass obj) {
Objects.requireNonNull(obj, "Validation error, obj cannot be null");
}
Using encodeURIComponent()
:
var url = 'index.php?data='+encodeURIComponent(JSON.stringify({"json":[{"j":"son"}]})),
To execute 'php' code inside 'html' or 'htm', for 'apache version 2.4.23'
Go to '/etc/apache2/mods-enabled' edit '@mime.conf'
Go to end of file and add the following line:
"AddType application/x-httpd-php .html .htm"
BEFORE tag '< /ifModules >' verified and tested with 'apache 2.4.23' and 'php 5.6.17-1' under 'debian'
Use subprocess.Popen:
import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)
Note that communicate blocks until the process terminates. You could use process.stdout.readline() if you need the output before it terminates. For more information see the documentation.
Since version 1.3.0
AngularJS introduced extra filter parameter timezone
, like following:
{{ date_expression | date : format : timezone}}
But in versions 1.3.x
only supported timezone is UTC
, which can be used as following:
{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}
Since version 1.4.0-rc.0
AngularJS supports other timezones too. I was not testing all possible timezones, but here's for example how you can get date in Japan Standard Time (JSP, GMT +9):
{{ clock | date: 'MMM d, y H:mm:ss' : '+0900' }}
Here you can find documentation of AngularJS date filters.
NOTE: this is working only with Angular 1.x
Here's working example
It seems to be this function
h_url=document.getElementById("u").value;
You can help yourself using some 'console.log' to see what object is Null.
Simple answer: If, and only if, you're certain that the list will always be used as a list, then join the list together on your end with a character (such as '\0') that will not be used in the text ever, and store that. Then when you retrieve it, you can split by '\0'. There are of course other ways of going about this stuff, but those are dependent on your specific database vendor.
As an example, you can store JSON in a Postgres database. If your list is text, and you just want the list without further hassle, that's a reasonable compromise.
Others have ventured suggestions of serializing, but I don't really think that serializing is a good idea: Part of the neat thing about databases is that several programs written in different languages can talk to one another. And programs serialized using Java's format would not do all that well if a Lisp program wanted to load it.
If you want a good way to do this sort of thing there are usually array-or-similar types available. Postgres for instance, offers array as a type, and lets you store an array of text, if that's what you want, and there are similar tricks for MySql and MS SQL using JSON, and IBM's DB2 offer an array type as well (in their own helpful documentation). This would not be so common if there wasn't a need for this.
What you do lose by going that road is the notion of the list as a bunch of things in sequence. At least nominally, databases treat fields as single values. But if that's all you want, then you should go for it. It's a value judgement you have to make for yourself.
You don't want to use terminal: false
since that's what's blocking the processing of inside the button. Instead, in your link
clear the attr.ngClick
to prevent the default behavior.
http://plnkr.co/edit/EySy8wpeQ02UHGPBAIvg?p=preview
app.directive('ngConfirmClick', [
function() {
return {
priority: 1,
link: function(scope, element, attr) {
var msg = attr.ngConfirmClick || "Are you sure?";
var clickAction = attr.ngClick;
attr.ngClick = "";
element.bind('click', function(event) {
if (window.confirm(msg)) {
scope.$eval(clickAction)
}
});
}
};
}
]);
Brad Wilson has a couple great articles on unobtrusive validation and unobtrusive ajax.
It is also shown very nicely in this Pluralsight video in the section on " AJAX and JavaScript".
Basically, it is simply Javascript validation that doesn't pollute your source code with its own validation code. This is done by making use of data-
attributes in HTML.
For MS T-SQL Server, I suggest looking into creating an index with the "include" statement. Uniqueness is not required, neither is the physical sorting of data associated with a clustered index. The "Index ... Include ()" creates a separate physical data storage automatically maintained by the system. It is conceptually very similar to an Oracle Materialized View.
https://msdn.microsoft.com/en-us/library/ms190806.aspx
https://technet.microsoft.com/en-us/library/ms189607(v=sql.105).aspx
sorry to revive this thread, i know there is the solution, but it is easy to change the language with the datatables. Here, i leave you with my own datatable example.
$(document).ready(function ()
// DataTable
var table = $('#tblUsuarios').DataTable({
aoColumnDefs: [
{"aTargets": [0], "bSortable": true},
{"aTargets": [2], "asSorting": ["asc"], "bSortable": true},
],
"language": {
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json"
}
});
The language you get from the following link:
http://cdn.datatables.net/plug-ins/9dcbecd42ad/i18n
Just replace the URL value in the language option with the one you like. Remember to always use the comma
Worked for me, hope it will work for anyone.
Best regards!
Always use the length property
There is a library or script adding the size method to the array prototype since this is not a native array method. This is commonly done to add support for a custom getter. An example of using this would be when you want to get the size in memory of an array (which is the only thing I can think of that would be useful for this name).
Underscore.js unfortunately defines a size
method which actually returns the length of an object or array. Since unfortunately the length property of a function is defined as the number of named arguments the function declares they had to use an alternative and size was chosen (count would have been a better choice).
It is not easier to replace all new lines by +
, add a 0
and send it to the Ruby
interpreter?
(sed -e "s/$/+/" file; echo 0)|irb
If you do not have irb
, you can send it to bc
, but you have to remove all newlines except the last one (of echo
). It is better to use tr
for this, unless you have a PhD in sed
.
(sed -e "s/$/+/" file|tr -d "\n"; echo 0)|bc
In some cases this is the best way because your code may have change something and j=i+1 won't check that.
for (int i = 0; i < list.size(); i++){
for (int j = 0; j < list.size(); j++) {
if(i == j) {
//to do code here
continue;
}
}
}
lodash and typescript
const clearSubTopics = _.filter(obj.subTopics, topic => (!_.isEqual(topic.subTopicId, 2)));
console.log(clearSubTopics);
As well as find
listed in other answers, better shells allow both recurvsive globs and filtering of glob matches, so in zsh
for example...
ls -lad **/*(/)
...lists all directories while keeping all the "-l" details that you want, which you'd otherwise need to recreate using something like...
find . -type d -exec ls -ld {} \;
(not quite as easy as the other answers suggest)
The benefit of find is that it's more independent of the shell - more portable, even for system()
calls from within a C/C++ program etc..
I think oracle is smart enough to convert the less efficient one (whichever that is) into the other. So I think the answer should rather depend on the readability of each (where I think that IN
clearly wins)
//creates a listener for when you press a key
window.onkeyup = keyup;
//creates a global Javascript variable
var inputTextValue;
function keyup(e) {
//setting your input text to the global Javascript Variable for every key press
inputTextValue = e.target.value;
//listens for you to press the ENTER key, at which point your web address will change to the one you have input in the search box
if (e.keyCode == 13) {
window.location = "http://www.myurl.com/search/" + inputTextValue;
}
}
Instead of using group concat()
you can use just concat()
Select concat(Col1, ',', Col2) as Foo_Bar from Table1;
edit this only works in mySQL; Oracle concat only accepts two arguments. In oracle you can use something like select col1||','||col2||','||col3 as foobar from table1; in sql server you would use + instead of pipes.
In Android Studio, go to your build.gradle (check both project and modules build.gradle files) and search for duplicate dependencies.
Delete those your project does not need.
Using PowerShell you can minimize from the same file without opening a new instance.
powershell -window minimized -command ""
Also -window hidden
and -window normal
is available to hide completely or restore.
Like the error says, row
is a tuple, so you can't do row["pool_number"]
. You need to use the index: row[0]
.
I prefer:
SUBSTRING (my_column, 1, 1)
because it is Standard SQL-92 syntax and therefore more portable.
Strictly speaking, the standard version would be
SUBSTRING (my_column FROM 1 FOR 1)
The point is, transforming from one to the other, hence to any similar vendor variation, is trivial.
p.s. It was only recently pointed out to me that functions in standard SQL are deliberately contrary, by having parameters lists that are not the conventional commalists, in order to make them easily identifiable as being from the standard!
Found here:
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>
/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' »
AS _message'..." << endl;
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
/* Connect to the MySQL test database */
con->setSchema("test");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
while (res->next()) {
cout << "\t... MySQL replies: ";
/* Access column data by alias or column name */
cout << res->getString("_message") << endl;
cout << "\t... MySQL says it again: ";
/* Access column fata by numeric offset, 1 is the first column */
cout << res->getString(1) << endl;
}
delete res;
delete stmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
<input type='text'
name='t1'
id='t1'
maxlength=10
placeholder='typing some text' >
<p></p>
This is the text box, it has a fixed length of 10 characters, and if you can try but this text box does not contain maximum length 10 character
Hmm.
POSIX pthread_exit
description from http://pubs.opengroup.org/onlinepubs/009604599/functions/pthread_exit.html:
After a thread has terminated, the result of access to local (auto) variables of the thread is
undefined. Thus, references to local variables of the exiting thread should not be used for
the pthread_exit() value_ptr parameter value.
Which seems contrary to the idea that local main() thread variables will remain accessible.
let user1 = {_x000D_
name: "John",_x000D_
address: {_x000D_
line1: "55 Green Park Road",_x000D_
line2: {_x000D_
a:[1,2,3]_x000D_
} _x000D_
},_x000D_
email:null_x000D_
}_x000D_
_x000D_
let user2 = {_x000D_
name: "John",_x000D_
address: {_x000D_
line1: "55 Green Park Road",_x000D_
line2: {_x000D_
a:[1,2,3]_x000D_
} _x000D_
},_x000D_
email:null_x000D_
}_x000D_
_x000D_
// Method 1_x000D_
_x000D_
function isEqual(a, b) {_x000D_
return JSON.stringify(a) === JSON.stringify(b);_x000D_
}_x000D_
_x000D_
// Method 2_x000D_
_x000D_
function isEqual(a, b) {_x000D_
// checking type of a And b_x000D_
if(typeof a !== 'object' || typeof b !== 'object') {_x000D_
return false;_x000D_
}_x000D_
_x000D_
// Both are NULL_x000D_
if(!a && !b ) {_x000D_
return true;_x000D_
} else if(!a || !b) {_x000D_
return false;_x000D_
}_x000D_
_x000D_
let keysA = Object.keys(a);_x000D_
let keysB = Object.keys(b);_x000D_
if(keysA.length !== keysB.length) {_x000D_
return false;_x000D_
}_x000D_
for(let key in a) {_x000D_
if(!(key in b)) {_x000D_
return false;_x000D_
}_x000D_
_x000D_
if(typeof a[key] === 'object') {_x000D_
if(!isEqual(a[key], b[key]))_x000D_
{_x000D_
return false;_x000D_
}_x000D_
} else {_x000D_
if(a[key] !== b[key]) {_x000D_
return false;_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
return true;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
console.log(isEqual(user1,user2));
_x000D_
I was taking a look at the call logs and I noticed that apart from the usual fields in the contents of managedCursor, we have a column "simid" in Dual SIM phones (I checked on Xolo A500s Lite), so as to tag each call in the call log with a SIM. This value is either 1 or 2, most probably denoting SIM1/SIM2.
managedCursor = context.getContentResolver().query(contacts, null, null, null, null);
managedCursor.moveToNext();
for(int i=0;i<managedCursor.getColumnCount();i++)
{//for dual sim phones
if(managedCursor.getColumnName(i).toLowerCase().equals("simid"))
indexSIMID=i;
}
I did not find this column in a single SIM phone (I checked on Xperia L).
So although I don't think this is a foolproof way to check for dual SIM nature, I am posting it here because it could be useful to someone.
if (foo)
is clear enough. Use it.
I'm running Windows 7 Ultimate N version and my Nexus 5 showed up with a yellow exclamation mark in Device Manager and none of the solutions here worked.
I verified that the phone reported itself as:
USB\VID_18D1&PID_4EE1
Which doesn't work with the current (v11) of the Google USB driver.
But after enabling Developer Options and USB debugging on the phone it identified itself as:
USB\VID_18D1&PID_4EE2&MI_01
USB\VID_18D1&PID_4EE2&REV_0232&MI_01
Which installs just fine.
So just enable Developer Options on your phone and retry the device install.
Another option is to check if it's busy with a timer:
Set the timer as disabled by default. Then whenever navigating, enable it. i.e.:
WebBrowser1.Navigate("https://www.somesite.com")
tmrBusy.Enabled = True
And the timer:
Private Sub tmrBusy_Tick(sender As Object, e As EventArgs) Handles tmrBusy.Tick
If WebBrowser1.IsBusy = True Then
Debug.WriteLine("WB Busy ...")
Else
Debug.WriteLine("WB Done.")
tmrBusy.Enabled = False
End If
End Sub
The biggest difference between Task.Delay
and Thread.Sleep
is that Task.Delay
is intended to run asynchronously. It does not make sense to use Task.Delay
in synchronous code. It is a VERY bad idea to use Thread.Sleep
in asynchronous code.
Normally you will call Task.Delay()
with the await
keyword:
await Task.Delay(5000);
or, if you want to run some code before the delay:
var sw = new Stopwatch();
sw.Start();
Task delay = Task.Delay(5000);
Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
await delay;
Guess what this will print? Running for 0.0070048 seconds.
If we move the await delay
above the Console.WriteLine
instead, it will print Running for 5.0020168 seconds.
Let's look at the difference with Thread.Sleep
:
class Program
{
static void Main(string[] args)
{
Task delay = asyncTask();
syncCode();
delay.Wait();
Console.ReadLine();
}
static async Task asyncTask()
{
var sw = new Stopwatch();
sw.Start();
Console.WriteLine("async: Starting");
Task delay = Task.Delay(5000);
Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
await delay;
Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
Console.WriteLine("async: Done");
}
static void syncCode()
{
var sw = new Stopwatch();
sw.Start();
Console.WriteLine("sync: Starting");
Thread.Sleep(5000);
Console.WriteLine("sync: Running for {0} seconds", sw.Elapsed.TotalSeconds);
Console.WriteLine("sync: Done");
}
}
Try to predict what this will print...
async: Starting
async: Running for 0.0070048 seconds
sync: Starting
async: Running for 5.0119008 seconds
async: Done
sync: Running for 5.0020168 seconds
sync: Done
Also, it is interesting to notice that Thread.Sleep
is far more accurate, ms accuracy is not really a problem, while Task.Delay
can take 15-30ms minimal. The overhead on both functions is minimal compared to the ms accuracy they have (use Stopwatch
Class if you need something more accurate). Thread.Sleep
still ties up your Thread, Task.Delay
release it to do other work while you wait.
I had the same problem. mysql -u root -p
worked for me. It later asks you for a password. You should then enter the password that you had set for mysql. The default password could be password
, if you did not set one. More info here.
You can also use barcodefragmentlib which is an extension of zxing but provides barcode scanning as fragment library, so can be very easily integrated.
Here is the supporting documentation for usage of library
This is what you are looking for. It has examples for each side you want with a shadow.
.top-box
{
box-shadow: inset 0 7px 9px -7px rgba(0,0,0,0.4);
}
.left-box
{
box-shadow: inset 7px 0 9px -7px rgba(0,0,0,0.4);
}
.right-box
{
box-shadow: inset -7px 0 9px -7px rgba(0,0,0,0.4);
}
.bottom-box
{
box-shadow: inset 0 -7px 9px -7px rgba(0,0,0,0.4);
}
See the snippet for more examples:
body {
background-color:#0074D9;
}
div {
background-color:#ffffff;
padding:20px;
margin-top:10px;
}
.top-box {
box-shadow: inset 0 7px 9px -7px rgba(0,0,0,0.7);
}
.left-box {
box-shadow: inset 7px 0 9px -7px rgba(0,0,0,0.7);
}
.right-box {
box-shadow: inset -7px 0 9px -7px rgba(0,0,0,0.7);
}
.bottom-box {
box-shadow: inset 0 -7px 9px -7px rgba(0,0,0,0.7);
}
.top-gradient-box {
background: linear-gradient(to bottom, #999 0, #ffffff 7px, #ffffff 100%);
}
.left-gradient-box {
background: linear-gradient(to right, #999 0, #ffffff 7px, #ffffff 100%);
}
.right-gradient-box {
background: linear-gradient(to left, #999 0, #ffffff 7px, #ffffff 100%);
}
.bottom-gradient-box {
background: linear-gradient(to top, #999 0, #ffffff 7px, #ffffff 100%);
}
_x000D_
<div class="top-box">
This area has a top shadow using box-shadow
</div>
<div class="left-box">
This area has a left shadow using box-shadow
</div>
<div class="right-box">
This area has a right shadow using box-shadow
</div>
<div class="bottom-box">
This area has a bottom shadow using box-shadow
</div>
<div class="top-gradient-box">
This area has a top shadow using gradients
</div>
<div class="left-gradient-box">
This area has a left shadow using gradients
</div>
<div class="right-gradient-box">
This area has a right shadow using gradients
</div>
<div class="bottom-gradient-box">
This area has a bottom shadow using gradients
</div>
_x000D_
In Python 2.7 and 3 you can use this:
import string
string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
As @Zaz says:
string.lowercase
is deprecated and no longer works in Python 3 but string.ascii_lowercase
works in both
It can be done like this:
import numpy as np
# create a random matrix:
A = np.random.normal(size=(5,2))
# add a column of zeros to it:
print(np.hstack((A,np.zeros((A.shape[0],1)))))
In general, if A is an m*n matrix, and you need to add a column, you have to create an n*1 matrix of zeros, then use "hstack" to add the matrix of zeros to the right of the matrix A.
The problem almost always has something to do with "nested" z-indexes. As an Example:
<div style="z-index:1">
some content A
<div style="z-index:1000000000">
some content B
</div>
</div>
<div style="z-index:10">
Some content C
</div>
if you look at the z-index only you would expect B,C,A, but because B is nested in a div that is expressly set to 1, it will show up as C,B,A.
Setting position:fixed locks the z-index for that element and all its children, which is why changing that can solve the problem.
The solution is to find the parent element that has the z-index set and either adjust the setting or move the content so the layers and their parent containers stack up the way you want. Firebug in Firefox has a tab in the far right named "Layout" and you can quickly go up the parent elements and see where the z-index is set.
It is a good question and unfortunately bad answers as var = None
is already assigning a value, and if your script runs multiple times it is overwritten with None
every time.
It is not the same as defining without assignment. I am still trying to figure out how to bypass this issue.
You can also contain "using namespace ..." inside a function for example:
void test(const std::string& s) {
using namespace std;
cout << s;
}
You need to login to your mysql terminal first using
mysql -u username -p password
Then use this:
SELECT @@sql_mode; or SELECT @@GLOBAL.sql_mode;
output will be like this:
STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER,NO_ENGINE_SUB
You can also set sql mode by this:
SET GLOBAL sql_mode=TRADITIONAL;
Super key: super key is a set of atttibutes in a relation(table).which can define every tupple in the relation(table) uniquely.
Candidate key: we can say minimal super key is candidate key. Candidate is the smallest sub set of super key. And can uniquely define each and every tupple.
Examples of all non-POD cases with static_assert
from C++11 to C++17 and POD effects
std::is_pod
was added in C++11, so let's consider that standard onwards for now.
std::is_pod
will be removed from C++20 as mentioned at https://stackoverflow.com/a/48435532/895245 , let's update this as support arrives for the replacements.
POD restrictions have become more and more relaxed as the standard evolved, I aim to cover all relaxations in the example through ifdefs.
libstdc++ has at tiny bit of testing at: https://github.com/gcc-mirror/gcc/blob/gcc-8_2_0-release/libstdc%2B%2B-v3/testsuite/20_util/is_pod/value.cc but it just too little. Maintainers: please merge this if you read this post. I'm lazy to check out all the C++ testsuite projects mentioned at: https://softwareengineering.stackexchange.com/questions/199708/is-there-a-compliance-test-for-c-compilers
#include <type_traits>
#include <array>
#include <vector>
int main() {
#if __cplusplus >= 201103L
// # Not POD
//
// Non-POD examples. Let's just walk all non-recursive non-POD branches of cppreference.
{
// Non-trivial implies non-POD.
// https://en.cppreference.com/w/cpp/named_req/TrivialType
{
// Has one or more default constructors, all of which are either
// trivial or deleted, and at least one of which is not deleted.
{
// Not trivial because we removed the default constructor
// by using our own custom non-default constructor.
{
struct C {
C(int) {}
};
static_assert(std::is_trivially_copyable<C>(), "");
static_assert(!std::is_trivial<C>(), "");
static_assert(!std::is_pod<C>(), "");
}
// No, this is not a default trivial constructor either:
// https://en.cppreference.com/w/cpp/language/default_constructor
//
// The constructor is not user-provided (i.e., is implicitly-defined or
// defaulted on its first declaration)
{
struct C {
C() {}
};
static_assert(std::is_trivially_copyable<C>(), "");
static_assert(!std::is_trivial<C>(), "");
static_assert(!std::is_pod<C>(), "");
}
}
// Not trivial because not trivially copyable.
{
struct C {
C(C&) {}
};
static_assert(!std::is_trivially_copyable<C>(), "");
static_assert(!std::is_trivial<C>(), "");
static_assert(!std::is_pod<C>(), "");
}
}
// Non-standard layout implies non-POD.
// https://en.cppreference.com/w/cpp/named_req/StandardLayoutType
{
// Non static members with different access control.
{
// i is public and j is private.
{
struct C {
public:
int i;
private:
int j;
};
static_assert(!std::is_standard_layout<C>(), "");
static_assert(!std::is_pod<C>(), "");
}
// These have the same access control.
{
struct C {
private:
int i;
int j;
};
static_assert(std::is_standard_layout<C>(), "");
static_assert(std::is_pod<C>(), "");
struct D {
public:
int i;
int j;
};
static_assert(std::is_standard_layout<D>(), "");
static_assert(std::is_pod<D>(), "");
}
}
// Virtual function.
{
struct C {
virtual void f() = 0;
};
static_assert(!std::is_standard_layout<C>(), "");
static_assert(!std::is_pod<C>(), "");
}
// Non-static member that is reference.
{
struct C {
int &i;
};
static_assert(!std::is_standard_layout<C>(), "");
static_assert(!std::is_pod<C>(), "");
}
// Neither:
//
// - has no base classes with non-static data members, or
// - has no non-static data members in the most derived class
// and at most one base class with non-static data members
{
// Non POD because has two base classes with non-static data members.
{
struct Base1 {
int i;
};
struct Base2 {
int j;
};
struct C : Base1, Base2 {};
static_assert(!std::is_standard_layout<C>(), "");
static_assert(!std::is_pod<C>(), "");
}
// POD: has just one base class with non-static member.
{
struct Base1 {
int i;
};
struct C : Base1 {};
static_assert(std::is_standard_layout<C>(), "");
static_assert(std::is_pod<C>(), "");
}
// Just one base class with non-static member: Base1, Base2 has none.
{
struct Base1 {
int i;
};
struct Base2 {};
struct C : Base1, Base2 {};
static_assert(std::is_standard_layout<C>(), "");
static_assert(std::is_pod<C>(), "");
}
}
// Base classes of the same type as the first non-static data member.
// TODO failing on GCC 8.1 -std=c++11, 14 and 17.
{
struct C {};
struct D : C {
C c;
};
//static_assert(!std::is_standard_layout<C>(), "");
//static_assert(!std::is_pod<C>(), "");
};
// C++14 standard layout new rules, yay!
{
// Has two (possibly indirect) base class subobjects of the same type.
// Here C has two base classes which are indirectly "Base".
//
// TODO failing on GCC 8.1 -std=c++11, 14 and 17.
// even though the example was copy pasted from cppreference.
{
struct Q {};
struct S : Q { };
struct T : Q { };
struct U : S, T { }; // not a standard-layout class: two base class subobjects of type Q
//static_assert(!std::is_standard_layout<U>(), "");
//static_assert(!std::is_pod<U>(), "");
}
// Has all non-static data members and bit-fields declared in the same class
// (either all in the derived or all in some base).
{
struct Base { int i; };
struct Middle : Base {};
struct C : Middle { int j; };
static_assert(!std::is_standard_layout<C>(), "");
static_assert(!std::is_pod<C>(), "");
}
// None of the base class subobjects has the same type as
// for non-union types, as the first non-static data member
//
// TODO: similar to the C++11 for which we could not make a proper example,
// but with recursivity added.
// TODO come up with an example that is POD in C++14 but not in C++11.
}
}
}
// # POD
//
// POD examples. Everything that does not fall neatly in the non-POD examples.
{
// Can't get more POD than this.
{
struct C {};
static_assert(std::is_pod<C>(), "");
static_assert(std::is_pod<int>(), "");
}
// Array of POD is POD.
{
struct C {};
static_assert(std::is_pod<C>(), "");
static_assert(std::is_pod<C[]>(), "");
}
// Private member: became POD in C++11
// https://stackoverflow.com/questions/4762788/can-a-class-with-all-private-members-be-a-pod-class/4762944#4762944
{
struct C {
private:
int i;
};
#if __cplusplus >= 201103L
static_assert(std::is_pod<C>(), "");
#else
static_assert(!std::is_pod<C>(), "");
#endif
}
// Most standard library containers are not POD because they are not trivial,
// which can be seen directly from their interface definition in the standard.
// https://stackoverflow.com/questions/27165436/pod-implications-for-a-struct-which-holds-an-standard-library-container
{
static_assert(!std::is_pod<std::vector<int>>(), "");
static_assert(!std::is_trivially_copyable<std::vector<int>>(), "");
// Some might be though:
// https://stackoverflow.com/questions/3674247/is-stdarrayt-s-guaranteed-to-be-pod-if-t-is-pod
static_assert(std::is_pod<std::array<int, 1>>(), "");
}
}
// # POD effects
//
// Now let's verify what effects does PODness have.
//
// Note that this is not easy to do automatically, since many of the
// failures are undefined behaviour.
//
// A good initial list can be found at:
// https://stackoverflow.com/questions/4178175/what-are-aggregates-and-pods-and-how-why-are-they-special/4178176#4178176
{
struct Pod {
uint32_t i;
uint64_t j;
};
static_assert(std::is_pod<Pod>(), "");
struct NotPod {
NotPod(uint32_t i, uint64_t j) : i(i), j(j) {}
uint32_t i;
uint64_t j;
};
static_assert(!std::is_pod<NotPod>(), "");
// __attribute__((packed)) only works for POD, and is ignored for non-POD, and emits a warning
// https://stackoverflow.com/questions/35152877/ignoring-packed-attribute-because-of-unpacked-non-pod-field/52986680#52986680
{
struct C {
int i;
};
struct D : C {
int j;
};
struct E {
D d;
} /*__attribute__((packed))*/;
static_assert(std::is_pod<C>(), "");
static_assert(!std::is_pod<D>(), "");
static_assert(!std::is_pod<E>(), "");
}
}
#endif
}
Tested with:
for std in 11 14 17; do echo $std; g++-8 -Wall -Werror -Wextra -pedantic -std=c++$std pod.cpp; done
on Ubuntu 18.04, GCC 8.2.0.
Tabview: lightweight python curses command line CSV file viewer (and also other tabular Python data, like a list of lists) is here on Github
Here's a way to do it:
>>> mylist = ['a', 'b', 'c', 'd']
>>> [item for item in enumerate(mylist)]
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
Alternatively, you can do:
>>> [(i, j) for i, j in enumerate(mylist)]
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
The reason you got an error was that you were missing the () around i
and j
to make it a tuple.
In my case I used the below script to overcome the issue
$('#id').off().on('click',function(){
//...
});
off()
unbinds all the events bind to #id
.
If you want to unbind only the click
event, then use off('click')
.
Multiple rows with checkboxes and select all using useState()
hooks. Requires minor implementation to adjust to own project.
const data;
const [ allToggled, setAllToggled ] = useState(false);
const [ toggled, setToggled ] = useState(Array.from(new Array(data.length), () => false));
const [ selected, setSelected ] = useState([]);
const handleToggleAll = allToggled => {
let selectAll = !allToggled;
setAllToggled(selectAll);
let toggledCopy = [];
let selectedCopy = [];
data.forEach(function (e, index) {
toggledCopy.push(selectAll);
if(selectAll) {
selectedCopy.push(index);
}
});
setToggled(toggledCopy);
setSelected(selectedCopy);
};
const handleToggle = index => {
let toggledCopy = [...toggled];
toggledCopy[index] = !toggledCopy[index];
setToggled(toggledCopy);
if( toggledCopy[index] === false ){
setAllToggled(false);
}
else if (allToggled) {
setAllToggled(false);
}
};
....
Header: state => (
<input
type="checkbox"
checked={allToggled}
onChange={() => handleToggleAll(allToggled)}
/>
),
Cell: row => (
<input
type="checkbox"
checked={toggled[row.index]}
onChange={() => handleToggle(row.index)}
/>
),
....
<ReactTable
...
getTrProps={(state, rowInfo, column, instance) => {
if (rowInfo && rowInfo.row) {
return {
onClick: (e, handleOriginal) => {
let present = selected.indexOf(rowInfo.index);
let selectedCopy = selected;
if (present === -1){
selected.push(rowInfo.index);
setSelected(selected);
}
if (present > -1){
selectedCopy.splice(present, 1);
setSelected(selectedCopy);
}
handleToggle(rowInfo.index);
},
style: {
background: selected.indexOf(rowInfo.index) > -1 ? '#00afec' : 'white',
color: selected.indexOf(rowInfo.index) > -1 ? 'white' : 'black'
},
}
}
else {
return {}
}
}}
/>
You could use GNU Awk, see this article of the user guide.
As an improvement to the solution presented in the article (in June 2015), the following gawk command allows double quotes inside double quoted fields; a double quote is marked by two consecutive double quotes ("") there. Furthermore, this allows empty fields, but even this can not handle multiline fields. The following example prints the 3rd column (via c=3
) of textfile.csv:
#!/bin/bash
gawk -- '
BEGIN{
FPAT="([^,\"]*)|(\"((\"\")*[^\"]*)*\")"
}
{
if (substr($c, 1, 1) == "\"") {
$c = substr($c, 2, length($c) - 2) # Get the text within the two quotes
gsub("\"\"", "\"", $c) # Normalize double quotes
}
print $c
}
' c=3 < <(dos2unix <textfile.csv)
Note the use of dos2unix
to convert possible DOS style line breaks (CRLF i.e. "\r\n") and UTF-16 encoding (with byte order mark) to "\n" and UTF-8 (without byte order mark), respectively. Standard CSV files use CRLF as line break, see Wikipedia.
If the input may contain multiline fields, you can use the following script. Note the use of special string for separating records in output (since the default separator newline could occur within a record). Again, the following example prints the 3rd column (via c=3
) of textfile.csv:
#!/bin/bash
gawk -- '
BEGIN{
RS="\0" # Read the whole input file as one record;
# assume there is no null character in input.
FS="" # Suppose this setting eases internal splitting work.
ORS="\n####\n" # Use a special output separator to show borders of a record.
}
{
nof=patsplit($0, a, /([^,"\n]*)|("(("")*[^"]*)*")/, seps)
field=0;
for (i=1; i<=nof; i++){
field++
if (field==c) {
if (substr(a[i], 1, 1) == "\"") {
a[i] = substr(a[i], 2, length(a[i]) - 2) # Get the text within
# the two quotes.
gsub(/""/, "\"", a[i]) # Normalize double quotes.
}
print a[i]
}
if (seps[i]!=",") field=0
}
}
' c=3 < <(dos2unix <textfile.csv)
There is another approach to the problem. csvquote can output contents of a CSV file modified so that special characters within field are transformed so that usual Unix text processing tools can be used to select certain column. For example the following code outputs the third column:
csvquote textfile.csv | cut -d ',' -f 3 | csvquote -u
csvquote
can be used to process arbitrary large files.
When you see "Verify return code: 19 (self signed certificate in certificate chain)
", then, either the servers is really trying to use a self-signed certificate (which a client is never going to be able to verify), or OpenSSL hasn't got access to the necessary root but the server is trying to provide it itself (which it shouldn't do because it's pointless - a client can never trust a server to supply the root corresponding to the server's own certificate).
Again, adding -showcerts will help you diagnose which.
I understand this is an older question, but I would like to add another disadvantage of Single Page Applications:
If you build an API that returns results in a data language (such as XML or JSON) rather than a formatting language (like HTML), you are enabling greater application interoperability, for example, in business-to-business (B2B) applications. Such interoperability has great benefits but does allow people to write software to "mine" (or steal) your data. This particular disadvantage is common to all APIs that use a data language, and not to SPAs in general (indeed, an SPA that asks the server for pre-rendered HTML avoids this, but at the expense of poor model/view separation). This risk exposed by this disadvantage can be mitigated by various means, such as request limiting and connection blocking, etc.
There's a built in windows cmd to do this: sc create. Not as fancy as nssm, but you don't have to download an additional piece of software.
sc create "ServiceName" start= demand displayname= "DisplayName" binpath= [path to .bat file]
Note
=
I assume you're using typescript.
To be extra cautious you can define your type
as an array of objects that need to match certain interface:
type MyArrayType = Array<{id: number, text: string}>;
const arr: MyArrayType = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
Or short syntax without defining a custom type:
const arr: Array<{id: number, text: string}> = [...];
1 ) Open the SpringToolSuite4.ini File.
2 ) Search For the openFile.
3 ) Provide the jvm.dll file location in SpringToolSuite4.ini
4 ) Note : Provide the New Line between -vm and your jvm.dll file location path.as shown below.
openFile
-vm
C:\Program Files\Java\jre8\bin\server\jvm.dll
-vmargs
-Dosgi.requiredJavaVersion=1.8
-Xms256m
I found very in-depth videos which cover $watch
, $apply
, $digest
and digest cycles in:
AngularJS - Understanding Watcher, $watch, $watchGroup, $watchCollection, ng-change
AngularJS - Understanding digest cycle (digest phase or digest process or digest loop)
AngularJS Tutorial - Understanding $apply and $digest (in depth)
Following are a couple of slides used in those videos to explain the concepts (just in case, if the above links are removed/not working).
In the above image, "$scope.c" is not being watched as it is not used in any of the data bindings (in markup). The other two ($scope.a
and $scope.b
) will be watched.
From the above image: Based on the respective browser event, AngularJS captures the event, performs digest cycle (goes through all the watches for changes), execute watch functions and update the DOM. If not browser events, the digest cycle can be manually triggered using $apply
or $digest
.
More about $apply
and $digest
:
This error may be actually being show because mysql is already started. Try to see the current status by:
mysql.server status
I just tested this extremely simple method and it works perfectly--but I use the built-in Administrator account, so I don't have to jump through hoops for elevated privileges.
The following batch file relieves the user of the need to move files in/out of system folders. It also leaves it up to Windows to apply the proper version of Regsvr32
.
INSTRUCTIONS:
In the folder that contains the library (-.dll
or -.ax
) file you wish to register, open a new text file and paste in ONE of the routines below :
echo BEGIN DRAG-AND-DROP %n1 REGISTRAR FOR 64-BIT SYSTEMS
copy %1 C:\Windows\System32
regsvr32 "%nx1"
echo END BATCH FILE
pause
echo BEGIN DRAG-AND-DROP %n1 REGISTRAR FOR 32-BIT SYSTEMS
copy %1 C:\Windows\SysWOW64
regsvr32 "%nx1"
echo END BATCH FILE
pause
Save your new text file as a batch (-.bat
) file; then simply drag-and-drop your -.dll
or -.ax
file on top of the batch file.
If UAC doesn't give you the opportunity to run the batch file as an Administrator, you may need to manually elevate privileges (instructions are for Windows 7):
Create shortcut
;Properties
;Compatibility
tab;Run this program as administrator
;-.dll
or -.ax
file on top of the new shortcut instead of the batch file.That's it. I chose COPY
instead of MOVE
to prevent the failure of any UAC-related follow-up attempt(s). Successful registration should be followed by deletion of the original library (-.dll
or -.ax
) file.
Don't worry about copies made to the system folder (C:\Windows\System32
or C:\Windows\SysWOW64
) by previous passes--they will be overwritten every time you run the batch file.
Unless you ran the wrong batch file, in which case you will probably want to delete the copy made to the wrong system folder (C:\Windows\System32
or C:\Windows\SysWOW64
) before running the proper batch file, ...or...
Help Windows choose the right library file to register by fully-qualifying its directory location.
C:\Windows\System32
C:\Windows\SysWOW64
%nx1
regsvr32 "C:\Windows\System32\%nx1"
regsvr32 "C:\Windows\SysWOW64\%nx1"
%nx1
from system folder pathRun this shotgun batch file, which will (in order):
C:\Windows\System32
;C:\Windows\System32
;C:\Windows\SystemWOW64
I'm guessing this question was mainly about InstallShield given the tags, but in case anyone comes here with the same problem for WiX-based packages (and possibly others), just call the installer with /extract, like so:
C:\> installer.exe /extract
That'll place the MSI in the folder alongside the installer.
To generate a shared library you need first to compile your C code with the -fPIC
(position independent code) flag.
gcc -c -fPIC hello.c -o hello.o
This will generate an object file (.o), now you take it and create the .so file:
gcc hello.o -shared -o libhello.so
EDIT: Suggestions from the comments:
You can use
gcc -shared -o libhello.so -fPIC hello.c
to do it in one step. – Jonathan Leffler
I also suggest to add -Wall
to get all warnings, and -g
to get debugging information, to your gcc
commands. – Basile Starynkevitch
$date = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
echo $date->format('d-m-Y H:i:s');
Update
//Also get am/pm in datetime:
echo $date->format('d-m-Y H:i:s a'); // output 30-12-2013 10:16:15 am
For the date format, PHP date() Function is useful.
To remove the key-value pairs from preference, you can easily do the following
getActivity().getSharedPreference().edit().remove("key").apply();
I have also developed a library for easy manipulation of shared preferences. You may find the following link
Perhaps something like this?
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<!-- general application log -->
<appender name="MainLogFile" class="org.apache.log4j.FileAppender">
<param name="File" value="server.log" />
<param name="Threshold" value="INFO" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %t [%-40.40c] %x - %m%n"/>
</layout>
</appender>
<!-- additional fooSystem logging -->
<appender name="FooLogFile" class="org.apache.log4j.FileAppender">
<param name="File" value="foo.log" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %t [%-40.40c] %x - %m%n"/>
</layout>
</appender>
<!-- foo logging -->
<logger name="com.example.foo">
<level value="DEBUG"/>
<appender-ref ref="FooLogFile"/>
</logger>
<!-- default logging -->
<root>
<level value="INFO"/>
<appender-ref ref="MainLogFile"/>
</root>
</log4j:configuration>
Thus, all info messages are written to server.log; by contrast, foo.log contains only com.example.foo messages, including debug-level messages.
You may have to perform a diff and put document.getElementById('name')
code inside a condition, in case your component is something like this:
// using the new hooks API
function Comp(props) {
const { isLoading, data } = props;
useEffect(() => {
if (data) {
var name = document.getElementById('name').value;
}
}, [data]) // this diff is necessary
if (isLoading) return <div>isLoading</div>
return (
<div id='name'>Comp</div>
);
}
If diff is not performed then, you will get null
.
Easy way to get JSON especially for Android SDK 23:
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new JsonTask().execute("Url address here");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
}
I came across the same problem.
If you install laravel debug bar you can see the queries and often see the problem
$ad->getcodes()->groupby('pid')->distinct()->count()
change to
$ad->getcodes()->distinct()->select('pid')->count()
You need to set the values to return as distinct. If you don't set the select fields it will return all the columns in the database and all will be unique. So set the query to distinct and only select the columns that make up your 'distinct' value you might want to add more. ->select('pid','date')
to get all the unique values for a user in a day
It's very simple. Right click inside the internal browser and click "refresh".
It appears that tkFileDialog.askdirectory
should work. documentation
Depends on whether you really need to physically concatenate the two vectors or you want to give the appearance of concatenation of the sake of iteration. The boost::join function
http://www.boost.org/doc/libs/1_43_0/libs/range/doc/html/range/reference/utilities/join.html
will give you this.
std::vector<int> v0;
v0.push_back(1);
v0.push_back(2);
v0.push_back(3);
std::vector<int> v1;
v1.push_back(4);
v1.push_back(5);
v1.push_back(6);
...
BOOST_FOREACH(const int & i, boost::join(v0, v1)){
cout << i << endl;
}
should give you
1
2
3
4
5
6
Note boost::join does not copy the two vectors into a new container but generates a pair of iterators (range) that cover the span of both containers. There will be some performance overhead but maybe less that copying all the data to a new container first.
Here's Microsoft's write up on using SET IDENTITY_INSERT, which might be helpful to others seeing this post if they, like me, found this post when trying to recreate deleted records while maintaining the original identity column value.
to recreate deleted records with original identity column value: http://msdn.microsoft.com/en-us/library/aa259221(v=sql.80).aspx
IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
INSERT INTO TABLE(FieldValue) VALUES('')
SELECT SCOPE_IDENTITY() AS TableID
END
See here for more information on IF ELSE
Note: written without a SQL Server install handy to double check this but I think it is correct
Also, I've changed the EXISTS bit to do SELECT 1 rather than SELECT * as you don't care what is returned within an EXISTS, as long as something is I've also changed the SCOPE_IDENTITY() bit to return just the identity assuming that TableID is the identity column
// this is a Jquery plugin function that fires an event when the size of an element is changed
// usage: $().sizeChanged(function(){})
(function ($) {
$.fn.sizeChanged = function (handleFunction) {
var element = this;
var lastWidth = element.width();
var lastHeight = element.height();
setInterval(function () {
if (lastWidth === element.width()&&lastHeight === element.height())
return;
if (typeof (handleFunction) == 'function') {
handleFunction({ width: lastWidth, height: lastHeight },
{ width: element.width(), height: element.height() });
lastWidth = element.width();
lastHeight = element.height();
}
}, 100);
return element;
};
}(jQuery));
I would suggest the following code, you can use this <script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
to get the latitude and longitude of a location, although it may not be so accurate however it worked for me;
code snippet below
<!DOCTYPE html>
<html>
<head>
<title>Using Javascript's Geolocation API</title>
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div id="mapContainer"></div>
<script type="text/javascript">
var lat = geoip_latitude();
var long = geoip_longitude();
document.write("Latitude: "+lat+"</br>Longitude: "+long);
</script>
</body>
</html>
In order to make it work, you have to set property GroupName of both radio buttons to the same value:
<asp:RadioButton id="rbMetric" runat="server" GroupName="measurementSystem"></asp:RadioButton>
<asp:RadioButton id="rbUS" runat="server" GroupName="measurementSystem"></asp:RadioButton>
Personally, I prefer to use a RadioButtonList:
<asp:RadioButtonList ID="rblMeasurementSystem" runat="server">
<asp:ListItem Text="Metric" Value="metric" />
<asp:ListItem Text="US" Value="us" />
</asp:RadioButtonList>
Here is a core JavaScript function to wait for the display of an element (well, its insertion into the DOM to be more accurate).
// Call the below function
waitForElementToDisplay("#div1",function(){alert("Hi");},1000,9000);
function waitForElementToDisplay(selector, callback, checkFrequencyInMs, timeoutInMs) {
var startTimeInMs = Date.now();
(function loopSearch() {
if (document.querySelector(selector) != null) {
callback();
return;
}
else {
setTimeout(function () {
if (timeoutInMs && Date.now() - startTimeInMs > timeoutInMs)
return;
loopSearch();
}, checkFrequencyInMs);
}
})();
}
This call will look for the HTML tag whose id="div1"
every 1000 milliseconds. If the element is found, it will display an alert message Hi. If no element is found after 9000 milliseconds, this function stops its execution.
Parameters:
selector
: String : This function looks for the element ${selector}.callback
: Function : This is a function that will be called if the element is found.checkFrequencyInMs
: Number : This function checks whether this element exists every ${checkFrequencyInMs} milliseconds.timeoutInMs
: Number : Optional. This function stops looking for the element after ${timeoutInMs} milliseconds.NB : Selectors are explained at https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
This happens when the app has not been uninstalled properly.
Use the below plugin of Android Studio to uninstall the app from the device [in case you were unable to find your app inside the settings of the device]
ADBIdea: https://github.com/pbreault/adb-idea
ADBIdea adds the following ADB commands to Android Studio and Intellij:
There are two basic ways to invoke a command:
Through the Tools->Android->ADB Idea menu By searching for "ADB" in "Find Actions" (osx: cmd+shift+a, windows/linux: ctrl+shift+a)
I tend to lean towards using DateTimeOffset for all date-time storage that isn't related to a local event (ie: meeting/party, etc, 12pm-3pm at the museum).
To get the current DTO as UTC:
DECLARE @utcNow DATETIMEOFFSET = CONVERT(DATETIMEOFFSET, SYSUTCDATETIME())
DECLARE @utcToday DATE = CONVERT(DATE, @utcNow);
DECLARE @utcTomorrow DATE = DATEADD(D, 1, @utcNow);
SELECT @utcToday [today]
,@utcTomorrow [tomorrow]
,@utcNow [utcNow]
NOTE: I will always use UTC when sending over the wire... client-side JS can easily get to/from local UTC. See: new Date().toJSON()
...
The following JS will handle parsing a UTC/GMT date in ISO8601 format to a local datetime.
if (typeof Date.fromISOString != 'function') {
//method to handle conversion from an ISO-8601 style string to a Date object
// Date.fromISOString("2009-07-03T16:09:45Z")
// Fri Jul 03 2009 09:09:45 GMT-0700
Date.fromISOString = function(input) {
var date = new Date(input); //EcmaScript5 includes ISO-8601 style parsing
if (!isNaN(date)) return date;
//early shorting of invalid input
if (typeof input !== "string" || input.length < 10 || input.length > 40) return null;
var iso8601Format = /^(\d{4})-(\d{2})-(\d{2})((([T ](\d{2}):(\d{2})(:(\d{2})(\.(\d{1,12}))?)?)?)?)?([Zz]|([-+])(\d{2})\:?(\d{2}))?$/;
//normalize input
var input = input.toString().replace(/^\s+/,'').replace(/\s+$/,'');
if (!iso8601Format.test(input))
return null; //invalid format
var d = input.match(iso8601Format);
var offset = 0;
date = new Date(+d[1], +d[2]-1, +d[3], +d[7] || 0, +d[8] || 0, +d[10] || 0, Math.round(+("0." + (d[12] || 0)) * 1000));
//use specified offset
if (d[13] == 'Z') offset = 0-date.getTimezoneOffset();
else if (d[13]) offset = ((parseInt(d[15],10) * 60) + (parseInt(d[16],10)) * ((d[14] == '-') ? 1 : -1)) - date.getTimezoneOffset();
date.setTime(date.getTime() + (offset * 60000));
if (date.getTime() <= new Date(-62135571600000).getTime()) // CLR DateTime.MinValue
return null;
return date;
};
}
I just tried SMTPop and it worked.
smtpop.dll
reference to my C# .NET projectWrote the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmtPop;
namespace SMT_POP3 {
class Program {
static void Main(string[] args) {
SmtPop.POP3Client pop = new SmtPop.POP3Client();
pop.Open("<hostURL>", 110, "<username>", "<password>");
// Get message list from POP server
SmtPop.POPMessageId[] messages = pop.GetMailList();
if (messages != null) {
// Walk attachment list
foreach(SmtPop.POPMessageId id in messages) {
SmtPop.POPReader reader= pop.GetMailReader(id);
SmtPop.MimeMessage msg = new SmtPop.MimeMessage();
// Read message
msg.Read(reader);
if (msg.AddressFrom != null) {
String from= msg.AddressFrom[0].Name;
Console.WriteLine("from: " + from);
}
if (msg.Subject != null) {
String subject = msg.Subject;
Console.WriteLine("subject: "+ subject);
}
if (msg.Body != null) {
String body = msg.Body;
Console.WriteLine("body: " + body);
}
if (msg.Attachments != null && false) {
// Do something with first attachment
SmtPop.MimeAttachment attach = msg.Attachments[0];
if (attach.Filename == "data") {
// Read data from attachment
Byte[] b = Convert.FromBase64String(attach.Body);
System.IO.MemoryStream mem = new System.IO.MemoryStream(b, false);
//BinaryFormatter f = new BinaryFormatter();
// DataClass data= (DataClass)f.Deserialize(mem);
mem.Close();
}
// Delete message
// pop.Dele(id.Id);
}
}
}
pop.Quit();
}
}
}
the prototype way
<div id="sub1" title="some text on mouse over">some text</div>
<script type="text/javascript">//<![CDATA[
$("sub1").observe("mouseover", function() {
alert(this.readAttribute("title"));
});
//]]></script>
include Prototype Lib for testing
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js"></script>
You've got an array of objects, so you'll need to use ng-repeat
twice, like:
<ul ng-repeat="item in items">
<li ng-repeat="(key, val) in item">
{{key}}: {{val}}
</li>
</ul>
Example: http://jsfiddle.net/Vwsej/
Note that properties order in objects are not guaranteed.
<table>
<tr>
<th ng-repeat="(key, val) in items[0]">{{key}}</th>
</tr>
<tr ng-repeat="item in items">
<td ng-repeat="(key, val) in item">{{val}}</td>
</tr>
</table>
Example: http://jsfiddle.net/Vwsej/2/
I know this is an old question.
Here's another option - attending to different platform requirements - Source
<link rel='shortcut icon' type='image/vnd.microsoft.icon' href='/favicon.ico'> <!-- IE -->
<link rel='apple-touch-icon' type='image/png' href='/icon.57.png'> <!-- iPhone -->
<link rel='apple-touch-icon' type='image/png' sizes='72x72' href='/icon.72.png'> <!-- iPad -->
<link rel='apple-touch-icon' type='image/png' sizes='114x114' href='/icon.114.png'> <!-- iPhone4 -->
<link rel='icon' type='image/png' href='/icon.114.png'> <!-- Opera Speed Dial, at least 144×114 px -->
This is the broadest approach I have found so far.
Ultimately the decision depends on your own needs. Ask yourself, who is your target audience?
UPDATE May 27, 2018: As expected, time goes by and things change. But there's good news too. I found a tool called Real Favicon Generator that generates all the required lines for the icon to work on all modern browsers and platforms. It doesn't handle backwards compatibility though.
I hit this discussion while trying to figure out how to get a value from a nested map of unknown depth and it helped me come up with the following solution to my problem. It is overkill for the original question but maybe it will be helpful to someone that finds themselves in a situation where you have less knowledge about the map being searched.
private static Object pullNestedVal(
Map<Object, Object> vmap,
Object ... keys) {
if ((keys.length == 0) || (vmap.size() == 0)) {
return null;
} else if (keys.length == 1) {
return vmap.get(keys[0]);
}
Object stageObj = vmap.get(keys[0]);
if (stageObj instanceof Map) {
Map<Object, Object> smap = (Map<Object, Object>) stageObj;
Object[] skeys = Arrays.copyOfRange(keys, 1, keys.length);
return pullNestedVal(smap, skeys);
} else {
return null;
}
}
Never call
setState
insiderender
method
You should never ever call setState
inside the render
method. Why? calling setState
eventually fires the render
method again. That means you are calling setState (mentioned in your render
block) in a loop that would never end. The correct way to do that is by using componentDidMount
hook in React, like so:
class CowtanApp extends Component {
state = {
timePassed: false
}
componentDidMount () {
setTimeout(() => this.setState({timePassed: true}), 1000)
}
render () {
return this.state.timePassed ? (
<NavigatorIOS
style = {styles.container}
initialRoute = {{
component: LoginPage,
title: 'Sign In',
}}/>
) : <LoadingPage/>
}
}
PS Use ternary operators for cleaner, shorter and readable code.
Working fine for the button size 80x80 pixels.
[self.leftButton setImageEdgeInsets:UIEdgeInsetsMake(0, 10.0, 20.0, 10.0)];
[self.leftButton setTitleEdgeInsets:UIEdgeInsetsMake(60, -75.0, 0.0, 0.0)];
In my case junk files from editor caused the problem. I had a config as below:
#...
http {
# ...
include ../sites/*;
}
In the ../sites
directory initially I had a default.config
file.
However, by mistake I saved duplicate files as default.config.save
and default.config.save.1
.
Removing them resolved the issue.
Why not try http://phpjs.org/functions/md5/?
Unfortunately performance is limited with any emulated script, however this can render real md5 hash. Although I would advice against using md5 for passwords, as it is a fast-rendered hash.
Go to cloud Messaging select: Server key
function sendGCM($message, $deviceToken) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'registration_ids' => array (
$id
),
'data' => array (
"title" => "Notification title",
"body" => $message,
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "YOUR_SERVER_KEY",
'Content-Type: application/json'
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
echo $result;
curl_close ($ch);
}
Using lambda:
strList.stream().map(org.apache.commons.lang3.math.NumberUtils::toInt).collect(Collectors.toList());
[
stands for single dimension array
Ljava.lang.String
stands for the string class (L followed by class/interface name)
Few Examples:
Class.forName("[D")
-> Array of primitive doubleClass.forName("[[Ljava.lang.String")
-> Two dimensional array of strings.List of notations:
Element Type : Notation
boolean : Z
byte : B
char : C
class or interface : Lclassname
double : D
float : F
int : I
long : J
short : S
Try this:
Create A Macro with the following thing inside:
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(-1, 1).Select
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(0, -1).Select
That particular macro will copy the current cell (place your cursor in the VOL cell you wish to copy) down one row and then copy the CAP cell also.
This is only a single loop so you can automate copying VOL and CAP of where your current active cell (where your cursor is) to down 1 row.
Just put it inside a For loop statement to do it x number of times. like:
For i = 1 to 100 'Do this 100 times
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(-1, 1).Select
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(0, -1).Select
Next i
Two things you should have for fetch = FetchType.LAZY
.
@Transactional
and
Hibernate.initialize(topicById.getComments());
I had the same problem as Dan, so I used his answer and improved it.
First select the row index, nothing different here.
SELECT row
FROM
(SELECT @rownum:=@rownum+1 row, a.*
FROM articles a, (SELECT @rownum:=0) r
ORDER BY date, id) as article_with_rows
WHERE id = 50;
Now use two separate queries. For example if the row index is 21, the query to select the next record will be:
SELECT *
FROM articles
ORDER BY date, id
LIMIT 21, 1
To select the previous record use this query:
SELECT *
FROM articles
ORDER BY date, id
LIMIT 19, 1
Keep in mind that for the first row (row index is 1), the limit will go to -1 and you will get a MySQL error. You can use an if-statement to prevent this. Just don't select anything, since there is no previous record anyway. In the case of the last record, there will be next row and therefor there will be no result.
Also keep in mind that if you use DESC for ordering, instead of ASC, you queries to select the next and previous rows are still the same, but switched.
The "14" and "6" in those driver names refer to the JVM they were written for. If you're still using JDK 1.4 I'd say you have a serious problem and need to upgrade. JDK 1.4 is long past its useful support life. It didn't even have generics! JDK 6 u21 is the current production standard from Oracle/Sun. I'd recommend switching to it if you haven't already.
This is confusing. When you say "form object", do you mean "<select>
element"? If not, your code won't work, so I'll assume your form
variable is in fact a reference to a <select>
element. Why do you want to rewrite this code? What you have has worked in all scriptable browsers since around 1996, and won't stop working any time soon. Doing it with jQuery will immediately make your code slower, more error-prone and less compatible across browsers.
Here's a function that uses your current code as a starting point and populates a <select>
element from an object:
<select id="mySelect"></select>
<script type="text/javascript>
function populateSelect(select, optionsData) {
var options = select.options, o, selected;
options.length = 0;
for (var i = 0, len = optionsData.length; i < len; ++i) {
o = optionsData[i];
selected = !!o.selected;
options[i] = new Option(o.text, o.value, selected, selected);
}
}
var optionsData = [
{
text: "Select a city / town in Sweden",
value: ""
},
{
text: "Melbourne",
value: "Melbourne",
selected: true
}
];
populateSelect(document.getElementById("mySelect"), optionsData);
</script>
There are a lot of answers already, and I found two claiming O(1) time complexity. The real O(1) algorithm is to leave the array storage untouched, and change how you index its elements. The goal here is that it does not consume additional memory, nor does it require additional time to iterate the data.
Rotations of 90, -90 and 180 degrees are simple transformations which can be performed as long as you know how many rows and columns are in your 2D array; To rotate any vector by 90 degrees, swap the axes and negate the Y axis. For -90 degree, swap the axes and negate the X axis. For 180 degrees, negate both axes without swapping.
Further transformations are possible, such as mirroring horizontally and/or vertically by negating the axes independently.
This can be done through e.g. an accessor method. The examples below are JavaScript functions, but the concepts apply equally to all languages.
// Get an array element in column/row order_x000D_
var getArray2d = function(a, x, y) {_x000D_
return a[y][x];_x000D_
};_x000D_
_x000D_
//demo_x000D_
var arr = [_x000D_
[5, 4, 6],_x000D_
[1, 7, 9],_x000D_
[-2, 11, 0],_x000D_
[8, 21, -3],_x000D_
[3, -1, 2]_x000D_
];_x000D_
_x000D_
var newarr = [];_x000D_
arr[0].forEach(() => newarr.push(new Array(arr.length)));_x000D_
_x000D_
for (var i = 0; i < newarr.length; i++) {_x000D_
for (var j = 0; j < newarr[0].length; j++) {_x000D_
newarr[i][j] = getArray2d(arr, i, j);_x000D_
}_x000D_
}_x000D_
console.log(newarr);
_x000D_
// Get an array element rotated 90 degrees clockwise_x000D_
function getArray2dCW(a, x, y) {_x000D_
var t = x;_x000D_
x = y;_x000D_
y = a.length - t - 1;_x000D_
return a[y][x];_x000D_
}_x000D_
_x000D_
//demo_x000D_
var arr = [_x000D_
[5, 4, 6],_x000D_
[1, 7, 9],_x000D_
[-2, 11, 0],_x000D_
[8, 21, -3],_x000D_
[3, -1, 2]_x000D_
];_x000D_
_x000D_
var newarr = [];_x000D_
arr[0].forEach(() => newarr.push(new Array(arr.length)));_x000D_
_x000D_
for (var i = 0; i < newarr[0].length; i++) {_x000D_
for (var j = 0; j < newarr.length; j++) {_x000D_
newarr[j][i] = getArray2dCW(arr, i, j);_x000D_
}_x000D_
}_x000D_
console.log(newarr);
_x000D_
// Get an array element rotated 90 degrees counter-clockwise_x000D_
function getArray2dCCW(a, x, y) {_x000D_
var t = x;_x000D_
x = a[0].length - y - 1;_x000D_
y = t;_x000D_
return a[y][x];_x000D_
}_x000D_
_x000D_
//demo_x000D_
var arr = [_x000D_
[5, 4, 6],_x000D_
[1, 7, 9],_x000D_
[-2, 11, 0],_x000D_
[8, 21, -3],_x000D_
[3, -1, 2]_x000D_
];_x000D_
_x000D_
var newarr = [];_x000D_
arr[0].forEach(() => newarr.push(new Array(arr.length)));_x000D_
_x000D_
for (var i = 0; i < newarr[0].length; i++) {_x000D_
for (var j = 0; j < newarr.length; j++) {_x000D_
newarr[j][i] = getArray2dCCW(arr, i, j);_x000D_
}_x000D_
}_x000D_
console.log(newarr);
_x000D_
// Get an array element rotated 180 degrees_x000D_
function getArray2d180(a, x, y) {_x000D_
x = a[0].length - x - 1;_x000D_
y = a.length - y - 1;_x000D_
return a[y][x];_x000D_
}_x000D_
_x000D_
//demo_x000D_
var arr = [_x000D_
[5, 4, 6],_x000D_
[1, 7, 9],_x000D_
[-2, 11, 0],_x000D_
[8, 21, -3],_x000D_
[3, -1, 2]_x000D_
];_x000D_
_x000D_
var newarr = [];_x000D_
arr.forEach(() => newarr.push(new Array(arr[0].length)));_x000D_
_x000D_
for (var i = 0; i < newarr[0].length; i++) {_x000D_
for (var j = 0; j < newarr.length; j++) {_x000D_
newarr[j][i] = getArray2d180(arr, i, j);_x000D_
}_x000D_
}_x000D_
console.log(newarr);
_x000D_
This code assumes an array of nested arrays, where each inner array is a row.
The method allows you to read (or write) elements (even in random order) as if the array has been rotated or transformed. Now just pick the right function to call, probably by reference, and away you go!
The concept can be extended to apply transformations additively (and non-destructively) through the accessor methods. Including arbitrary angle rotations and scaling.
You can iterate using the index access,
To avoid O(n^2) complexity you can use two indices, i - current testing index, j - index to store next item and at the end of the cycle new size of the vector.
code:
void erase(std::vector<int>& v, int num)
{
size_t j = 0;
for (size_t i = 0; i < v.size(); ++i) {
if (v[i] != num) v[j++] = v[i];
}
// trim vector to new size
v.resize(j);
}
In such case you have no invalidating of iterators, complexity is O(n), and code is very concise and you don't need to write some helper classes, although in some case using helper classes can benefit in more flexible code.
This code does not use erase
method, but solves your task.
Using pure stl you can do this in the following way (this is similar to the Motti's answer):
#include <algorithm>
void erase(std::vector<int>& v, int num) {
vector<int>::iterator it = remove(v.begin(), v.end(), num);
v.erase(it, v.end());
}
According to the grammar in the CSP spec, you need to specify schemes as scheme:
, not just scheme
. So, you need to change the image source directive to:
img-src 'self' data:;