If you want to use raw python rather than numpy or panda, you can use the python stats module to find the median of the upper and lower half of the list:
>>> import statistics as stat
>>> def quartile(data):
data.sort()
half_list = int(len(data)//2)
upper_quartile = stat.median(data[-half_list]
lower_quartile = stat.median(data[:half_list])
print("Lower Quartile: "+str(lower_quartile))
print("Upper Quartile: "+str(upper_quartile))
print("Interquartile Range: "+str(upper_quartile-lower_quartile)
>>> quartile(df.time_diff)
Line 1: import the statistics module under the alias "stat"
Line 2: define the quartile function
Line 3: sort the data into ascending order
Line 4: get the length of half of the list
Line 5: get the median of the lower half of the list
Line 6: get the median of the upper half of the list
Line 7: print the lower quartile
Line 8: print the upper quartile
Line 9: print the interquartile range
Line 10: run the quartile function for the time_diff column of the DataFrame
If the colspan
or rowspan
is all set to 1
, counting the children td
s will give the correct answer. However, if there are spans, we cannot count the number of columns exactly, even by the maximum number of td
s of the rows. Consider the following example:
var mytable = document.getElementById('table')_x000D_
for (var i=0; i < mytable.rows.length; ++i) {_x000D_
document.write(mytable.rows[i].cells.length + "<br>");_x000D_
}
_x000D_
table, th, td {_x000D_
border: 1px solid black;_x000D_
border-collapse: collapse;_x000D_
padding: 3px;_x000D_
}
_x000D_
<table id="table">_x000D_
<thead>_x000D_
<tr>_x000D_
<th colspan="2">Header</th>_x000D_
<th rowspan="2">Hi</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Month</th>_x000D_
<th>Savings</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td colspan="2">hello</td>_x000D_
<td>world</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>hello</td>_x000D_
<td colspan="2">again</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
The previous explanations are all overly detailed and complicated IMO. Put simply, OAuth 2 delegates security to the HTTPS protocol. OAuth 1 did not require this and consequentially had alternative methods to deal with various attacks. These methods required the application to engage in certain security protocols which are complicated and can be difficult to implement. Therefore, it is simpler to just rely on the HTTPS for security so that application developers dont need to worry about it.
As to your other questions, the answer depends. Some services dont want to require the use of HTTPS, were developed before OAuth 2, or have some other requirement which may prevent them from using OAuth 2. Furthermore, there has been a lot of debate about the OAuth 2 protocol itself. As you can see, Facebook, Google, and a few others each have slightly varying versions of the protocols implemented. So some people stick with OAuth 1 because it is more uniform across the different platforms. Recently, the OAuth 2 protocol has been finalized but we have yet to see how its adoption will take.
For those coming here from Google, and for whom the previous answers do not solve the mystery...
If you use XHR to make a server call, but do not return a response, this error will occur.
Example (from Nodejs/React but could equally be js/php):
App.tsx
const handleClickEvent = () => {
fetch('/routeInAppjs?someVar=someValue&nutherVar=summat_else', {
method: 'GET',
mode: 'same-origin',
credentials: 'include',
headers: {
'content-type': 'application/json',
dataType: 'json',
},
}).then((response) => {
console.log(response)
});
}
App.js
app.route('/getAllPublicDatasheets').get(async function (req, res) {
const { someVar, nutherVar } = req.query;
console.log('Ending here without a return...')
});
Console.log will here report:
Failed to show response data
To fix, add the return response to bottom of your route (server-side):
res.json('Adding this below the console.log in App.js route will solve it.');
Just wrap the float, boolean, int or similar in an NSNumber.
For structs, I don't know of a handy solution, but you could make a separate ObjC class that owns such a struct.
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int mSec = calendar.get(Calendar.MILLISECOND);
$("input[name='mygroup'][value='5']").attr("checked", true);
ok, that was my very stupid mistake. I post the answer here just in case someone has the same problem.
The correct path for files stored in assets folder is file:///android_asset/*
(with no "s" for assets folder which i was always thinking it must have a "s").
And, mWebView.loadUrl("file:///android_asset/myfile.html");
works under all API levels.
I still not figure out why mWebView.loadUrl("file:///android_res/raw/myfile.html");
works only on API level 8. But it doesn't matter now.
(Similar to Doin idea) To show what is being matched, I use this code
$keys = array_keys($_GET);
foreach($keys as $i=>$key){
echo "$i => $key <br>";
}
Save it to r.php on the server root and then do some tests in .htaccess
For example, i want to match urls that do not start with a language prefix
RewriteRule ^(?!(en|de)/)(.*)$ /r.php?$1&$2 [L] #$1&$2&...
RewriteRule ^(.*)$ /r.php?nomatch [L] #report nomatch and exit
POSIX SED:
$ - match last line
{ COMMANDS } - A group of commands may be enclosed between { and } characters. This is particularly useful when you want a group of commands to be triggered by a single address (or address-range) match.
Please note this doesn't solve the cookie sharing process, as in general this is bad practice.
You need to be using JSONP as your type:
From $.ajax documentation: Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.
$.ajax(
{
type: "POST",
url: "http://example.com/api/getlist.json",
dataType: 'jsonp',
xhrFields: {
withCredentials: true
},
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Cookie", "session=xxxyyyzzz");
},
success: function(){
alert('success');
},
error: function (xhr) {
alert(xhr.responseText);
}
}
);
JObjects can be enumerated via JProperty objects by casting it to a JToken:
foreach (JProperty x in (JToken)obj) { // if 'obj' is a JObject
string name = x.Name;
JToken value = x.Value;
}
If you have a nested JObject inside of another JObject, you don't need to cast because the accessor will return a JToken:
foreach (JProperty x in obj["otherObject"]) { // Where 'obj' and 'obj["otherObject"]' are both JObjects
string name = x.Name;
JToken value = x.Value;
}
you have to use the To_Date() function to convert the string to date ! http://www.techonthenet.com/oracle/functions/to_date.php
You could always use "%p" in order to display 8 bit hex numbers.
int main (void)
{
uint8_t a;
uint32_t b;
a=15;
b=a<<28;
printf("%p", b);
return 0;
}
Output:
0xf0000000
You should use 'title' attribute along with 'data-toogle' (bootstrap).
For example
<i class="fa fa-info" data-toggle="tooltip" title="Hooray!"></i>Hover over me
and do not forget to add the javascript to display the tooltip
<script>
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script>
The following worked for me:
ForceCursor = true;
Cursor = Cursors.Wait;
The seamless
attribute no longer exists. It was originally pitched to be included in the first HTML5 spec, but subsequently dropped. An unrelated attribute of the same name made a brief cameo in the HTML5.1 draft, but that too was ditched mid-2016:
So I think the gist of it all both from the implementor side and the web-dev side is that
seamless
as-specced doesn’t seem to be what anybody wanted to begin with. Or at least it’s more than anybody actually wanted. And anyway like @annevk says, it’s seems a lot of it’s since been “overcome by events” in light of Shadow DOM.
In other words: purge the seamless
attribute from your memory, and pretend it never existed.
For posterity's sake, here's my original answer from five years ago:
The attribute is in draft mode at the moment. For that reason, none of the current browsers are supporting it yet (as the implementation is subject to change). In the meantime, it's best just to use CSS to strip the borders/scrollbars from the iframe:
iframe[seamless]{
background-color: transparent;
border: 0px none transparent;
padding: 0px;
overflow: hidden;
}
There's more to the seamless attribute than what can be added with CSS: part of the reasoning behind the attribute was to allow nested content to inherit the same styles applied to the iframe (acting as though the embedded document was one big nested inside the element, for example).
Lastly, versions of Internet Explorer (8 and earlier) require additional attributes in order to remove the borders, scrollbars and background colour:
<iframe frameborder="0" allowtransparency="true" scrolling="no" src="..."></iframe>
Naturally, this doesn't validate. So it's up to you how to handle it. My (picky) approach would be to sniff the agent string and add the attributes for IE versions earlier than 9.
Hope that helps. :)
None of the other answers were "sticking" for me in RHEL 7, even setting JAVA_HOME
and PATH
directly in /etc/profile
or ~/.bash_profile
would not work. Each time I tried to check if JAVA_HOME
was set, it would come up blank:
$ echo $JAVA_HOME
(<-- no output)
What I had to do was set up a script in /etc/profile.d/jdk_home.sh
:
#!/bin/sh
export JAVA_HOME=/opt/ibm/java-x86_64-60/
export PATH=$JAVA_HOME/bin:$PATH
I initially neglected the first line (the #!/bin/sh
), and it won't work without it.
Now it's working:
$ echo $JAVA_HOME
/opt/ibm/java-x86_64-60/
Thanks for the solution !
It works, but in a french Excel environment, you should apply something like
TEXTE(F2;"jj/mm/aaaa")
to get the date preserved as it is displayed in F2 cell, after concatenation. Best Regards
You have set your %JAVA_HOME
to jdk 1.7, but you are trying to compile using 1.8. Install jdk 1.8 and make sure your %JAVA_HOME
points to that or drop the target release to 1.7.
invalid target release: 1.8
The target release refers to the jdk version.
If you want the entire package name with it, call:
String name = MyClass.class.getCanonicalName();
If you only want the last element, call:
String name = MyClass.class.getSimpleName();
if you have GNU date and i understood you correctly
$ date +%Y:%m:%d -d "yesterday"
2009:11:09
or
$ date +%Y:%m:%d -d "1 day ago"
2009:11:09
Unlike proposed by Nicolas, the meta
tag isn’t actually ignored by the browsers. However, the Content-Type
HTTP header always has precedence over the presence of a meta
tag in the document.
So make sure that you either send the correct encoding via the HTTP header, or don’t send this HTTP header at all (not recommended). The meta
tag is mainly a fallback option for local documents which aren’t sent via HTTP traffic.
Using HTML entities should also be considered a workaround – that’s tiptoeing around the real problem. Configuring the web server properly prevents a lot of nuisance.
Here is couple of ways to calculate length of variable :
echo ${#VAR}
echo -n $VAR | wc -m
echo -n $VAR | wc -c
printf $VAR | wc -m
expr length $VAR
expr $VAR : '.*'
and to set the result in another variable just assign above command with back quote into another variable as following:
otherVar=`echo -n $VAR | wc -m`
echo $otherVar
http://techopsbook.blogspot.in/2017/09/how-to-find-length-of-string-variable.html
You can loop through keys like this:
for (var key in data) {
console.log(key);
}
This logs "Name" and "Value".
If you have a more complex object type (not just a plain hash-like object, as in the original question), you'll want to only loop through keys that belong to the object itself, as opposed to keys on the object's prototype:
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(key);
}
}
As you noted, keys are not guaranteed to be in any particular order. Note how this differs from the following:
for each (var value in data) {
console.log(value);
}
This example loops through values, so it would log Property Name
and 0
. N.B.: The for each
syntax is mostly only supported in Firefox, but not in other browsers.
If your target browsers support ES5, or your site includes es5-shim.js
(recommended), you can also use Object.keys
:
var data = { Name: 'Property Name', Value: '0' };
console.log(Object.keys(data)); // => ["Name", "Value"]
and loop with Array.prototype.forEach
:
Object.keys(data).forEach(function (key) {
console.log(data[key]);
});
// => Logs "Property Name", 0
For me the issue was in Resharper License. It has been delinked from my account for some reason and it said that the license is invalid. When I linked it again to my JetBrains account it started to work properly after a few minutes.
Two comments:
and
and or
for logical operations in Python.If you are trying to transform a naive datetime into a datetime with timezone in django, here is my solution:
>>> import datetime
>>> from django.utils import timezone
>>> t1 = datetime.datetime.strptime("2019-07-16 22:24:00", "%Y-%m-%d %H:%M:%S")
>>> t1
datetime.datetime(2019, 7, 16, 22, 24)
>>> current_tz = timezone.get_current_timezone()
>>> t2 = current_tz.localize(t1)
>>> t2
datetime.datetime(2019, 7, 16, 22, 24, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)
>>>
t1 is a naive datetime and t2 is a datetime with timezone in django's settings.
While yourTextField.requestFocus()
is A solution, it is not the best since in the official Java documentation this is discourage as the method requestFocus()
is platform dependent.
The documentation says:
Note that the use of this method is discouraged because its behavior is platform dependent. Instead we recommend the use of requestFocusInWindow().
Use yourJTextField.requestFocusInWindow()
instead.
Just to add
KILL QUERY **Id**
where Id is connection id from show processlist
is more preferable if you are do not want to kill the connection usually when running from some application.
For more details you can read mysql doc here
ADT is a set of objects and operations, no where in an ADT’s definitions is there any mention of how the set of operations is implemented. Programmers who use collections only need to know how to instantiate and access data in some pre-determined manner, without concerns for the details of the collections implementations. In other words, from a user’s perspective, a collection is an abstraction, and for this reason, in computer science, some collections are referred to as abstract data types (ADTs). The user is only concern with learning its interface, or the set of operations its performs...more
I have placed here complete bins for above query. you can check demo link too.
Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop
HTML
<div id="panel">
<input type="button" class="button" value="1" id="btn1">
<input type="button" class="button" value="2" id="btn2">
<input type="button" class="button" value="3" id="btn3">
<br>
<input type="text" id="valueFromMyModal">
<!-- Dialog Box-->
<div class="dialog" id="myform">
<form>
<label id="valueFromMyButton">
</label>
<input type="text" id="name">
<div align="center">
<input type="button" value="Ok" id="btnOK">
</div>
</form>
</div>
</div>
JQuery
$(function() {
$(".button").click(function() {
$("#myform #valueFromMyButton").text($(this).val().trim());
$("#myform input[type=text]").val('');
$("#myform").show(500);
});
$("#btnOK").click(function() {
$("#valueFromMyModal").val($("#myform input[type=text]").val().trim());
$("#myform").hide(400);
});
});
CSS
.button{
border:1px solid #333;
background:#6479fd;
}
.button:hover{
background:#a4a9fd;
}
.dialog{
border:5px solid #666;
padding:10px;
background:#3A3A3A;
position:absolute;
display:none;
}
.dialog label{
display:inline-block;
color:#cecece;
}
input[type=text]{
border:1px solid #333;
display:inline-block;
margin:5px;
}
#btnOK{
border:1px solid #000;
background:#ff9999;
margin:5px;
}
#btnOK:hover{
border:1px solid #000;
background:#ffacac;
}
Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop
This is also possible with Notepad++:
Check Bookmark line (if there is no Mark tab update to the current version).
Enter your search term and click Mark All
Now go to the menu Search → Bookmark → Remove Bookmarked lines
Done.
You can also use the jQuery JavaScript framework:
To Hide Div Block
$(".divIDClass").hide();
To show Div Block
$(".divIDClass").show();
Simple answer: You can't. An array is fixed size in Java. You'll want to use a List<String>
.
Alternatively, you could create an array of fixed size and put things in it:
String[] array = new String[2];
array[0] = "Hello";
array[1] = "World!";
When I've done this, rather than fiddling the original migration, I create a new one with just the add column in the up section and a drop column in the down section.
You can change the original and rerun it if you migrate down between, but in this case I think that's made a migration that won't work properly.
As currently posted, you're adding the column and then creating the table.
If you change the order it might work. Or, as you're modifying an existing migration, just add it to the create table instead of doing a separate add column.
Rich86Man's answer is correct, but you can use categories to proxy properties such as layer.borderColor. (From the ConventionalC CocoaPod)
CALayer+XibConfiguration.h:
#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>
@interface CALayer(XibConfiguration)
// This assigns a CGColor to borderColor.
@property(nonatomic, assign) UIColor* borderUIColor;
@end
CALayer+XibConfiguration.m:
#import "CALayer+XibConfiguration.h"
@implementation CALayer(XibConfiguration)
-(void)setBorderUIColor:(UIColor*)color
{
self.borderColor = color.CGColor;
}
-(UIColor*)borderUIColor
{
return [UIColor colorWithCGColor:self.borderColor];
}
@end
layer.borderUIColor
The result will be apparent during runtime, not in Xcode.
Edit: You also need to set layer.borderWidth
to at least 1 to see the border with the chosen color.
In Swift 2.0:
extension CALayer {
var borderUIColor: UIColor {
set {
self.borderColor = newValue.CGColor
}
get {
return UIColor(CGColor: self.borderColor!)
}
}
}
In Swift 3.0:
extension CALayer {
var borderUIColor: UIColor {
set {
self.borderColor = newValue.cgColor
}
get {
return UIColor(cgColor: self.borderColor!)
}
}
}
JGraph from http://mmengineer.blogspot.com/2009/10/java-graph-floyd-class.html
Provides a powerfull software to work with graphs (direct or undirect). Also generates Graphivz code, you can see graphics representations. You can put your own code algorithms into pakage, for example: backtracking code. The package provide some algorithms: Dijkstra, backtracking minimun path cost, ect..
you might use default parameters in your function and then just pass the entire dataset itself, since the dataset is already a DOMStringMap Object
<div data-uid="aaa" data-name="bbb" data-value="ccc"
onclick="fun(this.dataset)">
<script>
const fun = ({uid:'ddd', name:'eee', value:'fff', other:'default'} = {}) {
//
}
</script>
that way, you can deal with any data-values that got set in the html tag, or use defaults if they weren't set - that kind of thing
maybe not in this situation, but in others, it might be advantageous to put all your preferences in a single data-attribute
<div data-all='{"uid":"aaa","name":"bbb","value":"ccc"}'
onclick="fun(JSON.parse(this.dataset.all))">
there are probably more terse ways of doing that, if you already know certain things about the order of the data
<div data-all="aaa,bbb,ccc" onclick="fun(this.dataset.all.split(','))">
I don't suggest you just hidding the stricts errors on your project. Intead, you should turn your method to static or try to creat a new instance of the object:
$var = new YourClass();
$var->method();
You can also use the new way to do the same since PHP 5.4:
(new YourClass)->method();
I hope it helps you!
You can use either - which means most people opt for "+" as it's more human readable.
If you're trying to use this on Cygwin, then you need to follow the instructions in this answer. (It's a problem how Cygwin treats Windows symlinks.)
As others have stated, you shouldn't have the same ID more than once in your HTML, however... elements with an ID are attached to the document object and to window on Internet Explorer. Refer to:
Do DOM tree elements with ids become global variables?
If more than one element with the same ID exists in your HTML, this property is attached as an array. I'm sorry, but I don't know where to look if this is the standard behavior or at least you get the same behavior between browsers, which I doubt.
2019 June answer
Great news! It seems that the @angular/cdk package now has first-class support for portals!
As of the time of writing, I didn't find the above official docs particularly helpful (particularly with regard to sending data into and receiving events from the dynamic components). In summary, you will need to:
Step 1) Update your AppModule
Import PortalModule
from the @angular/cdk/portal
package and register your dynamic component(s) inside entryComponents
@NgModule({
declarations: [ ..., AppComponent, MyDynamicComponent, ... ]
imports: [ ..., PortalModule, ... ],
entryComponents: [ ..., MyDynamicComponent, ... ]
})
export class AppModule { }
Step 2. Option A: If you do NOT need to pass data into and receive events from your dynamic components:
@Component({
selector: 'my-app',
template: `
<button (click)="onClickAddChild()">Click to add child component</button>
<ng-template [cdkPortalOutlet]="myPortal"></ng-template>
`
})
export class AppComponent {
myPortal: ComponentPortal<any>;
onClickAddChild() {
this.myPortal = new ComponentPortal(MyDynamicComponent);
}
}
@Component({
selector: 'app-child',
template: `<p>I am a child.</p>`
})
export class MyDynamicComponent{
}
Step 2. Option B: If you DO need to pass data into and receive events from your dynamic components:
// A bit of boilerplate here. Recommend putting this function in a utils
// file in order to keep your component code a little cleaner.
function createDomPortalHost(elRef: ElementRef, injector: Injector) {
return new DomPortalHost(
elRef.nativeElement,
injector.get(ComponentFactoryResolver),
injector.get(ApplicationRef),
injector
);
}
@Component({
selector: 'my-app',
template: `
<button (click)="onClickAddChild()">Click to add random child component</button>
<div #portalHost></div>
`
})
export class AppComponent {
portalHost: DomPortalHost;
@ViewChild('portalHost') elRef: ElementRef;
constructor(readonly injector: Injector) {
}
ngOnInit() {
this.portalHost = createDomPortalHost(this.elRef, this.injector);
}
onClickAddChild() {
const myPortal = new ComponentPortal(MyDynamicComponent);
const componentRef = this.portalHost.attach(myPortal);
setTimeout(() => componentRef.instance.myInput
= '> This is data passed from AppComponent <', 1000);
// ... if we had an output called 'myOutput' in a child component,
// this is how we would receive events...
// this.componentRef.instance.myOutput.subscribe(() => ...);
}
}
@Component({
selector: 'app-child',
template: `<p>I am a child. <strong>{{myInput}}</strong></p>`
})
export class MyDynamicComponent {
@Input() myInput = '';
}
listview.setOnItemClickListener(new OnItemClickListener(){
//setting onclick to items in the listview.
@Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
Intent intent;
switch(position){
// case 0 is the first item in the listView.
case 0:
intent = new Intent(Activity.this,firstActivity.class);
break;
//case 1 is the second item in the listView.
case 1:
intent = new Intent(Activity.this,secondActivity.class);
break;
case 2:
intent = new Intent(Activity.this,thirdActivity.class);
break;
//add more if you have more items in listView
startActivity(intent);
}
});
You can grant system privileges with or without the admin option. The default being without admin option.
GRANT CREATE SESSION TO username
or with admin option:
GRANT CREATE SESSION TO username WITH ADMIN OPTION
The Grantee with the ADMIN OPTION
can grant and revoke privileges to other users
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
I know this is years later but I ran into the same problem. The solution I found was to change the window title in main.cpp. I guess once the w.show();
is called the window title can no longer be changed. In my case I just wanted the title to reflect the current directory and it works.
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.setWindowTitle(QDir::currentPath());
w.show();
return a.exec();
}
Here is an example that I used.
<script>
$(document).ready(function(){
var array = $.makeArray(document.getElementsByTagName(“p”));
array.reverse();
$(array).appendTo(document.body);
});
</script>
Maybe you can try the following without XPath
from simplified_scrapy.simplified_doc import SimplifiedDoc
html = '''
<html>
<body>
<div>
<h1>Example Domain</h1>
<p>This domain is for use in illustrative examples in documents. You may use this
domain in literature without prior coordination or asking for permission.</p>
<p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>
'''
# What XPath can do, so can it
doc = SimplifiedDoc(html)
# The result is the same as doc.getElementByTag('body').getElementByTag('div').getElementByTag('h1').text
print (doc.body.div.h1.text)
print (doc.div.h1.text)
print (doc.h1.text) # Shorter paths will be faster
print (doc.div.getChildren())
print (doc.div.getChildren('p'))
Is there a method equivalent to getJSONArray in org.json so that I have proper error handling in case it isn't an array?
It depends on your input; i.e. the stuff you fetch from the URL. If the value of the "datasets" attribute is an associative array rather than a plain array, you will get a ClassCastException
.
But then again, the correctness of your old version also depends on the input. In the situation where your new version throws a ClassCastException
, the old version will throw JSONException
. Reference: http://www.json.org/javadoc/org/json/JSONObject.html#getJSONArray(java.lang.String)
The communication link between the driver and the data source to which the driver was attempting to connect failed before the function completed processing. So usually its a network error. This could be caused by packet drops or badly configured Firewall/Switch.
CSS3 object-fit
Am not sure how far its been implemented by webkit, IE and firefox. But Opera works like magic
object-fit
works with SVG content, but the same effect can also be achieved by setting thepreserveAspectRatio=""
attribute in the SVG itself.
img {
height: 100px;
width: 100px;
-o-object-fit: contain;
}
Chris Mills demo's it here http://dev.opera.com/articles/view/css3-object-fit-object-position/
The answer by @AKX works on the command line, but not within a batch file. Within a batch file, you need an extra %
, like this:
@echo off
for /R TutorialSteps %%F in (*.py) do echo %%~nF
I use buffers like tabs, using the BufExplorer plugin and a few macros:
" CTRL+b opens the buffer list
map <C-b> <esc>:BufExplorer<cr>
" gz in command mode closes the current buffer
map gz :bdelete<cr>
" g[bB] in command mode switch to the next/prev. buffer
map gb :bnext<cr>
map gB :bprev<cr>
With BufExplorer you don't have a tab bar at the top, but on the other hand it saves space on your screen, plus you can have an infinite number of files/buffers open and the buffer list is searchable...
Simply you cannot do it with FF3.
The other option could be using applet or other controls to select and upload files.
This is a one line solution involving LINQ.
var elements = new String[] { "1", "2", "3" };
Foo(elements.Cast<object>().ToArray())
jQuery UI has it's own elements, but jQuery alone hasn't.
Working example:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Dialog - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
</head>
<body>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
</body>
</html>
Timeout expired because the sql query is taking more time than you set in sqlCommand.CommandTimeout property.
Obviously you can increase CommandTimeout to solve this issue but before doing that you must optimize your query by adding index. If you run your query in Sql server management studio including actual execution plan then Sql server management studio will suggest you proper index. Most of the case you will get rid of timeout issue if you can optimize your query.
if you know what unknown is,
you can do something like
myArray = zeros(2,2);
for i: 1:unknown
myArray(:,i) = zeros(x,y);
end
However it has been a while since I last used matlab. so this page might shed some light on the matter :
$http is a promise too, you can make it simpler:
return $q.all(tasks.map(function(d){
return $http.post('upload/tasks',d).then(someProcessCallback, onErrorCallback);
}));
' i modify the code for Datatable
For Each c as DataColumn in dt.Columns
For j=0 To _dataTable.Columns.Count-1
xlWorksheet.Cells (i+1, j+1) = _dataTable.Columns(j).ColumnName
Next
Next
Hope this could be help!
The for
attribute shows that this label stands for related input field, or check box or radio button or any other data entering field associated with it.
for example
<li>
<label>{translate:blindcopy}</label>
<a class="" href="#" title="{translate:savetemplate}" onclick="" ><i class="fa fa-list" class="button" ></i></a>  
<input type="text" id="BlindCopy" name="BlindCopy" class="splitblindcopy" />
</li>
additionally you can just write
if(stop)
{
sb.append("y");
getWhoozitYs();
}
stack size can indeed be unlimited. _STK_LIM
is the default, _STK_LIM_MAX
is something that differs per architecture, as can be seen from include/asm-generic/resource.h
:
/*
* RLIMIT_STACK default maximum - some architectures override it:
*/
#ifndef _STK_LIM_MAX
# define _STK_LIM_MAX RLIM_INFINITY
#endif
As can be seen from this example generic value is infinite, where RLIM_INFINITY
is, again, in generic case defined as:
/*
* SuS says limits have to be unsigned.
* Which makes a ton more sense anyway.
*
* Some architectures override this (for compatibility reasons):
*/
#ifndef RLIM_INFINITY
# define RLIM_INFINITY (~0UL)
#endif
So I guess the real answer is - stack size CAN be limited by some architecture, then unlimited stack trace will mean whatever _STK_LIM_MAX
is defined to, and in case it's infinity - it is infinite. For details on what it means to set it to infinite and what implications it might have, refer to the other answer, it's way better than mine.
Yes you can sort using query method in Spring Data.
Ex:ascending order or descending order by using the value of the id field.
Code:
public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
public findAllByOrderByIdAsc();
}
alternative solution:
@Repository
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDAO studentDao;
@Override
public List<Student> findAll() {
return studentDao.findAll(orderByIdAsc());
}
private Sort orderByIdAsc() {
return new Sort(Sort.Direction.ASC, "id")
.and(new Sort(Sort.Direction.ASC, "name"));
}
}
Spring Data Sorting: Sorting
If you want a list with a predefined size you can also use:
List<Integer> arr = Arrays.asList(new Integer[10]);
Just for the fun, I'm offering an alternative solution using jOOQ and Java 8. Instead of using jOOQ, you could be using any other API that maps JDBC ResultSet
to List
, such as Spring JDBC or Apache DbUtils, or write your own ResultSetIterator
:
List<Object> list =
DSL.using(connection)
.fetch("SELECT col1, col2, col3, ...")
.stream()
.flatMap(r -> Arrays.stream(r.intoArray()))
.collect(Collectors.toList());
List<Object> list =
DSL.using(connection)
.fetch("SELECT col1, col2, col3, ...")
.stream()
.flatMap(Record::intoStream)
.collect(Collectors.toList());
(Disclaimer, I work for the company behind jOOQ)
If you are looking for a pure vanilla javascript method, you can also use:
document.createRange().selectNodeContents( element );
This will select all the text and is supported by all major browsers.
To trigger the selection on focus, you just need to add the event listener like so:
document.querySelector( element ).addEventListener( 'focusin', function () {
document.createRange().selectNodeContents( this );
} );
If you want to place it inline in your HTML, then you can do this:
<input type="text" name="myElement" onFocus="document.createRange().selectNodeContents(this)'" value="Some text to select" />
This is just another option. There appears to be a few ways of doing this. (document.execCommand("selectall") as mentioned here as well)
document.querySelector('#myElement1').addEventListener('focusin', function() {
document.createRange().selectNodeContents(this);
});
_x000D_
<p>Cicking inside field will not trigger the selection, but tabbing into the fields will.</p>
<label for="">JS File Example<label><br>
<input id="myElement1" value="This is some text" /><br>
<br>
<label for="">Inline example</label><br>
<input id="myElement2" value="This also is some text" onfocus="document.createRange().selectNodeContents( this );" />
_x000D_
File.Create returns a FileStream. You need to close that when you have written to the file:
using (FileStream fs = File.Create(path, 1024))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
You can use using for automatically closing the file.
There are many ways. Here are at least five:
/*
* An example of converting std::string to (const)char* using five
* different methods. Error checking is emitted for simplicity.
*
* Compile and run example (using gcc on Unix-like systems):
*
* $ g++ -Wall -pedantic -o test ./test.cpp
* $ ./test
* Original string (0x7fe3294039f8): hello
* s1 (0x7fe3294039f8): hello
* s2 (0x7fff5dce3a10): hello
* s3 (0x7fe3294000e0): hello
* s4 (0x7fe329403a00): hello
* s5 (0x7fe329403a10): hello
*/
#include <alloca.h>
#include <string>
#include <cstring>
int main()
{
std::string s0;
const char *s1;
char *s2;
char *s3;
char *s4;
char *s5;
// This is the initial C++ string.
s0 = "hello";
// Method #1: Just use "c_str()" method to obtain a pointer to a
// null-terminated C string stored in std::string object.
// Be careful though because when `s0` goes out of scope, s1 points
// to a non-valid memory.
s1 = s0.c_str();
// Method #2: Allocate memory on stack and copy the contents of the
// original string. Keep in mind that once a current function returns,
// the memory is invalidated.
s2 = (char *)alloca(s0.size() + 1);
memcpy(s2, s0.c_str(), s0.size() + 1);
// Method #3: Allocate memory dynamically and copy the content of the
// original string. The memory will be valid until you explicitly
// release it using "free". Forgetting to release it results in memory
// leak.
s3 = (char *)malloc(s0.size() + 1);
memcpy(s3, s0.c_str(), s0.size() + 1);
// Method #4: Same as method #3, but using C++ new/delete operators.
s4 = new char[s0.size() + 1];
memcpy(s4, s0.c_str(), s0.size() + 1);
// Method #5: Same as 3 but a bit less efficient..
s5 = strdup(s0.c_str());
// Print those strings.
printf("Original string (%p): %s\n", s0.c_str(), s0.c_str());
printf("s1 (%p): %s\n", s1, s1);
printf("s2 (%p): %s\n", s2, s2);
printf("s3 (%p): %s\n", s3, s3);
printf("s4 (%p): %s\n", s4, s4);
printf("s5 (%p): %s\n", s5, s5);
// Release memory...
free(s3);
delete [] s4;
free(s5);
}
from: Outline effect to text
.strokeme
{
color: white;
text-shadow:
-1px -1px 0 #000,
1px -1px 0 #000,
-1px 1px 0 #000,
1px 1px 0 #000;
}
XSD Diagram is free (GNU open license), doesn't need to be built, and gives an interactive diagram. You just open the file and Add the types you want on the (initially blank) diagram. Pretty straight forward.
In HTML5, the easiest, and fastest, way to center your <th>THcontent</th>
is to add a colspan
like this:
<th colspan="3">Thcontent</th>
This will work if your table is three columns. So if you have a four-column table, add a colspan
of 4, etc.
You can manage the location furthermore in the CSS file while you have put your colspan
in HTML like I said.
th {
text-align: center; /* Or right or left */
}
Use MySQL's STR_TO_DATE()
function to parse the string that you're attempting to insert:
INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
(STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))
This will help
wget -m -np -c --level 0 --no-check-certificate -R"index.html*"http://www.your-websitepage.com/dir
You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015
> 01/02/2016
because 09
> 01
. You need to either put your date in a comparable string format or compare DateTime
objects which are comparable.
<?php
$date_now = date("Y-m-d"); // this format is string comparable
if ($date_now > '2016-01-02') {
echo 'greater than';
}else{
echo 'Less than';
}
Or
<?php
$date_now = new DateTime();
$date2 = new DateTime("01/02/2016");
if ($date_now > $date2) {
echo 'greater than';
}else{
echo 'Less than';
}
if you want to open incognito window, put the command below:
start chrome /incognito
Assuming your "states" collection is like:
{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }
The query to find states with null cities would be:
db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});
It is a common mistake to query for nulls as:
db.states.find({"cities.name" : null});
because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.
Plotly's R API might be useful for you. The graph below is here.
library(plotly)
#add username and key
p <- plotly(username="Username", key="API_KEY")
#generate data
x0 = rnorm(500)
x1 = rnorm(500)+1
#arrange your graph
data0 = list(x=x0,
name = "Carrots",
type='histogramx',
opacity = 0.8)
data1 = list(x=x1,
name = "Cukes",
type='histogramx',
opacity = 0.8)
#specify type as 'overlay'
layout <- list(barmode='overlay',
plot_bgcolor = 'rgba(249,249,251,.85)')
#format response, and use 'browseURL' to open graph tab in your browser.
response = p$plotly(data0, data1, kwargs=list(layout=layout))
url = response$url
filename = response$filename
browseURL(response$url)
Full disclosure: I'm on the team.
I like the Apache Commons IO library. Take a look at its version of ByteArrayOutputStream, which has a toString(String enc)
method as well as toByteArray()
. Using existing and trusted components like the Commons project lets your code be smaller and easier to extend and repurpose.
Here, Environment.NewLine doesn't worked.
I put a "<br/>" in a string and worked.
Ex:
ltrYourLiteral.Text = "First line.<br/>Second Line.";
To see all keys of Jsonobject use this
String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";
JSONObject obj = new JSONObject(JSON);
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
System.out.pritnln(key);
}
Assuming that you want different names for the tables.
If you are using PHPmyadmin you can use their SQL option in the menu. Then you simply copy the SQL-code from the first table and paste it into the new table.
That worked out for me when I was moving from localhost to a webhost. Hope it works for you!
You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.
I am not convinced to expose security/config keys to client. I would not call it secure, not because some one can steal all private information from first day, because someone can make excessive request, and drain your quota and make you owe to Google a lot of money.
You need to think about many concepts from restricting people not to access where they are not supposed to be, DOS attacks etc.
I would more prefer the client first will hit to your web server, there you put what ever first hand firewall, captcha , cloudflare, custom security in between the client and server, or between server and firebase and you are good to go. At least you can first stop suspect activity before it reaches to firebase. You will have much more flexibility.
I only see one good usage scenario for using client based config for internal usages. For example, you have internal domain, and you are pretty sure outsiders cannot access there, so you can setup environment like browser -> firebase type.
I tried installing the module locally with version and it worked!!
npm install request@^2.*
Thanks.
The bootstrap v4 starter template css uses:
body {
padding-top: 5rem;
}
Just wanted to show that there is no performance difference between the 2 main ways of doing it:
df = pd.DataFrame(np.random.randint(0,10,size=(100, 4)), columns=list('ABCD'))
def loc():
df1.loc[df1["A"] == 2] = 5
%timeit loc
19.9 ns ± 0.0873 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
def replace():
df2['A'].replace(
to_replace=2,
value=5,
inplace=True
)
%timeit replace
19.6 ns ± 0.509 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In my case error caused next. I've tried to execute commands globally i.e outside of any target.
UPD. To run command globally one must be properly formed. For example command
ln -sf ../../user/curl/$SRC_NAME ./$SRC_NAME
would become:
$(shell ln -sf ../../user/curl/$(SRC_NAME) ./$(SRC_NAME))
Changing IE's JSON mime-type settings will effect the way IE treats all JSON responses.
Changing the mime-type header to text/html will effectively tell any browser that the JSON response you are returning is not JSON but plain text.
Neither options are preferable.
Instead you would want to use a plugin or tool like the above mentioned Fiddler or any other network traffic inspector proxy where you can choose each time how to process the JSON response.
Here is a the list of ajax libraries comparison based on the features and support. I prefer to use fetch for only client side development or isomorphic-fetch for using in both client side and server side development.
For more information on isomorphic-fetch vs fetch
Instead of adding and removing callbacks manually and having a bunch of delegate types declared everywhere:
// The hard way
public delegate void ObjectCallback(ObjectType broadcaster);
public class Object
{
public event ObjectCallback m_ObjectCallback;
void SetupListener()
{
ObjectCallback callback = null;
callback = (ObjectType broadcaster) =>
{
// one time logic here
broadcaster.m_ObjectCallback -= callback;
};
m_ObjectCallback += callback;
}
void BroadcastEvent()
{
m_ObjectCallback?.Invoke(this);
}
}
You could try this generic approach:
public class Object
{
public Broadcast<Object> m_EventToBroadcast = new Broadcast<Object>();
void SetupListener()
{
m_EventToBroadcast.SubscribeOnce((ObjectType broadcaster) => {
// one time logic here
});
}
~Object()
{
m_EventToBroadcast.Dispose();
m_EventToBroadcast = null;
}
void BroadcastEvent()
{
m_EventToBroadcast.Broadcast(this);
}
}
public delegate void ObjectDelegate<T>(T broadcaster);
public class Broadcast<T> : IDisposable
{
private event ObjectDelegate<T> m_Event;
private List<ObjectDelegate<T>> m_SingleSubscribers = new List<ObjectDelegate<T>>();
~Broadcast()
{
Dispose();
}
public void Dispose()
{
Clear();
System.GC.SuppressFinalize(this);
}
public void Clear()
{
m_SingleSubscribers.Clear();
m_Event = delegate { };
}
// add a one shot to this delegate that is removed after first broadcast
public void SubscribeOnce(ObjectDelegate<T> del)
{
m_Event += del;
m_SingleSubscribers.Add(del);
}
// add a recurring delegate that gets called each time
public void Subscribe(ObjectDelegate<T> del)
{
m_Event += del;
}
public void Unsubscribe(ObjectDelegate<T> del)
{
m_Event -= del;
}
public void Broadcast(T broadcaster)
{
m_Event?.Invoke(broadcaster);
for (int i = 0; i < m_SingleSubscribers.Count; ++i)
{
Unsubscribe(m_SingleSubscribers[i]);
}
m_SingleSubscribers.Clear();
}
}
If you are looking for something easier:
public MyTextView extends TextView{
public void resize(String text, float textViewWidth, float textViewHeight) {
Paint p = new Paint();
Rect bounds = new Rect();
p.setTextSize(1);
p.getTextBounds(text, 0, text.length(), bounds);
float widthDifference = (textViewWidth)/bounds.width();
float heightDifference = (textViewHeight);
textSize = Math.min(widthDifference, heightDifference);
setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}
Without walker menu
it's not possible to directly add it. You can, however, add it by javascript.
$('#menu > li').addClass('class_name');
You can not run/execute an .exe file that is in the users local machine or through a site. The user must first download the exe file and then run the executable file.
So there is no possible way
The following code works only when the EXE is Present in the User's Machine.
<a href = "C:\folder_name\program.exe">
I like @FractalizeR solution. But I would in addition keep and return the value from super.add(o)!
public class LimitedQueue<E> extends LinkedList<E> {
private int limit;
public LimitedQueue(int limit) {
this.limit = limit;
}
@Override
public boolean add(E o) {
boolean added = super.add(o);
while (added && size() > limit) {
super.remove();
}
return added;
}
}
Thanks you all! Now it's work. DATAJPA-231
It will be nice if was possible to create count…By… methods just like find…By ones. Example:
public interface UserRepository extends JpaRepository<User, Long> {
public Long /*or BigInteger */ countByActiveTrue();
}
My approach is to include FOUR different images of different sizes for phones, tablet, desktop, large desktop but only show ONE using bootstrap's responsive utility classes, as follow:
<!--<a class="navbar-brand" href="<?php echo home_url(); ?>/"><?php bloginfo('name'); ?></a>-->
<a class="navbar-brand visible-xs" href="<?php echo home_url(); ?>/"><img src="/assets/logo-phone.png" alt="<?php bloginfo('name'); ?> Logo" /></a>
<a class="navbar-brand visible-sm" href="<?php echo home_url(); ?>/"><img src="/assets/logo-tablet.png" alt="<?php bloginfo('name'); ?> Logo" /></a>
<a class="navbar-brand visible-md" href="<?php echo home_url(); ?>/"><img src="/assets/logo-desktop.png" alt="<?php bloginfo('name'); ?> Logo" /></a>
<a class="navbar-brand visible-lg" href="<?php echo home_url(); ?>/"><img src="/assets/logo-large.png" alt="<?php bloginfo('name'); ?> Logo" /></a>
Note: You can replace the commented line with the code provided. Replace the php code if you're not using wordpress.
Edit Note2: Yes, this adds requests to your server when loading the page which might slow down a bit but if you use a background css sprite technique, chances are the logo doesn't get printed when printing a page and the code above should get better SEO.
If you use Apache, you can use mod_bandwith.
See here for configuration parameters.
Another reason for "lost update" can be the next:
If it is the problem then U can avoid setting the state during update, you should check the state parameter value like this
static getDerivedStateFromProps(props: TimeCorrectionProps, state: TimeCorrectionState): TimeCorrectionState {
return state ? state : {disable: false, timeCorrection: props.timeCorrection};
}
Another solution is add a initialized property to state, and set it up in the first time (if the state is initialized to non null value.)
I guess this is what you are looking for?
Added an example:
The html:
<div class="example-date">
<span class="day">31</span>
<span class="month">July</span>
<span class="year">2009</span>
</div>
The css:
.year
{
display:block;
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); //For IE support
}
Alle examples are from the mentioned site.
Then just Select
:
var list = source.Select(s=>new { ID = s.ID, Name = s.Name }).ToList();
(edit) Actually - the names could be inferred in this case, so you could use:
var list = source.Select(s=>new { s.ID, s.Name }).ToList();
which saves a few electrons...
From your comment:
this line
DateTime Date = reader.GetDateTime(0);
was throwing the exception
The first column is not a valid DateTime. Most likely, you have multiple columns in your table, and you're retrieving them all by running this query:
SELECT * from INFO
Replace it with a query that retrieves only the two columns you're interested in:
SELECT YOUR_DATE_COLUMN, YOUR_TIME_COLUMN from INFO
Then try reading the values again:
var Date = reader.GetDateTime(0);
var Time = reader.GetTimeSpan(1); // equivalent to time(7) from your database
Or:
var Date = Convert.ToDateTime(reader["YOUR_DATE_COLUMN"]);
var Time = (TimeSpan)reader["YOUR_TIME_COLUMN"];
Abstract Class
1. Contains an abstract method
2. Cannot be directly initialized
3. Cannot create an object of abstract class
4. Only used for inheritance purposes
Abstract Method
1. Cannot contain a body
2. Cannot be defined as private
3. Child classes must define the methods declared in abstract class
Example Code:
abstract class A {
public function test1() {
echo 'Hello World';
}
abstract protected function f1();
abstract public function f2();
protected function test2(){
echo 'Hello World test';
}
}
class B extends A {
public $a = 'India';
public function f1() {
echo "F1 Method Call";
}
public function f2() {
echo "F2 Method Call";
}
}
$b = new B();
echo $b->test1() . "<br/>";
echo $b->a . "<br/>";
echo $b->test2() . "<br/>";
echo $b->f1() . "<br/>";
echo $b->f2() . "<br/>";
Output:
Hello World
India
Hello World test
F1 Method Call
F2 Method Call
JSON decoding in JavaScript is simply an eval() if you trust the string or the more safe code you can find on http://json.org if you don't.
You will then have a JavaScript datastructure that you can traverse for the data you need.
it's so simple:
def tail(fname,nl):
with open(fname) as f:
data=f.readlines() #readlines return a list
print(''.join(data[-nl:]))
Its also important to note that you will lose the chronological stack trace of the exception if you you have a void return type on an async method. I would recommend returning Task as follows. Going to make debugging a whole lot easier.
public async Task DoFoo()
{
try
{
return await Foo();
}
catch (ProtocolException ex)
{
/* Exception with chronological stack trace */
}
}
<form action="Delegate_update.php" method="post">
Name
<input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
Username
<input type="text" name= "Username" value= "<?php echo $row['Username']; ?> "size=10>
Password
<input type="text" name= "Password" value= "<?php echo $row['Password']; ?>" size=17>
<input type="submit" name= "submit" value="Update">
</form>
You didnt closed your opening Form in the first place, plus your code is very very messy. I wont go into the "use pdo or mysqli statements, instead of mysql" thats for you to find out on yourself. Also you have a php tag open and close below it, not sure what is needed there. Something else is that your code refers to an external page, which you didnt post, so if something isnt working there, might be handy to post it too.
Please also note that you had spaces between your $row array variables in the form. You have to link those up together by removing the space (see edited section from me). PHP isn't forgiving when it comes to those mistakes.
Then your HTML. I took the liberty to correct that too
<html>
<head>
<title> Delegate edit form</title>
</head>
<body>
<p>Delegate update form</p>
<?php
$usernm="root";
$passwd="";
$host="localhost";
$database="swift";
mysql_connect($host,$usernm,$passwd);
mysql_select_db($database);
$sql = "SELECT * FROM usermaster WHERE User_name='".$Username."'"; // Please look at this too.
$result = mysql_query($sql) or die (mysql_error()); // dont put spaces in between it, else your code wont recognize it the query that needs to be executed
while ($row = mysql_fetch_array($result)){ // here too, you put a space between it
$Name=$row['Name'];
$Username=$row['User_name'];
$Password=$row['User_password'];
}
?>
Also, try to be specific. "It doesnt work" doesnt help us much, a specific error type is commonly helpful, plus any indication what the code should do (well, it was kinda obvious here, since its a login/register edit here, but for larger chunks of code it should always be explained)
Anyway, welcome to Stack Overflow
Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant. This is actually the default behavior got when scaffolding with Rails.
I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.
Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.
This is my solution to the problem
const _ = require('lodash');
var objects = [{ 'x': 1, 'y': 2, 'z':3, a:{b:1, c:2, d:{n:0}}, p:[1, 2, 3] }, { 'x': 2, 'y': 1, z:3, a:{b:2, c:2,d:{n:1}}, p:[1,3], m:3 }];
const diffFn=(a,b, path='')=>_.reduce(a, function(result, value, key) {
if(_.isObjectLike(value)){
if(_.isEqual(value, b[key])){
return result;
}else{
return result.concat(diffFn(value, b[key], path?(`${path}.${key}`):key))
}
}else{
return _.isEqual(value, b[key]) ?
result : result.concat(path?(`${path}.${key}`):key);
}
}, []);
const diffKeys1=diffFn(objects[0], objects[1])
const diffKeys2=diffFn(objects[1], objects[0])
const diffKeys=_.union(diffKeys1, diffKeys2)
const res={};
_.forEach(diffKeys, (key)=>_.assign(res, {[key]:{ old: _.get(objects[0], key), new:_.get(objects[1], key)} }))
res
/*
Returns
{
x: { old: 1, new: 2 },
y: { old: 2, new: 1 },
'a.b': { old: 1, new: 2 },
'a.d.n': { old: 0, new: 1 },
'p.1': { old: 2, new: 3 },
'p.2': { old: 3, new: undefined },
m: { old: undefined, new: 3 }
}
*/
You should be pointing it towards the Developer
directory, not the Xcode application bundle. Run this:
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.
->
calls/sets object variables. Ex:
$obj = new StdClass;
$obj->foo = 'bar';
var_dump($obj);
=> Sets key/value pairs for arrays. Ex:
$array = array(
'foo' => 'bar'
);
var_dump($array);
\.jenkins\secrets\initialAdminPassword
Copy the password from the initialAdminPassword file and paste it into the Jenkins.
You can tell any click that bubbles all the way up the DOM to hide the dropdown, and any click that makes it to the parent of the dropdown to stop bubbling.
/* Anything that gets to the document
will hide the dropdown */
$(document).click(function(){
$("#dropdown").hide();
});
/* Clicks within the dropdown won't make
it past the dropdown itself */
$("#dropdown").click(function(e){
e.stopPropagation();
});
echo -ne '\n' | <yourfinecommandhere>
or taking advantage of the implicit newline that echo generates (thanks Marcin)
echo | <yourfinecommandhere>
Now we can simply use the --sk
option:
--sk
,--skip-keypress
Don't wait for a keypress after each test
i.e. sudo rkhunter --sk --checkall
This one helped me,
res.format({
json:function(){
var responseData = {};
responseData['status'] = 200;
responseData['outputPath'] = outputDirectoryPath;
responseData['sourcePath'] = url;
responseData['message'] = 'Scraping of requested resource initiated.';
responseData['logfile'] = logFileName;
res.json(JSON.stringify(responseData));
}
});
The posted solutions will not link any hidden files. To include them, try this:
cd /usr/lib
find /mnt/usr/lib -maxdepth 1 -print "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done
If you should happen to want to recursively create the directories and only link files (so that if you create a file within a directory, it really is in /usr/lib
not /mnt/usr/lib
), you could do this:
cd /usr/lib
find /mnt/usr/lib -mindepth 1 -depth -type d -printf "%P\n" | while read dir; do mkdir -p "$dir"; done
find /mnt/usr/lib -type f -printf "%P\n" | while read file; do ln -s "/mnt/usr/lib/$file" "$file"; done
You can use the String constructor.
System.out.println(new String(new char[]{a,b,c}));
If you're looking into trying to disable the downloading/saving of your images, scripts won't stop that. You would probably have better luck doing this on a server configuration level (like modifying your .htaccess
for example on Apache).
Try asking this on ServerFault.
This is no longer so complex you can just use the git filter-branch command on a clone of you repo to cull the subdirectories you don't want and then push to the new remote.
git filter-branch --prune-empty --subdirectory-filter <YOUR_SUBDIR_TO_KEEP> master
git push <MY_NEW_REMOTE_URL> -f .
It is because there is no package cache in the image, you need to run:
apt-get update
before installing packages, and if your command is in a Dockerfile, you'll then need:
apt-get -y install curl
To suppress the standard output from a command use -qq
. E.g.
apt-get -qq -y install curl
document.getElementsByClassName('btn-pageMenu')
delivers a nodeList. You should use: document.getElementsByClassName('btn-pageMenu')[0].style.display
(if it's the first element from that list you want to change.
If you want to change style.display
for all nodes loop through the list:
var elems = document.getElementsByClassName('btn-pageMenu');
for (var i=0;i<elems.length;i+=1){
elems[i].style.display = 'block';
}
to be complete: if you use jquery it is as simple as:
?$('.btn-pageMenu').css('display'???????????????????????????,'block');??????
If you want to be real smart, at the command line type:
echo svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service >CreateService.cmd
Then you have CreateService.cmd
that you can run whenever you want (.cmd
is just another extension for .bat
files)
This is answered in some of the answers to Can't find how to use HttpContent as well as in this blog post.
In summary, you can't directly set up an instance of HttpContent
because it is an abstract class. You need to use one the classes derived from it depending on your need. Most likely StringContent
, which lets you set the string value of the response, the encoding, and the media type in the constructor. See: http://msdn.microsoft.com/en-us/library/system.net.http.stringcontent.aspx
printStackTrace()
prints the locations where the exception occurred in the source code, thus allowing the author who wrote the program to see what went wrong. But since it shows problems in the source code, the user(s) who may or may not have any coding experience may not be able to understand what went wrong, so if the program allows the user to send error messages to the authors, the users may not be able to give good data on what went wrong.
You should consider the Logger.getLogger()
method, it offers a better exception handling (logging) facility, and besides printStackTrace()
without arguments is considered to be obsolete and should ONLY be used for debugging purposes, not for user display.
<img src="file://C:/wamp/www/site/img/mypicture.jpg"/>
Use this:
var dict = list.ToDictionary(x => x);
See MSDN for more info.
As Pranay points out in the comments, this will fail if an item exists in the list multiple times.
Depending on your specific requirements, you can either use var dict = list.Distinct().ToDictionary(x => x);
to get a dictionary of distinct items or you can use ToLookup
instead:
var dict = list.ToLookup(x => x);
This will return an ILookup<string, string>
which is essentially the same as IDictionary<string, IEnumerable<string>>
, so you will have a list of distinct keys with each string instance under it.
I agree with @Matthew, it will cost a lot if you perform such query.
[ADVICE FOR DEVELOPERS BEFORE STARTING THEIR PROJECTS]
Since we have foreseen this situation at the beginning, we can actually make a collection namely counters with a document to store all the counters in a field with type number
.
For example:
For each CRUD operation on the collection, update the counter document:
Next time, when you want to get the number of collection, you just need to query/point to the document field. [1 read operation]
In addition, you can store the collections name in an array, but this will be tricky, the condition of array in firebase is shown as below:
// we send this
['a', 'b', 'c', 'd', 'e']
// Firebase stores this
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}
// since the keys are numeric and sequential,
// if we query the data, we get this
['a', 'b', 'c', 'd', 'e']
// however, if we then delete a, b, and d,
// they are no longer mostly sequential, so
// we do not get back an array
{2: 'c', 4: 'e'}
So, if you are not going to delete the collection , you can actually use array to store list of collections name instead of querying all the collection every time.
Hope it helps!
You cannot directly see the query result using mysql_query its only fires the query in mysql nothing else.
For getting the result you have to add a lil things in your script like
require_once('db.php');
$sql="SELECT * FROM modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) ) FROM modul1open) ORDER BY idM1O LIMIT 1";
$result = mysql_query($sql);
//echo [$result];
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row);
}
This will give you result;
The universal adb driver installer worked for me. I went from an HTC to a Samsung to a LG Nexus. The drivers are all over the place for me.
Complementing the @NoahD's answer
To have a greater precision you can cast to decimal:
(decimal)100/863
//0.1158748551564310544611819235
Or:
Decimal.Divide(100, 863)
//0.1158748551564310544611819235
Double are represented allocating 64 bits while decimal uses 128
(double)100/863
//0.11587485515643106
For more details about the floating point representation in binary and its precision take a look at this article from Jon Skeet where he talks about floats
and doubles
and this one where he talks about decimals
.
Runtime rt = Runtime.getRuntime();
rt.maxMemory()
value is b
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
am.getMemoryClass()
value is MB
Here is a method that uses stamper and absolute coordinates showed in the different PDF clients (Adobe, FoxIt and etc. )
public static void AddTextToPdf(string inputPdfPath, string outputPdfPath, string textToAdd, System.Drawing.Point point)
{
//variables
string pathin = inputPdfPath;
string pathout = outputPdfPath;
//create PdfReader object to read from the existing document
using (PdfReader reader = new PdfReader(pathin))
//create PdfStamper object to write to get the pages from reader
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(pathout, FileMode.Create)))
{
//select two pages from the original document
reader.SelectPages("1-2");
//gettins the page size in order to substract from the iTextSharp coordinates
var pageSize = reader.GetPageSize(1);
// PdfContentByte from stamper to add content to the pages over the original content
PdfContentByte pbover = stamper.GetOverContent(1);
//add content to the page using ColumnText
Font font = new Font();
font.Size = 45;
//setting up the X and Y coordinates of the document
int x = point.X;
int y = point.Y;
y = (int) (pageSize.Height - y);
ColumnText.ShowTextAligned(pbover, Element.ALIGN_CENTER, new Phrase(textToAdd, font), x, y, 0);
}
}
Seems to me you could've saved some memory by declaring your activity with "implements Handler.Callback"
hey I think that you just copy your compiled class files and copy the jre folder and make the following as the content of the batch file and save all together any windows machine and just double click
@echo
setpath d:\jre
d:
cd myprogfolder
java myprogram
This is because of padding added to satisfy alignment constraints. Data structure alignment impacts both performance and correctness of programs:
SIGBUS
).Here's an example using typical settings for an x86 processor (all used 32 and 64 bit modes):
struct X
{
short s; /* 2 bytes */
/* 2 padding bytes */
int i; /* 4 bytes */
char c; /* 1 byte */
/* 3 padding bytes */
};
struct Y
{
int i; /* 4 bytes */
char c; /* 1 byte */
/* 1 padding byte */
short s; /* 2 bytes */
};
struct Z
{
int i; /* 4 bytes */
short s; /* 2 bytes */
char c; /* 1 byte */
/* 1 padding byte */
};
const int sizeX = sizeof(struct X); /* = 12 */
const int sizeY = sizeof(struct Y); /* = 8 */
const int sizeZ = sizeof(struct Z); /* = 8 */
One can minimize the size of structures by sorting members by alignment (sorting by size suffices for that in basic types) (like structure Z
in the example above).
IMPORTANT NOTE: Both the C and C++ standards state that structure alignment is implementation-defined. Therefore each compiler may choose to align data differently, resulting in different and incompatible data layouts. For this reason, when dealing with libraries that will be used by different compilers, it is important to understand how the compilers align data. Some compilers have command-line settings and/or special #pragma
statements to change the structure alignment settings.
You can use jquery for this by utilizing addClass() method
CSS
.defaultInput
{
width: 100px;
height:25px;
padding: 5px;
}
.error
{
border:1px solid red;
}
<input type="text" class="defaultInput"/>
Jquery Code
$(document).ready({
$('.defaultInput').focus(function(){
$(this).addClass('error');
});
});
Update: You can remove that error class using
$('.defaultInput').removeClass('error');
It won't remove that default style. It will remove .error class only
You are missing a parantheses in the denominator of your gaussian() function. As it is right now you divide by 2 and multiply with the variance (sig^2). But that is not true and as you can see of your plots the greater variance the more narrow the gaussian is - which is wrong, it should be opposit.
So just change the gaussian() function to:
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
(This is pointed out in a comment by Zan Lynx, but I think it deserves an aswer - given that the accepted answer doesn't mention it).
The essential difference between puts(mystr);
and printf(mystr);
is that in the latter the argument is interpreted as a formatting string. The result will be often the same (except for the added newline) if the string doesn't contain any control characters (%
) but if you cannot rely on that (if mystr
is a variable instead of a literal) you should not use it.
So, it's generally dangerous -and conceptually wrong- to pass a dynamic string as single argument of printf
:
char * myMessage;
// ... myMessage gets assigned at runtime, unpredictable content
printf(myMessage); // <--- WRONG! (what if myMessage contains a '%' char?)
puts(myMessage); // ok
printf("%s\n",myMessage); // ok, equivalent to the previous, perhaps less efficient
The same applies to fputs
vs fprintf
(but fputs
doesn't add the newline).
In linux terminal try this:
sudo service postgresql start
: to start the serversudo service postgresql stop
: to stop thee serversudo service postgresql status
: to check server statusYou just need to provide an alias for your aggregate columns in the CTE
d as (SELECT
duration,
sum(totalitems) as sumtotalitems
FROM
[DrySoftBranch].[dbo].[mnthItemWiseTotalQty] ('1') AS BkdQty
group by duration
)
<context:annotation-config>
is used to activate annotations in beans already registered in the application context (no matter if they were defined with XML or by package scanning).
<context:component-scan>
can also do what <context:annotation-config>
does but <context:component-scan>
also scans packages to find and register beans within the application context.
I'll use some examples to show the differences/similarities.
Lets start with a basic setup of three beans of type A
, B
and C
, with B
and C
being injected into A
.
package com.xxx;
public class B {
public B() {
System.out.println("creating bean B: " + this);
}
}
package com.xxx;
public class C {
public C() {
System.out.println("creating bean C: " + this);
}
}
package com.yyy;
import com.xxx.B;
import com.xxx.C;
public class A {
private B bbb;
private C ccc;
public A() {
System.out.println("creating bean A: " + this);
}
public void setBbb(B bbb) {
System.out.println("setting A.bbb with " + bbb);
this.bbb = bbb;
}
public void setCcc(C ccc) {
System.out.println("setting A.ccc with " + ccc);
this.ccc = ccc;
}
}
With the following XML configuration :
<bean id="bBean" class="com.xxx.B" />
<bean id="cBean" class="com.xxx.C" />
<bean id="aBean" class="com.yyy.A">
<property name="bbb" ref="bBean" />
<property name="ccc" ref="cBean" />
</bean>
Loading the context produces the following output:
creating bean B: com.xxx.B@c2ff5
creating bean C: com.xxx.C@1e8a1f6
creating bean A: com.yyy.A@1e152c5
setting A.bbb with com.xxx.B@c2ff5
setting A.ccc with com.xxx.C@1e8a1f6
OK, this is the expected output. But this is "old style" Spring. Now we have annotations so lets use those to simplify the XML.
First, lets autowire the bbb
and ccc
properties on bean A
like so:
package com.yyy;
import org.springframework.beans.factory.annotation.Autowired;
import com.xxx.B;
import com.xxx.C;
public class A {
private B bbb;
private C ccc;
public A() {
System.out.println("creating bean A: " + this);
}
@Autowired
public void setBbb(B bbb) {
System.out.println("setting A.bbb with " + bbb);
this.bbb = bbb;
}
@Autowired
public void setCcc(C ccc) {
System.out.println("setting A.ccc with " + ccc);
this.ccc = ccc;
}
}
This allows me to remove the following rows from the XML:
<property name="bbb" ref="bBean" />
<property name="ccc" ref="cBean" />
My XML is now simplified to this:
<bean id="bBean" class="com.xxx.B" />
<bean id="cBean" class="com.xxx.C" />
<bean id="aBean" class="com.yyy.A" />
When I load the context I get the following output:
creating bean B: com.xxx.B@5e5a50
creating bean C: com.xxx.C@54a328
creating bean A: com.yyy.A@a3d4cf
OK, this is wrong! What happened? Why aren't my properties autowired?
Well, annotations are a nice feature but by themselves they do nothing whatsoever. They just annotate stuff. You need a processing tool to find the annotations and do something with them.
<context:annotation-config>
to the rescue. This activates the actions for the annotations that it finds on the beans defined in the same application context where itself is defined.
If I change my XML to this:
<context:annotation-config />
<bean id="bBean" class="com.xxx.B" />
<bean id="cBean" class="com.xxx.C" />
<bean id="aBean" class="com.yyy.A" />
when I load the application context I get the proper result:
creating bean B: com.xxx.B@15663a2
creating bean C: com.xxx.C@cd5f8b
creating bean A: com.yyy.A@157aa53
setting A.bbb with com.xxx.B@15663a2
setting A.ccc with com.xxx.C@cd5f8b
OK, this is nice, but I've removed two rows from the XML and added one. That's not a very big difference. The idea with annotations is that it's supposed to remove the XML.
So let's remove the XML definitions and replace them all with annotations:
package com.xxx;
import org.springframework.stereotype.Component;
@Component
public class B {
public B() {
System.out.println("creating bean B: " + this);
}
}
package com.xxx;
import org.springframework.stereotype.Component;
@Component
public class C {
public C() {
System.out.println("creating bean C: " + this);
}
}
package com.yyy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.xxx.B;
import com.xxx.C;
@Component
public class A {
private B bbb;
private C ccc;
public A() {
System.out.println("creating bean A: " + this);
}
@Autowired
public void setBbb(B bbb) {
System.out.println("setting A.bbb with " + bbb);
this.bbb = bbb;
}
@Autowired
public void setCcc(C ccc) {
System.out.println("setting A.ccc with " + ccc);
this.ccc = ccc;
}
}
While in the XML we only keep this:
<context:annotation-config />
We load the context and the result is... Nothing. No beans are created, no beans are autowired. Nothing!
That's because, as I said in the first paragraph, the <context:annotation-config />
only works on beans registered within the application context. Because I removed the XML configuration for the three beans there is no bean created and <context:annotation-config />
has no "targets" to work on.
But that won't be a problem for <context:component-scan>
which can scan a package for "targets" to work on. Let's change the content of the XML config into the following entry:
<context:component-scan base-package="com.xxx" />
When I load the context I get the following output:
creating bean B: com.xxx.B@1be0f0a
creating bean C: com.xxx.C@80d1ff
Hmmmm... something is missing. Why?
If you look closelly at the classes, class A
has package com.yyy
but I've specified in the <context:component-scan>
to use package com.xxx
so this completely missed my A
class and only picked up B
and C
which are on the com.xxx
package.
To fix this, I add this other package also:
<context:component-scan base-package="com.xxx,com.yyy" />
and now we get the expected result:
creating bean B: com.xxx.B@cd5f8b
creating bean C: com.xxx.C@15ac3c9
creating bean A: com.yyy.A@ec4a87
setting A.bbb with com.xxx.B@cd5f8b
setting A.ccc with com.xxx.C@15ac3c9
And that's it! Now you don't have XML definitions anymore, you have annotations.
As a final example, keeping the annotated classes A
, B
and C
and adding the following to the XML, what will we get after loading the context?
<context:component-scan base-package="com.xxx" />
<bean id="aBean" class="com.yyy.A" />
We still get the correct result:
creating bean B: com.xxx.B@157aa53
creating bean C: com.xxx.C@ec4a87
creating bean A: com.yyy.A@1d64c37
setting A.bbb with com.xxx.B@157aa53
setting A.ccc with com.xxx.C@ec4a87
Even if the bean for class A
isn't obtained by scanning, the processing tools are still applied by <context:component-scan>
on all beans registered
in the application context, even for A
which was manually registered in the XML.
But what if we have the following XML, will we get duplicated beans because we've specified both <context:annotation-config />
and <context:component-scan>
?
<context:annotation-config />
<context:component-scan base-package="com.xxx" />
<bean id="aBean" class="com.yyy.A" />
No, no duplications, We again get the expected result:
creating bean B: com.xxx.B@157aa53
creating bean C: com.xxx.C@ec4a87
creating bean A: com.yyy.A@1d64c37
setting A.bbb with com.xxx.B@157aa53
setting A.ccc with com.xxx.C@ec4a87
That's because both tags register the same processing tools (<context:annotation-config />
can be omitted if <context:component-scan>
is specified) but Spring takes care of running them only once.
Even if you register the processing tools yourself multiple times, Spring will still make sure they do their magic only once; this XML:
<context:annotation-config />
<context:component-scan base-package="com.xxx" />
<bean id="aBean" class="com.yyy.A" />
<bean id="bla" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean id="bla1" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean id="bla2" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean id="bla3" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
will still generate the following result:
creating bean B: com.xxx.B@157aa53
creating bean C: com.xxx.C@ec4a87
creating bean A: com.yyy.A@25d2b2
setting A.bbb with com.xxx.B@157aa53
setting A.ccc with com.xxx.C@ec4a87
OK, that about raps it up.
I hope this information along with the responses from @Tomasz Nurkiewicz and @Sean Patrick Floyd are all you need to understand how
<context:annotation-config>
and <context:component-scan>
work.
Tried most of the solutions suggested above. Only this worked for me in this scenario. I was using *ngIf to toggle angular material's indeterminate progressive bar based on api calls and it was throwing ExpressionChangedAfterItHasBeenCheckedError
.
In the component in question:
constructor(
private ngZone: NgZone,
private changeDetectorRef: ChangeDetectorRef,
) {}
ngOnInit() {
this.ngZone.runOutsideAngular(() => {
this.appService.appLoader$.subscribe(value => {
this.loading = value;
this.changeDetectorRef.detectChanges();
});
});
}
The trick is to bypass angular component's change detection using ngzone.
PS: Not sure if this is an elegant solution but using AfterContentChecked and AfterViewChecked lifecycle hook is bound to raise performance issues as your application gets bigger as it is triggered numerous times.
After spending too much time on this issue and trying out all different answers, here is what found:
The accepted answer by @thewaywewere is no longer applicable. I think this was applicable when opencv-python module still wasn't available.
This is indeed a bug in Anaconda 4.2 because they forgot to ship python3.dll. They have fixed this in next releases but unfortunately 4.2 is the last release with Python 3.5 as default. If you are stuck with Python 3.5 (for example VS2015 is only aware of versions up to 3.5) then you must manually download python3.dll as described in answer by @Ramesh-X.
If you can move on to Python 3.6 (which at present bit difficult if you are using OpenCV and VS2015) then just install latest Anaconda version and you don't have to deal with any of these.
I get exactly the reported error if ccache is enabled, when using CMake's Xcode generator. Disabling ccache fixed the problem for me. Below I present a fix/check that works for MacOS, but should work similarly on other platforms.
Apparently, it is possible to use CMake's Xcode generator (and others) also in combination with ccache, as is described here. But I never tried it out myself.
# 1) To check if ccache is enabled:
echo $CC
echo $CXX
# This prints something like the following:
# ccache clang -Qunused-arguments -fcolor-diagnostics.
# CC or CXX are typically set in the `.bashrc` or `.zshrc` file.
# 2) To disable ccache, use the following:
CC=clang
CXX=clang++
# 3) Then regenerate the cmake project
cmake -G Xcode <path/to/CMakeLists.txt>
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
if (!$result) {
trigger_error('Invalid query: ' . $conn->error);
}
check the error with mysqli_error() function
probably your query has some faults.
Technically you could do it with a straight TCP socket. I wouldn't recommend it however. I would highly recommend you use Apache HttpClient instead. In its simplest form:
GetMethod get = new GetMethod("http://httpcomponents.apache.org");
// execute method and handle any error responses.
...
InputStream in = get.getResponseBodyAsStream();
// Process the data from the input stream.
get.releaseConnection();
and here is a more complete example.
I think I got it. It's:
"SVN Client Path" /command:update / path:"My folder path"
As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:
MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();
It's easy enough to write the equivalent of CopyTo
in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream
.
For efficient purposes you could check whether the stream returned is already a MemoryStream
:
byte[] data;
using (Stream inputStream = model.File.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
I wonder why there is no example of stand alone jar project.
In eclipse, we just check "Is Library" box in project setting dialog.
In Android studio, I followed this steps and got a jar file.
Create a project.
open file in the left project menu.(app/build.gradle): Gradle Scripts > build.gradle(Module: XXX)
change one line: apply plugin: 'com.android.application'
-> 'apply plugin: com.android.library'
remove applicationId in the file: applicationId "com.mycompany.testproject"
build project: Build > Rebuild Project
then you can get aar file: app > build > outputs > aar folder
change aar
file extension name into zip
unzip, and you can see classes.jar
in the folder.
rename and use it!
Anyway, I don't know why google makes jar creation so troublesome in android studio.
In C++11, use std::stoi
as:
std::string s = "10";
int i = std::stoi(s);
Note that std::stoi
will throw exception of type std::invalid_argument
if the conversion cannot be performed, or std::out_of_range
if the conversion results in overflow(i.e when the string value is too big for int
type). You can use std::stol
or std:stoll
though in case int
seems too small for the input string.
In C++03/98, any of the following can be used:
std::string s = "10";
int i;
//approach one
std::istringstream(s) >> i; //i is 10 after this
//approach two
sscanf(s.c_str(), "%d", &i); //i is 10 after this
Note that the above two approaches would fail for input s = "10jh"
. They will return 10 instead of notifying error. So the safe and robust approach is to write your own function that parses the input string, and verify each character to check if it is digit or not, and then work accordingly. Here is one robust implemtation (untested though):
int to_int(char const *s)
{
if ( s == NULL || *s == '\0' )
throw std::invalid_argument("null or empty string argument");
bool negate = (s[0] == '-');
if ( *s == '+' || *s == '-' )
++s;
if ( *s == '\0')
throw std::invalid_argument("sign character only.");
int result = 0;
while(*s)
{
if ( *s < '0' || *s > '9' )
throw std::invalid_argument("invalid input string");
result = result * 10 - (*s - '0'); //assume negative number
++s;
}
return negate ? result : -result; //-result is positive!
}
This solution is slightly modified version of my another solution.
If it's reasonable to alter the original Map
data structure to be serialized to better represent the actual value wanted to be serialized, that's probably a decent approach, which would possibly reduce the amount of Jackson configuration necessary. For example, just remove the null
key entries, if possible, before calling Jackson. That said...
To suppress serializing Map
entries with null values:
Before Jackson 2.9
you can still make use of WRITE_NULL_MAP_VALUES
, but note that it's moved to SerializationFeature
:
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
Since Jackson 2.9
The WRITE_NULL_MAP_VALUES
is deprecated, you can use the below equivalent:
mapper.setDefaultPropertyInclusion(
JsonInclude.Value.construct(Include.ALWAYS, Include.NON_NULL))
To suppress serializing properties with null values, you can configure the ObjectMapper
directly, or make use of the @JsonInclude
annotation:
mapper.setSerializationInclusion(Include.NON_NULL);
or:
@JsonInclude(Include.NON_NULL)
class Foo
{
public String bar;
Foo(String bar)
{
this.bar = bar;
}
}
To handle null Map
keys, some custom serialization is necessary, as best I understand.
A simple approach to serialize null
keys as empty strings (including complete examples of the two previously mentioned configurations):
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
public class JacksonFoo
{
public static void main(String[] args) throws Exception
{
Map<String, Foo> foos = new HashMap<String, Foo>();
foos.put("foo1", new Foo("foo1"));
foos.put("foo2", new Foo(null));
foos.put("foo3", null);
foos.put(null, new Foo("foo4"));
// System.out.println(new ObjectMapper().writeValueAsString(foos));
// Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?)
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer());
System.out.println(mapper.writeValueAsString(foos));
// output:
// {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}}
}
}
class MyNullKeySerializer extends JsonSerializer<Object>
{
@Override
public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused)
throws IOException, JsonProcessingException
{
jsonGenerator.writeFieldName("");
}
}
class Foo
{
public String bar;
Foo(String bar)
{
this.bar = bar;
}
}
To suppress serializing Map
entries with null
keys, further custom serialization processing would be necessary.
Try creating a shell script like the one below:
#!/bin/bash
mysql --user=[username] --password=[password] --database=[db name] --execute="DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) , timestamp ) >=7"
You can then add this to the cron
There is also another way for removing the "debug" banner from the flutter app. Now after new release there is no "debugShowCheckedModeBanner: false,"
code line in main .dart file. So I think these methods are effective:
"Dart DevTools"
from extensions. After installation, you can easily find "Dart DevTools"
text icon at the bottom of the VS Code. When you click on that text icon, a link will be open in google chrome. From that link page, you can easily remove the banner by just tapping on the banner icon as shown in this screenshot.NOTE:-- Dart DevTools is a dart language debugger extension in VS Code
Dart DevTools
is already installed in your VS Code, then you can directly open the google chrome and open this URL = "127.0.0.1: ZZZZZ/?hide=debugger&port=XXXXX"
NOTE:-- In this link replace "XXXXX" by 5 digit port-id (on which your flutter app is running) which will vary whenever you use "flutter run"
command and replace "ZZZZZ" by your global(unchangeable) 5 digit debugger-id
NOTE:-- these dart dev tools are only for "Google Chrome Browser"
Use INDIRECT()
=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))
One other way, using the splat operator:
*a, last = [1, 3, 4, 5]
STDOUT:
a: [1, 3, 4]
last: 5
If you are trying to write straightforward, yet forbidden code like this:
public class Person
{
public enum Gender
{
Male,
Female
}
//Won't compile: auto-property has same name as enum
public Gender Gender { get; set; }
}
Your options are:
Ignore the MS recommendation and use a prefix or suffix on the enum name:
public class Person
{
public enum GenderEnum
{
Male,
Female
}
public GenderEnum Gender { get; set; }
}
Move the enum definition outside the class, preferably into another class. Here is an easy solution to the above:
public class Characteristics
{
public enum Gender
{
Male,
Female
}
}
public class Person
{
public Characteristics.Gender Gender { get; set; }
}
If you are still looking for an answer, try checking this question thread. It helped me resolve a similar problem.
edit:
The solution that helped me was to run Update-Package Microsoft.AspNet.WebApi -reinstall
from the NugGet package manager, as suggested by Pathoschild.
I then had to delete my .suo file and restart VS, as suggested by Sergey Osypchuk in this thread.
Make sure the filename is correct (proper capitalisation, matching extension etc - as already suggested).
Use the Class.getResource
method to locate your file in the classpath - don't rely on the current directory:
URL url = insertionSort.class.getResource("10_Random");
File file = new File(url.toURI());
Specify the absolute file path via command-line arguments:
File file = new File(args[0]);
In Eclipse:
There are several ways to reload the current page using a button or other trigger. The examples below use a button click to reload the page but you can use a text hyperlink or any trigger you like.
<input type="button" value="Reload Page" onClick="window.location.reload()">
<input type="button" value="Reload Page" onClick="history.go(0)">
<input type="button" value="Reload Page" onClick="window.location.href=window.location.href">
The functions in the other answers are overkill for escaping entire regular expressions (they may be useful for escaping parts of regular expressions that will later be concatenated into bigger regexps).
If you escape an entire regexp and are done with it, quoting the metacharacters that are either standalone (.
, ?
, +
, *
, ^
, $
, |
, \
) or start something ((
, [
, {
) is all you need:
String.prototype.regexEscape = function regexEscape() {
return this.replace(/[.?+*^$|({[\\]/g, '\\$&');
};
And yes, it's disappointing that JavaScript doesn't have a function like this built-in.
To give an example to what Alex said, if you're using Magento, for example, .phtml files are only to be found in the /design area as template files, and contain both HTML and PHP lines. Meanwhile the PHP files are pure code and don't have any lines of HTML in them.
I wasn't able to do that with any swal(sweatAlert) default callback function, so I forced with jquery, got the Ok button class inspecting the element in chrome an made something like this:
<script>
sweetAlert({
title:'Warning!',
text: 'Invalid user or password!',
type:'warning'
},function(isConfirm){
alert('ok');
});
$('.swal2-confirm').click(function(){
window.location.href = 'index.php';
});
</script>
The 'Ok' alert in function(isConfirm) was just a test to see if it would get into this function, if so I should be able to redirect from there, but I wasn't...
So I used jQuery to determine if the button "OK" of swal was clicked by getting it class: ".swal2-confirm' then I could redirect with success...
Hope this helps you all !
PS: I am using php echo to run the script, I din't have to leave php to run it, just use single quotes and you're done !
For those saying that the answer of @kuester2000 does not work, please be aware that HTTP requests, first try to find the host IP with a DNS request and then makes the actual HTTP request to the server, so you may also need to set a timeout for the DNS request.
If your code worked without the timeout for the DNS request it's because you are able to reach a DNS server or you are hitting the Android DNS cache. By the way you can clear this cache by restarting the device.
This code extends the original answer to include a manual DNS lookup with a custom timeout:
//Our objective
String sURL = "http://www.google.com/";
int DNSTimeout = 1000;
int HTTPTimeout = 2000;
//Get the IP of the Host
URL url= null;
try {
url = ResolveHostIP(sURL,DNSTimeout);
} catch (MalformedURLException e) {
Log.d("INFO",e.getMessage());
}
if(url==null){
//the DNS lookup timed out or failed.
}
//Build the request parameters
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, HTTPTimeout);
HttpConnectionParams.setSoTimeout(params, HTTPTimeout);
DefaultHttpClient client = new DefaultHttpClient(params);
HttpResponse httpResponse;
String text;
try {
//Execute the request (here it blocks the execution until finished or a timeout)
httpResponse = client.execute(new HttpGet(url.toString()));
} catch (IOException e) {
//If you hit this probably the connection timed out
Log.d("INFO",e.getMessage());
}
//If you get here everything went OK so check response code, body or whatever
Used method:
//Run the DNS lookup manually to be able to time it out.
public static URL ResolveHostIP (String sURL, int timeout) throws MalformedURLException {
URL url= new URL(sURL);
//Resolve the host IP on a new thread
DNSResolver dnsRes = new DNSResolver(url.getHost());
Thread t = new Thread(dnsRes);
t.start();
//Join the thread for some time
try {
t.join(timeout);
} catch (InterruptedException e) {
Log.d("DEBUG", "DNS lookup interrupted");
return null;
}
//get the IP of the host
InetAddress inetAddr = dnsRes.get();
if(inetAddr==null) {
Log.d("DEBUG", "DNS timed out.");
return null;
}
//rebuild the URL with the IP and return it
Log.d("DEBUG", "DNS solved.");
return new URL(url.getProtocol(),inetAddr.getHostAddress(),url.getPort(),url.getFile());
}
This class is from this blog post. Go and check the remarks if you will use it.
public static class DNSResolver implements Runnable {
private String domain;
private InetAddress inetAddr;
public DNSResolver(String domain) {
this.domain = domain;
}
public void run() {
try {
InetAddress addr = InetAddress.getByName(domain);
set(addr);
} catch (UnknownHostException e) {
}
}
public synchronized void set(InetAddress inetAddr) {
this.inetAddr = inetAddr;
}
public synchronized InetAddress get() {
return inetAddr;
}
}
Below I split all the details of formatted address like City, State, Country and Zip code.
So when you start typing your street name and select any option then street name write over street field, city name write over city field and all other fields like state, country and zip code will fill automatically.
Using Google APIs.
------------------------------------------------
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function() {
var places = new google.maps.places.Autocomplete(document
.getElementById('txtPlaces'));
google.maps.event.addListener(places, 'place_changed', function() {
var place = places.getPlace();
var address = place.formatted_address;
var value = address.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
var z=state.split(" ");
document.getElementById("selCountry").text = country;
var i =z.length;
document.getElementById("pstate").value = z[1];
if(i>2)
document.getElementById("pzcode").value = z[2];
document.getElementById("pCity").value = city;
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
var mesg = address;
document.getElementById("txtPlaces").value = mesg;
var lati = latitude;
document.getElementById("plati").value = lati;
var longi = longitude;
document.getElementById("plongi").value = longi;
});
});
I have resolve a problem maybe like your. I tried to inspect element in firefox. I will show you some results:
As you see a:hover have text-decoration: underline. I only add to my css file:
a:hover {
text-decoration: none;
}
and problem is resolved. But I also set text-decoration: none in some another classes (like you :D), that may be make some effects (I guess).
NUMBER (precision, scale)
means precision
number of total digits, of which scale
digits are right of the decimal point.
NUMBER(2,2)
in other words means a number with 2 digits, both of which are decimals. You may mean to use NUMBER(4,2)
to get 4 digits, of which 2 are decimals. Currently you can just insert values with a zero integer part.
In ANSI SQL, double quotes quote object names (e.g. tables) which allows them to contain characters not otherwise permitted, or be the same as reserved words (Avoid this, really).
Single quotes are for strings.
However, MySQL is oblivious to the standard (unless its SQL_MODE is changed) and allows them to be used interchangably for strings.
Moreover, Sybase and Microsoft also use square brackets for identifier quoting.
So it's a bit vendor specific.
Other databases such as Postgres and IBM actually adhere to the ansi standard :)
Alternate way using Zk-Client:
If you do not prefer to pass arguments to ./zookeeper-shell.sh
and want to see the broker details from Zookeeper CLI, you need to install standalone Zookeeper (As traditional Kafka do not comes up with Jline JAR).
Once you install(unzip) the standalone Zookeeper,then:
Run the Zookeeper CLI:
$ zookeeper/bin/zkCli.sh -server localhost:2181
#Make sure your Broker is already running
If it is successful, you can see the Zk client running as:
WATCHER::
WatchedEvent state:SyncConnected type:None path:null
[zk: localhost:2181(CONNECTED) 0]
$ ls /brokers/ids
# Gives the list of active brokers
$ ls /brokers/topics
#Gives the list of topics
$ get /brokers/ids/0
#Gives more detailed information of the broker id '0'
Since there is no php.ini file in your /public_html directory......create a new file as phpinfo.php in /public_html directory
-Type this code in phpinfo.php and save it:
<?php
phpinfo();
?>
-Then type yourdomain.com/phpinfo.php...you will see all the details of your configuration
-To edit that config, create another file as php.ini in /public_html directory and paste this code:
memory_limit=512M
post_max_size=200M
upload_max_filesize=200M
-And then refresh yourdomain.com/phpinfo.php and see the changes,it will be done.
I would recommend you to use background-image instead of default list.
.listStyle {
list-style: none;
background: url(image_path.jpg) no-repeat left center;
padding-left: 30px;
width: 20px;
height: 20px;
}
Or, if you don't want to use background-image as bullet, there is an option to do it with pseudo element:
.liststyle{
list-style: none;
margin: 0;
padding: 0;
}
.liststyle:before {
content: "• ";
color: red; /* or whatever color you prefer */
font-size: 20px;/* or whatever the bullet size you prefer */
}
I am not a linux guru, but I believe you want to pipe your list of output files to xargs rm -rf
. I have used something like this in the past with good results. Test on a sample directory first!
EDIT - I might have misunderstood, based on the other answers that are appearing. If you can use wildcards, great. I assumed that your original list that you displayed was generated by a program to give you your "selection", so I thought piping to xargs
would be the way to go.
Try:
SELECT * FROM table1
LEFT OUTER JOIN table2
ON table1.FirstName = table2.FirstName and table1.LastName=table2.LastName
WHERE table2.BirthDate IS NULL
There's a new method to do this in ES6/2015 using findIndex and array spread operator:
const index = data.findIndex(obj => obj.id === id);
const newData = [
...data.slice(0, index),
...data.slice(index + 1)
]
You can turn it into a function for later reuse like this:
function remove(array, key, value) {
const index = array.findIndex(obj => obj[key] === value);
return index >= 0 ? [
...array.slice(0, index),
...array.slice(index + 1)
] : array;
}
This way you can to remove items by different keys using one method (and if there's no object that meets the criteria, you get original array returned):
const newData = remove(data, "id", "88");
const newData2 = remove(data, "name", "You are awesome!");
Or you can put it on your Array.prototype:
Array.prototype.remove = function (key, value) {
const index = this.findIndex(obj => obj[key] === value);
return index >= 0 ? [
...this.slice(0, index),
...this.slice(index + 1)
] : this;
};
And use it this way:
const newData = data.remove("id", "88");
const newData2 = data.remove("name", "You are awesome!");
If your main element has some child elements or text, you could make use of it.
Position your main element relative (or absolute/fixed) and use both :before and :after positioned absolute (in my situation it had to be absolute, don't know about your's).
Now if you want one more pseudo-element, attach an absolute :before to one of the main element's children (if you have only text, put it in a span, now you have an element), which is not relative/absolute/fixed.
This element will start acting like his owner is your main element.
HTML
<div class="circle">
<span>Some text</span>
</div>
CSS
.circle {
position: relative; /* or absolute/fixed */
}
.circle:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle:after {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle span {
/* not relative/absolute/fixed */
}
.circle span:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
Alternative which I did programming Angular:
<div class="form-row">
<div class="form-group col-md-7">
Left
</div>
<div class="form-group col-md-5">
Right
</div>
</div>
I encountered the same issue. This worked:
>>> import pkg_resources
>>> pkg_resources.require("google-api-python-client")
[google-api-python-client 1.5.3 (c:\python27), uritemplate 0.6 (c:\python27\lib\site-packages\uritemplate-0.6-py2.7.egg), six 1.10.0 (c:\python27\lib\site-packages\six-1.10.0-py2.7.egg), oauth2client 3.0.0 (c:\python27\lib\site-packages\oauth2client-3.0.0-py2.7.egg), httplib2 0.9.2 (c:\python27\lib\site-packages\httplib2-0.9.2-py2.7.egg), simplejson 3.8.2 (c:\python27\lib\site-packages\simplejson-3.8.2-py2.7-win32.egg), six 1.10.0 (c:\python27\lib\site-packages\six-1.10.0-py2.7.egg), rsa 3.4.2 (c:\python27\lib\site-packages\rsa-3.4.2-py2.7.egg), pyasn1-modules 0.0.8 (c:\python27\lib\site-packages\pyasn1_modules-0.0.8-py2.7.egg), pyasn1 0.1.9 (c:\python27\lib\site-packages\pyasn1-0.1.9-py2.7.egg)]
>>> from apiclient.discovery import build
>>>
Here x is a vector. You need to convert it into a dataframe for using $ operator.
x <- as.data.frame(x)
will work for you.
x<-c(1,2)
names(x)<- c("bob","ed")
x <- as.data.frame(x)
will give you output of x as:
bob 1
ed 2
And, will give you output of x$ed as:
NULL
If you want bob and ed as column names then you need to transpose the dataframe like x <- as.data.frame(t(x))
So your code becomes
x<-c(1,2)
x
names(x)<- c("bob","ed")
x$ed
x <- as.data.frame(t(x))
Now the output of x$ed is:
[1] 2
In my case, this happen because of I deleted the Main.storyboard
and in general tab Main Interface
property cleared and added custom one as Start
. After I Change the Main Interface
to Start.storyboard
except Start
it's working.
The main difference is when compiled in debug mode, pdb files are also created which allow debugging (so you can step through the code when its running). This however means that the code isn't optimized as much.
What the guidelines say is that the public API should not reveal the internal design decision of whether you are using a list, a set, a dictionary, a tree or whatever. A "team" is not necessarily a list. You may implement it as a list but users of your public API should use you class on a need to know basis. This allows you to change your decision and use a different data structure without affecting the public interface.
Put export LD_LIBRARY_PATH=/usr/local/lib
in ~/.bashrc
[preferably towards end of script to avoid any overrides in between, Default ~/.bashrc
comes with many if-else
statements]
Post that whenever you open a new terminal/konsole, LD_LIBRARY_PATH
will be reflected
The key here is to unlist the row first.
colnames(DF) <- as.character(unlist(DF[1,]))
DF = DF[-1, ]
You use the lpMultiByteStr [out] parameter by creating a new char array. You then pass this char array in to get it filled. You only need to initialize the length of the string + 1 so that you can have a null terminated string after the conversion.
Here are a couple of useful helper functions for you, they show the usage of all parameters.
#include <string>
std::string wstrtostr(const std::wstring &wstr)
{
// Convert a Unicode string to an ASCII string
std::string strTo;
char *szTo = new char[wstr.length() + 1];
szTo[wstr.size()] = '\0';
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);
strTo = szTo;
delete[] szTo;
return strTo;
}
std::wstring strtowstr(const std::string &str)
{
// Convert an ASCII string to a Unicode String
std::wstring wstrTo;
wchar_t *wszTo = new wchar_t[str.length() + 1];
wszTo[str.size()] = L'\0';
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo, (int)str.length());
wstrTo = wszTo;
delete[] wszTo;
return wstrTo;
}
--
Anytime in documentation when you see that it has a parameter which is a pointer to a type, and they tell you it is an out variable, you will want to create that type, and then pass in a pointer to it. The function will use that pointer to fill your variable.
So you can understand this better:
//pX is an out parameter, it fills your variable with 10.
void fillXWith10(int *pX)
{
*pX = 10;
}
int main(int argc, char ** argv)
{
int X;
fillXWith10(&X);
return 0;
}
As mentioned above, the gnuwin32 project has a Windows CLI version of grep.
If you want something with a graphical interface, I would recommend the (open-source) tool AstroGrep.
i wouldn't do it this way
I'd use name arrays in the form elements
so i'd get the layout
$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';
then you could do an array slice to get the amount you need
If you don't want to validate all the calls to doSomething()
, only the last one, you can just use ArgumentCaptor.getValue()
. According to the Mockito javadoc:
If the method was called multiple times then it returns the latest captured value
So this would work (assumes Foo
has a method getName()
):
ArgumentCaptor<Foo> fooCaptor = ArgumentCaptor.forClass(Foo.class);
verify(mockBar, times(2)).doSomething(fooCaptor.capture());
//getValue() contains value set in second call to doSomething()
assertEquals("2nd one", fooCaptor.getValue().getName());
There is one common answer I haven't see here yet, which is the Window Function. It is an alternative to the correlated sub-query, if your DB supports it.
SELECT sensorID,timestamp,sensorField1,sensorField2
FROM (
SELECT sensorID,timestamp,sensorField1,sensorField2
, ROW_NUMBER() OVER(
PARTITION BY sensorID
ORDER BY timestamp
) AS rn
FROM sensorTable s1
WHERE rn = 1
ORDER BY sensorID, timestamp;
I acually use this more than correlated sub-queries. Feel free to bust me in the comments over effeciancy, I'm not too sure how it stacks up in that regard.
yeah, this happens sometimes for no apparent reason. You can go to the "Problems"-Tab (right next to console output) and see the error message, so maybe you can narrow it down that way.
You can use .is(':visible')
Selects all elements that are visible.
For example:
if($('#selectDiv').is(':visible')){
Also, you can get the div which is visible by:
$('div:visible').callYourFunction();
Live example:
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
display: none; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
The main problem with doing it this way is mainly that you will need to remember to update your version number in your code every time you make any change to your css or js files.
A possibly better way to do it is to set a guaranteed unique parameter with each of your css or js files, like so:
<script src="scripts/myjavascript.js?_=<%=DateTime.Now.Ticks%>" type="text/javascript"></script>
<link href="styles/mystyle.css?_=<%=DateTime.Now.Ticks%>" rel="stylesheet" type="text/css" />
This forces the files to be requested from the server every single time, which also means that your site will not be as performant upon page load, since those files will never be cached, and will use unneeded bandwidth each time.
Essentially, if you can remember to update the version number every time a change is made, you can get away with how you're doing it.
e can also select rows based on values of a column that are not in a list or any iterable. We will create boolean variable just like before, but now we will negate the boolean variable by placing ~ in the front.
For example
list = [1, 0]
df[df.col1.isin(list)]
Check out the .read() method of the File object:
http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects
You could do something like:
concat = ""
for file in files:
concat += open(file).read()
or a more 'elegant' python-way:
concat = ''.join([open(f).read() for f in files])
which, according to this article: http://www.skymind.com/~ocrow/python_string/ would also be the fastest.
Just move it :)
command line :
move "C:\Documents and Setings\$USER\project" C:\project
or just drag the folder in explorer.
Git won't care where it is - all the metadata for the repository is inside a folder called .git
inside your project folder.
"Editor's" note: This post may contain outdated information. Please see comments and this question regarding changes in Git since 1.6.1.
Symlinked directories:
It's important to note what happens when there is a directory which is a soft link. Any Git pull with an update removes the link and makes it a normal directory. This is what I learnt hard way. Some insights here and here.
Example
Before
ls -l
lrwxrwxrwx 1 admin adm 29 Sep 30 15:28 src/somedir -> /mnt/somedir
git add/commit/push
It remains the same
After git pull
AND some updates found
drwxrwsr-x 2 admin adm 4096 Oct 2 05:54 src/somedir
You could split the string on the whitespace and then re-add it, since you know its in between every one of the entries.
var string = "text to split";
string = string.split(" ");
var stringArray = new Array();
for(var i =0; i < string.length; i++){
stringArray.push(string[i]);
if(i != string.length-1){
stringArray.push(" ");
}
}
Update: Removed trailing space.
The first set of errors, for the missing vtable, are caused because you do not implement takeaway::textualGame()
; instead you implement a non-member function, textualGame()
. I think that adding the missing takeaway::
will fix that.
The cause of the last error is that you're calling a virtual function, initialData()
, from the constructor of gameCore
. At this stage, virtual functions are dispatched according to the type currently being constructed (gameCore
), not the most derived class (takeaway
). This particular function is pure virtual, and so calling it here gives undefined behaviour.
Two possible solutions:
gameCore
out of the constructor and into a separate initialisation function, which must be called after the object is fully constructed; orgameCore
into two classes: an abstract interface to be implemented by takeaway
, and a concrete class containing the state. Construct takeaway
first, and then pass it (via a reference to the interface class) to the constructor of the concrete class.I would recommend the second, as it is a move towards smaller classes and looser coupling, and it will be harder to use the classes incorrectly. The first is more error-prone, as there is no way be sure that the initialisation function is called correctly.
One final point: the destructor of a base class should usually either be virtual (to allow polymorphic deletion) or protected (to prevent invalid polymorphic deletion).
If you want to be able to perform a lookup on each type to get its frequency then you will need to transform the enumeration into a dictionary.
var types = new[] {typeof(string), typeof(string), typeof(int)};
var x = types
.GroupBy(type => type)
.ToDictionary(g => g.Key, g => g.Count());
foreach (var kvp in x) {
Console.WriteLine("Type {0}, Count {1}", kvp.Key, kvp.Value);
}
Console.WriteLine("string has a count of {0}", x[typeof(string)]);