You have a view model to which your view is strongly typed => use strongly typed helpers:
<%= Html.DropDownListFor(
x => x.SelectedAccountId,
new SelectList(Model.Accounts, "Value", "Text")
) %>
Also notice that I use a SelectList
for the second argument.
And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:
public ActionResult AccountTransaction()
{
var accounts = Services.AccountServices.GetAccounts(false);
var viewModel = new AccountTransactionView
{
Accounts = accounts.Select(a => new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString()
})
};
return View(viewModel);
}
It seems that this is the correct way window.location.assign("http://www.mozilla.org");
I use Spring Boot, my solution to the problem was
"src/main/resources/myfile.extension"
Hope it helps someone.
Use
window.history.replaceState({}, document.title, updatedUri);
To update Url without reloading the page
var url = window.location.href;
var urlParts = url.split('?');
if (urlParts.length > 0) {
var baseUrl = urlParts[0];
var queryString = urlParts[1];
//update queryString in here...I have added a new string at the end in this example
var updatedQueryString = queryString + 'this_is_the_new_url'
var updatedUri = baseUrl + '?' + updatedQueryString;
window.history.replaceState({}, document.title, updatedUri);
}
To remove Query string without reloading the page
var url = window.location.href;
if (url.indexOf("?") > 0) {
var updatedUri = url.substring(0, url.indexOf("?"));
window.history.replaceState({}, document.title, updatedUri);
}
When you read()
the file, you may get a newline character '\n'
in your string. Try either
if UserInput.strip() == 'List contents':
or
if 'List contents' in UserInput:
Also note that your second file open
could also use with
:
with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile: if UserInput.strip() == 'List contents': # or if s in f: UserInputFile.write("ls") else: print "Didn't work"
Example for escaped string with variable:
@some-variable-height: 10px;
...
div {
height: ~"calc(100vh - "@some-variable-height~")";
}
compiles to
div {
height: calc(100vh - 10px );
}
Enabling delayed variable expansion solves you problem, the script produces "hi":
setlocal EnableDelayedExpansion
set var1=A
set var2=B
set AB=hi
set newvar=!%var1%%var2%!
echo %newvar%
SELECT *
FROM MyTable
WHERE CreatedDate >= getdate()
AND CreatedDate <= dateadd(day, 90, getdate())
How about something like this?
<input name="myvalue" type="text" onfocus="if(this.value=='enter value')this.value='';" onblur="if(this.value=='')this.value='enter value';">
This will clear upon focusing the first time, but then won't clear on subsequent focuses after the user enters their value, when left blank it restores the given value.
For me, only "Integer.toHexString(registered)" worked the way I wanted:
char registered = '®';
System.out.println("Answer:"+Integer.toHexString(registered));
This answer will give you only string representations what are usually presented in the tables. Jon Skeet's answer explains more.
If one want to keep getting updated processes (on the example, 2 seconds) on a shell session without having to manually interact with it use:
watch -n 2 'mysql -h 127.0.0.1 -P 3306 -u some_user -psome_pass some_database -e "show full processlist;"'
The only bad thing about the show [full] processlist
is that you can't filter the output result. On the other hand, issuing the SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST
open possibilities to remove from the output anything you don't want to see:
SELECT * from INFORMATION_SCHEMA.PROCESSLIST
WHERE DB = 'somedatabase'
AND COMMAND <> 'Sleep'
AND HOST NOT LIKE '10.164.25.133%' \G
Try delete
:
models.User.query.delete()
From the docs: Returns the number of rows deleted, excluding any cascades.
For separate modules (x86 and x64), if you want a customized installation without downloading loads of crap, see Servers Microsoft® SQL Server® 2012 Express.
Run the following query from Management Studio on a running process:
DBCC inputbuffer( spid# )
This will return the SQL currently being run against the database for the SPID provided. Note that you need appropriate permissions to run this command.
This is better than running a trace since it targets a specific SPID. You can see if it's long running based on its CPUTime and DiskIO.
Example to get details of SPID 64:
DBCC inputbuffer(64)
date --date="2:00:01 PM" +%T
14:00:01
date --date="2:00 PM" +%T | cut -d':' -f1-2
14:00
var="2:00:02 PM"
date --date="$var" +%T
14:00:02
you can use getline from a file using this code. this code will take a whole line from the file. and then you can use a while loop to go all lines while (ins);
ifstream ins(filename);
string s;
std::getline (ins,s);
You can store any kind of data in a session using:
Session["VariableName"]=value;
This variable will last 20 mins or so.
Here are couple ways of doing it:
>>> t = ((1, 'a'), (2, 'b'))
>>> # using reversed function
>>> dict(reversed(i) for i in t)
{'a': 1, 'b': 2}
>>> # using slice operator
>>> dict(i[::-1] for i in t)
{'a': 1, 'b': 2}
Yes, delete this;
has defined results, as long as (as you've noted) you assure the object was allocated dynamically, and (of course) never attempt to use the object after it's destroyed. Over the years, many questions have been asked about what the standard says specifically about delete this;
, as opposed to deleting some other pointer. The answer to that is fairly short and simple: it doesn't say much of anything. It just says that delete
's operand must be an expression that designates a pointer to an object, or an array of objects. It goes into quite a bit of detail about things like how it figures out what (if any) deallocation function to call to release the memory, but the entire section on delete
(§[expr.delete]) doesn't mention delete this;
specifically at all. The section on destrucors does mention delete this
in one place (§[class.dtor]/13):
At the point of definition of a virtual destructor (including an implicit definition (15.8)), the non-array deallocation function is determined as if for the expression delete this appearing in a non-virtual destructor of the destructor’s class (see 8.3.5).
That tends to support the idea that the standard considers delete this;
to be valid--if it was invalid, its type wouldn't be meaningful. That's the only place the standard mentions delete this;
at all, as far as I know.
Anyway, some consider delete this
a nasty hack, and tell anybody who will listen that it should be avoided. One commonly cited problem is the difficulty of ensuring that objects of the class are only ever allocated dynamically. Others consider it a perfectly reasonable idiom, and use it all the time. Personally, I'm somewhere in the middle: I rarely use it, but don't hesitate to do so when it seems to be the right tool for the job.
The primary time you use this technique is with an object that has a life that's almost entirely its own. One example James Kanze has cited was a billing/tracking system he worked on for a phone company. When start to you make a phone call, something takes note of that and creates a phone_call
object. From that point onward, the phone_call
object handles the details of the phone call (making a connection when you dial, adding an entry to the database to say when the call started, possibly connect more people if you do a conference call, etc.) When the last people on the call hang up, the phone_call
object does its final book-keeping (e.g., adds an entry to the database to say when you hung up, so they can compute how long your call was) and then destroys itself. The lifetime of the phone_call
object is based on when the first person starts the call and when the last people leave the call--from the viewpoint of the rest of the system, it's basically entirely arbitrary, so you can't tie it to any lexical scope in the code, or anything on that order.
For anybody who might care about how dependable this kind of coding can be: if you make a phone call to, from, or through almost any part of Europe, there's a pretty good chance that it's being handled (at least in part) by code that does exactly this.
There are many ways to achieve this, like flatten-and-filter or simply enumerate, but I think using Boolean/mask array is the easiest one (and iirc a much faster one):
>>> y = np.array([[123,24123,32432], [234,24,23]])
array([[ 123, 24123, 32432],
[ 234, 24, 23]])
>>> b = y > 200
>>> b
array([[False, True, True],
[ True, False, False]], dtype=bool)
>>> y[b]
array([24123, 32432, 234])
>>> len(y[b])
3
>>>> y[b].sum()
56789
Update:
As nneonneo has answered, if all you want is the number of elements that passes threshold, you can simply do:
>>>> (y>200).sum()
3
which is a simpler solution.
Speed comparison with filter
:
### use boolean/mask array ###
b = y > 200
%timeit y[b]
100000 loops, best of 3: 3.31 us per loop
%timeit y[y>200]
100000 loops, best of 3: 7.57 us per loop
### use filter ###
x = y.ravel()
%timeit filter(lambda x:x>200, x)
100000 loops, best of 3: 9.33 us per loop
%timeit np.array(filter(lambda x:x>200, x))
10000 loops, best of 3: 21.7 us per loop
%timeit filter(lambda x:x>200, y.ravel())
100000 loops, best of 3: 11.2 us per loop
%timeit np.array(filter(lambda x:x>200, y.ravel()))
10000 loops, best of 3: 22.9 us per loop
*** use numpy.where ***
nb = np.where(y>200)
%timeit y[nb]
100000 loops, best of 3: 2.42 us per loop
%timeit y[np.where(y>200)]
100000 loops, best of 3: 10.3 us per loop
The __doPostBack()
method works well.
Another solution (very hackish) is to simply add an invisible ASP button in your markup and click it with a JavaScript method.
<div style="display: none;">
<asp:Button runat="server" ... OnClick="ButtonClickHandlerMethod" />
</div>
From your JavaScript, retrieve the reference to the button using its ClientID and then call the .click() method on it.
var button = document.getElementById(/* button client id */);
button.click();
I had the same issue. I tried building my project with an iPhone that I never used before and I didn't add a new framework. For me, cleaning up worked fine (Shift+Command+K). Maybe it's because I use beta 5 of Xcode 7 and an iPhone 6 with iOS 9 Beta, but it worked.
Static memory allocation is allocated memory before execution pf program during compile time. Dynamic memory alocation is alocated memory during execution of program at run time.
New, resurrected project site (Win7 compability and more!): http://sshwindows.sourceforge.net
1st January 2012
- OpenSSH for Windows 5.6p1-2 based release created!!
- Happy New Year all! Since COpSSH has started charging I've resurrected this project
- Updated all binaries to current releases
- Added several new supporting DLLs as required by all executables in package
- Renamed switch.exe to bash.exe to remove the need to modify and compile mkpasswd.exe each build
- Please note there is a very minor bug in this release, detailed in the docs. I'm working on fixing this, anyone who can code in C and can offer a bit of help it would be much appreciated
Image manipulation is a complex topic, and it's best if you do use a library. I can recommend gdmodule which provides easy access to many different image formats from within Python.
Sometimes this happens because symlinks are not allowed in template settings:
Advanced > Developer > Template Settings > Allow Symlinks
The following code is an in-place permutation of a given list, implemented as a generator. Since it only returns references to the list, the list should not be modified outside the generator. The solution is non-recursive, so uses low memory. Work well also with multiple copies of elements in the input list.
def permute_in_place(a):
a.sort()
yield list(a)
if len(a) <= 1:
return
first = 0
last = len(a)
while 1:
i = last - 1
while 1:
i = i - 1
if a[i] < a[i+1]:
j = last - 1
while not (a[i] < a[j]):
j = j - 1
a[i], a[j] = a[j], a[i] # swap the values
r = a[i+1:last]
r.reverse()
a[i+1:last] = r
yield list(a)
break
if i == first:
a.reverse()
return
if __name__ == '__main__':
for n in range(5):
for a in permute_in_place(range(1, n+1)):
print a
print
for a in permute_in_place([0, 0, 1, 1, 1]):
print a
print
You could create a hashtable. The keys can be the string and the value can be and integer. Setup your integers for the values as constants and then you can check for them with the switch
.
Here are a couple of alternative ways of doing it, that may be faster or more suitable than KennyTM's answer, depending on the context.
1) use a regular expression:
import re
words_re = re.compile("|".join(list_of_words))
if words_re.search('some one long two phrase three'):
# do logic you want to perform
2) You could use sets if you want to match whole words, e.g. you do not want to find the word "the" in the phrase "them theorems are theoretical":
word_set = set(list_of_words)
phrase_set = set('some one long two phrase three'.split())
if word_set.intersection(phrase_set):
# do stuff
Of course you can also do whole word matches with regex using the "\b" token.
The performance of these and Kenny's solution are going to depend on several factors, such as how long the word list and phrase string are, and how often they change. If performance is not an issue then go for the simplest, which is probably Kenny's.
It may be easier to use XPath to locate the nodes that you wish to delete. This stackoverflow thread might give you some ideas.
In your case you will find the four nodes that you want using this expression:
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");
Android make the default avd files in the C:\Users\[USERNAME]\.android directory. Just make sure you copy the avd folder from this directory C:\Users\[USERNAME]\.android to C:\Android\.android. My problem was resolved after doing this.
It's a dynamic object, meaning you can add properties to it in the controller, and read them later in the view, because you are essentially creating the object as you do, a feature of the dynamic type. See this MSDN article on dynamics. See this article on it's usage in relation to MVC.
If you wanted to use this for web forms, add a dynamic property to a base page class like so:
public class BasePage : Page
{
public dynamic ViewBagProperty
{
get;
set;
}
}
Have all of your pages inherit from this. You should be able to, in your ASP.NET markup, do:
<%= ViewBagProperty.X %>
That should work. If not, there are ways to work around it.
You haven't set the timezone only added a Z
to the end of the date/time, so it will look like a GMT date/time but this doesn't change the value.
Set the timezone to GMT and it will be correct.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
This is a common formatting floating number use case.
Unfortunately, all of the built-in one-letter format strings (eg. F, G, N) won't achieve this directly.
For example, num.ToString("F2")
will always show 2 decimal places like 123.40
.
You'll have to use 0.##
pattern even it looks a little verbose.
A complete code example:
double a = 123.4567;
double b = 123.40;
double c = 123.00;
string sa = a.ToString("0.##"); // 123.46
string sb = b.ToString("0.##"); // 123.4
string sc = c.ToString("0.##"); // 123
According to this post this error message means:
Heap size is larger than your computer's physical memory.
Edit: Heap is not the only memory that is reserved, I suppose. At least there are other JVM settings like PermGenSpace that ask for the memory. With heap size 128M and a PermGenSpace of 64M you already fill the space available.
Why not downsize other memory settings to free up space for the heap?
If you have luasocket installed:
local socket = require 'socket'
socket.sleep(0.2)
EF 4.7 actually gives a hint when you run Enable-migrations at multiple context.
More than one context type was found in the assembly 'Service.Domain'.
To enable migrations for 'Service.Domain.DatabaseContext.Context1',
use Enable-Migrations -ContextTypeName Service.Domain.DatabaseContext.Context1.
To enable migrations for 'Service.Domain.DatabaseContext.Context2',
use Enable-Migrations -ContextTypeName Service.Domain.DatabaseContext.Context2.
Just wanted to provide a different option for this. In my case, I usually work on my individual branches then merge to master, and the individual commits I do to my local are not that important.
Due to a git hook that checks for the appropriate ticket number on Jira but was case sensitive, I was prevented from pushing my code. Also, the commit was done long ago and I didn't want to count how many commits to go back on the rebase.
So what I did was to create a new branch from latest master and squash all commits from problem branch into a single commit on new branch. It was easier for me and I think it's good idea to have it here as future reference.
From latest master:
git checkout -b new-branch
Then
git merge --squash problem-branch
git commit -m "new message"
Width 100% : It will make content with 100%. margin, border, padding will be added to this width and element will overflow if any of these added.
Width auto : It will fit the element in available space including margin, border and padding. space remaining after adjusting margin + padding + border will be available width/ height.
Width 100% + box-sizing: border box : It will also fits the element in available space including border, padding (margin will make it overflow the container).
Here's what you can do:
return View("another view name", anotherviewmodel);
If you have no FIRST/FIRST conflicts and no FIRST/FOLLOW conflicts, your grammar is LL(1).
An example of a FIRST/FIRST conflict:
S -> Xb | Yc
X -> a
Y -> a
By seeing only the first input symbol a, you cannot know whether to apply the production S -> Xb or S -> Yc, because a is in the FIRST set of both X and Y.
An example of a FIRST/FOLLOW conflict:
S -> AB
A -> fe | epsilon
B -> fg
By seeing only the first input symbol f, you cannot decide whether to apply the production A -> fe or A -> epsilon, because f is in both the FIRST set of A and the FOLLOW set of A (A can be parsed as epsilon and B as f).
Notice that if you have no epsilon-productions you cannot have a FIRST/FOLLOW conflict.
Did you try something like:
body {background: url('[url to your image]') no-repeat right bottom;}
In React you don't need the html data, use a function return a other function; like this it's very simple send custom params and you can acces the custom data and the event.
render: function() {
...
<a style={showStyle} onClick={this.removeTag(i)}></a>
...
removeTag: (i) => (event) => {
this.setState({inputVal: i});
},
_WIN32 identifier is not defined.
use #include <SDKDDKVer.h>
MSVS generated projects wrap this include by generating a local "targetver.h"
which is included by "stdafx.h"
that is comiled into a precompiled-header through "stdafx.cpp"
.
EDIT : do you have a /D "WIN32" on your commandline ?
After a few "try and test" iterations I've found a way (still not present here) to get size of file in cycle variable (not a command line parameter):
for %%i in (*.txt) do (
echo %%~z%i
)
Please click on "edit" -> then keyboard shortcuts. It`s straight forward from there. Just select the command from the list, and press the + button.
You will need to create a duplicate set, then select it again from the list. And finally set a keyboard shortcut!
Now, before saving, press the shortcut you just created!
class(mtcars)
my.mean <- unlist(lapply(mtcars, mean)); my.mean
mpg cyl disp hp drat wt qsec vs
20.090625 6.187500 230.721875 146.687500 3.596563 3.217250 17.848750 0.437500
am gear carb
0.406250 3.687500 2.812500
The title
attribute displays a tooltip when the mouse is hovering the element. While this is a great addition, it doesn't help people who cannot use the mouse (due to mobility disabilities) or people who can't see this tooltip (e.g.: people with visual disabilities or people who use a screen reader).
As such, the mindful approach here would be to serve all users. I would add both title
and aria-label
attributes (serving different types of users and different types of usage of the web).
Here's a good article that explains aria-label
in depth
As of iOS 10, videos now can autoplay, but only of they are either muted, or have no audio track. Yay!
In short:
<video autoplay>
elements will now honor the autoplay attribute, for
elements which meet the following conditions:
<video>
elements will be allowed to autoplay without a user gesture if their source media contains no audio tracks.<video muted>
elements will also be allowed to autoplay without a user gesture.<video>
element gains an audio track or becomes un-muted without a user gesture, playback will pause.<video autoplay>
elements will only begin playing when visible on-screen such as when they are scrolled into the viewport, made
visible through CSS, and inserted into the DOM.<video autoplay>
elements will pause if they become non-visible, such as by being scrolled out of the viewport.More info here: https://webkit.org/blog/6784/new-video-policies-for-ios/
Pseudo-random number generators work by performing some operation on a value. Generally this value is the previous number generated by the generator. However, the first time you use the generator, there is no previous value.
Seeding a pseudo-random number generator gives it its first "previous" value. Each seed value will correspond to a sequence of generated values for a given random number generator. That is, if you provide the same seed twice, you get the same sequence of numbers twice.
Generally, you want to seed your random number generator with some value that will change each execution of the program. For instance, the current time is a frequently-used seed. The reason why this doesn't happen automatically is so that if you want, you can provide a specific seed to get a known sequence of numbers.
$tz = new DateTimeZone('Europe/London');
$date = new DateTime($today, $tz);
$date->modify('+10 hours');
// use $date->format() to outputs the result.
see DateTime Class (PHP 5 >= 5.2.0)
Here is my version. It stores data based on categories.
import matplotlib.pyplot as plt
import numpy as np
data_a = [[1,2,5], [5,7,2,2,5], [7,2,5]]
data_b = [[6,4,2], [1,2,5,3,2], [2,3,5,1]]
ticks = ['A', 'B', 'C']
def set_box_color(bp, color):
plt.setp(bp['boxes'], color=color)
plt.setp(bp['whiskers'], color=color)
plt.setp(bp['caps'], color=color)
plt.setp(bp['medians'], color=color)
plt.figure()
bpl = plt.boxplot(data_a, positions=np.array(xrange(len(data_a)))*2.0-0.4, sym='', widths=0.6)
bpr = plt.boxplot(data_b, positions=np.array(xrange(len(data_b)))*2.0+0.4, sym='', widths=0.6)
set_box_color(bpl, '#D7191C') # colors are from http://colorbrewer2.org/
set_box_color(bpr, '#2C7BB6')
# draw temporary red and blue lines and use them to create a legend
plt.plot([], c='#D7191C', label='Apples')
plt.plot([], c='#2C7BB6', label='Oranges')
plt.legend()
plt.xticks(xrange(0, len(ticks) * 2, 2), ticks)
plt.xlim(-2, len(ticks)*2)
plt.ylim(0, 8)
plt.tight_layout()
plt.savefig('boxcompare.png')
I am short of reputation so I cannot post an image to here. You can run it and see the result. Basically it's very similar to what Molly did.
Note that, depending on the version of python you are using, you may need to replace xrange
with range
// Find, Replace, Case
// i.e "Test to see if this works? (Yes|No)".replaceAll('(Yes|No)', 'Yes!');
// i.e.2 "Test to see if this works? (Yes|No)".replaceAll('(yes|no)', 'Yes!', true);
String.prototype.replaceAll = function(_f, _r, _c){
var o = this.toString();
var r = '';
var s = o;
var b = 0;
var e = -1;
if(_c){ _f = _f.toLowerCase(); s = o.toLowerCase(); }
while((e=s.indexOf(_f)) > -1)
{
r += o.substring(b, b+e) + _r;
s = s.substring(e+_f.length, s.length);
b += e+_f.length;
}
// Add Leftover
if(s.length>0){ r+=o.substring(o.length-s.length, o.length); }
// Return New String
return r;
};
If your local directory has git initialized and you have not committed the changes that include the delete, you can use git checkout -f
to throw away local changes.
The illegal character is not in $matches[1]
, but in $xml
Try
iconv($matches[1], 'utf-8//TRANSLIT', $xml);
And showing us the input string would be nice for a better answer.
if your table is like this
rowId col1 col2 col3 col4
1 a e 12 2
2 b f 42 5
3 a e 32 2
4 b f 44 5
var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 = r.Field<int>("col1"), pp2 = r.Field<int>("col2")});
I know this is quite an old question -
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Let's say, you want to extract the first 2 rows and first 3 columns
A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
[4, 5, 6]]
Understanding the syntax
A_NEW = A[start_index_row : stop_index_row,
start_index_column : stop_index_column)]
If one wants row 2 and column 2 and 3
A_NEW = A[1:2, 1:3]
Reference the numpy indexing and slicing article - Indexing & Slicing
Starting with react_router 1.0, the props will be passed onto the anchor tag. You can directly use target="_blank"
. Discussed here: https://github.com/ReactTraining/react-router/issues/2188
The workaround is
(this will remove all the new lines and there should be whole one line)
now perform your replacements
search and replace thisismynewlineword to \r\n
(to undo the step 1)
in my case I added the following line in my terminal:
export PATH="/Users/Username/Library/Android/sdk/platform-tools":$PATH
make sure that you replace "username" with YOUR user name.
hit enter then type 'adb' to see if the error is gone. if it is, this is what you should see: Android Debug Bridge version 1.0.40
...followed by a bunch of commands..and ending with this: $ADB_TRACE comma-separated list of debug info to log: all,adb,sockets,packets,rwx,usb,sync,sysdeps,transport,jdwp $ADB_VENDOR_KEYS colon-separated list of keys (files or directories) $ANDROID_SERIAL serial number to connect to (see -s) $ANDROID_LOG_TAGS tags to be used by logcat (see logcat --help)
if you get that, run npm run android again and it should work..
The tinymce API takes care of many events in the editors iframe. I strongly suggest to use them. Here is an example for the click handler
// Adds an observer to the onclick event using tinyMCE.init
tinyMCE.init({
...
setup : function(ed) {
ed.onClick.add(function(ed, e) {
console.debug('Iframe clicked:' + e.target);
});
}
});
Here is an Alternative that worked for me:
yourFrame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource(Filepath)));
It's very similar to the accepted Answer.
I can see a reason, unrelated to the original post, to automatically compile jQuery code into standard JavaScript:
16k -- or whatever the gzipped, minified jQuery library is -- might be too much for your website that is intended for a mobile browser. The w3c is recommending that all HTTP requests for mobile websites should be a maximum of 20k.
So I enjoy coding in my nice, terse, chained jQuery. But now I need to optimize for mobile. Should I really go back and do the difficult, tedious work of rewriting all the helper functions I used in the jQuery library? Or is there some kind of convenient app that will help me recompile?
That would be very sweet. Sadly, I don't think such a thing exists.
Try This
SELECT @PrimaryContactKey = c.PrimaryCntctKey
FROM tarcustomer c, tarinvoice i
WHERE i.custkey = c.custkey
AND i.invckey = @tmp_key
UPDATE tarinvoice SET confirmtocntctkey = @PrimaryContactKey
WHERE invckey = @tmp_key
FETCH NEXT FROM @get_invckey INTO @tmp_key
You would declare this variable outside of your loop as just a standard TSQL variable.
I should also note that this is how you would do it for any type of select into a variable, not just when dealing with cursors.
for integer 'X' you want to know the number of digits , alright without using any loop , this solution act in one formula in one line only so this is the most optimal solution i have ever seen to this problem .
int x = 1000 ;
cout<<numberOfDigits = 1+floor(log10(x))<<endl ;
For the replacement string and the replacement pattern as specified by $
.
here a resume:
link to doc : here
"hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")
Note:
If you want to have a $
in the replacement string use $$
. Same as with vscode snippet system.
To do it the GUI way, you need to go edit your login. One of its properties is the default database used for that login. You can find the list of logins under the Logins node under the Security node. Then select your login and right-click and pick Properties. Change the default database and your life will be better!
Note that someone with sysadmin privs needs to be able to login to do this or to run the query from the previous post.
I find that this simple solution works best for me:
function setEqualHeight(a, b) {
if (!$(a).height()) {
return window.setTimeout(function(){ setEqualHeight(a, b); }, 1000);
}
$(b).height($(a).height());
}
$(document).ready(function() {
setEqualHeight('#image', '#description');
$(window).resize(function(){setEqualHeight('#image', '#description')});
});
</script>
This seems to be a recurring issue with 1GB and smaller server instances. Apart from trying to shutdown processes and tweak swap settings, you could install on a local machine and upload.
For current datetime, you can use now() function in postgresql insert query.
You can also refer following link.
insert statement in postgres for data type timestamp without time zone NOT NULL,.
If someone is in search for a quick minimal solution,
import signal
# The code which crashes program on interruption
signal.signal(signal.SIGINT, call_this_function_if_interrupted)
# The code skipped if interrupted
If you're using VS Code then it'll should unable to watch in large workspace error.
"Visual Studio Code is unable to watch for file changes in this large workspace" (error ENOSPC)
It indicates that the VS Code file watcher is running out of handles because the workspace is large and contains many files. The current limit can be viewed by running:
cat /proc/sys/fs/inotify/max_user_watches
The limit can be increased to its maximum by editing /etc/sysctl.conf
and adding this line to the end of the file:
fs.inotify.max_user_watches=524288
The new value can then be loaded in by running sudo sysctl -p
.
Note: 524288 is the max value to watch the files. Though you can watch any no of files but is also recommended to watch upto that limit only.
From the git-branch manual page:
git branch --contains <commit>
Only list branches which contain the specified commit (HEAD if not specified). Implies
--list
.
git branch -r --contains <commit>
Lists remote tracking branches as well (as mentioned in user3941992's answer below) that is "local branches that have a direct relationship to a remote branch".
As noted by Carl Walsh, this applies only to the default refspec
fetch = +refs/heads/*:refs/remotes/origin/*
If you need to include other ref namespace (pull request, Gerrit, ...), you need to add that new refspec, and fetch again:
git config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"
git fetch
git branch -r --contains <commit>
See also this git ready article.
The
--contains
tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you’ve got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.
$ git log -1 tests
commit d590f2ac0635ec0053c4a7377bd929943d475297
Author: Nick Quaranto <[email protected]>
Date: Wed Apr 1 20:38:59 2009 -0400
Green all around, finally.
$ git branch --contains d590f2
tests
* master
Note: if the commit is on a remote tracking branch, add the -a
option.
(as MichielB comments below)
git branch -a --contains <commit>
MatrixFrog comments that it only shows which branches contain that exact commit.
If you want to know which branches contain an "equivalent" commit (i.e. which branches have cherry-picked that commit) that's git cherry
:
Because
git cherry
compares the changeset rather than the commit id (sha1), you can usegit cherry
to find out if a commit you made locally has been applied<upstream>
under a different commit id.
For example, this will happen if you’re feeding patches<upstream>
via email rather than pushing or pulling commits directly.
__*__*__*__*__> <upstream>
/
fork-point
\__+__+__-__+__+__-__+__> <head>
(Here, the commits marked '-
' wouldn't show up with git cherry
, meaning they are already present in <upstream>
.)
Here is worker like this. \o/
- name: "Exec items"
shell: "{{ item }}"
with_items:
- echo "hello"
- echo "hello2"
I was facing this error while running Karma Unit Test cases Adding MatSelectModule in the imports fixes the issue
imports: [
HttpClientTestingModule,
FormsModule,
MatTableModule,
MatSelectModule,
NoopAnimationsModule
],
Put the following code in your CSS, this works with Bootstrap 4:
.w-100 {
width: 100% !important;
height: 75vh;
}
I was getting the issue 'Newtonsoft.Json' already has a dependency defined for 'Microsoft.CSharp'
on the TeamCity build server.
I changed the "Update Mode" of the Nuget Installer build step from solution file to packages.config and NuGet.exe to the latest version (I had 3.5.0) and it worked !!
I would propose a clean version based on DISTINCT ON
(see docs):
SELECT DISTINCT ON (usr_id)
time_stamp,
lives_remaining,
usr_id,
trans_id
FROM lives
ORDER BY usr_id, time_stamp DESC, trans_id DESC;
open(filename,'r') #2nd argument is r and not w
will open the file or give an error if it doesn't exist. If there's an error, then you can try to write to the path, if you can't then you get a second error
try:
open(filename,'r')
return True
except IOError:
try:
open(filename, 'w')
return True
except IOError:
return False
Also have a look here about permissions on windows
You can use this configuration:
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M
I've found that there are some files that may affect the $PATH
variable in macOS (works for me, 10.11 El Capitan), listed below:
As the top voted answer said, vi /etc/paths
, which is recommended from my point of view.
Also don't forget the /etc/paths.d
directory, which contains files may affect the $PATH
variable, set the git
and mono-command
path in my case. You can ls -l /etc/paths.d
to list items and rm /etc/paths.d/path_you_dislike
to remove items.
If you're using a "bash" environment (the default Terminal.app
, for example), you should check out ~/.bash_profile
or ~/.bashrc
. There may be not that file yet, but these two files have effects on the $PATH
.
If you're using a "zsh" environment (Oh-My-Zsh, for example), you should check out ~./zshrc
instead of ~/.bash*
thing.
And don't forget to restart all the terminal windows, then echo $PATH
. The $PATH
string will be PATH_SET_IN_3&4:PATH_SET_IN_1:PATH_SET_IN_2
.
Noticed that the first two ways (/etc/paths
and /etc/path.d
) is in /
directory which will affect all the accounts in your computer while the last two ways (~/.bash*
or ~/.zsh*
) is in ~/
directory (aka, /Users/yourusername/
) which will only affect your account settings.
The critical step is getting the merge itself to be in-place. It's not as difficult as those sources make out, but you lose something when you try.
Looking at one step of the merge:
[...list-sorted...|x...list-A...|y...list-B...]
We know that the sorted sequence is less than everything else, that x is less than everything else in A, and that y is less than everything else in B. In the case where x is less than or equal to y, you just move your pointer to the start of A on one. In the case where y is less than x, you've got to shuffle y past the whole of A to sorted. That last step is what makes this expensive (except in degenerate cases).
It's generally cheaper (especially when the arrays only actually contain single words per element, e.g., a pointer to a string or structure) to trade off some space for time and have a separate temporary array that you sort back and forth between.
Little fix that works for many UITextFields
#pragma mark UIKeyboard handling
#define kMin 150
-(void)textFieldDidBeginEditing:(UITextField *)sender
{
if (currTextField) {
[currTextField release];
}
currTextField = [sender retain];
//move the main view, so that the keyboard does not hide it.
if (self.view.frame.origin.y + currTextField.frame.origin. y >= kMin) {
[self setViewMovedUp:YES];
}
}
//method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMovedUp:(BOOL)movedUp
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3]; // if you want to slide up the view
CGRect rect = self.view.frame;
if (movedUp)
{
// 1. move the view's origin up so that the text field that will be hidden come above the keyboard
// 2. increase the size of the view so that the area behind the keyboard is covered up.
rect.origin.y = kMin - currTextField.frame.origin.y ;
}
else
{
// revert back to the normal state.
rect.origin.y = 0;
}
self.view.frame = rect;
[UIView commitAnimations];
}
- (void)keyboardWillShow:(NSNotification *)notif
{
//keyboard will be shown now. depending for which textfield is active, move up or move down the view appropriately
if ([currTextField isFirstResponder] && currTextField.frame.origin.y + self.view.frame.origin.y >= kMin)
{
[self setViewMovedUp:YES];
}
else if (![currTextField isFirstResponder] && currTextField.frame.origin.y + self.view.frame.origin.y < kMin)
{
[self setViewMovedUp:NO];
}
}
- (void)keyboardWillHide:(NSNotification *)notif
{
//keyboard will be shown now. depending for which textfield is active, move up or move down the view appropriately
if (self.view.frame.origin.y < 0 ) {
[self setViewMovedUp:NO];
}
}
- (void)viewWillAppear:(BOOL)animated
{
// register for keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification object:self.view.window];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification object:self.view.window];
}
- (void)viewWillDisappear:(BOOL)animated
{
// unregister for keyboard notifications while not visible.
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}
Like Jason S's answer:
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
I put this in my Main and look to my app.config
and test if (ConfigurationManager.AppSettings["IgnoreSSLCertificates"] == "True")
before calling that line of code.
It appears to be a known issue.
http://dev.mysql.com/doc/refman/5.1/en/unnamed-views.html
http://bugs.mysql.com/bug.php?id=16757
Many IN queries can be re-written as (left outer) joins and an IS (NOT) NULL of some sort. for example
SELECT * FROM FOO WHERE ID IN (SELECT ID FROM FOO2)
can be re-written as
SELECT FOO.* FROM FOO JOIN FOO2 ON FOO.ID=FOO2.ID
or
SELECT * FROM FOO WHERE ID NOT IN (SELECT ID FROM FOO2)
can be
SELECT FOO.* FROM FOO
LEFT OUTER JOIN FOO2
ON FOO.ID=FOO2.ID WHERE FOO.ID IS NULL
I recently discovered the rather useful sweep
function and add it here for the sake of completeness:
sweep
The basic idea is to sweep through an array row- or column-wise and return a modified array. An example will make this clear (source: datacamp):
Let's say you have a matrix and want to standardize it column-wise:
dataPoints <- matrix(4:15, nrow = 4)
# Find means per column with `apply()`
dataPoints_means <- apply(dataPoints, 2, mean)
# Find standard deviation with `apply()`
dataPoints_sdev <- apply(dataPoints, 2, sd)
# Center the points
dataPoints_Trans1 <- sweep(dataPoints, 2, dataPoints_means,"-")
# Return the result
dataPoints_Trans1
## [,1] [,2] [,3]
## [1,] -1.5 -1.5 -1.5
## [2,] -0.5 -0.5 -0.5
## [3,] 0.5 0.5 0.5
## [4,] 1.5 1.5 1.5
# Normalize
dataPoints_Trans2 <- sweep(dataPoints_Trans1, 2, dataPoints_sdev, "/")
# Return the result
dataPoints_Trans2
## [,1] [,2] [,3]
## [1,] -1.1618950 -1.1618950 -1.1618950
## [2,] -0.3872983 -0.3872983 -0.3872983
## [3,] 0.3872983 0.3872983 0.3872983
## [4,] 1.1618950 1.1618950 1.1618950
NB: for this simple example the same result can of course be achieved more easily by
apply(dataPoints, 2, scale)
For check of email use email_validator
from email_validator import validate_email, EmailNotValidError
def check_email(email):
try:
v = validate_email(email) # validate and get info
email = v["email"] # replace with normalized form
print("True")
except EmailNotValidError as e:
# email is not valid, exception message is human-readable
print(str(e))
check_email("test@gmailcom")
Perhaps a more realistic example about not sorting a Map object but preparing the sorting up front before doing the Map. The syntax gets actually pretty compact if you do it like this. You can apply the sorting before the map function like this, with a sort function before map (Example from a React app I am working on using JSX syntax)
Mark that I here define a sorting function inside using an arrow function that returns -1 if it is smaller and 0 otherwise sorted on a property of the Javascript objects in the array I get from an API.
report.ProcedureCodes.sort((a, b) => a.NumericalOrder < b.NumericalOrder ? -1 : 0).map((item, i) =>
<TableRow key={i}>
<TableCell>{item.Code}</TableCell>
<TableCell>{item.Text}</TableCell>
{/* <TableCell>{item.NumericalOrder}</TableCell> */}
</TableRow>
)
try this one last:
so I tried all the suggestions on this page.. none worked.. The way my problem started was by following the steps in this tutorial that teaches how to link static libraries. With my sample project the instructions worked fine.. but then on my actual project I started getting the error above.
So what I did was go through each step of the said tutorial and built after each step.. the offending line turned out to be this one: adding -all_load to build settings-> other linker flags
it turns out that this flag was recommended once upon a time to link categories to static libraries.. but then it turned out that this flag was no longer necessary Xcode 4.2+.. (same goes for the -force_load flag.. which was also recommended in other posts)..
Do this:
data = [4, 5, 6]
def print_data():
global data
print(data)
print_data()
The linker tells you that you have the variable k
defined multiple times. Indeed, you have a definition in A.cpp and another in B.cpp. Both compilation units produce a corresponding object file that the linker uses to create your program. The problem is that in your case the linker does not know whic definition of k
to use. In C++ you can have only one defintion of the same construct (variable, type, function).
To fix it, you will have to decide what your goal is
k
, you can use an anonymous namespace in both .cpp files, then refer to k
as you are doing now:.
namespace {
int k;
}
k
s to something else, thus avoiding the duplicate defintion.k
and use that in both .cpp files, you need to declare in one as extern int k;
, and leave it as it is in the other. This will tell the linker to use the one definition (the unchanged version) in both cases -- extern
implies that the variable is defined in another compilation unit.I've found this to work:
var element1 = document.createElement("input");
element1.type = "hidden";
element1.value = "10";
element1.name = "a";
document.getElementById("chells").appendChild(element1);
After reading the answer of davidhund on this page I came up with a solution that your web font isn't loaded correctly that me be a issue of wrong paths.
Here is what he said:
My first guess is that you include the FontAwesome webfont from a different (sub-)domain. So make sure you set the correct headers on those webfont-files: "you'll need to add the Access-Control-Allow-Origin header, whitelisting the domain you're pulling the asset from." https://github.com/h5bp/html5boilerplate.com/blob/master/src/.htaccess#L78-86
And also look at the font-gotchas :)
Hope I am clear and helped you :)
On the same page, f135ta said:
...I fixed the issue by uploading the file "fontawesome-webfont.ttf" to my webserver and installing it like a regular font.. I dont know if its part of the pre-req's for using it anyway, but it works for me ;-
I think you can create a simple SQL query:
$sql="select username from user where id in (select id from idtables)";
$query=$this->db->query($sql);
and then you can use it normally.
As myJSON
is an object you can just set its properties, for example:
myJSON.list1 = ["1","2"];
If you dont know the name of the properties, you have to use the array access syntax:
myJSON['list'+listnum] = ["1","2"];
If you want to add an element to one of the properties, you can do;
myJSON.list1.push("3");
No. You can't. But it is very possible in Scala:
class Foo {val bar = "a"}
class Bar {val foo = "b"}
You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:
var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
if(!pattern.test(userinput))
{
alert('not a valid e-mail address');
}?
Since you only want to remove the $ sign in all column names, you could just do:
df = df.rename(columns=lambda x: x.replace('$', ''))
OR
df.rename(columns=lambda x: x.replace('$', ''), inplace=True)
Try:
With DependencedIncidents AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
),
lalala AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
)
And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.
Use the map
method:
var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
_x000D_
var c = a.map(function(e, i) {_x000D_
return [e, b[i]];_x000D_
});_x000D_
_x000D_
console.log(c)
_x000D_
new string (str.OrderBy(c => c).ToArray())
Just rename the class in the source code.
Eclipse will point out an error by underlining the class name with a red squiggly line.
Hover on that line with your mouse pointer and eclipse will give you the option to rename compilation unit
.
Click on that.
I think there is no one right way. There are a lot of different ways to iterate, and each has its own niche.
each
is sufficient for many usages, since I don't often care about the indexes. each_ with _index
acts like Hash#each - you get the value and the index.each_index
- just the indexes. I don't use this one often. Equivalent to "length.times".map
is another way to iterate, useful when you want to transform one array into another.select
is the iterator to use when you want to choose a subset.inject
is useful for generating sums or products, or collecting a single result. It may seem like a lot to remember, but don't worry, you can get by without knowing all of them. But as you start to learn and use the different methods, your code will become cleaner and clearer, and you'll be on your way to Ruby mastery.
Using ping in C# is achieved by using the method Ping.Send(System.Net.IPAddress)
, which runs a ping request to the provided (valid) IP address or URL and gets a response which is called an Internet Control Message Protocol (ICMP) Packet. The packet contains a header of 20 bytes which contains the response data from the server which received the ping request. The .Net framework System.Net.NetworkInformation
namespace contains a class called PingReply
that has properties designed to translate the ICMP
response and deliver useful information about the pinged server such as:
The following is a simple example using WinForms
to demonstrate how ping works in c#. By providing a valid IP address in textBox1
and clicking button1
, we are creating an instance of the Ping
class, a local variable PingReply
, and a string to store the IP or URL address. We assign PingReply
to the ping Send
method, then we inspect if the request was successful by comparing the status of the reply to the property IPAddress.Success
status. Finally, we extract from PingReply
the information we need to display for the user, which is described above.
using System;
using System.Net.NetworkInformation;
using System.Windows.Forms;
namespace PingTest1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Ping p = new Ping();
PingReply r;
string s;
s = textBox1.Text;
r = p.Send(s);
if (r.Status == IPStatus.Success)
{
lblResult.Text = "Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " Successful"
+ " Response delay = " + r.RoundtripTime.ToString() + " ms" + "\n";
}
}
private void textBox1_Validated(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(textBox1.Text) || textBox1.Text == "")
{
MessageBox.Show("Please use valid IP or web address!!");
}
}
}
}
Visual Studio in left panel is Python "interactive Select karnel"
Pyton 3.7.x anaconda3/python.exe ('base':conda) I'm this fixing
AFAIK you cannot do it with linear layouts, you'll have to go for a RelativeLayout.
Try SuperPuTTY. It is similar to puttycm.
The easiest method without using javaScript is to put all your <select> dropdown inside a <form> tag and use form reset button. Example:
<form>
<select>
<option>one</option>
<option>two</option>
<option selected>three</option>
</select>
<input type="reset" value="Reset" />
</form>
Or, using JavaScript, it can be done in following way:
HTML Code:
<select>
<option selected>one</option>
<option>two</option>
<option>three</option>
</select>
<button id="revert">Reset</button>
And JavaScript code:
const button = document.getElementById("revert");
const options = document.querySelectorAll('select option');
button.onclick = () => {
for (var i = 0; i < options.length; i++) {
options[i].selected = options[i].defaultSelected;
}
}
Both of these methods will work if you have multiple selected items or single selected item.
Answer is adding this 2 lines of code to Global.asax.cs Application_Start method
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.All;
Reference: Handling Circular Object References
The easiest way to do it is:
vector<int> ints = {10, 20, 30};
Use MySQL Workbench. create SQL dump file of your database
Follow below steps:
For a production system, you can use this configuration :
--ACCESS DB
REVOKE CONNECT ON DATABASE nova FROM PUBLIC;
GRANT CONNECT ON DATABASE nova TO user;
--ACCESS SCHEMA
REVOKE ALL ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO user;
--ACCESS TABLES
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC ;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO read_write ;
GRANT ALL ON ALL TABLES IN SCHEMA public TO admin ;
When using bootstrap 4 or 5, flexbox could be used to achieve desired effect:
<body class="d-flex flex-column min-vh-100">
<header>HEADER</header>
<content>CONTENT</content>
<footer class="mt-auto"></footer>
</body>
Please check the examples: Bootstrap 4 Bootstrap 5
In bootstrap 3 and without use of bootstrap. The simplest and cross browser solution for this problem is to set a minimal height for body
object. And then set absolute
position for the footer with bottom: 0
rule.
body {
min-height: 100vh;
position: relative;
margin: 0;
padding-bottom: 100px; //height of the footer
box-sizing: border-box;
}
footer {
position: absolute;
bottom: 0;
height: 100px;
}
Please check this example: Bootstrap 3
In most cases, you should use the instanceof
operator to test whether an object is an array.
Generally, you test an object's type before downcasting to a particular type which is known at compile time. For example, perhaps you wrote some code that can work with a Integer[]
or an int[]
. You'd want to guard your casts with instanceof
:
if (obj instanceof Integer[]) {
Integer[] array = (Integer[]) obj;
/* Use the boxed array */
} else if (obj instanceof int[]) {
int[] array = (int[]) obj;
/* Use the primitive array */
} else ...
At the JVM level, the instanceof
operator translates to a specific "instanceof" byte code, which is optimized in most JVM implementations.
In rarer cases, you might be using reflection to traverse an object graph of unknown types. In cases like this, the isArray()
method can be helpful because you don't know the component type at compile time; you might, for example, be implementing some sort of serialization mechanism and be able to pass each component of the array to the same serialization method, regardless of type.
There are two special cases: null references and references to primitive arrays.
A null reference will cause instanceof
to result false
, while the isArray
throws a NullPointerException
.
Applied to a primitive array, the instanceof
yields false
unless the component type on the right-hand operand exactly matches the component type. In contrast, isArray()
will return true
for any component type.
One line ES6 solution. So many answers using object as a map but I can't see anyone using an actual Map
const map = arr.reduce((acc, e) => acc.set(e, (acc.get(e) || 0) + 1), new Map());
Use map.keys()
to get unique elements
Use map.values()
to get the occurrences
Use map.entries()
to get the pairs [element, frequency]
var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4]_x000D_
_x000D_
const map = arr.reduce((acc, e) => acc.set(e, (acc.get(e) || 0) + 1), new Map());_x000D_
_x000D_
console.info([...map.keys()])_x000D_
console.info([...map.values()])_x000D_
console.info([...map.entries()])
_x000D_
First I would suggest putting a Log in each case of your switch to be sure that your code is being called.
Then I would check that the layouts are actually different.
tar -zcvf compressFileName.tar.gz folderToCompress
everything in folderToCompress will go to compressFileName
Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName
<a href="/fruits/index.html">Back to Fruits List</a>
For debugging purposes, you could use print(repr(data))
.
To display text, always print Unicode. Don't hardcode the character encoding of your environment such as Cp850 inside your script. To decode the HTTP response, see A good way to get the charset/encoding of an HTTP response in Python.
To print Unicode to Windows console, you could use win-unicode-console
package.
While the official docs are happy not to provide switch, I have seen a solution using dictionaries.
For example:
# define the function blocks
def zero():
print "You typed zero.\n"
def sqr():
print "n is a perfect square\n"
def even():
print "n is an even number\n"
def prime():
print "n is a prime number\n"
# map the inputs to the function blocks
options = {0 : zero,
1 : sqr,
4 : sqr,
9 : sqr,
2 : even,
3 : prime,
5 : prime,
7 : prime,
}
Then the equivalent switch block is invoked:
options[num]()
This begins to fall apart if you heavily depend on fall through.
Generally a .lock
file is created and it decides lock/unlock state checking the existince of this file. I think if you delete this .lock
file only, then the problem will go away.
I solved it.
I used destroy instead close function (it doesn't make any sense), but it worked.
$(document).ready(function() {
$('#showTerms').click(function()
{
$('#terms').css('display','inline');
$('#terms').dialog({resizable: false,
modal: true,
width: 400,
height: 450,
overlay: { backgroundColor: "#000", opacity: 0.5 },
buttons:{ "Close": function() { $(this).dialog('**destroy**'); } },
close: function(ev, ui) { $(this).close(); },
});
});
$('#form1 input#calendarTEST').datepicker({ dateFormat: 'MM d, yy' });
});
Respectfully to all those saying you can't insert a parameter in the middle of an alias I just tested it and found that it did work.
alias mycommand = "python3 "$1" script.py --folderoutput RESULTS/"
when I then ran mycommand foobar it worked exactly as if I had typed the command out longhand.
I found this tool that helped me get rid of a tfs binding complitly its found here https://marketplace.visualstudio.com/items?itemName=RonJacobs.CleanProject-CleansVisualStudioSolutionsForUploadi
it creates a zip with the removed source binding without modifying the orginal project.
Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;
This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79
.
Add any file in the documentation which will include your content, for example toc.h:
@ mainpage Manual SDK
<hr/>
@ section pageTOC Content
-# @ref Description
-# @ref License
-# @ref Item
...
And in your Doxyfile
:
INPUT = toc.h \
Example (in Russian):
<?php
header("Location: index.html");
?>
Just make sure nothing is actually written to the page prior to this code, or it won't work.
import re
regex = re.compile("u'2022'",re.UNICODE)
newstring = re.sub(regex, something, yourstring, <optional flags>)
first_key, *rest_keys = mydict
Or you could do this from NuGet Package Manager Console
Install-Package Microsoft.AspNet.WebApi -Version 5.0.0
And then you will be able to add the reference to System.Web.Http.WebHost 5.0
As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.
Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash
is incorrect and should have been callbackOnLocationHash
(note the mis-spelling of "Location").
This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.
Example:
interface TextOptions {
alignment?: string;
color?: string;
padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'
There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes
Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v
or v as T
) do not check for extra properties, so you can use them in place of a type annotation:
interface Options {
x?: string;
y?: number;
}
// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;
Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking
Before
interface Model {
name: string;
}
function createModel(x: Model) { ... }
// Error
createModel({name: 'hello', length: 100});
After
interface Model {
name: string;
[others: string]: any;
}
function createModel(x: Model) { ... }
// OK
createModel({name: 'hello', length: 100});
interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }
let x: Animal;
if(...) {
x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
x = { move: 'catwalk', meow: 'mrar' };
} else {
x = { move: 'gallop', neigh: 'wilbur' };
}
Two good solutions come to mind here
Specify a closed set for x
// Removes all errors
let x: Dog|Cat|Horse;
or Type assert each thing
// For each initialization
x = { move: 'doggy paddle', woof: 'bark' } as Dog;
A clean solution to the "data model" problem using intersection types:
interface DataModelOptions {
name?: string;
id?: number;
}
interface UserProperties {
[key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
/* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
/* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });
See also https://github.com/Microsoft/TypeScript/issues/3755
I also spent several hours fighting with this as well. The fix is real simple. Edit your Entitlements.plist file in the root of your project's directory. Find the line that says <key>get-task-allow</key>
. Underneath it should be <false/>
. Change that to <true/>
.
The way how I'm handling the Divider view and also Divider Insets is by adding a RecyclerView extension.
Add a new extension file by naming View or RecyclerView:
RecyclerViewExtension.kt
and add the setDivider
extension method inside the RecyclerViewExtension.kt file.
/*
* RecyclerViewExtension.kt
* */
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
fun RecyclerView.setDivider(@DrawableRes drawableRes: Int) {
val divider = DividerItemDecoration(
this.context,
DividerItemDecoration.VERTICAL
)
val drawable = ContextCompat.getDrawable(
this.context,
drawableRes
)
drawable?.let {
divider.setDrawable(it)
addItemDecoration(divider)
}
}
Create a Drawable resource file inside of drawable
package like recycler_view_divider.xml
:
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="10dp"
android:insetRight="10dp">
<shape>
<size android:height="0.5dp" />
<solid android:color="@android:color/darker_gray" />
</shape>
</inset>
where you can specify the left and right margin on android:insetLeft
and android:insetRight
.
On your Activity or Fragment where the RecyclerView is initialized, you can set the custom drawable by calling:
recyclerView.setDivider(R.drawable.recycler_view_divider)
Cheers
The builtin copy(dst, src)
copies min(len(dst), len(src))
elements.
So if your dst
is empty (len(dst) == 0
), nothing will be copied.
Try tmp := make([]int, len(arr))
(Go Playground):
arr := []int{1, 2, 3}
tmp := make([]int, len(arr))
copy(tmp, arr)
fmt.Println(tmp)
fmt.Println(arr)
Output (as expected):
[1 2 3]
[1 2 3]
Unfortunately this is not documented in the builtin
package, but it is documented in the Go Language Specification: Appending to and copying slices:
The number of elements copied is the minimum of
len(src)
andlen(dst)
.
Edit:
Finally the documentation of copy()
has been updated and it now contains the fact that the minimum length of source and destination will be copied:
Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).
let viewDemo = UIView()
viewDemo.frame = CGRect(x: 50, y: 50, width: 50, height: 50)
self.view.addSubview(viewDemo)
package com.acn.demo.action;
public class RemoveCharFromString {
static String input = "";
public static void main(String[] args) {
input = "abadbbeb34erterb";
char token = 'b';
removeChar(token);
}
private static void removeChar(char token) {
// TODO Auto-generated method stub
System.out.println(input);
for (int i=0;i<input.length();i++) {
if (input.charAt(i) == token) {
input = input.replace(input.charAt(i), ' ');
System.out.println("MATCH FOUND");
}
input = input.replaceAll(" ", "");
System.out.println(input);
}
}
}
You could try setting the failOnError
property (see plugin documentation) to false
:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<failOnError>false</failOnError>
</configuration>
</execution>
</executions>
</plugin>
As you can see from the docs, the default value is true
.
If you want to register only one single key press even if the user pressed it for more than once or kept pressing the key longer. To avoid getting multiple pressed inputs use the while loop and pass it.
import keyboard
while(True):
if(keyboard.is_pressed('w')):
s+=1
while(keyboard.is_pressed('w')):
pass
if(keyboard.is_pressed('s')):
s-=1
while(keyboard.is_pressed('s')):
pass
print(s)
I know it's a bit late in the game, but I remembered this question from when it was new and I had a similar dillemma, and I accidently found the "right" solution, if anyone is still looking for one:
<path
d="
M cx cy
m -r, 0
a r,r 0 1,0 (r * 2),0
a r,r 0 1,0 -(r * 2),0
"
/>
In other words, this:
<circle cx="100" cy="100" r="75" />
can be achieved as a path with this:
<path
d="
M 100, 100
m -75, 0
a 75,75 0 1,0 150,0
a 75,75 0 1,0 -150,0
"
/>
The trick is to have two arcs, the second one picking up where the first left off and using the negative diameter to get back to the original arc start point.
The reason it can't be done as a full circle in one arc (and I'm just speculating) is because you would be telling it to draw an arc from itself (let's say 150,150) to itself (150,150), which it renders as "oh, I'm already there, no arc necessary!".
The benefits of the solution I'm offering are:
None of this would matter if they would just allow textpaths to accept shapes. But I think they are avoiding that solution since shape elements like circle don't technically have a "start" point.
jsfiddle demo: http://jsfiddle.net/crazytonyi/mNt2g/
If you are using the path for a textPath
reference and you are wanting the text to render on the outer edge of the arc, you would use the exact same method but change the sweep-flag from 0 to 1 so that it treats the outside of the path as the surface instead of the inside (think of 1,0
as someone sitting at the center and drawing a circle around themselves, while 1,1
as someone walking around the center at radius distance and dragging their chalk beside them, if that's any help). Here is the code as above but with the change:
<path
d="
M cx cy
m -r, 0
a r,r 0 1,1 (r * 2),0
a r,r 0 1,1 -(r * 2),0
"
/>
You are correct in guessing that the aim of using string builder is not achieved, at least not to its full extent.
However, when the compiler sees the expression "select id1, " + " id2 " + " from " + " table"
it emits code which actually creates a StringBuilder
behind the scenes and appends to it, so the end result is not that bad afterall.
But of course anyone looking at that code is bound to think that it is kind of retarded.
For beginners above answer might be difficult, this is the easiest way to understand it:
Traits
trait SayWorld {
public function sayHello() {
echo 'World!';
}
}
so if you want to have sayHello
function in other classes without re-creating the whole function you can use traits,
class MyClass{
use SayWorld;
}
$o = new MyClass();
$o->sayHello();
Cool right!
Not only functions you can use anything in the trait(function, variables, const...). Also, you can use multiple traits: use SayWorld, AnotherTraits;
Interface
interface SayWorld {
public function sayHello();
}
class MyClass implements SayWorld {
public function sayHello() {
echo 'World!';
}
}
So this is how interfaces differ from traits: You have to re-create everything in the interface in an implemented class. Interfaces don't have an implementation and interfaces can only have functions and constants, it cannot have variables.
I hope this helps!
Precision is the main difference.
Float - 7 digits (32 bit)
Double-15-16 digits (64 bit)
Decimal -28-29 significant digits (128 bit)
Decimals have much higher precision and are usually used within financial applications that require a high degree of accuracy. Decimals are much slower (up to 20X times in some tests) than a double/float.
Decimals and Floats/Doubles cannot be compared without a cast whereas Floats and Doubles can. Decimals also allow the encoding or trailing zeros.
float flt = 1F/3;
double dbl = 1D/3;
decimal dcm = 1M/3;
Console.WriteLine("float: {0} double: {1} decimal: {2}", flt, dbl, dcm);
Result :
float: 0.3333333
double: 0.333333333333333
decimal: 0.3333333333333333333333333333
boostrap comes today with the possibility to fill a row evenly with built-in class that do not tell how many columns out of twelve to span :
you can use a col
/col-xx
:
div div div {_x000D_
border: solid;_x000D_
margin: 2px;/* this can be added without breaking the row */_x000D_
}_x000D_
div div div:before {_x000D_
content:attr(class);/* show class used */_x000D_
color:crimson
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<p>Class used , play snippet in full page to test behavior on resizing :</p>_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-sm"></div>_x000D_
<div class="col-sm"></div>_x000D_
<div class="col-sm"></div>_x000D_
<div class="col-sm"></div>_x000D_
<div class="col-sm"></div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-md"></div>_x000D_
<div class="col-md"></div>_x000D_
<div class="col-md"></div>_x000D_
<div class="col-md"></div>_x000D_
<div class="col-md"></div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col"></div>_x000D_
<div class="col"></div>_x000D_
<div class="col"></div>_x000D_
<div class="col"></div>_x000D_
<div class="col"></div>_x000D_
</div>_x000D_
</div>
_x000D_
flex-grow-x could be used too
div div div {_x000D_
border: solid;_x000D_
/* it allows margins too */_x000D_
margin: 3px;_x000D_
}_x000D_
_x000D_
div div div:before {_x000D_
content: attr(class);_x000D_
/* show class used */_x000D_
color: crimson_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="flex-grow-1"></div>_x000D_
<div class="flex-grow-1"></div>_x000D_
<div class="flex-grow-1"></div>_x000D_
<div class="flex-grow-1"></div>_x000D_
<div class="flex-grow-1"></div>_x000D_
</div>_x000D_
</div>
_x000D_
you can specify the max length for the multiline textbox in pageLoad Javascript Event
function pageLoad(){
$("[id$='txtInput']").attr("maxlength","10");
}
I have set the max length property of txtInput multiline textbox to 10 characters in pageLoad() Javascript function
I face with same thing, so i handle this with a generic why and i build a function for this:
//example: //array: [{name: 'idan', workerType: '3'}, {name: 'stas', workerType: '5'}, {name: 'kirill', workerType: '2'}] //keyField: 'workerType' // keysArray: ['4', '3', '2', '5', '6']
sortByArrayOfKeys = (array, keyField, keysArray) => {
array.sort((a, b) => {
const aIndex = keysArray.indexOf(a[keyField])
const bIndex = keysArray.indexOf(b[keyField])
if (aIndex < bIndex) return -1;
if (aIndex > bIndex) return 1;
return 0;
})
}
Many Linux distros (mostly Debian-based) configure OpenJDK to use /dev/random
for entropy.
/dev/random
is by definition slow (and can even block).
From here you have two options on how to unblock it:
Option 1, Improve entropy
To get more entropy into /dev/random
, try the haveged daemon. It's a daemon that continuously collects HAVEGE entropy, and works also in a virtualized environment because it doesn't require any special hardware, only the CPU itself and a clock.
On Ubuntu/Debian:
apt-get install haveged
update-rc.d haveged defaults
service haveged start
On RHEL/CentOS:
yum install haveged
systemctl enable haveged
systemctl start haveged
Option 2. Reduce randomness requirements
If for some reason the solution above doesn't help or you don't care about cryptographically strong randomness, you can switch to /dev/urandom
instead, which is guaranteed not to block.
To do it globally, edit the file jre/lib/security/java.security
in your default Java installation to use /dev/urandom
(due to another bug it needs to be specified as /dev/./urandom
).
Like this:
#securerandom.source=file:/dev/random
securerandom.source=file:/dev/./urandom
Then you won't ever have to specify it on the command line.
Note: If you do cryptography, you need good entropy. Case in point - android PRNG issue reduced the security of Bitcoin wallets.
<dependency>
<groupId>group id name</groupId>
<artifactId>artifact name</artifactId>
<version>version number</version>
<scope>system</scope>
<systemPath>jar location</systemPath>
</dependency>
Your code is correct. I tested:
r = requests.get("http://www.google.com")
print(r.content)
And it returned plenty of content. Check the url, try "http://www.google.com". Cheers!
var icon1 = "imageA.png";
var icon2 = "imageB.png";
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: icon1,
title: "some marker"
});
google.maps.event.addListener(marker, 'mouseover', function() {
marker.setIcon(icon2);
});
google.maps.event.addListener(marker, 'mouseout', function() {
marker.setIcon(icon1);
});
Simply:
// Default export (recommended)
export {default} from './MyClass'
// Default export with alias
export {default as d1} from './MyClass'
// In >ES7, it could be
export * from './MyClass'
// In >ES7, with alias
export * as d1 from './MyClass'
Or by functions names :
// export by function names
export { funcName1, funcName2, …} from './MyClass'
// export by aliases
export { funcName1 as f1, funcName2 as f2, …} from './MyClass'
More infos: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export
There is a universal way to get this:
Function FileName() As String
FileName = Mid(Application.Caption, 1, InStrRev(Application.Caption, "-") - 2)
End Function
For the iterative algorithm, however, we have:
int iterativeEGCD(long long n, long long m) {
long long a;
int numberOfIterations = 0;
while ( n != 0 ) {
a = m;
m = n;
n = a % n;
numberOfIterations ++;
}
printf("\nIterative GCD iterated %d times.", numberOfIterations);
return m;
}
With Fibonacci pairs, there is no difference between iterativeEGCD()
and iterativeEGCDForWorstCase()
where the latter looks like the following:
int iterativeEGCDForWorstCase(long long n, long long m) {
long long a;
int numberOfIterations = 0;
while ( n != 0 ) {
a = m;
m = n;
n = a - n;
numberOfIterations ++;
}
printf("\nIterative GCD iterated %d times.", numberOfIterations);
return m;
}
Yes, with Fibonacci Pairs, n = a % n
and n = a - n
, it is exactly the same thing.
We also know that, in an earlier response for the same question, there is a prevailing decreasing factor: factor = m / (n % m)
.
Therefore, to shape the iterative version of the Euclidean GCD in a defined form, we may depict as a "simulator" like this:
void iterativeGCDSimulator(long long x, long long y) {
long long i;
double factor = x / (double)(x % y);
int numberOfIterations = 0;
for ( i = x * y ; i >= 1 ; i = i / factor) {
numberOfIterations ++;
}
printf("\nIterative GCD Simulator iterated %d times.", numberOfIterations);
}
Based on the work (last slide) of Dr. Jauhar Ali, the loop above is logarithmic.
Yes, small Oh because the simulator tells the number of iterations at most. Non Fibonacci pairs would take a lesser number of iterations than Fibonacci, when probed on Euclidean GCD.
I have found simpler solution:
$('#clickToCreate').live('click', function() {
$('#yourDialogId')
.dialog({
title: "Set the title to Create"
})
.dialog('open');
});
$('#clickToEdit').live('click', function() {
$('#yourDialogId')
.dialog({
title: "Set the title To Edit"
})
.dialog('open');
});
Hope that helps!
See this JSFiddle
input[type="text"]_x000D_
{_x000D_
border: 0;_x000D_
border-bottom: 1px solid red;_x000D_
outline: 0;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
</form>
_x000D_
Try using second parameter for json_decode function:
$json = json_decode(file_get_contents($file), true);
curl --head https://www.example.net
I was pointed to this by curl itself; when I issued the command with -X HEAD
, it printed:
Warning: Setting custom HTTP method to HEAD with -X/--request may not work the
Warning: way you want. Consider using -I/--head instead.
Update 2018
While everything written below still holds true, Rails 5.2 now includes active_storage
, which allows stuff like uploading directly to S3 (or other cloud storage services), image transformations, etc. You should check out the rails guide and decide for yourself what fits your needs.
While there are plenty of gems that solve file uploading pretty nicely (see https://www.ruby-toolbox.com/categories/rails_file_uploads for a list), rails has built-in helpers which make it easy to roll your own solution.
Use the file_field
-form helper in your form, and rails handles the uploading for you:
<%= form_for @person do |f| %>
<%= f.file_field :picture %>
<% end %>
You will have access in the controller to the uploaded file as follows:
uploaded_io = params[:person][:picture]
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
end
It depends on the complexity of what you want to achieve, but this is totally sufficient for easy file uploading/downloading tasks. This example is taken from the rails guides, you can go there for further information: http://guides.rubyonrails.org/form_helpers.html#uploading-files
In general, in C++ functions have to be declared before you call them. So sometime before the definition of getSkewNormal()
, the compiler needs to see the declaration:
double integrate (double start, double stop, int numSteps, Evaluatable evalObj);
Mostly what people do is put all the declarations (only) in the header file, and put the actual code -- the definitions of the functions and methods -- into a separate source (*.cc
or *.cpp
) file. This neatly solves the problem of needing all the functions to be declared.
If you ever wondered how to do it using the new BDD style of Mockito:
willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));
And for future reference one may need to throw exception and then do nothing:
willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));
In angular 1.4 +, in addition to adding the dependency
angular.module('myApp', ['ngRoute'])
,we also need to reference the separate angular-route.js file
<script src="angular.js">
<script src="angular-route.js">
Since Java 7
File file = Paths.get(url.toURI()).toFile();
std::string::compare() returns an int
:
s
and t
are equal,s
is less than t
,s
is greater than t
.If you want your first code snippet to be equivalent to the second one, it should actually read:
if (!s.compare(t)) {
// 's' and 't' are equal.
}
The equality operator only tests for equality (hence its name) and returns a bool
.
To elaborate on the use cases, compare()
can be useful if you're interested in how the two strings relate to one another (less or greater) when they happen to be different. PlasmaHH rightfully mentions trees, and it could also be, say, a string insertion algorithm that aims to keep the container sorted, a dichotomic search algorithm for the aforementioned container, and so on.
EDIT: As Steve Jessop points out in the comments, compare()
is most useful for quick sort and binary search algorithms. Natural sorts and dichotomic searches can be implemented with only std::less.
Just give a try using subset
nrow(subset(data,condition))
Example
nrow(subset(myData,sCode == "CA"))
As noticed in comments start with sent_tokenize(), because word_tokenize() works only on a single sentence. You can filter out punctuation with filter(). And if you have an unicode strings make sure that is a unicode object (not a 'str' encoded with some encoding like 'utf-8').
from nltk.tokenize import word_tokenize, sent_tokenize
text = '''It is a blue, small, and extraordinary ball. Like no other'''
tokens = [word for sent in sent_tokenize(text) for word in word_tokenize(sent)]
print filter(lambda word: word not in ',-', tokens)
You can use str.contains
alone with a regex pattern using OR (|)
:
s[s.str.contains('og|at')]
Or you could add the series to a dataframe
then use str.contains
:
df = pd.DataFrame(s)
df[s.str.contains('og|at')]
Output:
0 cat
1 hat
2 dog
3 fog
There is no -r option on HP and Sun servers, this way worked for me on my HP server
find . -name "*.c" | xargs grep -i "my great text"
-i is for case insensitive search of string
You can also use -S
, -D
or -P
which are equivalent of saving the package to an app dependency, a dev dependency or prod dependency. See more NPM shortcuts below:
-v: --version
-h, -?, --help, -H: --usage
-s, --silent: --loglevel silent
-q, --quiet: --loglevel warn
-d: --loglevel info
-dd, --verbose: --loglevel verbose
-ddd: --loglevel silly
-g: --global
-C: --prefix
-l: --long
-m: --message
-p, --porcelain: --parseable
-reg: --registry
-f: --force
-desc: --description
-S: --save
-P: --save-prod
-D: --save-dev
-O: --save-optional
-B: --save-bundle
-E: --save-exact
-y: --yes
-n: --yes false
ll and la commands: ls --long
This list of shortcuts can be obtained by running the following command:
$ npm help 7 config
This is slighly more OS independent way:
# do this init somewhere
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
font = pygame.font.Font(pygame.font.get_default_font(), 36)
# now print the text
text_surface = font.render('Hello world', antialias=True, color=(0, 0, 0))
screen.blit(text_surface, dest=(0,0))
The difference between
import java.util.*;
and
import java.util.*;
import java.util.List;
import java.util.Arrays;
becomes apparent when the code refers to some other List
or Arrays
(for example, in the same package, or also imported generally). In the first case, the compiler will assume that the Arrays
declared in the same package is the one to use, in the latter, since it is declared specifically, the more specific java.util.Arrays
will be used.
def func(a, b, c, d):
return a + b * c % d
map(lambda x: func(*x), [[1,2,3,4], [5,6,7,8]])
By wrapping the function call with a lambda and using the star unpack, you can do map with arbitrary number of arguments.
With the background-size property in those browsers which support this very new feature of CSS.
This can also happen when trying to throw an ArgumentException
where you inadvertently call the ArgumentException
constructor overload
public static void Dostuff(Foo bar)
{
// this works
throw new ArgumentException(String.Format("Could not find {0}", bar.SomeStringProperty));
//this gives the error
throw new ArgumentException(String.Format("Could not find {0}"), bar.SomeStringProperty);
}
Here is some pseudo-code to retrieve the following:
Example code:
Include the library dependency: Advapi32.lib
HKEY hKey;
LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &hKey);
bool bExistsAndSuccess (lRes == ERROR_SUCCESS);
bool bDoesNotExistsSpecifically (lRes == ERROR_FILE_NOT_FOUND);
std::wstring strValueOfBinDir;
std::wstring strKeyDefaultValue;
GetStringRegKey(hKey, L"BinDir", strValueOfBinDir, L"bad");
GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad");
LONG GetDWORDRegKey(HKEY hKey, const std::wstring &strValueName, DWORD &nValue, DWORD nDefaultValue)
{
nValue = nDefaultValue;
DWORD dwBufferSize(sizeof(DWORD));
DWORD nResult(0);
LONG nError = ::RegQueryValueExW(hKey,
strValueName.c_str(),
0,
NULL,
reinterpret_cast<LPBYTE>(&nResult),
&dwBufferSize);
if (ERROR_SUCCESS == nError)
{
nValue = nResult;
}
return nError;
}
LONG GetBoolRegKey(HKEY hKey, const std::wstring &strValueName, bool &bValue, bool bDefaultValue)
{
DWORD nDefValue((bDefaultValue) ? 1 : 0);
DWORD nResult(nDefValue);
LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue);
if (ERROR_SUCCESS == nError)
{
bValue = (nResult != 0) ? true : false;
}
return nError;
}
LONG GetStringRegKey(HKEY hKey, const std::wstring &strValueName, std::wstring &strValue, const std::wstring &strDefaultValue)
{
strValue = strDefaultValue;
WCHAR szBuffer[512];
DWORD dwBufferSize = sizeof(szBuffer);
ULONG nError;
nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize);
if (ERROR_SUCCESS == nError)
{
strValue = szBuffer;
}
return nError;
}
With get()
method you get a collection (all data that match the query), try to use first()
instead, it return only one element, like this:
$about = Page::where('page', 'about-me')->first();
Bitwise exclusive-or is already built-in to Python, in the operator
module (which is identical to the ^
operator):
from operator import xor
xor(bool(a), bool(b)) # Note: converting to bools is essential
<c:if test="${companies.size() > 0}">
</c:if>
This syntax works only in EL 2.2 or newer (Servlet 3.0 / JSP 2.2 or newer). If you're facing a XML parsing error because you're using JSPX or Facelets instead of JSP, then use gt
instead of >
.
<c:if test="${companies.size() gt 0}">
</c:if>
If you're actually facing an EL parsing error, then you're probably using a too old EL version. You'll need JSTL fn:length()
function then. From the documentation:
length( java.lang.Object) - Returns the number of items in a collection, or the number of characters in a string.
Put this at the top of JSP page to allow the fn
namespace:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Or if you're using JSPX or Facelets:
<... xmlns:fn="http://java.sun.com/jsp/jstl/functions">
And use like this in your page:
<p>The length of the companies collection is: ${fn:length(companies)}</p>
So to test with length of a collection:
<c:if test="${fn:length(companies) gt 0}">
</c:if>
Alternatively, for this specific case you can also simply use the EL empty
operator:
<c:if test="${not empty companies}">
</c:if>
If Len(Dir(ThisWorkbook.Path & "\YOUR_DIRECTORY", vbDirectory)) = 0 Then
MkDir ThisWorkbook.Path & "\YOUR_DIRECTORY"
End If
@Mock
is used to declare/mock the references of the dependent beans, while @InjectMocks
is used to mock the bean for which test is being created.
For example:
public class A{
public class B b;
public void doSomething(){
}
}
test for class A
:
public class TestClassA{
@Mocks
public class B b;
@InjectMocks
public class A a;
@Test
public testDoSomething(){
}
}
You can simply use jQuery’s delay() method to set the delay time interval.
HTML code:
<div class="box"></div>
JQuery code:
$(document).ready(function(){
$(".show-box").click(function(){
$(this).text('loading...').delay(1000).queue(function() {
$(this).hide();
showBox();
$(this).dequeue();
});
});
});
You can see an example here: How to Call a Function After Some Time in jQuery
If you want control over the duration and style of the animation, you can do:
[UIView animateWithDuration:2.0f delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
scrollView.contentOffset = CGPointMake(x, y);
} completion:NULL];
Adjust the duration (2.0f
) and options (UIViewAnimationOptionCurveLinear
) to taste!
Just for completeness, you can also use ORA_DATABASE_NAME.
It might be worth noting that not all of the methods give you the same output:
SQL> select sys_context('userenv','db_name') from dual;
SYS_CONTEXT('USERENV','DB_NAME')
--------------------------------------------------------------------------------
orcl
SQL> select ora_database_name from dual;
ORA_DATABASE_NAME
--------------------------------------------------------------------------------
ORCL.XYZ.COM
SQL> select * from global_name;
GLOBAL_NAME
--------------------------------------------------------------------------------
ORCL.XYZ.COM
select *
into existing table database..existingtable
from database..othertables....
If you have used select * into tablename from other tablenames
already, next time, to append, you say select * into existing table tablename from other tablenames
Just use substring: "apple".substring(3);
will return le
If the "Customer don't want to install and buy MS Office on a server not at any price", then you cannot use Excel ... But I cannot get the trick: it's all about one basic Office licence which costs something like 150 USD ... And I guess that spending time finding an alternative will cost by far more than this amount!
just use jQuery bind method !jquery-selector!.bind('event', !fn!);
From docs TWIG docs:
Unlike in PHP, it's not possible to break or continue in a loop.
But still:
You can however filter the sequence during iteration which allows you to skip items.
Example 1 (for huge lists you can filter posts using slice, slice(start, length)
):
{% for post in posts|slice(0,10) %}
<h2>{{ post.heading }}</h2>
{% endfor %}
Example 2:
{% for post in posts if post.id < 10 %}
<h2>{{ post.heading }}</h2>
{% endfor %}
You can even use own TWIG filters for more complexed conditions, like:
{% for post in posts|onlySuperPosts %}
<h2>{{ post.heading }}</h2>
{% endfor %}
Use the object tag:
<object data="http://iamawesome.com" type="text/html" width="200" height="200">
<a href="http://iamawesome.com">access the page directly</a>
</object>
Ref: http://debug.ga/embedding-external-pages-without-iframes/
I too got this same error on my image handler that I wrote. I got it like 30 times a day on site with heavy traffic, managed to reproduce it also. You get this when a user cancels the request (closes the page or his internet connection is interrupted for example), in my case in the following row:
myContext.Response.OutputStream.Write(buffer, 0, bytesRead);
I can’t think of any way to prevent it but maybe you can properly handle this. Ex:
try
{
…
myContext.Response.OutputStream.Write(buffer, 0, bytesRead);
…
}catch (HttpException ex)
{
if (ex.Message.StartsWith("The remote host closed the connection."))
;//do nothing
else
//handle other errors
}
catch (Exception e)
{
//handle other errors
}
finally
{//close streams etc..
}
I had a similar problem where CREATE FULLTEXT
timed out after 30 seconds:
Setting DBMS connection read timeout interval to 0 under Edit -> Preferences -> SQL Editor fixed the issue for me:
Also, I did not have to restart mysql workbench for this to work.
To Remove Special character
String t2 = "!@#$%^&*()-';,./?><+abdd";
t2 = t2.replaceAll("\\W+","");
Output will be : abdd.
This works perfectly.
Jest has a method, toThrow(error)
, to test that a function throws when it is called.
So, in your case you should call it so:
expect(t).toThrowError(TypeError);
Create your xml in drawable, layout_background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="@color/your_colour" />
<stroke
android:width="2dp"
android:color="@color/your_colour" />
<corners android:radius="10dp" />
</shape>
<--width, color, radius should be as per your requirement-->
and then, add this in your layout.xml
android:background="@drawable/layout_background"
This is for future developers, you can also try this. Simple too
echo preg_replace('/\D/', '', '604-619-5135');
You can try following code:
foreach ($arry as $key => $value)
{
echo $key;
foreach ($value as $val)
{
echo $val;
}
}
res = request.GET['paymentid']
will raise a KeyError
if paymentid
is not in the GET data.
Your sample php code checks to see if paymentid
is in the POST data, and sets $payID
to '' otherwise:
$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''
The equivalent in python is to use the get()
method with a default argument:
payment_id = request.POST.get('payment_id', '')
while debugging, this is what I see in the
response.GET: <QueryDict: {}>
,request.POST: <QueryDict: {}>
It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.
Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.
I had this error for some time and found a fix. This fix is for Asp.net application, Strange it failed only in IE non compatibility mode, but works in Firefox and Crome. Giving access to the webservice service folder for all/specific users solved the issue.
Add the following code in web.config file:
<location path="YourWebserviceFolder">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
You need to use lookahead as some of the other responders have said, but the lookahead has to account for other characters between its target word and the current match position. For example:
(?=.*word1)(?=.*word2)(?=.*word3)
The .*
in the first lookahead lets it match however many characters it needs to before it gets to "word1". Then the match position is reset and the second lookahead seeks out "word2". Reset again, and the final part matches "word3"; since it's the last word you're checking for, it isn't necessary that it be in a lookahead, but it doesn't hurt.
In order to match a whole paragraph, you need to anchor the regex at both ends and add a final .*
to consume the remaining characters. Using Perl-style notation, that would be:
/^(?=.*word1)(?=.*word2)(?=.*word3).*$/m
The 'm' modifier is for multline mode; it lets the ^
and $
match at paragraph boundaries ("line boundaries" in regex-speak). It's essential in this case that you not use the 's' modifier, which lets the dot metacharacter match newlines as well as all other characters.
Finally, you want to make sure you're matching whole words and not just fragments of longer words, so you need to add word boundaries:
/^(?=.*\bword1\b)(?=.*\bword2\b)(?=.*\bword3\b).*$/m
Google Apps Script is JavaScript, the date object is initiated with new Date()
and all JavaScript methods apply, see doc here
This is for longs, but you can modify it easily to work with ints.
private static long[] ConvertStringArrayToLongArray(string str)
{
return str.Split(",".ToCharArray()).Select(x => long.Parse(x.ToString())).ToArray();
}