Modern IPython uses the "--matplotlib
" argument with an optional backend parameter. It defaults to "auto", which is usually good enough on Mac and Windows. I haven't tested it on Ubuntu or any other Linux distribution, but I would expect it to work.
ipython --matplotlib
Selected date at the example is interesting. Example code block is:
Calendar c1 = GregorianCalendar.getInstance();
c1.set(2000, 1, 30); //January 30th 2000
Date sDate = c1.getTime();
System.out.println(sDate);
and output Wed Mar 01 19:32:21 JST 2000
.
When I first read the example i think that output is wrong but it is true:)
Calendar.Month
is starting from 0 so 1 means February.Wrap your AND logic in parenthesis, like this:
mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo' OR date='$Date_FiveDaysAgo' OR date='$Date_SixDaysAgo' OR date='$Date_SevenDaysAgo')");
The best solution is the attribute selector in CSS (input[type="text"]
) as the others suggested.
But if you have to support Internet Explorer 6, you cannot use it (QuirksMode). Well, only if you have to and also are willing to support it.
In this case your only option seems to be to define classes on input elements.
<input type="text" class="input-box" ... />
<input type="submit" class="button" ... />
...
and target them with a class selector:
input.input-box, textarea { background: cyan; }
USE BINARY
This is a simple select
SELECT * FROM myTable WHERE 'something' = 'Something'
= 1
This is a select with binary
SELECT * FROM myTable WHERE BINARY 'something' = 'Something'
or
SELECT * FROM myTable WHERE 'something' = BINARY 'Something'
= 0
You can use the requests library, it simplifies things a lot in comparison to taking the urllib2 approach. First install it from pip:
pip install requests
More on installing requests.
Then setup the put request:
import requests
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
# Create your header as required
headers = {"content-type": "application/json", "Authorization": "<auth-key>" }
r = requests.put(url, data=json.dumps(payload), headers=headers)
See the quickstart for requests library. I think this is a lot simpler than urllib2 but does require this additional package to be installed and imported.
If you trust the data source, you can use eval
to convert your string into a dictionary:
eval(your_json_format_string)
Example:
>>> x = "{'a' : 1, 'b' : True, 'c' : 'C'}"
>>> y = eval(x)
>>> print x
{'a' : 1, 'b' : True, 'c' : 'C'}
>>> print y
{'a': 1, 'c': 'C', 'b': True}
>>> print type(x), type(y)
<type 'str'> <type 'dict'>
>>> print y['a'], type(y['a'])
1 <type 'int'>
>>> print y['a'], type(y['b'])
1 <type 'bool'>
>>> print y['a'], type(y['c'])
1 <type 'str'>
This seems to work for me.
def make_Ramp( ramp_colors ):
from colour import Color
from matplotlib.colors import LinearSegmentedColormap
color_ramp = LinearSegmentedColormap.from_list( 'my_list', [ Color( c1 ).rgb for c1 in ramp_colors ] )
plt.figure( figsize = (15,3))
plt.imshow( [list(np.arange(0, len( ramp_colors ) , 0.1)) ] , interpolation='nearest', origin='lower', cmap= color_ramp )
plt.xticks([])
plt.yticks([])
return color_ramp
custom_ramp = make_Ramp( ['#754a28','#893584','#68ad45','#0080a5' ] )
Perhaps another way to code conditional constructs in XML:
<rule>
<if>
<conditions>
<condition var="something" operator=">">400</condition>
<!-- more conditions possible -->
</conditions>
<statements>
<!-- do something -->
</statements>
</if>
<elseif>
<conditions></conditions>
<statements></statements>
</elseif>
<else>
<statements></statements>
</else>
</rule>
If df
is a pandas.DataFrame
then df['new_col']= Series list_object of length len(df)
will add the or Series list_object as a column named 'new_col'
. df['new_col']= scalar
(such as 5 or 6 in your case) also works and is equivalent to df['new_col']= [scalar]*len(df)
So a two-line code serves the purpose:
df = pd.DataFrame({'a':[1, 2], 'b':[3, 4]})
s = pd.Series({'s1':5, 's2':6})
for x in s.index:
df[x] = s[x]
Output:
a b s1 s2
0 1 3 5 6
1 2 4 5 6
For such a simple XML structure, you may not want to involve a full blown XML module. Consider a string template for the simplest structures, or Jinja for something a little more complex. Jinja can handle looping over a list of data to produce the inner xml of your document list. That is a bit trickier with raw python string templates
For a Jinja example, see my answer to a similar question.
Here is an example of generating your xml with string templates.
import string
from xml.sax.saxutils import escape
inner_template = string.Template(' <field${id} name="${name}">${value}</field${id}>')
outer_template = string.Template("""<root>
<doc>
${document_list}
</doc>
</root>
""")
data = [
(1, 'foo', 'The value for the foo document'),
(2, 'bar', 'The <value> for the <bar> document'),
]
inner_contents = [inner_template.substitute(id=id, name=name, value=escape(value)) for (id, name, value) in data]
result = outer_template.substitute(document_list='\n'.join(inner_contents))
print result
Output:
<root>
<doc>
<field1 name="foo">The value for the foo document</field1>
<field2 name="bar">The <value> for the <bar> document</field2>
</doc>
</root>
The downer of the template approach is that you won't get escaping of <
and >
for free. I danced around that problem by pulling in a util from xml.sax
See code example below:
SimpleDateFormat df = new SimpleDateFormat("hh:mm");
String formattedDate = df.format(new Date());
out.println(formattedDate);
Since swift 3.0 there is more convenient way: #imageLiterals here is text example. And below animated example from here:
ES6 Generator version
function* chunkArray(array,size=1){
var clone = array.slice(0);
while (clone.length>0)
yield clone.splice(0,size);
};
var a = new Array(100).fill().map((x,index)=>index);
for(const c of chunkArray(a,10))
console.log(c);
Basically, you should include the class' header file in the code where you want to use the class in the shared library. Then, when you link, use the '-l' flag to link your code with the shared library. Of course, this requires the .so to be where the OS can find it. See 3.5. Installing and Using a Shared Library
Using dlsym is for when you don't know at compile time which library you want to use. That doesn't sound like it's the case here. Maybe the confusion is that Windows calls the dynamically loaded libraries whether you do the linking at compile or run-time (with analogous methods)? If so, then you can think of dlsym as the equivalent of LoadLibrary.
If you really do need to dynamically load the libraries (i.e., they're plug-ins), then this FAQ should help.
Go to Tools
-> Java Platforms
. There, click on Add Platform, point it to C:\Program Files (x86)\Java\jdk1.6.0_25
. You can either set the another JDK version or remove existing versions.
Another solution suggested in the oracle (sun) site is,
netbeans.exe --jdkhome "C:\Program Files\jdk1.6.0_20"
I tried this on 6.9.1. You may change the JDK per project as well. You need to set the available JDKs via Java Platforms
dialog. Then, go to Run
-> Set Project Configuration
-> Customize
.
After that, in the opened Dialog box go to Build
-> Compile
. Set the version.
I had the same need using argparse
too.
The thing is parse_args
function of an argparse.ArgumentParser
object instance implicitly takes its arguments by default from sys.args
. The work around, following Martijn line, consists of making that explicit, so you can change the arguments you pass to parse_args
as desire.
def main(args):
# some stuff
parser = argparse.ArgumentParser()
# some other stuff
parsed_args = parser.parse_args(args)
# more stuff with the args
if __name__ == '__main__':
import sys
main(sys.argv[1:])
The key point is passing args to parse_args
function.
Later, to use the main, you just do as Martijn tell.
From the documentation:
Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called
static
in your package or next to your module and it will be available at/static
on the application.To generate URLs for static files, use the special
'static'
endpoint name:url_for('static', filename='style.css')
The file has to be stored on the filesystem as
static/style.css
.
One way to achieve it is to wrap your input in <form>
tag and reset it.
I'm not considering attaching thr form to NgForm
or FormControl
either.
@Component({
selector: 'form-component',
template: `
<form #form>
<input type="file" placeholder="File Name" name="filename">
</form>
<button (click)="reset()">Reset</button>
`
})
class FormComponent {
@ViewChild('form') form;
reset() {
this.form.nativeElement.reset()
}
}
Works, just figured this out a week ago, and just now got to testing it.
double theta = Math.atan2(cir.getX()-sqr.getX()*1.0,
cir.getY()-sqr.getY()*1.0); //radians of the angle
double dBox; //distance from box to edge of box in direction of the circle
if((theta > Math.PI/4 && theta < 3*Math.PI / 4) ||
(theta < -Math.PI/4 && theta > -3*Math.PI / 4)) {
dBox = sqr.getS() / (2*Math.sin(theta));
} else {
dBox = sqr.getS() / (2*Math.cos(theta));
}
boolean touching = (Math.abs(dBox) >=
Math.sqrt(Math.pow(sqr.getX()-cir.getX(), 2) +
Math.pow(sqr.getY()-cir.getY(), 2)));
You have missed typescript installation, just run below command and then try tsc --init
npm install -g typescript
Yes you can. You can even test it:
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
console.log(++i);_x000D_
if (i === 5) clearInterval(timer);_x000D_
console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
In this example, this timer clears when i
reaches 5.
This is how I finally did it! You can put a layer (full sized) over your body with high z-index and, of course hidden. You will make it visible when the window is open, make it focused on click over parent window (the layer), and finally will disappear it when the opened window is closed or submitted or whatever.
.layer
{
position: fixed;
opacity: 0.7;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 999999;
background-color: #BEBEBE;
display: none;
cursor: not-allowed;
}
and layer in the body:
<div class="layout" id="layout"></div>
function that opens the popup window:
var new_window;
function winOpen(){
$(".layer").show();
new_window=window.open(srcurl,'','height=750,width=700,left=300,top=200');
}
keeping new window focused:
$(document).ready(function(){
$(".layout").click(function(e) {
new_window.focus();
}
});
and in the opened window:
function submit(){
var doc = window.opener.document,
doc.getElementById("layer").style.display="none";
window.close();
}
window.onbeforeunload = function(){
var doc = window.opener.document;
doc.getElementById("layout").style.display="none";
}
I hope it would help :-)
Here's a solution with flexbox
for images with variable width and height:
.container {
display: flex;
flex-wrap: no-wrap;
overflow-x: auto;
margin: 20px;
}
img {
flex: 0 0 auto;
width: auto;
height: 100px;
max-width: 100%;
margin-right: 10px;
}
Example: JsFiddle
You can use xdpyinfo
(can be installed via apt-get install x11-utils
).
Simple and effective approach is models.py
from django.contrib.auth.models import User
class CustomUser(User):
profile_pic = models.ImageField(upload_to='...')
other_field = models.CharField()
Is the result of getElementsByClassName an Array?
No
If not, what is it?
As with all DOM methods that return multiple elements, it is a NodeList, see https://developer.mozilla.org/en/DOM/document.getElementsByClassName
The good option is to use AdminClient as below before starting to produce or consume the messages
private static final int ADMIN_CLIENT_TIMEOUT_MS = 5000;
try (AdminClient client = AdminClient.create(properties)) {
client.listTopics(new ListTopicsOptions().timeoutMs(ADMIN_CLIENT_TIMEOUT_MS)).listings().get();
} catch (ExecutionException ex) {
LOG.error("Kafka is not available, timed out after {} ms", ADMIN_CLIENT_TIMEOUT_MS);
return;
}
There are a lot of very nice answers on this page and I googled for some more, but none of the answers ticked all the checkboxes on my wish list:
So I mixed the code of several examples, fixed the things that I needed and here is the result:
I used the following CSS and HTML:
/* Progress Tracker v2 */_x000D_
ol.progress[data-steps="2"] li { width: 49%; }_x000D_
ol.progress[data-steps="3"] li { width: 33%; }_x000D_
ol.progress[data-steps="4"] li { width: 24%; }_x000D_
ol.progress[data-steps="5"] li { width: 19%; }_x000D_
ol.progress[data-steps="6"] li { width: 16%; }_x000D_
ol.progress[data-steps="7"] li { width: 14%; }_x000D_
ol.progress[data-steps="8"] li { width: 12%; }_x000D_
ol.progress[data-steps="9"] li { width: 11%; }_x000D_
_x000D_
.progress {_x000D_
width: 100%;_x000D_
list-style: none;_x000D_
list-style-image: none;_x000D_
margin: 20px 0 20px 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.progress li {_x000D_
float: left;_x000D_
text-align: center;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.progress .name {_x000D_
display: block;_x000D_
vertical-align: bottom;_x000D_
text-align: center;_x000D_
margin-bottom: 1em;_x000D_
color: black;_x000D_
opacity: 0.3;_x000D_
}_x000D_
_x000D_
.progress .step {_x000D_
color: black;_x000D_
border: 3px solid silver;_x000D_
background-color: silver;_x000D_
border-radius: 50%;_x000D_
line-height: 1.2;_x000D_
width: 1.2em;_x000D_
height: 1.2em;_x000D_
display: inline-block;_x000D_
z-index: 0;_x000D_
}_x000D_
_x000D_
.progress .step span {_x000D_
opacity: 0.3;_x000D_
}_x000D_
_x000D_
.progress .active .name,_x000D_
.progress .active .step span {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
.progress .step:before {_x000D_
content: "";_x000D_
display: block;_x000D_
background-color: silver;_x000D_
height: 0.4em;_x000D_
width: 50%;_x000D_
position: absolute;_x000D_
bottom: 0.6em;_x000D_
left: 0;_x000D_
z-index: -1;_x000D_
}_x000D_
_x000D_
.progress .step:after {_x000D_
content: "";_x000D_
display: block;_x000D_
background-color: silver;_x000D_
height: 0.4em;_x000D_
width: 50%;_x000D_
position: absolute;_x000D_
bottom: 0.6em;_x000D_
right: 0;_x000D_
z-index: -1;_x000D_
}_x000D_
_x000D_
.progress li:first-of-type .step:before {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.progress li:last-of-type .step:after {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.progress .done .step,_x000D_
.progress .done .step:before,_x000D_
.progress .done .step:after,_x000D_
.progress .active .step,_x000D_
.progress .active .step:before {_x000D_
background-color: yellowgreen;_x000D_
}_x000D_
_x000D_
.progress .done .step,_x000D_
.progress .active .step {_x000D_
border: 3px solid yellowgreen;_x000D_
}
_x000D_
<!-- Progress Tracker v2 -->_x000D_
<ol class="progress" data-steps="4">_x000D_
<li class="done">_x000D_
<span class="name">Foo</span>_x000D_
<span class="step"><span>1</span></span>_x000D_
</li>_x000D_
<li class="done">_x000D_
<span class="name">Bar</span>_x000D_
<span class="step"><span>2</span></span>_x000D_
</li>_x000D_
<li class="active">_x000D_
<span class="name">Baz</span>_x000D_
<span class="step"><span>3</span></span>_x000D_
</li>_x000D_
<li>_x000D_
<span class="name">Quux</span>_x000D_
<span class="step"><span>4</span></span>_x000D_
</li>_x000D_
</ol>
_x000D_
As can be seen in the example above, there are now two list item classes to take note of: active
and done
. Use class="active"
for the current step, use class="done"
for all steps before it.
Also note the data-steps="4"
in the ol
tag; set this to the total number of steps to apply the correct size to all list items.
Feel free to play around with the JSFiddle. Enjoy!
I found xip.io which automatically converts a fixed url to a embedded localhost domain.
For example lets say your localhost server is running on 127.0.0.1:8000
You can go to http://www.127.0.0.1.xip.io:5555/
to access this server.
You can then add this address to Oauth configuration for Facebook or Google.
Many sites use AJAX/XHR/fetch to add, show, modify content dynamically and window.history API instead of in-site navigation so current URL is changed programmatically. Such sites are called SPA, short for Single Page Application.
MutationObserver (docs) to literally detect DOM changes:
Performance of MutationObserver to detect nodes in entire DOM.
Simple example:
let lastUrl = location.href;
new MutationObserver(() => {
const url = location.href;
if (url !== lastUrl) {
lastUrl = url;
onUrlChange();
}
}).observe(document, {subtree: true, childList: true});
function onUrlChange() {
console.log('URL changed!', location.href);
}
Event listener for sites that signal content change by sending a DOM event:
pjax:end
on document
used by many pjax-based sites e.g. GitHub,message
on window
used by e.g. Google search in Chrome browser,yt-navigate-finish
used by Youtube,Periodic checking of DOM via setInterval:
Obviously this will work only in cases when you wait for a specific element identified by its id/selector to appear, and it won't let you universally detect new dynamically added content unless you invent some kind of fingerprinting the existing contents.
Cloaking History API:
let _pushState = History.prototype.pushState;
History.prototype.pushState = function (state, title, url) {
_pushState.call(this, state, title, url);
console.log('URL changed', url)
};
Listening to hashchange, popstate events:
window.addEventListener('hashchange', e => {
console.log('URL hash changed', e);
doSomething();
});
window.addEventListener('popstate', e => {
console.log('State changed', e);
doSomething();
});
All above-mentioned methods can be used in a content script. Note that content scripts aren't automatically executed by the browser in case of programmatic navigation via window.history in the web page because only the URL was changed but the page itself remained the same (the content scripts run automatically only once in page lifetime).
Now let's look at the background script.
There are advanced API to work with navigation: webNavigation, webRequest, but we'll use simple chrome.tabs.onUpdated event listener that sends a message to the content script:
manifest.json:
declare background/event page
declare content script
add "tabs"
permission.
background.js
var rxLookfor = /^https?:\/\/(www\.)?google\.(com|\w\w(\.\w\w)?)\/.*?[?#&]q=/;
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (rxLookfor.test(changeInfo.url)) {
chrome.tabs.sendMessage(tabId, 'url-update');
}
});
content.js
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg === 'url-update') {
// doSomething();
}
});
As per the documentation on the return
statement, return
may only occur syntactically nested in a function definition. The same is true for yield
.
The compiler cannot guess what should be passed for the base constructor argument. You have to do it explicitly:
public class child : parent {
public child(int i) : base(i) {
Console.WriteLine("child");
}
}
I tried to write a procedure doing that, based on @PhilHibbs codes, on a different way. Please have a look and test.
CREATE OR REPLACE FUNCTION dump(IN p_schema text, IN p_table text, IN p_where text)
RETURNS setof text AS
$BODY$
DECLARE
dumpquery_0 text;
dumpquery_1 text;
selquery text;
selvalue text;
valrec record;
colrec record;
BEGIN
-- ------ --
-- GLOBAL --
-- build base INSERT
-- build SELECT array[ ... ]
dumpquery_0 := 'INSERT INTO ' || quote_ident(p_schema) || '.' || quote_ident(p_table) || '(';
selquery := 'SELECT array[';
<<label0>>
FOR colrec IN SELECT table_schema, table_name, column_name, data_type
FROM information_schema.columns
WHERE table_name = p_table and table_schema = p_schema
ORDER BY ordinal_position
LOOP
dumpquery_0 := dumpquery_0 || quote_ident(colrec.column_name) || ',';
selquery := selquery || 'CAST(' || quote_ident(colrec.column_name) || ' AS TEXT),';
END LOOP label0;
dumpquery_0 := substring(dumpquery_0 ,1,length(dumpquery_0)-1) || ')';
dumpquery_0 := dumpquery_0 || ' VALUES (';
selquery := substring(selquery ,1,length(selquery)-1) || '] AS MYARRAY';
selquery := selquery || ' FROM ' ||quote_ident(p_schema)||'.'||quote_ident(p_table);
selquery := selquery || ' WHERE '||p_where;
-- GLOBAL --
-- ------ --
-- ----------- --
-- SELECT LOOP --
-- execute SELECT built and loop on each row
<<label1>>
FOR valrec IN EXECUTE selquery
LOOP
dumpquery_1 := '';
IF not found THEN
EXIT ;
END IF;
-- ----------- --
-- LOOP ARRAY (EACH FIELDS) --
<<label2>>
FOREACH selvalue in ARRAY valrec.MYARRAY
LOOP
IF selvalue IS NULL
THEN selvalue := 'NULL';
ELSE selvalue := quote_literal(selvalue);
END IF;
dumpquery_1 := dumpquery_1 || selvalue || ',';
END LOOP label2;
dumpquery_1 := substring(dumpquery_1 ,1,length(dumpquery_1)-1) || ');';
-- LOOP ARRAY (EACH FIELD) --
-- ----------- --
-- debug: RETURN NEXT dumpquery_0 || dumpquery_1 || ' --' || selquery;
-- debug: RETURN NEXT selquery;
RETURN NEXT dumpquery_0 || dumpquery_1;
END LOOP label1 ;
-- SELECT LOOP --
-- ----------- --
RETURN ;
END
$BODY$
LANGUAGE plpgsql VOLATILE;
And then :
-- for a range
SELECT dump('public', 'my_table','my_id between 123456 and 123459');
-- for the entire table
SELECT dump('public', 'my_table','true');
tested on my postgres 9.1, with a table with mixed field datatype (text, double, int,timestamp without time zone, etc).
That's why the CAST in TEXT type is needed. My test run correctly for about 9M lines, looks like it fail just before 18 minutes of running.
ps : I found an equivalent for mysql on the WEB.
I had the error after trying to select a subset of rows:
df = df.reindex(index=my_index)
Turns out that my_index
contained values that were not contained in df.index
, so the reindex function inserted some new rows and filled them with nan
.
Open Notepad.
Type the following lines into it (obviously replace the folders with your ones)
@echo off
rem you could also remove the line above, because it might help you to see what happens
rem /i option is needed to avoid the batch file asking you whether destination folder is a file or a folder
rem /e option is needed to copy also all folders and subfolders
xcopy "c:\New Folder" "c:\Copy of New Folder" /i /e
Save the file as backup.bat (not .txt)
Double click on the file to run it. It will backup the folder and all its contents files/subfolders.
Now if you want the batch file to be run everytime you login in Windows, you should place it in Windows Startup menu. You find it under: Start > All Program > Startup To place the batch file in there either drag it into the Startup menu or RIGH click on the Windows START button and select Explore, go in Programs > Startup, and copy the batch file into there.
To run the batch file everytime the folder is updated you need an application, it can not be done with just a batch file.
If you only want to know if an object is a subtype of a given type then there is a simpler approach:
class Shape {}
class Circle : Shape {}
class Rectangle : Shape {}
func area (shape: Shape) -> Double {
if shape is Circle { ... }
else if shape is Rectangle { ... }
}
“Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it is not.” Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.
In the above the phrase 'of a certain subclass type' is important. The use of is Circle
and is Rectangle
is accepted by the compiler because that value shape
is declared as Shape
(a superclass of Circle
and Rectangle
).
If you are using primitive types, the superclass would be Any
. Here is an example:
21> func test (obj:Any) -> String {
22. if obj is Int { return "Int" }
23. else if obj is String { return "String" }
24. else { return "Any" }
25. }
...
30> test (1)
$R16: String = "Int"
31> test ("abc")
$R17: String = "String"
32> test (nil)
$R18: String = "Any"
Angular has several timepoints to start executing functions. If you seek for something like jQuery's
$(document).ready();
You may find this analog in angular to be very useful:
$scope.$watch('$viewContentLoaded', function(){
//do something
});
This one is helpful when you want to manipulate the DOM elements. It will start executing only after all te elements are loaded.
UPD: What is said above works when you want to change css properties. However, sometimes it doesn't work when you want to measure the element properties, such as width, height, etc. In this case you may want to try this:
$scope.$watch('$viewContentLoaded',
function() {
$timeout(function() {
//do something
},0);
});
Don't know others issue, Only this code worked for me.
$('select').val('').select2();
Others have answered your question perfectly, but I just thought I would throw out another way. It's always a good idea to separate HTML markup, CSS styling, and javascript code when possible. The cleanest way to hide something, with that in mind, is using a class. It allows the definition of "hide" to be defined in the CSS where it belongs. Using this method, you could later decide you want the ul
to hide by scrolling up or fading away using CSS transition
, all without changing your HTML or code. This is longer, but I feel it's a better overall solution.
Demo: http://jsfiddle.net/ThinkingStiff/RkQCF/
HTML:
<a id="showTags" href="#" title="Show Tags">Show All Tags</a>
<ul id="subforms" class="subforums hide"><li>one</li><li>two</li><li>three</li></ul>
CSS:
#subforms {
overflow-x: visible;
overflow-y: visible;
}
.hide {
display: none;
}
Script:
document.getElementById( 'showTags' ).addEventListener( 'click', function () {
document.getElementById( 'subforms' ).toggleClass( 'hide' );
}, false );
Element.prototype.toggleClass = function ( className ) {
if( this.className.split( ' ' ).indexOf( className ) == -1 ) {
this.className = ( this.className + ' ' + className ).trim();
} else {
this.className = this.className.replace( new RegExp( '(\\s|^)' + className + '(\\s|$)' ), ' ' ).trim();
};
};
I did the following:
import sys
!{sys.executable} -m pip install sklearn
I strongly recommend BOUML. It's a free UML modelling application, which:
Believe me, there is no better tool. StarUML is a retarded turtle compared to BOUML. ArgoUML simply doesn't work. Dia is a ergonomy^-1 software.
Use DecimalFormat
double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));
For all of those, who still experiencing this problem, I just spent 2 days tracking down the bloody thing. I was getting the same error when there was no rows in dataset. Seems obvious, but error message is very obscure, hence 2 days.
See the Parameter Expansion section in the Bash man
page. A[@]
returns the contents of the array, :1:2
takes a slice of length 2, starting at index 1.
A=( foo bar "a b c" 42 )
B=("${A[@]:1:2}")
C=("${A[@]:1}") # slice to the end of the array
echo "${B[@]}" # bar a b c
echo "${B[1]}" # a b c
echo "${C[@]}" # bar a b c 42
echo "${C[@]: -2:2}" # a b c 42 # The space before the - is necesssary
Note that the fact that "a b c" is one array element (and that it contains an extra space) is preserved.
If you put position:relative;
on the outer element, the inner element will place itself according to this one. Then a width:auto;
on the inner element will be the same as the width of the outer.
You need to load jquery first before bootstrap.
require.config({
paths: {
jquery: 'libs/jquery/jquery',
underscore: 'libs/underscore/underscore',
backbone: 'libs/backbone/backbone',
bootstrap: 'libs/bootstrap',
jquerytablesorter: 'libs/tablesorter/jquery.tablesorter',
tablesorter: 'libs/tablesorter/tables',
ajaxupload: 'libs/ajax-upload',
templates: '../templates'
},
shim: {
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'jquery': {
exports: '$'
},
'bootstrap': {
deps: ['jquery'],
exports: '$'
},
'jquerytablesorter': {
deps: ['jquery'],
exports: '$'
},
'tablesorter': {
deps: ['jquery'],
exports: '$'
},
'ajaxupload': {
deps: ['jquery'],
exports: '$'
},
'underscore': {
exports: '_'
},
}
});
require(['app', ], function(App) {
App.initialize();
});
Works like charm! quick and easy fix.
I know this is an old question but on Windows, this filters the git output to the files and changed line numbers:
(git diff -p --stat) | findstr "@@ --git"
diff --git a/dir1/dir2/file.cpp b/dir1/dir2/file.cpp
@@ -47,6 +47,7 @@ <some function name>
@@ -97,7 +98,7 @@ <another functon name>
To extract the files and the changed lines from that is a bit more work:
for /f "tokens=3,4* delims=-+ " %f in ('^(git diff -p --stat .^) ^| findstr ^"@@ --git^"') do @echo %f
a/dir1/dir2/file.cpp
47,7
98,7
If you are on windows got to control pannel -> windows Credentials then remove github credential from generic credential option. Then try to clone
Similarly using Bash regexp. Shall be able to snatch any key/value pair.
key="Body"
re="\"($key)\": \"([^\"]*)\""
while read -r l; do
if [[ $l =~ $re ]]; then
name="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[2]}"
echo "$name=$value"
else
echo "No match"
fi
done
Regular expression can be tuned to match multiple spaces/tabs or newline(s). Wouldn't work if value has embedded "
. This is an illustration. Better to use some "industrial" parser :)
<input type="text" id="firstname" placeholder="First Name"
Note: You can change the placeholder, id and type value to "email" or whatever suits your need.
More details by W3Schools at:http://www.w3schools.com/tags/att_input_placeholder.asp
But by far the best solutions are by Floern and Vivek Mhatre ( edited by j0k )
I want to initialize every single element of the array to some initial value. So if I have an array Dim myArray(300) As Integer of 300 integers, for example, all 300 elements would hold the same initial value (say, the number 13).
Can anyone explain how to do this, without looping? I'd like to do it in one statement if possible.
What do I win?
Sub SuperTest()
Dim myArray
myArray = Application.Transpose([index(Row(1:300),)-index(Row(1:300),)+13])
End Sub
td:hover{
background-color:red;
color:white;
}
This will work for Linux, for example if you want to check if banshee is running... (banshee is a music player)
import subprocess
def running_process(process):
"check if process is running. < process > is the name of the process."
proc = subprocess.Popen(["if pgrep " + process + " >/dev/null 2>&1; then echo 'True'; else echo 'False'; fi"], stdout=subprocess.PIPE, shell=True)
(Process_Existance, err) = proc.communicate()
return Process_Existance
# use the function
print running_process("banshee")
If you want to enable unblur, you cannot just add the blur CSS to the body, you need to blur each visible child one level directly under the body and then remove the CSS to unblur. The reason is because of the "Cascade" in CSS, you cannot undo the cascading of the CSS blur effect for a child of the body. Also, to blur the body's background image you need to use the pseudo element :before
//HTML
<div id="fullscreen-popup" style="position:absolute;top:50%;left:50%;">
<div class="morph-button morph-button-overlay morph-button-fixed">
<button id="user-interface" type="button">MORE INFO</button>
<!--a id="user-interface" href="javascript:void(0)">popup</a-->
<div class="morph-content">
<div>
<div class="content-style-overlay">
<span class="icon icon-close">Close the overlay</span>
<h2>About Parsley</h2>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
<p>Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</p>
<p>Turnip greens yarrow ricebean rutabaga endive cauliflower sea lettuce kohlrabi amaranth water spinach avocado daikon napa cabbage asparagus winter purslane kale. Celery potato scallion desert raisin horseradish spinach carrot soko. Lotus root water spinach fennel kombu maize bamboo shoot green bean swiss chard seakale pumpkin onion chickpea gram corn pea. Brussels sprout coriander water chestnut gourd swiss chard wakame kohlrabi beetroot carrot watercress. Corn amaranth salsify bunya nuts nori azuki bean chickweed potato bell pepper artichoke.</p>
</div>
</div>
</div>
</div>
</div>
//CSS
/* Blur - doesn't work on IE */
.blur-on, .blur-element {
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-o-filter: blur(10px);
-ms-filter: blur(10px);
filter: blur(10px);
-webkit-transition: all 5s linear;
transition : all 5s linear;
-moz-transition : all 5s linear;
-webkit-transition: all 5s linear;
-o-transition : all 5s linear;
}
.blur-off {
-webkit-filter: blur(0px) !important;
-moz-filter : blur(0px) !important;
-o-filter : blur(0px) !important;
-ms-filter : blur(0px) !important;
filter : blur(0px) !important;
}
.blur-bgimage:before {
content: "";
position: absolute;
height: 20%; width: 20%;
background-size: cover;
background: inherit;
z-index: -1;
transform: scale(5);
transform-origin: top left;
filter: blur(2px);
-moz-transform: scale(5);
-moz-transform-origin: top left;
-moz-filter: blur(2px);
-webkit-transform: scale(5);
-webkit-transform-origin: top left;
-webkit-filter: blur(2px);
-o-transform: scale(5);
-o-transform-origin: top left;
-o-filter: blur(2px);
transition : all 5s linear;
-moz-transition : all 5s linear;
-webkit-transition: all 5s linear;
-o-transition : all 5s linear;
}
//Javascript
function blurBehindPopup() {
if(blurredElements.length == 0) {
for(var i=0; i < document.body.children.length; i++) {
var element = document.body.children[i];
if(element.id && element.id != 'fullscreen-popup' && element.isVisible == true) {
classie.addClass( element, 'blur-element' );
blurredElements.push(element);
}
}
} else {
for(var i=0; i < blurredElements.length; i++) {
classie.addClass( blurredElements[i], 'blur-element' );
}
}
}
function unblurBehindPopup() {
for(var i=0; i < blurredElements.length; i++) {
classie.removeClass( blurredElements[i], 'blur-element' );
}
}
var StopWatch = function (performance) {
this.startTime = 0;
this.stopTime = 0;
this.running = false;
this.performance = performance === false ? false : !!window.performance;
};
StopWatch.prototype.currentTime = function () {
return this.performance ? window.performance.now() : new Date().getTime();
};
StopWatch.prototype.start = function () {
this.startTime = this.currentTime();
this.running = true;
};
StopWatch.prototype.stop = function () {
this.stopTime = this.currentTime();
this.running = false;
};
StopWatch.prototype.getElapsedMilliseconds = function () {
if (this.running) {
this.stopTime = this.currentTime();
}
return this.stopTime - this.startTime;
};
StopWatch.prototype.getElapsedSeconds = function () {
return this.getElapsedMilliseconds() / 1000;
};
StopWatch.prototype.printElapsed = function (name) {
var currentName = name || 'Elapsed:';
console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]');
};
Benchmark
var stopwatch = new StopWatch();
stopwatch.start();
for (var index = 0; index < 100; index++) {
stopwatch.printElapsed('Instance[' + index + ']');
}
stopwatch.stop();
stopwatch.printElapsed();
Output
Instance[0] [0ms] [0s]
Instance[1] [2.999999967869371ms] [0.002999999967869371s]
Instance[2] [2.999999967869371ms] [0.002999999967869371s]
/* ... */
Instance[99] [10.999999998603016ms] [0.010999999998603016s]
Elapsed: [10.999999998603016ms] [0.010999999998603016s]
performance.now() is optional - just pass false into StopWatch constructor function.
First of all, as others mentioned, you will be using the "array_search()" & the "unset()" methodsas shown below:-
<?php
$arrayDummy = array( 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg' );
unset( $arrayDummy[array_search( 'dddd', $arrayDummy )] ); // Index 3 is getting unset here.
print_r( $arrayDummy ); // This will show the indexes as 0, 1, 2, 4, 5, 6.
?>
Now to re-index the same array, without sorting any of the array values, you will need to use the "array_values()" method as shown below:-
<?php
$arrayDummy = array_values( $arrayDummy );
print_r( $arrayDummy ); // Now, you will see the indexes as 0, 1, 2, 3, 4, 5.
?>
Hope it helps.
So this is what I did:
I read the basics about filters here and I figured out that I need to create a custom filter that will be first in the filter chain and will have a try catch to catch all runtime exceptions that might occur there. Then i need to create the json manually and put it in the response.
So here is my custom filter:
public class ExceptionHandlerFilter extends OncePerRequestFilter {
@Override
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
filterChain.doFilter(request, response);
} catch (RuntimeException e) {
// custom error response class used across my project
ErrorResponse errorResponse = new ErrorResponse(e);
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.getWriter().write(convertObjectToJson(errorResponse));
}
}
public String convertObjectToJson(Object object) throws JsonProcessingException {
if (object == null) {
return null;
}
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(object);
}
}
And then i added it in the web.xml before the CorsFilter
. And it works!
<filter>
<filter-name>exceptionHandlerFilter</filter-name>
<filter-class>xx.xxxxxx.xxxxx.api.controllers.filters.ExceptionHandlerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>exceptionHandlerFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
If you want to pull a particular file from another branch just do
git checkout branch1 -- filenamefoo.txt
This will pull a version of the file from one branch into the current tree
The most clean and modern way to use singletons in Android is just to use the Dependency Injection framework called Dagger 2. Here you have an explanation of possible scopes you can use. Singleton is one of these scopes. Dependency Injection is not that easy but you shall invest a bit of your time to understand it. It also makes testing easier.
Simply my project wasn't in htdocs thats why it was showing me an this error make sure you put your project in HTdocs not in directory inside it
If you got nothing when inputted fastboot devices
, it meaned you devices fail to enter fastboot model. Make sure that you enter fastboot model via press these three button simultaneously, power key, volume key(both '+' and '-').
Then you can see you devices via fastboot devices
and continue to flash your devices.
note:I entered fastboot model only pressed 'power key' and '-' key before, and present the same problem.
just add
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
<scope>runtime</scope>
</dependency>
Use a timer. There are 3 basic kinds, each suited for different purposes.
Use only in a Windows Form application. This timer is processed as part of the message loop, so the the timer can be frozen under high load.
When you need synchronicity, use this one. This means that the tick event will be run on the thread that started the timer, allowing you to perform GUI operations without much hassle.
This is the most high-powered timer, which fires ticks on a background thread. This lets you perform operations in the background without freezing the GUI or the main thread.
For most cases, I recommend System.Timers.Timer.
Run this:
SELECT CASE transaction_isolation_level
WHEN 0 THEN 'Unspecified'
WHEN 1 THEN 'ReadUncommitted'
WHEN 2 THEN 'ReadCommitted'
WHEN 3 THEN 'Repeatable'
WHEN 4 THEN 'Serializable'
WHEN 5 THEN 'Snapshot' END AS TRANSACTION_ISOLATION_LEVEL
FROM sys.dm_exec_sessions
where session_id = @@SPID
Use git push origin master
instead.
You have a repository locally and the initial git push
is "pushing" to it. It's not necessary to do so (as it is local) and it shows everything as up-to-date. git push origin master
specifies a a remote repository (origin
) and the branch located there (master
).
For more information, check out this resource.
Another way to validate is like this.
var $radio = $('input:radio[name="nameRadioButton"]');
$radio.addClass("validate[required]");
I hope my example will help you
I had a problem where the value was not set because of a syntax error before the call.
$("#someId").value(33); //script bailed here without showing any errors Note: .value instead of .val
$("#gate").val('Gateway 2'); //this line didn't work.
Check for syntax errors before the call.
You can try just finishAffinity() , its close all current activities to works on above v4.1
The correct way to do it would be:
adb -s 123abc12 shell getprop
Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop
to access its value directly, like this:
adb -s 123abc12 shell getprop ro.product.model
The details in adb devices -l
consist of the following three properties: ro.product.name
, ro.product.model
and ro.product.device
.
Note that ADB shell ends lines with \r\n
, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7
you might get Nexus 7\r
).
The function export_fig on the MATLAB file exchange will crop the whitespace around an output PDF/EPS file by default when it exports a figure.
Static classes don't require you to create an object of that class/instantiate them, you can prefix the C# keyword static in front of the class name, to make it static.
Remember: we're not instantiating the Console class, String class, Array Class.
class Book
{
public static int myInt = 0;
}
public class Exercise
{
static void Main()
{
Book book = new Book();
//Use the class name directly to call the property myInt,
//don't use the object to access the value of property myInt
Console.WriteLine(Book.myInt);
Console.ReadKey();
}
}
Check out this link for more details.
To find files which are created in last one hour in current directory, you can use -amin
find . -amin -60 -type f
This will find files which are created with in last 1 hour.
If you want to check the python version in a particular cond environment you can also use conda list python
I have used task.topActivity instead of task.baseActivity and it works fine for me.
protected Boolean isNotificationActivityRunning() {
ActivityManager activityManager = (ActivityManager) getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (ActivityManager.RunningTaskInfo task : tasks) {
if (task.topActivity.getClassName().equals(NotificationsActivity.class.getCanonicalName()))
return true;
}
return false;
}
SQL NULL value
IF ( value IS NULL )
if (obj == DBNull.Value)
{}
Best practice when reading from a data reader:
var reader = cmd.ExecuteReader();
...
var result = (reader[i] == DBNull.Value ? "" : reader[i].ToString());
In my experience, there are some cases the returned value can be missing and thus execution fails by returning null. An example would be
select MAX(ID) from <table name> where <impossible condition>
The above script cannot find anything to find a MAX in. So it fails. In these such cases we must compare the old fashion way (compare with C# null
)
var obj = cmd.ExecuteScalar();
var result = (obj == null ? -1 : Convert.ToInt32(obj));
You can always just use jQuery to add a class, .addClass
or .toggleClass
. Then you can keep all your styles in your CSS and out of your scripts.
I translate it into C# code in Spanish version, regards:
public string ObtenerNumeroMes(string NombreMes){
string NumeroMes;
switch(NombreMes) {
case ("ENERO") :
NumeroMes = "01";
return NumeroMes;
case ("FEBRERO") :
NumeroMes = "02";
return NumeroMes;
case ("MARZO") :
NumeroMes = "03";
return NumeroMes;
case ("ABRIL") :
NumeroMes = "04";
return NumeroMes;
case ("MAYO") :
NumeroMes = "05";
return NumeroMes;
case ("JUNIO") :
NumeroMes = "06";
return NumeroMes;
case ("JULIO") :
NumeroMes = "07";
return NumeroMes;
case ("AGOSTO") :
NumeroMes = "08";
return NumeroMes;
case ("SEPTIEMBRE") :
NumeroMes = "09";
return NumeroMes;
case ("OCTUBRE") :
NumeroMes = "10";
return NumeroMes;
case ("NOVIEMBRE") :
NumeroMes = "11";
return NumeroMes;
case ("DICIEMBRE") :
NumeroMes = "12";
return NumeroMes;
default:
Console.WriteLine("Error");
return "ERROR";
}
}
There MUST be en easier way to do this... Low and behold, there is...!
"sp_describe_first_result_set" is your friend!
Now I do realise the question was asked specifically for SQL Server 2000, but I was looking for a similar solution for later versions and discovered some native support in SQL to achieve this.
In SQL Server 2012 onwards cf. "sp_describe_first_result_set" - Link to BOL
I had already implemented a solution using a technique similar to @Trisped's above and ripped it out to implement the native SQL Server implementation.
In case you're not on SQL Server 2012 or Azure SQL Database yet, here's the stored proc I created for pre-2012 era databases:
CREATE PROCEDURE [fn].[GetQueryResultMetadata]
@queryText VARCHAR(MAX)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
--SET NOCOUNT ON;
PRINT @queryText;
DECLARE
@sqlToExec NVARCHAR(MAX) =
'SELECT TOP 1 * INTO #QueryMetadata FROM ('
+
@queryText
+
') T;'
+ '
SELECT
C.Name [ColumnName],
TP.Name [ColumnType],
C.max_length [MaxLength],
C.[precision] [Precision],
C.[scale] [Scale],
C.[is_nullable] IsNullable
FROM
tempdb.sys.columns C
INNER JOIN
tempdb.sys.types TP
ON
TP.system_type_id = C.system_type_id
AND
-- exclude custom types
TP.system_type_id = TP.user_type_id
WHERE
[object_id] = OBJECT_ID(N''tempdb..#QueryMetadata'');
'
EXEC sp_executesql @sqlToExec
END
This is extension of answer provided by Ranjith
I would suggest, you to choose a choice-parameter build, and specify the branches that you would like to build. Active Choice Parameter
And after that, you can specify branches to build. Branch to Build
Now, when you would build your project, you would be provided with "Build with Parameters, where you can choose the branch to build"
You can also write a groovy script to fetch all your branches to in active choice parameter.
As a newbie in React world, I came across a similar issues where I could not edit
the textarea and struggled
with binding. It's worth knowing about controlled
and uncontrolled
elements when it comes to react.
The value of the following uncontrolled textarea
cannot be changed because of value
<textarea type="text" value="some value"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following uncontrolled textarea
can be changed because of use of defaultValue
or no value attribute
<textarea type="text" defaultValue="sample"
onChange={(event) => this.handleOnChange(event)}></textarea>
<textarea type="text"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following controlled textarea
can be changed because of how
value is mapped to a state as well as the onChange
event listener
<textarea value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
Here is my solution using different syntax. I prefer the auto-bind
than manual binding however, if I were to not use {(event) => this.onXXXX(event)}
then that would cause the content of textarea
to be not editable OR the event.preventDefault()
does not work as expected. Still a lot to learn I suppose.
class Editor extends React.Component {
constructor(props) {
super(props)
this.state = {
textareaValue: ''
}
}
handleOnChange(event) {
this.setState({
textareaValue: event.target.value
})
}
handleOnSubmit(event) {
event.preventDefault();
this.setState({
textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
})
}
render() {
return <div>
<form onSubmit={(event) => this.handleOnSubmit(event)}>
<textarea rows={10} cols={30} value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
<br/>
<input type="submit" value="Save"/>
</form>
</div>
}
}
ReactDOM.render(<Editor />, document.getElementById("content"));
The versions of libraries are
"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4"
First off, see How Big can a Python Array Get? and Numpy, problem with long arrays
Second, the only real limit comes from the amount of memory you have and how your system stores memory references. There is no per-list limit, so Python will go until it runs out of memory. Two possibilities:
The DLL must be present at all times - as the name indicates, a reference only tells VS that you're trying to use stuff from the DLL. In the project file, VS stores the actual path and file name of the referenced DLL. If you move or delete it, VS is not able to find it anymore.
I usually create a libs
folder within my project's folder where I copy DLLs that are not installed to the GAC. Then, I actually add this folder to my project in VS (show hidden files in VS, then right-click and "Include in project"). I then reference the DLLs from the folder, so when checking into source control, the library is also checked in. This makes it much easier when more than one developer will have to change the project.
(Please make sure to set the build type to "none" and "don't copy to output folder" for the DLL in your project.)
PS: I use a German Visual Studio, so the captions I quoted may not exactly match the English version...
Try to Clean
your solution and then try once again.
It will definitely work. Because every thing in code seems to be ok.
Go through this link for cleaning solution>
http://social.msdn.microsoft.com/Forums/en-US/vsdebug/thread/e53aab69-75b9-434a-bde3-74ca0865c165/
For example see https://web.archive.org/web/20080506194329/http://www.arthurkoziel.com/2008/05/02/git-configuration/
The interesting part is
Colorized output:
git config --global color.branch auto git config --global color.diff auto git config --global color.interactive auto git config --global color.status auto
The del statement is what you're looking for. If you have a dictionary named foo with a key called 'bar', you can delete 'bar' from foo like this:
del foo['bar']
Note that this permanently modifies the dictionary being operated on. If you want to keep the original dictionary, you'll have to create a copy beforehand:
>>> foo = {'bar': 'baz'}
>>> fu = dict(foo)
>>> del foo['bar']
>>> print foo
{}
>>> print fu
{'bar': 'baz'}
The dict
call makes a shallow copy. If you want a deep copy, use copy.deepcopy
.
Here's a method you can copy & paste, for your convenience:
def minus_key(key, dictionary):
shallow_copy = dict(dictionary)
del shallow_copy[key]
return shallow_copy
I used this regex expression:
string s = "søme string";
Regex regex = new Regex(@"[^a-zA-Z0-9\s]", (RegexOptions)0);
return regex.Replace(s, "");
An easy solution is to rename all non-index.php files to .inc, then deny access to *.inc files. I use this in a lot of my projects and it works perfectly fine.
Altering the class model-dialog
you can achieve expected result. These small tricks work for me. Hope it will help you to solve this issue.
.modal-dialog {
width: 70%;
}
To my knowledge, you can't mock constructors with mockito, only methods. But according to the wiki on the Mockito google code page there is a way to mock the constructor behavior by creating a method in your class which return a new instance of that class. then you can mock out that method. Below is an excerpt directly from the Mockito wiki:
Pattern 1 - using one-line methods for object creation
To use pattern 1 (testing a class called MyClass), you would replace a call like
Foo foo = new Foo( a, b, c );
with
Foo foo = makeFoo( a, b, c );
and write a one-line method
Foo makeFoo( A a, B b, C c ) { return new Foo( a, b, c ); }
It's important that you don't include any logic in the method; just the one line that creates the object. The reason for this is that the method itself is never going to be unit tested.
When you come to test the class, the object that you test will actually be a Mockito spy, with this method overridden, to return a mock. What you're testing is therefore not the class itself, but a very slightly modified version of it.
Your test class might contain members like
@Mock private Foo mockFoo; private MyClass toTest = spy(new MyClass());
Lastly, inside your test method you mock out the call to makeFoo with a line like
doReturn( mockFoo ) .when( toTest ) .makeFoo( any( A.class ), any( B.class ), any( C.class ));
You can use matchers that are more specific than any() if you want to check the arguments that are passed to the constructor.
If you're just wanting to return a mocked object of your class I think this should work for you. In any case you can read more about mocking object creation here:
Some SelectMany may not be necessary. Below 2 queries give the same result.
Customers.Where(c=>c.Name=="Tom").SelectMany(c=>c.Orders)
Orders.Where(o=>o.Customer.Name=="Tom")
For 1-to-Many relationship,
from o in Orders
join c in Customers on o.CustomerID equals c.ID
where c.Name == "Tom"
select o
Create a model which contains your list and other things you need for the view.
For example:
public class MyModel
{
public List<string> _MyList { get; set; }
}
From the action method put your desired list to the Model, _MyList
property, like:
public ActionResult ArticleList(MyModel model)
{
model._MyList = new List<string>{"item1","item2","item3"};
return PartialView(@"~/Views/Home/MyView.cshtml", model);
}
In your view access the model as follows
@model MyModel
foreach (var item in Model)
{
<div>@item</div>
}
I think it will help for start.
I'm using Angular 5.
In my case, I needed to import ReactiveFormsModule too.
File app.module.ts (or anymodule.module.ts):
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
My favorite way to do it is with git log
's -G
option (added in version 1.7.4).
-G<regex>
Look for differences whose added or removed line matches the given <regex>.
There is a subtle difference between the way the -G
and -S
options determine if a commit matches:
-S
option essentially counts the number of times your search matches in a file before and after a commit. The commit is shown in the log if the before and after counts are different. This will not, for example, show commits where a line matching your search was moved.-G
option, the commit is shown in the log if your search matches any line that was added, removed, or changed.Take this commit as an example:
diff --git a/test b/test
index dddc242..60a8ba6 100644
--- a/test
+++ b/test
@@ -1 +1 @@
-hello hello
+hello goodbye hello
Because the number of times "hello" appears in the file is the same before and after this commit, it will not match using -Shello
. However, since there was a change to a line matching hello
, the commit will be shown using -Ghello
.
First, you need to compile your code with appropriate flags, enabling debug into code.
$ gcc -Wall -g -ggdb -o ex1 ex1.c
then just run you code with your favourite debugger
$ gdb ./ex1
show me the code.
(gdb) list
1 #include <stdio.h>
2 int main(void)
3 {
4 int i = 0;
5 for(i=0;i<7;++i)
6 printf("%d\n", i);
7
8 return 0;
9 }
break on lines 5 and looks if i == 5.
(gdb) b 5
Breakpoint 1 at 0x4004fb: file ex1.c, line 5.
(gdb) rwatch i if i==5
Hardware read watchpoint 5: i
checking breakpoints
(gdb) info b
Num Type Disp Enb Address What
1 breakpoint keep y 0x00000000004004fb in main at ex1.c:5
breakpoint already hit 1 time
5 read watchpoint keep y i
stop only if i==5
running the program
(gdb) c
Continuing.
0
1
2
3
4
Hardware read watchpoint 5: i
Value = 5
0x0000000000400523 in main () at ex1.c:5
5 for(i=0;i<7;++i)
I also had some trouble with my scrollable modals, so I did something like this:
$('.modal').on('shown.bs.modal', function () {
$('body').addClass('modal-open');
// BS adds some padding-right to acomodate the scrollbar at right
$('body').removeAttr('style');
})
$(".modal [data-toggle='modal']").click(function(){
$(this).closest(".modal").modal('hide');
});
It will serve for any modal whithin a modal that comes to appear. Note that the first its closed so the second can appear. No changes in the Bootstrap structure.
One cool solution might be separating all environment-specific values into some separate angular module, that all other modules depend on:
angular.module('configuration', [])
.constant('API_END_POINT','123456')
.constant('HOST','localhost');
Then your modules that need those entries can declare a dependency on it:
angular.module('services',['configuration'])
.factory('User',['$resource','API_END_POINT'],function($resource,API_END_POINT){
return $resource(API_END_POINT + 'user');
});
Now you could think about further cool stuff:
The module, that contains the configuration can be separated into configuration.js, that will be included at your page.
This script can be easily edited by each of you, as long as you don’t check this separate file into git. But it's easier to not check in the configuration if it is in a separate file. Also, you could branch it locally.
Now, if you have a build-system, like ANT or Maven, your further steps could be implementing some placeholders for the values API_END_POINT, that will be replaced during build-time, with your specific values.
Or you have your configuration_a.js
and configuration_b.js
and decide at the backend which to include.
http://encosia.com/using-cors-to-access-asp-net-services-across-domains/
refer the above link for more details on Cross domain resource sharing.
you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.
sample below:
ajax call:
$(document).ready(function () {
$.ajax({
crossDomain: true,
type:"GET",
contentType: "application/json; charset=utf-8",
async:false,
url: "<your middle man service url here>/GetQuote?callback=?",
data: { symbol: 'ctsh' },
dataType: "jsonp",
jsonpCallback: 'fnsuccesscallback'
});
});
service (asmx) which will return jsonp:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void GetQuote(String symbol,string callback)
{
WebProxy myProxy = new WebProxy("<proxy url here>", true);
myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
SQ.Proxy = myProxy;
String result = SQ.GetQuote(symbol);
StringBuilder sb = new StringBuilder();
JavaScriptSerializer js = new JavaScriptSerializer();
sb.Append(callback + "(");
sb.Append(js.Serialize(result));
sb.Append(");");
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write(sb.ToString());
Context.Response.End();
}
fade the other in in the callback of fadeout, which runs when fadeout is done. Using your code:
$('#two, #three').hide();
$('.slide').click(function(){
var $this = $(this);
$this.fadeOut(function(){ $this.next().fadeIn(); });
});
alternatively, you can just "pause" the chain, but you need to specify for how long:
$(this).fadeOut().next().delay(500).fadeIn();
You can only have one output path.
from the docs https://github.com/webpack/docs/wiki/configuration#output
Options affecting the output of the compilation. output options tell Webpack how to write the compiled files to disk. Note, that while there can be multiple entry points, only one output configuration is specified.
If you use any hashing ([hash] or [chunkhash]) make sure to have a consistent ordering of modules. Use the OccurenceOrderPlugin or recordsPath.
Try this, this should also get rid of those empty lines also:
SELECT prereq FROM test WHERE prereq IS NOT NULL;
There is slight change in mysql_real_escape_string mysqli_real_escape_string. below syntax
mysql_real_escape_string syntax will be mysql_real_escape_string($_POST['sample_var'])
mysqli_real_escape_string syntax will be mysqli_real_escape_string($conn,$_POST['sample_var'])
tl;dr:
For classes, you might be looking for:
let index = someArray.firstIndex{$0 === someObject}
Full answer:
I think it's worth mentioning that with reference types (class
) you might want to perform an identity comparison, in which case you just need to use the ===
identity operator in the predicate closure:
Swift 5, Swift 4.2:
let person1 = Person(name: "John")
let person2 = Person(name: "Sue")
let person3 = Person(name: "Maria")
let person4 = Person(name: "Loner")
let people = [person1, person2, person3]
let indexOfPerson1 = people.firstIndex{$0 === person1} // 0
let indexOfPerson2 = people.firstIndex{$0 === person2} // 1
let indexOfPerson3 = people.firstIndex{$0 === person3} // 2
let indexOfPerson4 = people.firstIndex{$0 === person4} // nil
Note that the above syntax uses trailing closures syntax, and is equivalent to:
let indexOfPerson1 = people.firstIndex(where: {$0 === person1})
Swift 4 / Swift 3 - the function used to be called index
Swift 2 - the function used to be called indexOf
* Note the relevant and useful comment by paulbailey about class
types that implement Equatable
, where you need to consider whether you should be comparing using ===
(identity operator) or ==
(equality operator). If you decide to match using ==
, then you can simply use the method suggested by others (people.firstIndex(of: person1)
).
One of recent the TFS Rocks pocasts mentioned such an organisation, may have been number 16.
>>> s = "123mango abcd mango kiwi peach"
>>> s.split("mango", 1)
['123', ' abcd mango kiwi peach']
>>> s.split("mango", 1)[1]
' abcd mango kiwi peach'
This is how I do it in my code.
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));
or
wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));
to be precise.
See also:
Just as a reference, here is an example of how to convert between String
and char[]
with a dynamic length -
// Define
String str = "This is my string";
// Length (with one extra character for the null terminator)
int str_len = str.length() + 1;
// Prepare the character array (the buffer)
char char_array[str_len];
// Copy it over
str.toCharArray(char_array, str_len);
Yes, this is painfully obtuse for something as simple as a type conversion, but sadly it's the easiest way.
Native C++ codified version of Oleg's answer -- this is copy/pasted from a project I work on under the Boost Software License.
BOOL noError;
STARTUPINFO startupInfo;
PROCESS_INFORMATION processInformation;
ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
startupInfo.dwFlags = STARTF_USESHOWWINDOW;
startupInfo.wShowWindow = SW_HIDE;
noError = CreateProcess(
NULL, //lpApplicationName
//Okay the const_cast is bad -- this code was written a while ago.
//should probably be &commandLine[0] instead. Oh, and commandLine is
//a std::wstring
const_cast<LPWSTR>(commandLine.c_str()), //lpCommandLine
NULL, //lpProcessAttributes
NULL, //lpThreadAttributes
FALSE, //bInheritHandles
CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT, //dwCreationFlags
//This is for passing in a custom environment block -- you can probably
//just use NULL here.
options.e ? environment : NULL, //lpEnvironment
NULL, //lpCurrentDirectory
&startupInfo, //lpStartupInfo
&processInformation //lpProcessInformation
);
if(!noError)
{
return GetLastError();
}
DWORD exitCode = 0;
if (options.w) //Wait
{
WaitForSingleObject(processInformation.hProcess, INFINITE);
if (GetExitCodeProcess(processInformation.hProcess, &exitCode) == 0)
{
exitCode = (DWORD)-1;
}
}
CloseHandle( processInformation.hProcess );
CloseHandle( processInformation.hThread );
EDIT: I hadn't noticed you needed the position as well. You can't use IndexOf
directly on a value of an array type, because it's implemented explicitly. However, you can use:
IList<string> arrayAsList = (IList<string>) stringArray;
int index = arrayAsList.IndexOf(value);
if (index != -1)
{
...
}
(This is similar to calling Array.IndexOf
as per Darin's answer - just an alternative approach. It's not clear to me why IList<T>.IndexOf
is implemented explicitly in arrays, but never mind...)
I had virtual env site package problem and this helped me, maybe it will help you too
This will work very quickly but will not generate random values but monotonously increasing ones (for a given thread).
import threading
_uid = threading.local()
def genuid():
if getattr(_uid, "uid", None) is None:
_uid.tid = threading.current_thread().ident
_uid.uid = 0
_uid.uid += 1
return (_uid.tid, _uid.uid)
It is thread safe and working with tuples may have benefit as opposed to strings (shorter if anything). If you do not need thread safety feel free remove the threading bits (in stead of threading.local, use object() and remove tid altogether).
Hope that helps.
i prefer to use ng-value with ng-if, [ng-value] will handle trigger changes
<input type="radio" name="isStudent" ng-model="isStudent" ng-value="true" />
//to show and hide input by removing it from the DOM, that's make me secure from malicious data
<input type="text" ng-if="isStudent" name="textForStudent" ng-model="job">
since the problem is still there I though I throw in another solution.
My case was that I wanted to auto deploy all pull requests to s3 for testing before merge making them accessible on [mydomain]/pull-requests/[pr number]/
(ex. www.example.com/pull-requests/822/)
To the best of my knowledge non of s3 rules scenarios would allow to have multiple projects in one bucket using html5 routing so while above most voted suggestion works for a project in root folder, it doesn't for multiple projects in own subfolders.
So I pointed my domain to my server where following nginx config did the job
location /pull-requests/ {
try_files $uri @get_files;
}
location @get_files {
rewrite ^\/pull-requests\/(.*) /$1 break;
proxy_pass http://<your-amazon-bucket-url>;
proxy_intercept_errors on;
recursive_error_pages on;
error_page 404 = @get_routes;
}
location @get_routes {
rewrite ^\/(\w+)\/(.+) /$1/ break;
proxy_pass http://<your-amazon-bucket-url>;
proxy_intercept_errors on;
recursive_error_pages on;
error_page 404 = @not_found;
}
location @not_found {
return 404;
}
it tries to get the file and if not found assumes it is html5 route and tries that. If you have a 404 angular page for not found routes you will never get to @not_found and get you angular 404 page returned instead of not found files, which could be fixed with some if rule in @get_routes or something.
I have to say I don't feel too comfortable in area of nginx config and using regex for that matter, I got this working with some trial and error so while this works I am sure there is room for improvement and please do share your thoughts.
Note: remove s3 redirection rules if you had them in S3 config.
and btw works in Safari
If your input rows are lists rather than dictionaries, then the following is a simple solution:
import pandas as pd
list_of_lists = []
list_of_lists.append([1,2,3])
list_of_lists.append([4,5,6])
pd.DataFrame(list_of_lists, columns=['A', 'B', 'C'])
# A B C
# 0 1 2 3
# 1 4 5 6
When you're running npm install
in the project's root, it installs all of the npm dependencies into the project's node_modules
directory.
If you take a look at the project's node_modules
directory, you should see a directory called http-server
, which holds the http-server
package, and a .bin
folder, which holds the executable binaries from the installed dependencies. The .bin
directory should have the http-server
binary (or a link to it).
So in your case, you should be able to start the http-server
by running the following from your project's root directory (instead of npm start
):
./node_modules/.bin/http-server -a localhost -p 8000 -c-1
This should have the same effect as running npm start
.
If you're running a Bash shell, you can simplify this by adding the ./node_modules/.bin
folder to your $PATH
environment variable:
export PATH=./node_modules/.bin:$PATH
This will put this folder on your path, and you should be able to simply run
http-server -a localhost -p 8000 -c-1
Slight modification of efnx clckclcks's javascript function. I changed the formatting from spaces to tab, but most importantly I allowed text to remain on one line:
var formatXml = this.formatXml = function (xml) {
var reg = /(>)\s*(<)(\/*)/g; // updated Mar 30, 2015
var wsexp = / *(.*) +\n/g;
var contexp = /(<.+>)(.+\n)/g;
xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2');
var pad = 0;
var formatted = '';
var lines = xml.split('\n');
var indent = 0;
var lastType = 'other';
// 4 types of tags - single, closing, opening, other (text, doctype, comment) - 4*4 = 16 transitions
var transitions = {
'single->single': 0,
'single->closing': -1,
'single->opening': 0,
'single->other': 0,
'closing->single': 0,
'closing->closing': -1,
'closing->opening': 0,
'closing->other': 0,
'opening->single': 1,
'opening->closing': 0,
'opening->opening': 1,
'opening->other': 1,
'other->single': 0,
'other->closing': -1,
'other->opening': 0,
'other->other': 0
};
for (var i = 0; i < lines.length; i++) {
var ln = lines[i];
// Luca Viggiani 2017-07-03: handle optional <?xml ... ?> declaration
if (ln.match(/\s*<\?xml/)) {
formatted += ln + "\n";
continue;
}
// ---
var single = Boolean(ln.match(/<.+\/>/)); // is this line a single tag? ex. <br />
var closing = Boolean(ln.match(/<\/.+>/)); // is this a closing tag? ex. </a>
var opening = Boolean(ln.match(/<[^!].*>/)); // is this even a tag (that's not <!something>)
var type = single ? 'single' : closing ? 'closing' : opening ? 'opening' : 'other';
var fromTo = lastType + '->' + type;
lastType = type;
var padding = '';
indent += transitions[fromTo];
for (var j = 0; j < indent; j++) {
padding += '\t';
}
if (fromTo == 'opening->closing')
formatted = formatted.substr(0, formatted.length - 1) + ln + '\n'; // substr removes line break (\n) from prev loop
else
formatted += padding + ln + '\n';
}
return formatted;
};
You create handler in background thread this way
private void createHandler() {
Thread thread = new Thread() {
public void run() {
Looper.prepare();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Do Work
handler.removeCallbacks(this);
Looper.myLooper().quit();
}
}, 2000);
Looper.loop();
}
};
thread.start();
}
Your logic is flawed... basically, you need to:
You're not doing step 2.
Here's the code you want:
Properties prop = new Properties();
prop.load(new FileInputStream("/displayCategerization.properties"));
for (Map.Entry<Object, Object> entry : prop.entrySet())
{
List<String> categoryList = categoryMap.get((String) entry.getKey());
if (categoryList == null)
{
categoryList = new ArrayList<String>();
LogDisplayService.categoryMap.put((String) entry.getKey(), categoryList);
}
categoryList.add((String) entry.getValue());
}
Note also the "correct" way to iterate over the entries of a map/properties - via its entrySet()
.
Basically we had to enable TLS 1.2 for .NET 4.x. Making this registry changed worked for me, and stopped the event log filling up with the Schannel error.
More information on the answer can be found here
Enable TLS 1.2 at the system (SCHANNEL) level:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
(equivalent keys are probably also available for other TLS versions)
Tell .NET Framework to use the system TLS versions:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
This may not be desirable for edge cases where .NET Framework 4.x applications need to have different protocols enabled and disabled than the OS does.
If you can do the construction in a single operation, then something like the vstack-with-fancy-indexing answer is a fine approach. But if your condition is more complicated or your rows come in on the fly, you may want to grow the array. In fact the numpythonic way to do something like this - dynamically grow an array - is to dynamically grow a list:
A = np.array([[1,2,3],[4,5,6]])
Alist = [r for r in A]
for i in range(100):
newrow = np.arange(3)+i
if i%5:
Alist.append(newrow)
A = np.array(Alist)
del Alist
Lists are highly optimized for this kind of access pattern; you don't have convenient numpy multidimensional indexing while in list form, but for as long as you're appending it's hard to do better than a list of row arrays.
Always use EntityFunctions.TruncateTime() for both x.DateTimeStart and currentDate. such as :
var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference).Where(x => EntityFunctions.TruncateTime(x.DateTimeStart) == EntityFunctions.TruncateTime(currentDate));
The statement java.io.IOException: Could not locate executable null\bin\winutils.exe
explains that the null is received when expanding or replacing an Environment Variable. If you see the Source in Shell.Java in Common Package you will find that HADOOP_HOME variable is not getting set and you are receiving null in place of that and hence the error.
So, HADOOP_HOME needs to be set for this properly or the variable hadoop.home.dir property.
Hope this helps.
Thanks, Kamleshwar.
Right click on your project, select New -> Source Folder
Enter src as Folder name, then click finish.
Eclipse will then recognize the src folder as containing Java code, and you should be able to set up a run configuration
According to this site add
CONFIG += c++11
to your .pro file (see at the bottom of that web page). It requires Qt 5.
The other answers, suggesting
QMAKE_CXXFLAGS += -std=c++11
(or QMAKE_CXXFLAGS += -std=c++0x
)
also work with Qt 4.8 and gcc / clang.
let calendar = Calendar.current
let hours = calendar.component(.hour, from: Date())
let minutes = calendar.component(.minute, from: Date())
let seconds = calendar.component(.second, from: Date())
maven-compiler-plugin it's already present in plugins hierarchy dependency in pom.xml. Check in Effective POM.
For short you can use properties like this:
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
I'm using Maven 3.2.5.
This is the right CSS3 answer. Hope this helps you somehow now :D I really recommend you to read the book: https://www.amazon.com/Book-CSS3-Developers-Future-Design/dp/1593272863 Actually I have made this solution from reading this book now. :D
#wrapper{_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
border: 1px solid black;_x000D_
}_x000D_
#first{_x000D_
width: 300px;_x000D_
border: 1px solid red;_x000D_
}_x000D_
#second{_x000D_
border: 1px solid green;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="first">Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.</div>_x000D_
<div id="second">When you post a new question, other users will almost immediately see it and try to provide good answers. This often happens in a matter of minutes, so be sure to check back frequently when your question is still new for the best response.</div>_x000D_
</div>
_x000D_
Use SQL Server's date styles to pre-format your date values.
SELECT
CONVERT(varchar(2), GETDATE(), 101) AS monthLeadingZero -- Date Style 101 = mm/dd/yyyy
,CONVERT(varchar(2), GETDATE(), 103) AS dayLeadingZero -- Date Style 103 = dd/mm/yyyy
I only change/remove the class:
function removeClass() {
var element = angular.element('#nameInput');
element.removeClass('nameClass');
};
Try this one using Grid Layout:
.grid-container {_x000D_
display: grid;_x000D_
grid-template-columns: auto auto auto;_x000D_
padding: 10px;_x000D_
}_x000D_
.grid-item {_x000D_
background-color: rgba(255, 255, 255, 0.8);_x000D_
border: 1px solid rgba(0, 0, 0, 0.8);_x000D_
padding: 20px;_x000D_
font-size: 30px;_x000D_
text-align: center;_x000D_
}
_x000D_
<div class="grid-container">_x000D_
<div class="grid-item">1</div>_x000D_
<div class="grid-item">2</div>_x000D_
<div class="grid-item">3</div> _x000D_
<div class="grid-item">4</div>_x000D_
<div class="grid-item">5</div>_x000D_
<div class="grid-item">6</div> _x000D_
<div class="grid-item">7</div>_x000D_
<div class="grid-item">8</div>_x000D_
<div class="grid-item">9</div> _x000D_
</div>
_x000D_
I'll add my solution here. We can use floor when values are above 0 and ceil when they are less than zero:
function truncateToInt(x)
{
if(x > 0)
{
return Math.floor(x);
}
else
{
return Math.ceil(x);
}
}
Then:
y = truncateToInt(2.9999); // results in 2
y = truncateToInt(-3.118); //results in -3
Notice: This answer was written when Math.trunc(x)
was fairly new and not supported by a lot of browsers. Today, modern browsers support Math.trunc(x)
.
jQuery has the hasClass() function that returns true if any element in the wrapped set contains the specified class
if (!$(this).hasClass("selected")) {
//do stuff
}
Take a look at my example of use
Here is the code for it
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #FFF; font: 16px Helvetica, Arial; color: #000; }
</style>
<!-- jQuery code here -->
<script type="text/javascript">
$(function() {
$('#myButton').click(function(e) {
$('#div2').addClass('selected');
});
$('.thumbs').bind('click',function(e) { alert('You clicked ' + e.target.id ); } );
$('.thumbs').hover(fadeItIn, fadeItOut);
});
function fadeItIn(e) {
if (!$(e.target).hasClass('selected'))
{
$(e.target).fadeTo('normal', 1.0);
}
}
function fadeItOut(e) {
if (!$(e.target).hasClass('selected'))
{
$(e.target).fadeTo('slow', 0.3);
}
}
</script>
</head>
<body>
<div id="div1" class="thumbs" style=" background-color: #0f0; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both;">
One div with a thumbs class
</div>
<div id="div2" class="thumbs" style=" background-color: #f00; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both;">
Another one with a thumbs class
</div>
<input type="button" id="myButton" value="add 'selected' class to red div" />
</body>
</html>
EDIT:
this is just a guess, but are you trying to achieve something like this?
jQuery Code is here-
$(function() {
$('.thumbs').bind('click',function(e) { $(e.target).toggleClass('selected'); } );
$('.thumbs').hover(fadeItIn, fadeItOut);
$('.thumbs').css('opacity', 0.3);
});
function fadeItIn(e) {
if (!$(e.target).hasClass('selected'))
{
$(e.target).fadeTo('normal', 1.0);
}
}
function fadeItOut(e) {
if (!$(e.target).hasClass('selected'))
{
$(e.target).fadeTo('slow', 0.3);
}
}
<div id="div1" class="thumbs" style=" background-color: #0f0; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both; cursor:pointer;">
One div with a thumbs class
</div>
<div id="div2" class="thumbs" style=" background-color: #f00; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both; cursor:pointer;">
Another one with a thumbs class
</div>
To display the category image for the currently displayed category in archive-product.php
, use the current category term_id
when is_product_category()
is true:
// verify that this is a product category page
if ( is_product_category() ){
global $wp_query;
// get the query object
$cat = $wp_query->get_queried_object();
// get the thumbnail id using the queried category term_id
$thumbnail_id = get_term_meta( $cat->term_id, 'thumbnail_id', true );
// get the image URL
$image = wp_get_attachment_url( $thumbnail_id );
// print the IMG HTML
echo "<img src='{$image}' alt='' width='762' height='365' />";
}
Path In Android Studio in mac:
Android Studio -> Preferences -> Editor -> Inspections
Expand Android -> Expand Lint -> Expand Correctness
Uncheck the checkbox for Using system app permission
Click on "APPLY" -> "OK"
https://stackoverflow.com/a/16350929/11860907
If you add e.SuppressKeyPress = true;
as shown in the answer in this link you will suppress the annoying ding sound that occurs.
Since you asked about ready-made Api's ... well Apache's commons. collections library has a CollectionUtils class that provides easy-to-use methods for Collection manipulation/checking, such as intersection, difference, and union.
As of C++11, you have two major additional options. First, you can use insert()
with list initialization syntax:
function.insert({0, 42});
This is functionally equivalent to
function.insert(std::map<int, int>::value_type(0, 42));
but much more concise and readable. As other answers have noted, this has several advantages over the other forms:
operator[]
approach requires the mapped type to be assignable, which isn't always the case.operator[]
approach can overwrite existing elements, and gives you no way to tell whether this has happened.insert
that you list involve an implicit type conversion, which may slow your code down.The major drawback is that this form used to require the key and value to be copyable, so it wouldn't work with e.g. a map with unique_ptr
values. That has been fixed in the standard, but the fix may not have reached your standard library implementation yet.
Second, you can use the emplace()
method:
function.emplace(0, 42);
This is more concise than any of the forms of insert()
, works fine with move-only types like unique_ptr
, and theoretically may be slightly more efficient (although a decent compiler should optimize away the difference). The only major drawback is that it may surprise your readers a little, since emplace
methods aren't usually used that way.
Are you mixing C and C++? One issue that can occur is that the declarations in the .h
file for a .c
file need to be surrounded by:
#if defined(__cplusplus)
extern "C" { // Make sure we have C-declarations in C++ programs
#endif
and:
#if defined(__cplusplus)
}
#endif
Note: if unable / unwilling to modify the .h
file(s) in question, you can surround their inclusion with extern "C"
:
extern "C" {
#include <abc.h>
} //extern
The answers mentioning adding @Transactional
are correct, but for simplicity you could just have your test class extends AbstractTransactionalJUnit4SpringContextTests
.
In dplyr 0.3 this can be easily achieved using the distinct()
method.
Here is an example:
distinct_df = df %>% distinct(field1)
You can get a vector of the distinct values with:
distinct_vector = distinct_df$field1
You can also select a subset of columns at the same time as you perform the distinct()
call, which can be cleaner to look at if you examine the data frame using head/tail/glimpse.:
distinct_df = df %>% distinct(field1) %>% select(field1)
distinct_vector = distinct_df$field1
You can use a much simpler formula. I just created a new workbook to test it.
Column A = Date1 | Column B = Date2 | Column C = Date3
Highlight Column A and enter the conditional formatting formula:
=AND(A1>B1,A1<C1)
You can do this using list:
new_list = list(fL)
Be aware that any spaces in the line will be included in this list, to the best of my knowledge.
An easy method, use ticks:
new DateTime((DateTime.Now - DateTime.Now.AddHours(-1.55)).Ticks).ToString("HH:mm:ss:fff")
This function will give you a date (Without Day / Month / Year)
There are mainly three types of variables in MySQL:
User-defined variables (prefixed with @
):
You can access any user-defined variable without declaring it or
initializing it. If you refer to a variable that has not been
initialized, it has a value of NULL
and a type of string.
SELECT @var_any_var_name
You can initialize a variable using SET
or SELECT
statement:
SET @start = 1, @finish = 10;
or
SELECT @start := 1, @finish := 10;
SELECT * FROM places WHERE place BETWEEN @start AND @finish;
User variables can be assigned a value from a limited set of data types: integer, decimal, floating-point, binary or nonbinary string, or NULL value.
User-defined variables are session-specific. That is, a user variable defined by one client cannot be seen or used by other clients.
They can be used in SELECT
queries using Advanced MySQL user variable techniques.
Local Variables (no prefix) :
Local variables needs to be declared using DECLARE
before
accessing it.
They can be used as local variables and the input parameters inside a stored procedure:
DELIMITER //
CREATE PROCEDURE sp_test(var1 INT)
BEGIN
DECLARE start INT unsigned DEFAULT 1;
DECLARE finish INT unsigned DEFAULT 10;
SELECT var1, start, finish;
SELECT * FROM places WHERE place BETWEEN start AND finish;
END; //
DELIMITER ;
CALL sp_test(5);
If the DEFAULT
clause is missing, the initial value is NULL
.
The scope of a local variable is the BEGIN ... END
block within
which it is declared.
Server System Variables (prefixed with @@
):
The MySQL server maintains many system variables configured to a default value.
They can be of type GLOBAL
, SESSION
or BOTH
.
Global variables affect the overall operation of the server whereas session variables affect its operation for individual client connections.
To see the current values used by a running server, use the SHOW VARIABLES
statement or SELECT @@var_name
.
SHOW VARIABLES LIKE '%wait_timeout%';
SELECT @@sort_buffer_size;
They can be set at server startup using options on the command line or in an option file.
Most of them can be changed dynamically while the server is running using SET GLOBAL
or SET SESSION
:
-- Syntax to Set value to a Global variable:
SET GLOBAL sort_buffer_size=1000000;
SET @@global.sort_buffer_size=1000000;
-- Syntax to Set value to a Session variable:
SET sort_buffer_size=1000000;
SET SESSION sort_buffer_size=1000000;
SET @@sort_buffer_size=1000000;
SET @@local.sort_buffer_size=10000;
Your code was very close to working.
Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.
Here's some code that writes each key/value pair on a separate row:
import csv
somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
w = csv.writer(f)
w.writerows(somedict.items())
If instead you want all the keys on one row and all the values on the next, that is also easy:
with open('mycsvfile.csv','wb') as f:
w = csv.writer(f)
w.writerow(somedict.keys())
w.writerow(somedict.values())
Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr)
so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f)
.
#div-name
{
background-image: url('../images/background-art-main.jpg');
background-position: top right 50px;
background-repeat: no-repeat;
}
You can use the monitoring program glances with its GPU monitoring plug-in:
sudo apt-get install -y python-pip; sudo pip install glances[gpu]
sudo glances
It also monitors the CPU, disk IO, disk space, network, and a few other things:
We can use the DataFrame.iterrows() function to iterate over each of the rows of the given Dataframe and construct a list out of the data of each row:
# Empty list
row_list =[]
# Iterate over each row
for index, rows in df.iterrows():
# Create list for the current row
my_list =[rows.Date, rows.Event, rows.Cost]
# append the list to the final list
row_list.append(my_list)
# Print
print(row_list)
We can successfully extract each row of the given data frame into a list
As of Bootstrap 4, you can use the spacing utilities.
Add for instance px-2
in the classes of the nav-item
to increase the padding.
Here is an example of processing xpath with vtd-xml... for heavy duty XML processing it is second to none. here is the a recent paper on this subject Processing XML with Java – A Performance Benchmark
import com.ximpleware.*;
public class changeAttrVal {
public static void main(String s[]) throws VTDException,java.io.UnsupportedEncodingException,java.io.IOException{
VTDGen vg = new VTDGen();
if (!vg.parseFile("input.xml", false))
return;
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
XMLModifier xm = new XMLModifier(vn);
ap.selectXPath("/*/place[@id=\"p14\" and @initialMarking=\"2\"]/@initialMarking");
int i=0;
while((i=ap.evalXPath())!=-1){
xm.updateToken(i+1, "499");// change initial marking from 2 to 499
}
xm.output("new.xml");
}
}
It should be like
params.permit(:id => [])
Also since rails version 4+ you can use:
params.permit(id: [])
Two points:
List
is an array. If your memory is heavily fragmented, there may not be enough contiguous space to allocate your List
, even though in total you have plenty of free memory.Figured out a simple and nice way:
>>> df
A B C
one 1 2 3
>>> df.loc["two"] = [4,5,6]
>>> df
A B C
one 1 2 3
two 4 5 6
Note the caveat with performance as noted in the comments
You don't have JSON. You have a JavaScript data structure consisting of objects, an array, some strings and some numbers.
Use JSON.stringify(object)
to turn it into (a string of) JSON text.
Just use MultipleActiveResultSets=True
in your connection string.
You can use the following command:
git reset -- my-file.txt
which will update both the working copy of my-file.txt
when added.
With version 1.7 of the official 10gen driver, this is the current (non-obsolete) API:
const string uri = "mongodb://localhost/mydb";
var client = new MongoClient(uri);
var db = client.GetServer().GetDatabase(new MongoUrl(uri).DatabaseName);
var collection = db.GetCollection("mycollection");
Importing the Single Table
To import a single table into an existing database you would use the following command:
mysql -u username -p -D database_name < tableName.sql
Note:It is better to use full path of the sql file tableName.sql
Python offers a stepping stone into the world of programming. Even though Python Programming Language has been around for 25 years, it is still rising in popularity. Some of the biggest advantage of Python are it's
As a general purpose programming language, Python can be used for multiple things. Python can be easily used for small, large, online and offline projects. The best options for utilizing Python are web development, simple scripting and data analysis. Below are a few examples of what Python will let you do:
Web Development:
You can use Python to create web applications on many levels of complexity. There are many excellent Python web frameworks including, Pyramid, Django and Flask, to name a few.
Data Analysis:
Python is the leading language of choice for many data scientists. Python has grown in popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its superb libraries for data visualisation like Matplotlib and Seaborn.
Machine Learning:
What if you could predict customer satisfaction or analyse what factors will affect household pricing or to predict stocks over the next few days, based on previous years data? There are many wonderful libraries implementing machine learning algorithms such as Scikit-Learn, NLTK and TensorFlow.
Computer Vision:
You can do many interesting things such as Face detection, Color detection while using Opencv and Python.
Internet Of Things With Raspberry Pi:
Raspberry Pi is a very tiny and affordable computer which was developed for education and has gained enormous popularity among hobbyists with do-it-yourself hardware and automation. You can even build a robot and automate your entire home. Raspberry Pi can be used as the brain for your robot in order to perform various actions and/or react to the environment. The coding on a Raspberry Pi can be performed using Python. The Possibilities are endless!
Game Development:
Create a video game using module Pygame. Basically, you use Python to write the logic of the game. PyGame applications can run on Android devices.
Web Scraping:
If you need to grab data from a website but the site does not have an API to expose data, use Python to scraping data.
Writing Scripts:
If you're doing something manually and want to automate repetitive stuff, such as emails, it's not difficult to automate once you know the basics of this language.
Browser Automation:
Perform some neat things such as opening a browser and posting a Facebook status, you can do it with Selenium with Python.
GUI Development:
Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.
Rapid Prototyping:
Python has libraries for just about everything. Use it to quickly built a (lower-performance, often less powerful) prototype. Python is also great for validating ideas or products for established companies and start-ups alike.
Python can be used in so many different projects. If you're a programmer looking for a new language, you want one that is growing in popularity. As a newcomer to programming, Python is the perfect choice for learning quickly and easily.
It's the same as android:typeface
.
built-in fonts are:
See android:typeface.
You could eagerly create the a thread-safe Singleton instance, depending on your application needs, this is succinct code, though I would prefer @andasa's lazy version.
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton() { }
public static Singleton Instance()
{
return instance;
}
}
Why not to use FusedLocationApi
instead of OnMyLocationChangeListener
? You need to initialize GoogleApiClient object and use LocationServices.FusedLocationApi.requestLocationUpdates()
method to register location change listener. It is important to note, that don't forget to remove the registered listener and disconnect GoogleApiClient
.
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private LocationListener mLocationListener;
private void initGoogleApiClient(Context context)
{
mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
{
@Override
public void onConnected(Bundle bundle)
{
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000);
setLocationListener();
}
@Override
public void onConnectionSuspended(int i)
{
Log.i("LOG_TAG", "onConnectionSuspended");
}
}).build();
if (mGoogleApiClient != null)
mGoogleApiClient.connect();
}
private void setLocationListener()
{
mLocationListener = new LocationListener()
{
@Override
public void onLocationChanged(Location location)
{
String lat = String.valueOf(location.getLatitude());
String lon = String.valueOf(location.getLongitude());
Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
}
};
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
}
private void removeLocationListener()
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
}
Use a pattern along these lines:
function getValue(file) {
return lookupValue(file);
}
getValue('myFile.txt').then(function(res) {
// do whatever with res here
});
(although this is a bit redundant, I'm sure your actual code is more complicated)
I agree with Brandrew, the problem is most likely caused by some missing dlls that can't be found neither on the system path nor in the folder where the executable is. Try putting the following DLLs nearby the executable:
Alternatively, try loading the executable into Dependency Walker ( http://www.dependencywalker.com/ ), it should point out the missing dlls for you.
This works to enforce a max of 2 decimal places without automatically rounding to 2 places if the user isn't finished typing.
function naturalRound(e) {
let dec = e.target.value.indexOf(".")
let tooLong = e.target.value.length > dec + 3
let invalidNum = isNaN(parseFloat(e.target.value))
if ((dec >= 0 && tooLong) || invalidNum) {
e.target.value = e.target.value.slice(0, -1)
}
}
You can write your select query as,
select * from table_name where to_char(date_time_column, 'YYYY-MM') = '2011-03';
WARNING: setting this value too high may cause your system to experience a significant hiccup. The higher the value you set, the more virtual memory is allocated to the screen process when initiating the screen session. I set my ~/.screenrc to "defscrollback 123456789" and when I initiated a screen, my entire system froze up for a good 10 minutes before coming back to the point that I was able to kill the screen process (which was consuming 16.6GB of VIRT mem by then).
Try this instead for 'only' scrolling vertical.
(auto scroll needs to be false before it will accept changes)
mypanel.AutoScroll = false;
mypanel.HorizontalScroll.Enabled = false;
mypanel.HorizontalScroll.Visible = false;
mypanel.HorizontalScroll.Maximum = 0;
mypanel.AutoScroll = true;
from the commandline:
chkdsk l: (wait for the scan to finish)
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
base.OnActionExecuting(filterContext);
}
}
[AllowCrossSiteJson]
public ActionResult YourMethod()
{
return Json("Works better?");
}
using System;
using System.Web.Http.Filters;
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Response != null)
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
base.OnActionExecuted(actionExecutedContext);
}
}
[AllowCrossSiteJson]
public class ValuesController : ApiController
{
[AllowCrossSiteJson]
public IEnumerable<PartViewModel> Get()
{
...
}
IE <= 9 doesn't support CORS. I've written a javascript that will automatically route those requests through a proxy. It's all 100% transparent (you just have to include my proxy and the script).
Download it using nuget corsproxy
and follow the included instructions.
$("#example").dataTable(
{
"aoColumnDefs": [{
"bSortable": false,
"aTargets": [0, 1, 2, 3, 4, 5]
}]
}
);
This should get you started:
R> qplot(hwy, cty, data = mpg) +
facet_grid(. ~ manufacturer) +
theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))
See also this question: How can I manipulate the strip text of facet plots in ggplot2?
What about this:
git diff abcdef 123456 | less
It's handy to just pipe it to less if you want to compare many different diffs on the fly.
I've created a clearable textbox in just CSS. It requires no javascript code to make it work
below is the demo link
REST is a software design pattern typically used for web applications. In layman's terms this means that it is a commonly used idea used in many different projects. It stands for REpresentational State Transfer. The basic idea of REST is treating objects on the server-side (as in rows in a database table) as resources than can be created or destroyed.
The most basic way of thinking about REST is as a way of formatting the URLs of your web applications. For example, if your resource was called "posts", then:
/posts
Would be how a user would access ALL the posts, for displaying.
/posts/:id
Would be how a user would access and view an individual post, retrieved based on their unique id.
/posts/new
Would be how you would display a form for creating a new post.
Sending a POST request to /users
would be how you would actually create a new post on the database level.
Sending a PUT request to /users/:id
would be how you would update the attributes of a given post, again identified by a unique id.
Sending a DELETE request to /users/:id
would be how you would delete a given post, again identified by a unique id.
As I understand it, the REST pattern was mainly popularized (for web apps) by the Ruby on Rails framework, which puts a big emphasis on RESTful routes. I could be wrong about that though.
I may not be the most qualified to talk about it, but this is how I've learned it (specifically for Rails development).
When someone refers to a "REST api," generally what they mean is an api that uses RESTful urls for retrieving data.
My simple solution:
$("form").children('input[type="submit"]').click();
It is work for me.
You actually invoked undefined behaviour.
Returning the address of a temporary works, but as temporaries are destroyed at the end of a function the results of accessing them will be undefined.
So you did not modify a
but rather the memory location where a
once was. This difference is very similar to the difference between crashing and not crashing.
for word in d:
if d in paid[j]:
do_something()
will try all the words in the list d
and check if they can be found in the string paid[j]
.
This is not very efficient since paid[j]
has to be scanned again for each word in d
. You could also use two sets, one composed of the words in the sentence, one of your list, and then look at the intersection of the sets.
sentence = "words don't come easy"
d = ["come", "together", "easy", "does", "it"]
s1 = set(sentence.split())
s2 = set(d)
print (s1.intersection(s2))
Output:
{'come', 'easy'}
It's compiler dependent. That said, in general using "
prioritizes headers in the current working directory over system headers. <>
usually is used for system headers. From to the specification (Section 6.10.2):
A preprocessing directive of the form
# include <h-char-sequence> new-line
searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the
<
and>
delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.A preprocessing directive of the form
# include "q-char-sequence" new-line
causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the
"
delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read# include <h-char-sequence> new-line
with the identical contained sequence (including
>
characters, if any) from the original directive.
So on most compilers, using the ""
first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <>
starts the search with system headers.
In case anyone else looking for additional "enter" keypress support, here's an update to the fiddle provided by Gloppy
Code for keypress binding:
elm.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
ngModelCtrl.$setViewValue(elm.val());
});
}
});
We have a Guava class for this: com.google.common.net.MediaType
.
It was released with Guava 12 as stated in the source code and in Issue 823. Sources are available, too.
this is best document I found describing getName(), getSimpleName(), getCanonicalName()
// Primitive type
int.class.getName(); // -> int
int.class.getCanonicalName(); // -> int
int.class.getSimpleName(); // -> int
// Standard class
Integer.class.getName(); // -> java.lang.Integer
Integer.class.getCanonicalName(); // -> java.lang.Integer
Integer.class.getSimpleName(); // -> Integer
// Inner class
Map.Entry.class.getName(); // -> java.util.Map$Entry
Map.Entry.class.getCanonicalName(); // -> java.util.Map.Entry
Map.Entry.class.getSimpleName(); // -> Entry
// Anonymous inner class
Class<?> anonymousInnerClass = new Cloneable() {}.getClass();
anonymousInnerClass.getName(); // -> somepackage.SomeClass$1
anonymousInnerClass.getCanonicalName(); // -> null
anonymousInnerClass.getSimpleName(); // -> // An empty string
// Array of primitives
Class<?> primitiveArrayClass = new int[0].getClass();
primitiveArrayClass.getName(); // -> [I
primitiveArrayClass.getCanonicalName(); // -> int[]
primitiveArrayClass.getSimpleName(); // -> int[]
// Array of objects
Class<?> objectArrayClass = new Integer[0].getClass();
objectArrayClass.getName(); // -> [Ljava.lang.Integer;
objectArrayClass.getCanonicalName(); // -> java.lang.Integer[]
objectArrayClass.getSimpleName(); // -> Integer[]
yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.
so:
>>> def printer(*args):
print args
>>> printer(2,3,4)
(2, 3, 4)
>>> printer(*range(2, 5))
(2, 3, 4)
>>> printer(range(2, 5))
([2, 3, 4],)
>>>
i get the solution. i've using cygwin and this is the problem the rsync command for Windows work only in windows shell and works in the windows powershell.
A few times it has happened the same error between two linux boxes. and appears to be by incompatible versions of rsync
Sure.. Why not?
Abstract base classes are just a convenience to house behavior and data common to 2 or more classes in a single place for efficiency of storage and maintenance. Its an implementation detail.
Take care however that you are not using an abstract base class where you should be using an interface. Refer to Interface vs Base class
The <NAME>
you use in multer's upload.single(<NAME>)
function must be the same as the one you use in <input type="file" name="<NAME>" ...>
.
So you need to change
var type = upload.single('file')
to
var type = upload.single('recfile')
in you app.js
Hope this helps.
And one more....
var _e = $(e.target); // e being the event triggered
var element = _e.parent(); // the element the event was triggered on
console.log("_E " + element.context); // [object HTMLInputElement]
console.log("_E FORM " + element.context.form); // [object HTMLFormElement]
console.log("_E FORM " + element.context.form.id); // form id
@gnarf answer is right . wanted to add more information .
Mozilla Bug Reference : https://bugzilla.mozilla.org/show_bug.cgi?id=627942
Terminate these steps if header is a case-insensitive match for one of the following headers:
Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via
Source : https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader
You can create a session:
import boto3
session = boto3.Session(
aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY,
aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY,
)
Then use that session to get an S3 resource:
s3 = session.resource('s3')
Google has open sourced its excellent PDF rendering engine - PDFium - that it wrote with Foxit Software.
There is a C# nuget package called PdfiumViewer which gives a C# wrapper around PDFium and allows PDFs to be displayed and printed.
I have used it and was very impressed with the quality of the rendering.
PDFium works directly with streams so it doesn't require any data to be written to disk.
This is my example from a WinForms app
public void LoadPdf(byte[] pdfBytes)
{
var stream = new MemoryStream(pdfBytes);
LoadPdf(stream)
}
public void LoadPdf(Stream stream)
{
// Create PDF Document
var pdfDocument = PdfDocument.Load(stream);
// Load PDF Document into WinForms Control
pdfRenderer.Load(pdfDocument);
}
Edit: To get the pdfRenderer control in WinForm: Add the PdfiumViewer
NuGet package to the project; open the projects packages folder in Windows Explorer and drag the PdfiumViewer.dll
file onto the Toolbox
window; A control called PdfRenderer
will be available to add:
You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.
To affect all flex-items of the container, choose this:
You have to set align-items: flex-start;
to div
and all flex-items of this container get the height of their content.
div {_x000D_
align-items: flex-start;_x000D_
background: tan;_x000D_
display: flex;_x000D_
height: 200px;_x000D_
}_x000D_
span {_x000D_
background: red;_x000D_
}
_x000D_
<div>_x000D_
<span>This is some text.</span>_x000D_
</div>
_x000D_
To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start;
to this flex-item. All other flex-items of the container aren't affected.
div {_x000D_
display: flex;_x000D_
height: 200px;_x000D_
background: tan;_x000D_
}_x000D_
span.only {_x000D_
background: red;_x000D_
align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
background:green;_x000D_
}
_x000D_
<div>_x000D_
<span class="only">This is some text.</span>_x000D_
<span>This is more text.</span>_x000D_
</div>
_x000D_
Why is this happening to the span
?
The default value of the property align-items
is stretch
. This is the reason why the span
fill the height of the div
.
Difference between baseline
and flex-start
?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start
the flex-item will be set to the top of the container (without space).
div {_x000D_
align-items: baseline;_x000D_
background: tan;_x000D_
display: flex;_x000D_
height: 200px;_x000D_
}_x000D_
span {_x000D_
background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
<span class="fontsize">This is some text.</span>_x000D_
<span>This is more text.</span>_x000D_
</div>
_x000D_
You can find more information about the difference between
baseline
andflex-start
here:
What's the difference between flex-start and baseline?
For those who are looking for Kotlin
solution to get Bitmap
from ImageView
.
var bitmap = (image.drawable as BitmapDrawable).bitmap
I had the same problem. All i did was - From the pom.xml file i deleted the dependency for junit 3.8 and added a new dependency for junit 4.8. Then i did maven clean and maven install. It did the trick. To verify , after maven install i went project->properties-build path->maven dependencies and saw that now the junit 3.8 jar is gone !, instead junit 4.8 jar is listed. cool!!. Now my test runs like a charm.. Hope this helps somehow..
Here the official link for jdk source. http://www.oracle.com/technetwork/java/javase/downloads/index.html (you may need to scroll to the bottom of the page)
In mathematics, I think the dot in numpy makes more sense
dot(a,b)_{i,j,k,a,b,c} =
since it gives the dot product when a and b are vectors, or the matrix multiplication when a and b are matrices
As for matmul operation in numpy, it consists of parts of dot result, and it can be defined as
So, you can see that matmul(a,b) returns an array with a small shape, which has smaller memory consumption and make more sense in applications. In particular, combining with broadcasting, you can get
matmul(a,b)_{i,j,k,l} =
for example.
From the above two definitions, you can see the requirements to use those two operations. Assume a.shape=(s1,s2,s3,s4) and b.shape=(t1,t2,t3,t4)
To use dot(a,b) you need
To use matmul(a,b) you need
Use the following piece of code to convince yourself.
import numpy as np
for it in xrange(10000):
a = np.random.rand(5,6,2,4)
b = np.random.rand(6,4,3)
c = np.matmul(a,b)
d = np.dot(a,b)
#print 'c shape: ', c.shape,'d shape:', d.shape
for i in range(5):
for j in range(6):
for k in range(2):
for l in range(3):
if not c[i,j,k,l] == d[i,j,k,j,l]:
print it,i,j,k,l,c[i,j,k,l]==d[i,j,k,j,l] #you will not see them
This can happen if you accidentally are not dragging the element that does have an id assigned (for example you are dragging the surrounding element). In that case the ID is empty and the function drag() is assigning an empty value which is then passed to drop() and fails there.
Try assigning the ids to all of your elements, including the tds, divs, or whatever is around your draggable element.
You can use reorder
:
qplot(reorder(factor(cyl),factor(cyl),length),data=mtcars,geom="bar")
Edit:
To have the tallest bar at the left, you have to use a bit of a kludge:
qplot(reorder(factor(cyl),factor(cyl),function(x) length(x)*-1),
data=mtcars,geom="bar")
I would expect this to also have negative heights, but it doesn't, so it works!
scala> val list = List(1,2,4,2,4,7,3,2,4)
list: List[Int] = List(1, 2, 4, 2, 4, 7, 3, 2, 4)
scala> println(list.filter(_ == 2).size)
3
OK it's 2019 now, and from Java 11 you have a constructor with Charset:
FileWriter?(String fileName, Charset charset)
Unfortunately, we still cannot modify the byte buffer size, and it's set to 8192. (https://www.baeldung.com/java-filewriter)