1) you can float the image to the left:
<img style="float:left" src="http://i.imgur.com/hCrQkJi.png">
2)You can use an HTML table to place elements on one line.
Code below
<div class="navigation-bar">
<div id="navigation-container">
<table>
<tr>
<td><img src="http://i.imgur.com/hCrQkJi.png"></td>
<td><ul>
<li><a href="#">Home</a></li>
<li><a href="#">Projects</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Get in Touch</a></li>
</ul>
</td></tr></table>
</div>
Use the jQuery hashchange event plugin instead. Regarding your full ajax navigation, try to have SEO friendly ajax. Otherwise your pages shown nothing in browsers with JavaScript limitations.
To create icon you can use Glyphicon in Bootstrap:
<a href="#" class="btn btn-info btn-sm">
<span class="glyphicon glyphicon-menu-hamburger"></span>
</a>
And then control size of icon in css:
.glyphicon-menu-hamburger {
font-size: npx;
}
Use text-align:justify
on the container, this way it will work no matter how many elements you have in your list (you don't have to work out % widths for each list item
#nav {_x000D_
text-align: justify;_x000D_
min-width: 500px;_x000D_
}_x000D_
#nav:after {_x000D_
content: '';_x000D_
display: inline-block;_x000D_
width: 100%;_x000D_
}_x000D_
#nav li {_x000D_
display: inline-block;_x000D_
}
_x000D_
<ul id="nav">_x000D_
<li><a href="#">HOME</a></li>_x000D_
<li><a href="#">ABOUT</a></li>_x000D_
<li><a href="#">BASIC SERVICES</a></li>_x000D_
<li><a href="#">OUR STAFF</a></li>_x000D_
<li><a href="#">CONTACT US</a></li>_x000D_
</ul>
_x000D_
The CSS :active
state means the active state of the clicked link - the moment when you clicked on it, but not released the mouse button yet, for example. It doesn't know which page you're on and can't apply any styles to the menu items.
To fix your problem you have to create a class and add it manually to the current page's menu:
a.active { color: #f00 }
<ul>
<li><a href="index.php" class="active">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
<li><a href="three.php">ABOUT</a></li>
<li><a href="four.php">CONTACT</a></li>
<li><a href="five.php">SHOP</a></li>
</ul>
Try these:
window.location.href = 'http://www.google.com';
window.location.assign("http://www.w3schools.com");
window.location = 'http://www.google.com';
For more see this link: other ways to reload the page with JavaScript
Add this code in your view controller
UIView *myView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 300, 30)];
UIBarButtonItem *btnL = [[UIBarButtonItem alloc]initWithCustomView:myView];
self.navigationItem.leftBarButtonItem = btnL;
If there isn't a pressing need to use images for the separators, you could do this with pure CSS.
nav li + li:before{
content: " | ";
padding: 0 10px;
}
This puts a bar between each list item, just as the image in the original question described. But since we're using the adjacent selectors, it doesn't put the bar before the first element. And since we're using the :before
pseudo selector, it doesn't put one at the end.
I've found the best implementation. It's in the Google I/O 2014 app.
They use the same approach as Kevin's. If you can abstract yourself from all unneeded stuff in I/O app, you could extract everything you need and it is assured by Google that it's a correct usage of navigation drawer pattern.
Each activity optionally has a DrawerLayout
as its main layout. The interesting part is how the navigation to other screens is done. It is implemented in BaseActivity
like this:
private void goToNavDrawerItem(int item) {
Intent intent;
switch (item) {
case NAVDRAWER_ITEM_MY_SCHEDULE:
intent = new Intent(this, MyScheduleActivity.class);
startActivity(intent);
finish();
break;
This differs from the common way of replacing current fragment by a fragment transaction. But the user doesn't spot a visual difference.
i think it is simple just add headerLeft : null
, i am using react-native cli, so this is the example :
static navigationOptions = {
headerLeft : null
};
There really isn't a difference; there are about 5 different methods of doing it. However, the ones I see most often are document.location
and window.location
because they're supported by all major browsers. (I've personally never seen window.navigate
used in production code, so maybe it doesn't have very good support?)
If you only want your navigation to toggle when used on a mobile screen, just adding data-toggle="collapse"
and data-target="#navbar"
to your a elements will work on the mobile screen, but will give you a weird flicker when clicked on a desktop screen. The jQuery solutions do not work well if you are in an Aurelia or Angular environment.
The best solution for me was to create a custom attribute that listens to the corresponding media query and adds in the data-toggle="collapse"
attribute if desired:
<a href="#" ... collapse-toggle-if-less768 data-target="#navbar"> ...
The custom attribute with Aurelia looks like this:
import {autoinject} from 'aurelia-framework';_x000D_
_x000D_
@autoinject_x000D_
export class CollapseToggleIfLess768CustomAttribute {_x000D_
element: Element;_x000D_
_x000D_
constructor(element: Element) {_x000D_
this.element = element;_x000D_
var mql = window.matchMedia("(min-width: 768px)");_x000D_
mql.addListener((mediaQueryList: MediaQueryList) => this.handleMediaChange(mediaQueryList));_x000D_
this.handleMediaChange(mql);_x000D_
}_x000D_
_x000D_
handleMediaChange(mediaQueryList: MediaQueryList) {_x000D_
if (mediaQueryList.matches) {_x000D_
var dataToggle = this.element.attributes.getNamedItem("data-toggle");_x000D_
if (dataToggle) {_x000D_
this.element.attributes.removeNamedItem("data-toggle");_x000D_
}_x000D_
} else {_x000D_
var dataToggle = this.element.attributes.getNamedItem("data-toggle");_x000D_
if (!dataToggle) {_x000D_
var dataToggle = document.createAttribute("data-toggle");_x000D_
dataToggle.value = "collapse";_x000D_
this.element.attributes.setNamedItem(dataToggle);_x000D_
}_x000D_
}_x000D_
}_x000D_
}
_x000D_
Just want to add some description over @Jackpap answer:
automaticallyImplyLeading:
This checks whether we want to apply the back widget(leading widget) over the app bar or not. If the automaticallyImplyLeading is false then automatically space is given to the title and if If the leading widget is true, then this parameter has no effect.
void main() {
runApp(
new MaterialApp(
home: new Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false, // Used for removing back buttoon.
title: new Center(
child: new Text("Demo App"),
),
),
body: new Container(
child: new Center(
child: Text("Hello world!"),
),
),
),
),
);
}
Try this. I think this will help you.
override fun onBackPressed() {
when (mNavController.getCurrentDestination()!!.getId()) {
R.id.loginFragment -> {
onWarningAlertDialog(this, "Alert", "Do you want to close this application ?")
}
R.id.registerFragment -> {
super.onBackPressed()
}
}
}
private fun onWarningAlertDialog(mainActivity: MainActivity, s: String, s1: String) {
val dialogBuilder = AlertDialog.Builder(this)
dialogBuilder.setMessage(/*""*/s1)
.setCancelable(false)
.setPositiveButton("Proceed", DialogInterface.OnClickListener { dialog, id ->
finish()
})
.setNegativeButton("Cancel", DialogInterface.OnClickListener { dialog, id ->
dialog.cancel()
})
// create dialog box
val alert = dialogBuilder.create()
// set title for alert dialog box
alert.setTitle("AlertDialogExample")
// show alert dialog
alert.show()
}
According to pywin32 github you must run
pip install pywin32
and after that, you must run
python Scripts/pywin32_postinstall.py -install
I know I'm reviving an old thread, but I just had this problem and this was the only way to solve it.
To avoid entering username, but still be prompted to enter a password, then you can simply clone your repository including the username:
git clone [email protected]/my_repo.git
One more solution using Typescript:
let updatedArray = [];
for (let el of this.oldArray) {
if (el !== elementToRemove) {
updated.push(el);
}
}
this.oldArray = updated;
In my case, the issue was that my teammate mentioned *ngfor
in templates instead of *ngFor
. Strange that there is no correct error to handle this issue (In Angular 4).
You should use raw_input
to take a string input. then use islower
method of str
object.
s = raw_input('Type a word')
l = []
for c in s.strip():
if c.islower():
print c
l.append(c)
print 'Total number of lowercase letters: %d'%(len(l) + 1)
Just do -
dir(s)
and you will find islower
and other attributes of str
I've chmoded my keypair to 600 in order to get into my personal instance last night,
And this is the way it is supposed to be.
From the EC2 documentation we have "If you're using OpenSSH (or any reasonably paranoid SSH client) then you'll probably need to set the permissions of this file so that it's only readable by you." The Panda documentation you link to links to Amazon's documentation but really doesn't convey how important it all is.
The idea is that the key pair files are like passwords and need to be protected. So, the ssh client you are using requires that those files be secured and that only your account can read them.
Setting the directory to 700 really should be enough, but 777 is not going to hurt as long as the files are 600.
Any problems you are having are client side, so be sure to include local OS information with any follow up questions!
For Eclipse users...
Click Run —> Run configuration —> are —> set Alternate JRE for 1.6 or 1.7
You can also use a counter! It doesn't preserve the order, but it'll consider the duplicates:
>>> from collections import Counter
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> d1, d2 = Counter(a), Counter(b)
>>> c = [n for n in d1.keys() & d2.keys() for _ in range(min(d1[n], d2[n]))]
>>> print(c)
[1,3,5]
Protected Member
Protected Member of a class in only available in the contained class (in which it has been declared) and in the derived class within the assembly and also outside the assembly.
Means if a class that resides outside the assembly can use the protected member of the other assembly by inherited that class only.
We can exposed the Protected member outside the assembly by inherited that class and use it in the derived class only.
Note: Protected members are not accessible using the object in the derived class.
Internal Member
Internal Member of a class is available or access within the assembly either creating object or in a derived class or you can say it is accessible across all the classes within the assembly.
Note: Internal members not accessible outside the assembly either using object creating or in a derived class.
Protected Internal
Protected Internal access modifier is combination Protected or Internal.
Protected Internal Member can be available within the entire assembly in which it declared either creating object or by inherited that class. And can be accessible outside the assembly in a derived class only.
Note: Protected Internal member works as Internal within the same assembly and works as Protected for outside the assembly.
What is ARIA?
ARIA emerged as a way to address the accessibility problem of using a markup language intended for documents, HTML, to build user interfaces (UI). HTML includes a great many features to deal with documents (P, h3,UL,TABLE) but only basic UI elements such as A, INPUT and BUTTON. Windows and other operating systems support APIs that allow (Assistive Technology) AT to access the functionality of UI controls. Internet Explorer and other browsers map the native HTML elements to the accessibility API, but the html controls are not as rich as the controls common on desktop operating systems, and are not enough for modern web applications Custom controls can extend html elements to provide the rich UI needed for modern web applications. Before ARIA, the browser had no way to expose this extra richness to the accessibility API or AT. The classic example of this issue is adding a click handler to an image. It creates what appears to be a clickable button to a mouse user, but is still just an image to a keyboard or AT user.
The solution was to create a set of attributes that allow developers to extend HTML with UI semantics. The ARIA term for a group of HTML elements that have custom functionality and use ARIA attributes to map these functions to accessibility APIs is a “Widget. ARIA also provides a means for authors to document the role of content itself, which in turn, allows AT to construct alternate navigation mechanisms for the content that are much easier to use than reading the full text or only iterating over a list of the links.
It is important to remember that in simple cases, it is much preferred to use native HTML controls and style them rather than using ARIA. That is don’t reinvent wheels, or checkboxes, if you don’t have to.
Fortunately, ARIA markup can be added to existing sites without changing the behavior for mainstream users. This greatly reduces the cost of modifying and testing the website or application.
To select data in numerical range you can use BETWEEN
which is inclusive.
SELECT JOB FROM MYTABLE WHERE ID BETWEEN 10 AND 15;
you can use this project to play any you tube video , in your android app . Now for other video , or Video id ... you can do this https://gdata.youtube.com/feeds/api/users/eminemvevo/uploads/ where eminemvevo = channel .
after finding , video id , you can put that id in cueVideo("video_id")
src -> com -> examples -> youtubeapidemo -> PlayerViewDemoActivity
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player , boolean wasRestored) {
if (!wasRestored) {
player.cueVideo("wKJ9KzGQq0w");
}
}
And specially for reading that video_id in a better way open this , and it as a xml[1st_file
] file in your desktop after it create a new Xml file in your project
or upload that[1st_file
] saved file in your project , and right_click in it , and open it with xml_editor file , here you will find the video id of the particular video .
It's an old question now, nevertheless I had the same issue and found a solution that works for me: I wrote MultiRedirectMixin.
from django.http import HttpResponseRedirect
class MultiRedirectMixin(object):
"""
A mixin that supports submit-specific success redirection.
Either specify one success_url, or provide dict with names of
submit actions given in template as keys
Example:
In template:
<input type="submit" name="create_new" value="Create"/>
<input type="submit" name="delete" value="Delete"/>
View:
MyMultiSubmitView(MultiRedirectMixin, forms.FormView):
success_urls = {"create_new": reverse_lazy('create'),
"delete": reverse_lazy('delete')}
"""
success_urls = {}
def form_valid(self, form):
""" Form is valid: Pick the url and redirect.
"""
for name in self.success_urls:
if name in form.data:
self.success_url = self.success_urls[name]
break
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
"""
Returns the supplied success URL.
"""
if self.success_url:
# Forcing possible reverse_lazy evaluation
url = force_text(self.success_url)
else:
raise ImproperlyConfigured(
_("No URL to redirect to. Provide a success_url."))
return url
What ever attribute is added to the button/anchor/link to disable it, bootstrap is just adding style to it and user will still be able to click it while there is still onclick event. So my simple solution is to check if it is disabled and remove/add onclick event:
if (!('#button').hasAttr('disabled'))
$('#button').attr('onclick', 'someFunction();');
else
$('#button').removeattr('onclick');
package main
import "fmt"
import "strconv"
func FloatToString(input_num float64) string {
// to convert a float number to a string
return strconv.FormatFloat(input_num, 'f', 6, 64)
}
func main() {
fmt.Println(FloatToString(21312421.213123))
}
If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg
strconv.FormatFloat(input_num, 'f', -1, 64)
Personally I find fmt
easier to use. (Playground link)
fmt.Printf("x = %.6f\n", 21312421.213123)
Or if you just want to convert the string
fmt.Sprintf("%.6f", 21312421.213123)
The first method is right.
The second method kills kittens if you attempt to do anything with x
after the fact other than Object
methods.
Put very simple ::
is the scoping operator, .
is the access operator (I forget what the actual name is?), and ->
is the dereference arrow.
::
- Scopes a function. That is, it lets the compiler know what class the function lives in and, thus, how to call it. If you are using this operator to call a function, the function is a static
function.
.
- This allows access to a member function on an already created object. For instance, Foo x; x.bar()
calls the method bar()
on instantiated object x
which has type Foo
. You can also use this to access public class variables.
->
- Essentially the same thing as .
except this works on pointer types. In essence it dereferences the pointer, than calls .
. Using this is equivalent to (*ptr).method()
I tried the answer by Sibeesh Venu, but that didn't work for me. I believe that if I had killed all chrome processes, it would have worked. I completed some other testing and found that turning off "Continue where you left off" in Chrome settings ensured that this did not occur again for me.
Ask "What unit testing framework do you use? and why?"
You can decide if actually using a testing framework is really necessary, but the conversation might tell you a lot about how expert the person is.
I don't think you can "legally" load only part of an XML file, since then it would be malformed (there would be a missing closing element somewhere).
Using LINQ-to-XML, you can do var doc = XDocument.Load("yourfilepath")
. From there its just a matter of querying the data you want, say like this:
var authors = doc.Root.Elements().Select( x => x.Element("Author") );
HTH.
EDIT:
Okay, just to make this a better sample, try this (with @JWL_'s suggested improvement):
using System;
using System.Xml.Linq;
namespace ConsoleApplication1 {
class Program {
static void Main( string[] args ) {
XDocument doc = XDocument.Load( "XMLFile1.xml" );
var authors = doc.Descendants( "Author" );
foreach ( var author in authors ) {
Console.WriteLine( author.Value );
}
Console.ReadLine();
}
}
}
You will need to adjust the path in XDocument.Load()
to point to your XML file, but the rest should work. Ask questions about which parts you don't understand.
One line solution:
& ((Split-Path $MyInvocation.InvocationName) + "\MyScript1.ps1")
Run below command into the current branch folder to merge from this <commit-id>
to current branch, --no-commit
do not make a new commit automatically
git merge --no-commit <commit-id>
git merge --continue
can only be run after the merge has resulted in conflicts.
git merge --abort
Abort the current conflict resolution process, and try to reconstruct the pre-merge state.
The CP1 means 'Code Page 1' - technically this translates to code page 1252
For those who want to do this in pure javascript, look at:
As Joe comment it, KeyboardEvent is now the standard.
Same example to fire an enter (keyCode 13):
const ke = new KeyboardEvent('keydown', {
bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);
You can use this page help you to find the right keyboard event.
Outdated answer:
You can do something like (here for Firefox)
var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);
Define "doesn't work".
const date = moment("2015-07-02"); // Thursday Feb 2015_x000D_
const dow = date.day();_x000D_
console.log(dow);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
This prints "4", as expected.
You may be used to MySQL's syntax: Microsoft SQL @
is the same as the MySQL's ?
I'm not sure what your goal is, but might it be better to use addClass instead? I mean an objects ID in my opinion should be static and specific to that object. If you are just trying to change it from showing on the page or something like that I would put those details in a class and then add it to the object rather then trying to change it's ID. Again, I'm saying that without understand your underlining goal.
FYI, I've got the same error from Chrome console. I thought my AJAX function causing it, but I uncommented my minified script from /javascripts/ajax-vanilla.min.js
to /javascripts/ajax-vanilla.js
. But in reality the source file was at /javascripts/src/ajax-vanilla.js
. So in Chrome you getting bad MIME type error even if the file cannot be found. In this case, the error message is described as text/plain
bad MIME type.
It's simple, every time you open Jupyter Notebook and you are in your current work directory, open the Terminal in the near top right corner position where create new Python file in. The terminal in Jupyter will appear in the new tab.
Type command cd <your new work directory>
and enter, and then type Jupyter Notebook
in that terminal, a new Jupyter Notebook will appear in the new tab with your new work directory.
It looks to me like PATH lists the first-generation dependencies directly from your gemspec, whereas GEM lists second-generation dependencies (i.e. what your dependencies depend on) and those from your Gemfile. PATH::remote is .
because it relied on a local gemspec in the current directory to find out what belongs in PATH::spec, whereas GEM::remote is rubygems.org
, since that's where it had to go to find out what belongs in GEM::spec.
In a Rails plugin, you'll see a PATH section, but not in a Rails app. Since the app doesn't have a gemspec file, there would be nothing to put in PATH.
As for DEPENDENCIES, gembundler.com states:
Runtime dependencies in your gemspec are treated like base dependencies,
and development dependencies are added by default to the group, :development
The Gemfile generated by rails plugin new my_plugin
says something similar:
# Bundler will treat runtime dependencies like base dependencies, and
# development dependencies will be added by default to the :development group.
What this means is that the difference between
s.add_development_dependency "july" # (1)
and
s.add_dependency "july" # (2)
is that (1) will only include "july" in Gemfile.lock (and therefore in the application) in a development environment. So when you run bundle install
, you'll see "july" not only under PATH but also under DEPENDENCIES, but only in development. In production, it won't be there at all. However, when you use (2), you'll see "july" only in PATH, not in DEPENDENCIES, but it will show up when you bundle install
from a production environment (i.e. in some other gem that includes yours as a dependency), not only development.
These are just my observations and I can't fully explain why any of this is the way it is but I welcome further comments.
In your code:
var obj = {
myProp: string;
};
You are actually creating a object literal and assigning the variable string to the property myProp. Although very bad practice this would actually be valid TS code (don't use this!):
var string = 'A string';
var obj = {
property: string
};
However, what you want is that the object literal is typed. This can be achieved in various ways:
Interface:
interface myObj {
property: string;
}
var obj: myObj = { property: "My string" };
Type alias:
type myObjType = {
property: string
};
var obj: myObjType = { property: "My string" };
Object type literal:
var obj: { property: string; } = { property: "Mystring" };
The following commands (modified after those found here) worked for me on my WSL install of Ubuntu after hours of trial and error:
sudo service mysql stop
sudo mysqld --skip-grant-tables &
mysql -u root mysql
UPDATE mysql.user SET authentication_string=null WHERE User='root';
flush privileges;
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_new_password_here';
flush privileges;
exit;
The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity
changes.
Instead you could try the following approach. Change your markup to the following:
<div ng-controller="myAppController" style="text-align:center">
<p style="font-size:28px;">Enter Quantity:
<input type="text" ng-model="quantity"/>
</p>
<button ng-click="calculateQuantity()">Calculate</button>
<h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>
Next, update your controller:
myAppModule.controller('myAppController', function($scope,calculateService) {
$scope.quantity=1;
$scope.quantityResult = 0;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
};
});
Here's a JSBin example that demonstrates the above approach.
The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity
changes.
This would involve updating the template to add an ng-change
on the input, and an ng-if
on the result:
<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>
and
<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>
In the controller add:
$scope.showQuantityResult = false;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
$scope.showQuantityResult = true;
};
$scope.hideQuantityResult = function() {
$scope.showQuantityResult = false;
};
These updates can be seen in this JSBin demo.
I am using ng-class for adding style :-
ng-class="column.label=='Description' ? 'tableStyle':
column.label == 'Markdown Type' ? 'Mtype' :
column.label == 'Coupon Number' ? 'couponNur' : ''
"
Using ternary operator along with ng-class directives in angular.js for giving style. Then define the style for class in .css or .scss file. Eg :-
.Mtype{
width: 90px !important;
min-width: 90px !important;
max-width: 90px !important;
}
.tableStyle{
width: 129px !important;
min-width: 129px !important;
max-width: 129px !important;
}
.couponNur{
width: 250px !important;
min-width: 250px !important;
max-width: 250px !important;
}
1.
To_Date(To_Char(MaxDate, 'DD/MM/YYYY')) = REP_DATE
is causing the issue. when you use to_date without the time format, oracle will use the current sessions NLS format to convert, which in your case might not be "DD/MM/YYYY". Check this...
SQL> select sysdate from dual;
SYSDATE
---------
26-SEP-12
Which means my session's setting is DD-Mon-YY
SQL> select to_char(sysdate,'MM/DD/YYYY') from dual;
TO_CHAR(SY
----------
09/26/2012
SQL> select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual;
select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual
*
ERROR at line 1:
ORA-01843: not a valid month
SQL> select to_date(to_char(sysdate,'MM/DD/YYYY'),'MM/DD/YYYY') from dual;
TO_DATE(T
---------
26-SEP-12
2.
More importantly, Why are you converting to char and then to date, instead of directly comparing
MaxDate = REP_DATE
If you want to ignore the time component in MaxDate before comparision, you should use..
trunc(MaxDate ) = rep_date
instead.
==Update : based on updated question.
Rep_Date = 01/04/2009 Rep_Time = 01/01/1753 13:00:00
I think the problem is more complex. if rep_time is intended to be only time, then you cannot store it in the database as a date. It would have to be a string or date to time interval or numerically as seconds (thanks to Alex, see this) . If possible, I would suggest using one column rep_date that has both the date and time and compare it to the max date column directly.
If it is a running system and you have no control over repdate, you could try this.
trunc(rep_date) = trunc(maxdate) and
to_char(rep_date,'HH24:MI:SS') = to_char(maxdate,'HH24:MI:SS')
Either way, the time is being stored incorrectly (as you can tell from the year 1753) and there could be other issues going forward.
JAVA Fax Api documentation
You could download the mac 2.2 preview release from here and unzip it.
http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html
The javadoc won't quite match 2.1, but it will be close and if you use the preview instead, it will match exactly.
I think this would help you :)
Primitives vs. References
First :-
Primitive types are the basic types of data:
byte
, short
, int
, long
, float
, double
, boolean
, char
.
Primitive variables store primitive values.
Reference types are any instantiable class as well as arrays:
String
, Scanner
, Random
, Die
, int[]
, String[]
, etc.
Reference variables store addresses to locations in memory for where the data is stored.
Second:-
Primitive types store values but Reference type store handles to objects in heap space. Remember, reference variables are not pointers like you might have seen in C and C++, they are just handles to objects, so that you can access them and make some change on object's state.
On socket.io >=1.0, after the connect event has triggered:
var socket = io('localhost');
var id = socket.io.engine.id
The cookie API is kind of lame. Let me clarify...
You don't update cookies; you overwrite them:
document.cookie = "username=Arnold"; // Create 'username' cookie
document.cookie = "username=Chuck"; // Update, i.e. overwrite, the 'username' cookie to "Chuck"
You also don't delete cookies; you expire them by setting the expires
key to a time in the past (-1 works too).
Source: https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
How do I print out my $ids and $nIds?
print "$ids\n";
print "$nIds\n";
I tried simply print $ids
, but Perl complains.
Complains about what? Uninitialised value? Perhaps your loop was never entered due to an error opening the file. Be sure to check if open
returned an error, and make sure you are using use strict; use warnings;
.
my ($ids, $nIds)
is a list, right? With two elements?
It's a (very special) function call. $ids,$nIds
is a list with two elements.
To make locking reliable you need an atomic operation. Many of the above proposals are not atomic. The proposed lockfile(1) utility looks promising as the man-page mentioned, that its "NFS-resistant". If your OS does not support lockfile(1) and your solution has to work on NFS, you have not many options....
NFSv2 has two atomic operations:
With NFSv3 the create call is also atomic.
Directory operations are NOT atomic under NFSv2 and NFSv3 (please refer to the book 'NFS Illustrated' by Brent Callaghan, ISBN 0-201-32570-5; Brent is a NFS-veteran at Sun).
Knowing this, you can implement spin-locks for files and directories (in shell, not PHP):
lock current dir:
while ! ln -s . lock; do :; done
lock a file:
while ! ln -s ${f} ${f}.lock; do :; done
unlock current dir (assumption, the running process really acquired the lock):
mv lock deleteme && rm deleteme
unlock a file (assumption, the running process really acquired the lock):
mv ${f}.lock ${f}.deleteme && rm ${f}.deleteme
Remove is also not atomic, therefore first the rename (which is atomic) and then the remove.
For the symlink and rename calls, both filenames have to reside on the same filesystem. My proposal: use only simple filenames (no paths) and put file and lock into the same directory.
use this : export MYVAR="$(dirname "$(dirname "$(dirname "$(dirname $PWD)")")")"
if you want 4th parent directory
export MYVAR="$(dirname "$(dirname "$(dirname $PWD)")")"
if you want 3rd parent directory
export MYVAR="$(dirname "$(dirname $PWD)")"
if you want 2nd parent directory
SELECT name, city, count(*) as qty
FROM stuff
GROUP BY name, city HAVING count(*)> 1
To make the text on the tick labels fully visible and read in the same direction as the y-axis label, change the last line to
q + theme(axis.text.x=element_text(angle=90, hjust=1))
I've had similar problems when the main method is on a different class than that passed to SpringApplcation.run()
So the solution would be to use the line you've commented out:
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
If you have installed a module on Xampp (on Linux) via Bitnami and changed chown
settings, make sure that the /opt/lampp/apps/<app>/htdocs
and tmp
usergroup is daemon
with all other sibling files and folders chown
ed to the user you installed as, e.g. cd /opt/lampp/apps/<app>
, sudo chown -R root:root .
, followed by sudo chown -R root:daemon htdocs tmp
.
This works in Windows; didn't check Linux but don't see why it wouldn't work. Download the zip files for 5.6.8 portable. Unzip the files and copy the xampp/htdocs to the xampp/htdocs in your install directory.
The built-in string constructor will automatically call obj.__str__
:
''.join(map(str,list))
The JSON sample you provided is not valid. Check it online with this JSON Validator http://jsonlint.com/. You need to remove the extra comma on line 59.
One you have valid json you can use this code to convert it to an array.
json_decode($json, true);
Array
(
[bpath] => http://www.sampledomain.com/
[clist] => Array
(
[0] => Array
(
[cid] => 11
[display_type] => grid
[ctitle] => abc
[acount] => 71
[alist] => Array
(
[0] => Array
(
[aid] => 6865
[adate] => 2 Hours ago
[atitle] => test
[adesc] => test desc
[aimg] =>
[aurl] => ?nid=6865
[weburl] => news.php?nid=6865
[cmtcount] => 0
)
[1] => Array
(
[aid] => 6857
[adate] => 20 Hours ago
[atitle] => test1
[adesc] => test desc1
[aimg] =>
[aurl] => ?nid=6857
[weburl] => news.php?nid=6857
[cmtcount] => 0
)
)
)
[1] => Array
(
[cid] => 1
[display_type] => grid
[ctitle] => test1
[acount] => 2354
[alist] => Array
(
[0] => Array
(
[aid] => 6851
[adate] => 1 Days ago
[atitle] => test123
[adesc] => test123 desc
[aimg] =>
[aurl] => ?nid=6851
[weburl] => news.php?nid=6851
[cmtcount] => 7
)
[1] => Array
(
[aid] => 6847
[adate] => 2 Days ago
[atitle] => test12345
[adesc] => test12345 desc
[aimg] =>
[aurl] => ?nid=6847
[weburl] => news.php?nid=6847
[cmtcount] => 7
)
)
)
)
)
What's a "block scheme"?
If I were drawing it, I might draw a box with "for each x in y" written in it.
If you're drawing a flowchart, there's always a loop with a decision box.
Nassi-Schneiderman diagrams have a loop construct you could use.
Indeed, you should use directives, and there is no event tied to the end of a ng-Repeat loop (as each element is constructed individually, and has it's own event). But a) using directives might be all you need and b) there are a few ng-Repeat specific properties you can use to make your "on ngRepeat finished" event.
Specifically, if all you want is to style/add events to the whole of the table, you can do so using in a directive that encompasses all the ngRepeat elements. On the other hand, if you want to address each element specifically, you can use a directive within the ngRepeat, and it will act on each element, after it is created.
Then, there are the $index
, $first
, $middle
and $last
properties you can use to trigger events. So for this HTML:
<div ng-controller="Ctrl" my-main-directive>
<div ng-repeat="thing in things" my-repeat-directive>
thing {{thing}}
</div>
</div>
You can use directives like so:
angular.module('myApp', [])
.directive('myRepeatDirective', function() {
return function(scope, element, attrs) {
angular.element(element).css('color','blue');
if (scope.$last){
window.alert("im the last!");
}
};
})
.directive('myMainDirective', function() {
return function(scope, element, attrs) {
angular.element(element).css('border','5px solid red');
};
});
See it in action in this Plunker. Hope it helps!
Python 3's range
type works just like Python 2's xrange
. I'm not sure why you're seeing a slowdown, since the iterator returned by your xrange
function is exactly what you'd get if you iterated over range
directly.
I'm not able to reproduce the slowdown on my system. Here's how I tested:
Python 2, with xrange
:
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)
18.631936646865853
Python 3, with range
is a tiny bit faster:
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)
17.31399508687869
I recently learned that Python 3's range
type has some other neat features, such as support for slicing: range(10,100,2)[5:25:5]
is range(20, 60, 10)
!
Yes it should be possible, even if the site is from another domain.
For example, in an HTML page on my site I have an iFrame whose contents are sourced from another website. The iFrame content is a single select field.
I need to be able to read the selected value on my site. In other words, I need to use the select list from another domain inside my own application. I do not have control over any server settings.
Initially therefore we might be tempted to do something like this (simplified):
HTML in my site:
<iframe name='select_frame' src='http://www.othersite.com/select.php?initial_name=jim'></iframe>
<input type='button' name='save' value='SAVE'>
HTML contents of iFrame (loaded from select.php
on another domain):
<select id='select_name'>
<option value='john'>John</option>
<option value='jim' selected>Jim</option>
</select>
jQuery:
$('input:button[name=save]').click(function() {
var name = $('iframe[name=select_frame]').contents().find('#select_name').val();
});
However, I receive this javascript error when I attempt to read the value:
Blocked a frame with origin "http://www.myownsite.com" from accessing a frame with origin "http://www.othersite.com". Protocols, domains, and ports must match.
To get around this problem, it seems that you can indirectly source the iFrame from a script in your own site, and have that script read the contents from the other site using a method like file_get_contents()
or curl
etc.
So, create a script (for example: select_local.php
in the current directory) on your own site with contents similar to this:
PHP content of select_local.php:
<?php
$url = "http://www.othersite.com/select.php?" . $_SERVER['QUERY_STRING'];
$html_select = file_get_contents($url);
echo $html_select;
?>
Also modify the HTML to call this local (instead of the remote) script:
<iframe name='select_frame' src='select_local.php?initial_name=jim'></iframe>
<input type='button' name='save' value='SAVE'>
Now your browser should think that it is loading the iFrame content from the same domain.
Double (called float in some languages) is fraut with problems due to rounding issues, it's good only if you need approximate values.
The Decimal data type does what you want.
For reference decimal and Decimal are the same in .NET C#, as are the double and Double types, they both refer to the same type (decimal and double are very different though, as you've seen).
Beware that the Decimal data type has some costs associated with it, so use it with caution if you're looking at loops etc.
What do you get from running which port
as your regular user account? Try it from a freshly opened terminal. Try again after renaming .bash_profile
to .profile
. Can you run port
as a regular user, even with no arguments?
In ~/.subversion/auth/svn.simple/
you should find a file with a long hexadecimal name. The password is in there in plaintext.
If there is more than one file you'll need to find that one that references the server you need the password for.
W3C doc says regarding "border-radius" property: "supported in IE9+, Firefox, Chrome, Safari, and Opera".
Hence I assume you're testing on IE8 or below.
For "regular elements" there is a solution compatible with IE8 & other old/poor browsers. See below.
HTML:
<div class="myWickedClass">
<span class="myCoolItem">Some text</span> <span class="myCoolItem">Some text</span> <span class="myCoolItem"> Some text</span> <span class="myCoolItem">Some text</span>
</div>
CSS:
.myWickedClass{
padding: 0 5px 0 0;
background: #F7D358 url(../img/roundedCorner_right.png) top right no-repeat scroll;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
font: normal 11px Verdana, Helvetica, sans-serif;
color: #A4A4A4;
}
.myWickedClass > .myCoolItem:first-child {
padding-left: 6px;
background: #F7D358 url(../img/roundedCorner_left.png) 0px 0px no-repeat scroll;
}
.myWickedClass > .myCoolItem {
padding-right: 5px;
}
You need to create both roundedCorner_right.png & roundedCorner_left.png. These are work around for IE8 (& below) to fake the rounded corner feature.
So in this example above we apply the left rounded corner to the first span element in the containing div, & we apply the right rounded corner to the containing div. These images overlap the browser-provided "squary corners" & give the illusion of being part of a rounded element.
The idea for inputs would be to do the same logic. However, input is an empty element, " element is empty, it contains attributes only", in other word, you cannot wrap a span into an input such as <input><span class="myCoolItem"></span></input>
to then use background images like in the previous example.
Hence the solution seems to be to do the opposite: wrap the input into another element. see this answer rounded corners of input elements in IE
set scan off; Above command also works.
Just need to put condition to execute task for specific distribution
- name: Creates directory
file: path=/src/www state=directory
when: ansible_distribution == 'Debian'
You could use Regex.Split:
string[] tokens = Regex.Split(input, @"\r?\n|\r");
Edit: added |\r
to account for (older) Mac line terminators.
I'm going to add my 2 cents in case someone finds himself in a position like mine. I too was looking for an MVC project type and could not see it. All I saw is a "Web Application Project". So I freaked out and rushed into trying all solutions listed on this page.
But.
IT IS ACTUALLY THERE.
Just go with the "Web application" project and it will give you the MVC option on the next step.
int count = 0;
using (new SqlConnection connection = new SqlConnection("connectionString"))
{
sqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM table_name", connection);
connection.Open();
count = (int32)cmd.ExecuteScalar();
}
I use this trick for equal data bucketing. Instead of text result you get the number. Here is example for four buckets. Suppose you have data in A1:A100
range. Put this formula in B1:
=MAX(ROUNDUP(PERCENTRANK($A$1:$A$100,A1) *4,0),1)
Fill down the formula all across B column and you are done. The formula divides the range into 4 equal buckets and it returns the bucket number which the cell A1 falls into. The first bucket contains the lowest 25% of values.
Adjust the number of buckets according to thy wish:
=MAX(ROUNDUP(PERCENTRANK([Range],[OneCellOfTheRangeToTest]) *[NumberOfBuckets],0),1)
The number of observation in each bucket will be equal or almost equal. For example if you have a 100 observations and you want to split it into 3 buckets (like in your example) then the buckets will contain 33, 33, 34 observations. So almost equal. You do not have to worry about that - the formula works that out for you.
The simplest way to do that is using plain HTML.
You can use one of these ways:
<embed type="text/html" src="header.html">
or:
<object name="foo" type="text/html" data="header.html"></object>
Because python 3 print() function allows end="" definition, that satisfies the majority of issues.
In my case, I wanted to PrettyPrint and was frustrated that this module wasn't similarly updated. So i made it do what i wanted:
from pprint import PrettyPrinter
class CommaEndingPrettyPrinter(PrettyPrinter):
def pprint(self, object):
self._format(object, self._stream, 0, 0, {}, 0)
# this is where to tell it what you want instead of the default "\n"
self._stream.write(",\n")
def comma_ending_prettyprint(object, stream=None, indent=1, width=80, depth=None):
"""Pretty-print a Python object to a stream [default is sys.stdout] with a comma at the end."""
printer = CommaEndingPrettyPrinter(
stream=stream, indent=indent, width=width, depth=depth)
printer.pprint(object)
Now, when I do:
comma_ending_prettyprint(row, stream=outfile)
I get what I wanted (substitute what you want -- Your Mileage May Vary)
My solution was to use the "-OutBuffer 2147483647" parameter in my query, which is part of the Common Parameters. PS C:> Get-Help about_CommonParameters -Full
if you have long processing server side code, I don't think it does fall into 404 as you said ("it goes to a webpage is not found error page")
Browser should report request timeout error.
You may do 2 things:
Based on CGI/Server side engine increase timeout there
PHP : http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time - default is 30 seconds
In php.ini:
max_execution_time 60
Increase apache timeout - default is 300 (in version 2.4 it is 60).
In your httpd.conf (in server config or vhost config)
TimeOut 600
Note that first setting allows your PHP script to run longer, it will not interferre with network timeout.
Second setting modify maximum amount of time the server will wait for certain events before failing a request
Sorry, I'm not sure if you are using PHP as server side processing, but if you provide more info I will be more accurate.
Set 'Program/script' -- > file.bat set 'Start in' the rest of path (file.bat)
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {_x000D_
private LayoutInflater inflater;_x000D_
private Context context;_x000D_
List<Information>data= Collections.emptyList();_x000D_
public AdapterClass(Context context,List<Information>data){_x000D_
this.context=context;_x000D_
_x000D_
inflater= LayoutInflater.from(context);_x000D_
this.data=data;_x000D_
}_x000D_
@Override_x000D_
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {_x000D_
View view= inflater.inflate(R.layout.custom_row,parent,false);_x000D_
MyViewHolder holder=new MyViewHolder(view);_x000D_
return holder;_x000D_
}_x000D_
_x000D_
@Override_x000D_
public void onBindViewHolder(MyViewHolder holder, int position) {_x000D_
Information current=data.get(position);_x000D_
holder.title.setText(current.title);_x000D_
holder.icon.setImageResource(current.iconId);_x000D_
_x000D_
}_x000D_
_x000D_
@Override_x000D_
public int getItemCount() {_x000D_
return data.size();_x000D_
}_x000D_
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{_x000D_
TextView title;_x000D_
ImageView icon;_x000D_
_x000D_
public MyViewHolder(View itemView) {_x000D_
super(itemView);_x000D_
title=(TextView)itemView.findViewById(R.id.listText);_x000D_
icon=(ImageView)itemView.findViewById(R.id.listIcon);_x000D_
itemView.setClickable(true);_x000D_
itemView.setOnClickListener(this);_x000D_
}_x000D_
_x000D_
@Override_x000D_
public void onClick(View v) {_x000D_
_x000D_
Toast.makeText(context,"The Item Clicked is: "+getPosition(),Toast.LENGTH_SHORT).show();_x000D_
}_x000D_
};_x000D_
}
_x000D_
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {_x000D_
private LayoutInflater inflater;_x000D_
private Context context;_x000D_
List<Information>data= Collections.emptyList();_x000D_
public AdapterClass(Context context,List<Information>data){_x000D_
this.context=context;_x000D_
_x000D_
inflater= LayoutInflater.from(context);_x000D_
this.data=data;_x000D_
}_x000D_
@Override_x000D_
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {_x000D_
View view= inflater.inflate(R.layout.custom_row,parent,false);_x000D_
MyViewHolder holder=new MyViewHolder(view);_x000D_
return holder;_x000D_
}_x000D_
_x000D_
@Override_x000D_
public void onBindViewHolder(MyViewHolder holder, int position) {_x000D_
Information current=data.get(position);_x000D_
holder.title.setText(current.title);_x000D_
holder.icon.setImageResource(current.iconId);_x000D_
_x000D_
}_x000D_
_x000D_
@Override_x000D_
public int getItemCount() {_x000D_
return data.size();_x000D_
}_x000D_
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{_x000D_
TextView title;_x000D_
ImageView icon;_x000D_
_x000D_
public MyViewHolder(View itemView) {_x000D_
super(itemView);_x000D_
title=(TextView)itemView.findViewById(R.id.listText);_x000D_
icon=(ImageView)itemView.findViewById(R.id.listIcon);_x000D_
itemView.setClickable(true);_x000D_
itemView.setOnClickListener(this);_x000D_
}_x000D_
_x000D_
@Override_x000D_
public void onClick(View v) {_x000D_
_x000D_
Toast.makeText(context,"The Item Clicked is: "+getPosition(),Toast.LENGTH_SHORT).show();_x000D_
}_x000D_
};_x000D_
}
_x000D_
Substring. This method extracts strings. It requires the location of the substring (a start index, a length). It then returns a new string with the characters in that range.
See a small example :
string input = "OneTwoThree";
// Get first three characters.
string sub = input.Substring(0, 3);
Console.WriteLine("Substring: {0}", sub);
Output : Substring: One
Instead of creating your own class to validate and store case insensitive string as a HashMap key, you can use:
Eg:
Map<String, Integer> linkedHashMap = new LinkedCaseInsensitiveMap<>();
linkedHashMap.put("abc", 1);
linkedHashMap.put("AbC", 2);
System.out.println(linkedHashMap);
Output: {AbC=2}
Mvn Dependency:
Spring Core is a Spring Framework module that also provides utility classes, including LinkedCaseInsensitiveMap.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
Eg:
Map<String, Integer> commonsHashMap = new CaseInsensitiveMap<>();
commonsHashMap.put("ABC", 1);
commonsHashMap.put("abc", 2);
commonsHashMap.put("aBc", 3);
System.out.println(commonsHashMap);
Output: {abc=3}
Dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
Therefore, if we provide a case-insensitive String Comparator, we'll get a case-insensitive TreeMap.
Eg:
Map<String, Integer> treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
treeMap.put("ABC", 1);
treeMap.put("ABc", 2);
treeMap.put("cde", 1);
System.out.println(treeMap);
Output: {ABC=2, cde=1}
I come across this issue myself and I performed the steps below to reuse my ExceptionController
that is annotated with @ControllerAdvise
for Exceptions
thrown in a registered Filter.
There are obviously many ways to handle exception but, in my case, I wanted the exception to be handled by my ExceptionController
because I am stubborn and also because I don't want to copy/paste the same code (i.e. I have some processing/logging code in ExceptionController
). I would like to return the beautiful JSON
response just like the rest of the exceptions thrown not from a Filter.
{
"status": 400,
"message": "some exception thrown when executing the request"
}
Anyway, I managed to make use of my ExceptionHandler
and I had to do a little bit of extra as shown below in steps:
Steps
@ControllerAdvise
i.e. MyExceptionControllerSample code
//sample Filter, to be added in web.xml
public MyFilterThatThrowException implements Filter {
//Spring Controller annotated with @ControllerAdvise which has handlers
//for exceptions
private MyExceptionController myExceptionController;
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void init(FilterConfig arg0) throws ServletException {
//Manually get an instance of MyExceptionController
ApplicationContext ctx = WebApplicationContextUtils
.getRequiredWebApplicationContext(arg0.getServletContext());
//MyExceptionHanlder is now accessible because I loaded it manually
this.myExceptionController = ctx.getBean(MyExceptionController.class);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
try {
//code that throws exception
} catch(Exception ex) {
//MyObject is whatever the output of the below method
MyObject errorDTO = myExceptionController.handleMyException(req, ex);
//set the response object
res.setStatus(errorDTO .getStatus());
res.setContentType("application/json");
//pass down the actual obj that exception handler normally send
ObjectMapper mapper = new ObjectMapper();
PrintWriter out = res.getWriter();
out.print(mapper.writeValueAsString(errorDTO ));
out.flush();
return;
}
//proceed normally otherwise
chain.doFilter(request, response);
}
}
And now the sample Spring Controller that handles Exception
in normal cases (i.e. exceptions that are not usually thrown in Filter level, the one we want to use for exceptions thrown in a Filter)
//sample SpringController
@ControllerAdvice
public class ExceptionController extends ResponseEntityExceptionHandler {
//sample handler
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(SQLException.class)
public @ResponseBody MyObject handleSQLException(HttpServletRequest request,
Exception ex){
ErrorDTO response = new ErrorDTO (400, "some exception thrown when "
+ "executing the request.");
return response;
}
//other handlers
}
Sharing the solution with those who wish to use ExceptionController
for Exceptions
thrown in a Filter.
transform
to avoid performance issues (mobile)A common pitfall is to animate
left
/top
/right
/bottom
properties instead of using css-transform to achieve the same effect. For a variety of reasons, the semantics of transforms make them easier to offload, butleft
/top
/right
/bottom
are much more difficult.
Source: Mozilla Developer Network (MDN)
Demo:
var $slider = document.getElementById('slider');
var $toggle = document.getElementById('toggle');
$toggle.addEventListener('click', function() {
var isOpen = $slider.classList.contains('slide-in');
$slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in');
});
_x000D_
#slider {
position: absolute;
width: 100px;
height: 100px;
background: blue;
transform: translateX(-100%);
-webkit-transform: translateX(-100%);
}
.slide-in {
animation: slide-in 0.5s forwards;
-webkit-animation: slide-in 0.5s forwards;
}
.slide-out {
animation: slide-out 0.5s forwards;
-webkit-animation: slide-out 0.5s forwards;
}
@keyframes slide-in {
100% { transform: translateX(0%); }
}
@-webkit-keyframes slide-in {
100% { -webkit-transform: translateX(0%); }
}
@keyframes slide-out {
0% { transform: translateX(0%); }
100% { transform: translateX(-100%); }
}
@-webkit-keyframes slide-out {
0% { -webkit-transform: translateX(0%); }
100% { -webkit-transform: translateX(-100%); }
}
_x000D_
<div id="slider" class="slide-in">
<ul>
<li>Lorem</li>
<li>Ipsum</li>
<li>Dolor</li>
</ul>
</div>
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
OUTPUTS = []
for number in range(len(list_of_tuples))):
tup_ = list_of_tuples[number]
list_ = list(tup_)
item_ = list_[0] + list_[1] + list_[2] + list_[3]
list_.append(item_)
OUTPUTS.append(tuple(list_))
OUTPUTS is what you desire
rowMeans
is nice, but if you are still trying to wrap your head around the apply
family of functions, this is a good opprotunity to begin understanding it.
DF['Mean'] <- apply(DF[,2:4], 1, mean)
Notice I'm doing a slightly different assignment than the first example. This approach makes it easier to incorporate it into for loops.
Using template literals with variables also works:
{"firstname": {$regex : `^${req.body.firstname}.*` , $options: 'si' }}
std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
This is a great place for auto
:
auto now = std::chrono::system_clock::now();
Since you want to traffic at millisecond
precision, it would be good to go ahead and covert to it in the time_point
:
auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
now_ms
is a time_point
, based on system_clock
, but with the precision of milliseconds
instead of whatever precision your system_clock
has.
auto epoch = now_ms.time_since_epoch();
epoch
now has type std::chrono::milliseconds
. And this next statement becomes essentially a no-op (simply makes a copy and does not make a conversion):
auto value = std::chrono::duration_cast<std::chrono::milliseconds>(epoch);
Here:
long duration = value.count();
In both your and my code, duration
holds the number of milliseconds
since the epoch of system_clock
.
This:
std::chrono::duration<long> dur(duration);
Creates a duration
represented with a long
, and a precision of seconds
. This effectively reinterpret_cast
s the milliseconds
held in value
to seconds
. It is a logic error. The correct code would look like:
std::chrono::milliseconds dur(duration);
This line:
std::chrono::time_point<std::chrono::system_clock> dt(dur);
creates a time_point
based on system_clock
, with the capability of holding a precision to the system_clock
's native precision (typically finer than milliseconds). However the run-time value will correctly reflect that an integral number of milliseconds are held (assuming my correction on the type of dur
).
Even with the correction, this test will (nearly always) fail though:
if (dt != now)
Because dt
holds an integral number of milliseconds
, but now
holds an integral number of ticks finer than a millisecond
(e.g. microseconds
or nanoseconds
). Thus only on the rare chance that system_clock::now()
returned an integral number of milliseconds
would the test pass.
But you can instead:
if (dt != now_ms)
And you will now get your expected result reliably.
Putting it all together:
int main ()
{
auto now = std::chrono::system_clock::now();
auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
auto value = now_ms.time_since_epoch();
long duration = value.count();
std::chrono::milliseconds dur(duration);
std::chrono::time_point<std::chrono::system_clock> dt(dur);
if (dt != now_ms)
std::cout << "Failure." << std::endl;
else
std::cout << "Success." << std::endl;
}
Personally I find all the std::chrono
overly verbose and so I would code it as:
int main ()
{
using namespace std::chrono;
auto now = system_clock::now();
auto now_ms = time_point_cast<milliseconds>(now);
auto value = now_ms.time_since_epoch();
long duration = value.count();
milliseconds dur(duration);
time_point<system_clock> dt(dur);
if (dt != now_ms)
std::cout << "Failure." << std::endl;
else
std::cout << "Success." << std::endl;
}
Which will reliably output:
Success.
Finally, I recommend eliminating temporaries to reduce the code converting between time_point
and integral type to a minimum. These conversions are dangerous, and so the less code you write manipulating the bare integral type the better:
int main ()
{
using namespace std::chrono;
// Get current time with precision of milliseconds
auto now = time_point_cast<milliseconds>(system_clock::now());
// sys_milliseconds is type time_point<system_clock, milliseconds>
using sys_milliseconds = decltype(now);
// Convert time_point to signed integral type
auto integral_duration = now.time_since_epoch().count();
// Convert signed integral type to time_point
sys_milliseconds dt{milliseconds{integral_duration}};
// test
if (dt != now)
std::cout << "Failure." << std::endl;
else
std::cout << "Success." << std::endl;
}
The main danger above is not interpreting integral_duration
as milliseconds
on the way back to a time_point
. One possible way to mitigate that risk is to write:
sys_milliseconds dt{sys_milliseconds::duration{integral_duration}};
This reduces risk down to just making sure you use sys_milliseconds
on the way out, and in the two places on the way back in.
And one more example: Let's say you want to convert to and from an integral which represents whatever duration system_clock
supports (microseconds, 10th of microseconds or nanoseconds). Then you don't have to worry about specifying milliseconds as above. The code simplifies to:
int main ()
{
using namespace std::chrono;
// Get current time with native precision
auto now = system_clock::now();
// Convert time_point to signed integral type
auto integral_duration = now.time_since_epoch().count();
// Convert signed integral type to time_point
system_clock::time_point dt{system_clock::duration{integral_duration}};
// test
if (dt != now)
std::cout << "Failure." << std::endl;
else
std::cout << "Success." << std::endl;
}
This works, but if you run half the conversion (out to integral) on one platform and the other half (in from integral) on another platform, you run the risk that system_clock::duration
will have different precisions for the two conversions.
OnClick is triggered when the user releases the button. But if you still want to use the TouchListener you need to add it in code. It's just:
myView.setOnTouchListener(new View.OnTouchListener()
{
// Implementation;
});
This method safely enables cross-origin
communication.
And if you have access to parent page code then any parent method can be called as well as any data can be passed directly from Iframe
. Here is a small example:
Parent page:
if (window.addEventListener) {
window.addEventListener("message", onMessage, false);
}
else if (window.attachEvent) {
window.attachEvent("onmessage", onMessage, false);
}
function onMessage(event) {
// Check sender origin to be trusted
if (event.origin !== "http://example.com") return;
var data = event.data;
if (typeof(window[data.func]) == "function") {
window[data.func].call(null, data.message);
}
}
// Function to be called from iframe
function parentFunc(message) {
alert(message);
}
Iframe code:
window.parent.postMessage({
'func': 'parentFunc',
'message': 'Message text from iframe.'
}, "*");
// Use target origin instead of *
UPDATES:
Security note:
Always provide a specific targetOrigin, NOT *
, if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site (comment by ZalemCitizen).
References:
To me was better hardcoding "example.com" as string, so I need less rules, even you can use it to redirect from .org to .com or similar too:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} !^example\.com$ [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [L,NE,R=301]
</IfModule>
What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.
There is also a shorter form for $(document).ready(function(){...})
in $(function(){...})
.
So, this is all you need:
$(function(){
$('div.easy_editor').css('border','9px solid red');
});
If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:
$(function(){
$('.easy_editor').css('border','9px solid red');
});
dir /b *.jpg >file.bat
This will give you lines such as:
Vacation2010 001.jpg
Vacation2010 002.jpg
Vacation2010 003.jpg
Edit file.bat in your favorite Windows text-editor, doing the equivalent of:
s/Vacation2010(.+)/rename "&" "December \1"/
That's a regex; many editors support them, but none that come default with Windows (as far as I know). You can also get a command line tool such as sed or perl which can take the exact syntax I have above, after escaping for the command line.
The resulting lines will look like:
rename "Vacation2010 001.jpg" "December 001.jpg"
rename "Vacation2010 002.jpg" "December 002.jpg"
rename "Vacation2010 003.jpg" "December 003.jpg"
You may recognize these lines as rename commands, one per file from the original listing. ;) Run that batch file in cmd.exe.
var associativeArray = {};
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";
If you are coming from an object-oriented language you should check this article.
Try change update="insTable:display"
to update="display"
. I believe you cannot prefix the id with the form ID like that.
The answer given by Matt K works perfectly fine.
However it is important to note one thing - If the div you are applying it to has absolute positioning, it wont work. For it to work, do this -
<div style="position:absolute; hei...">
<div style="position:relative; display: table-cell; vertical-align:middle; hei...">
<!-- here position MUST be relative, this div acts as a wrapper-->
...
</div>
</div>
just use:
setTimeout("window.location.href='yoururl';",4000);
..where the '4000' is m.second
bbox_to_anchor
)A legend is positioned inside the bounding box of the axes using the loc
argument to plt.legend
.
E.g. loc="upper right"
places the legend in the upper right corner of the bounding box, which by default extents from (0,0)
to (1,1)
in axes coordinates (or in bounding box notation (x0,y0, width, height)=(0,0,1,1)
).
To place the legend outside of the axes bounding box, one may specify a tuple (x0,y0)
of axes coordinates of the lower left corner of the legend.
plt.legend(loc=(1.04,0))
A more versatile approach is to manually specify the bounding box into which the legend should be placed, using the bbox_to_anchor
argument. One can restrict oneself to supply only the (x0, y0)
part of the bbox. This creates a zero span box, out of which the legend will expand in the direction given by the loc
argument. E.g.
plt.legend(bbox_to_anchor=(1.04,1), loc="upper left")
places the legend outside the axes, such that the upper left corner of the legend is at position (1.04,1)
in axes coordinates.
Further examples are given below, where additionally the interplay between different arguments like mode
and ncols
are shown.
l1 = plt.legend(bbox_to_anchor=(1.04,1), borderaxespad=0)
l2 = plt.legend(bbox_to_anchor=(1.04,0), loc="lower left", borderaxespad=0)
l3 = plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)
l4 = plt.legend(bbox_to_anchor=(0,1.02,1,0.2), loc="lower left",
mode="expand", borderaxespad=0, ncol=3)
l5 = plt.legend(bbox_to_anchor=(1,0), loc="lower right",
bbox_transform=fig.transFigure, ncol=3)
l6 = plt.legend(bbox_to_anchor=(0.4,0.8), loc="upper right")
Details about how to interpret the 4-tuple argument to bbox_to_anchor
, as in l4
, can be found in this question. The mode="expand"
expands the legend horizontally inside the bounding box given by the 4-tuple. For a vertically expanded legend, see this question.
Sometimes it may be useful to specify the bounding box in figure coordinates instead of axes coordinates. This is shown in the example l5
from above, where the bbox_transform
argument is used to put the legend in the lower left corner of the figure.
Having placed the legend outside the axes often leads to the undesired situation that it is completely or partially outside the figure canvas.
Solutions to this problem are:
Adjust the subplot parameters
One can adjust the subplot parameters such, that the axes take less space inside the figure (and thereby leave more space to the legend) by using plt.subplots_adjust
. E.g.
plt.subplots_adjust(right=0.7)
leaves 30% space on the right-hand side of the figure, where one could place the legend.
Tight layout
Using plt.tight_layout
Allows to automatically adjust the subplot parameters such that the elements in the figure sit tight against the figure edges. Unfortunately, the legend is not taken into account in this automatism, but we can supply a rectangle box that the whole subplots area (including labels) will fit into.
plt.tight_layout(rect=[0,0,0.75,1])
Saving the figure with bbox_inches = "tight"
The argument bbox_inches = "tight"
to plt.savefig
can be used to save the figure such that all artist on the canvas (including the legend) are fit into the saved area. If needed, the figure size is automatically adjusted.
plt.savefig("output.png", bbox_inches="tight")
automatically adjusting the subplot params
A way to automatically adjust the subplot position such that the legend fits inside the canvas without changing the figure size can be found in this answer: Creating figure with exact size and no padding (and legend outside the axes)
Comparison between the cases discussed above:
A figure legend
One may use a legend to the figure instead of the axes, matplotlib.figure.Figure.legend
. This has become especially useful for matplotlib version >=2.1, where no special arguments are needed
fig.legend(loc=7)
to create a legend for all artists in the different axes of the figure. The legend is placed using the loc
argument, similar to how it is placed inside an axes, but in reference to the whole figure - hence it will be outside the axes somewhat automatically. What remains is to adjust the subplots such that there is no overlap between the legend and the axes. Here the point "Adjust the subplot parameters" from above will be helpful. An example:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,2*np.pi)
colors=["#7aa0c4","#ca82e1" ,"#8bcd50","#e18882"]
fig, axes = plt.subplots(ncols=2)
for i in range(4):
axes[i//2].plot(x,np.sin(x+i), color=colors[i],label="y=sin(x+{})".format(i))
fig.legend(loc=7)
fig.tight_layout()
fig.subplots_adjust(right=0.75)
plt.show()
Legend inside dedicated subplot axes
An alternative to using bbox_to_anchor
would be to place the legend in its dedicated subplot axes (lax
).
Since the legend subplot should be smaller than the plot, we may use gridspec_kw={"width_ratios":[4,1]}
at axes creation.
We can hide the axes lax.axis("off")
but still put a legend in. The legend handles and labels need to obtained from the real plot via h,l = ax.get_legend_handles_labels()
, and can then be supplied to the legend in the lax
subplot, lax.legend(h,l)
. A complete example is below.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = 6,2
fig, (ax,lax) = plt.subplots(ncols=2, gridspec_kw={"width_ratios":[4,1]})
ax.plot(x,y, label="y=sin(x)")
....
h,l = ax.get_legend_handles_labels()
lax.legend(h,l, borderaxespad=0)
lax.axis("off")
plt.tight_layout()
plt.show()
This produces a plot, which is visually pretty similar to the plot from above:
We could also use the first axes to place the legend, but use the bbox_transform
of the legend axes,
ax.legend(bbox_to_anchor=(0,0,1,1), bbox_transform=lax.transAxes)
lax.axis("off")
In this approach, we do not need to obtain the legend handles externally, but we need to specify the bbox_to_anchor
argument.
loc
argument can take numbers instead of strings, which make calls shorter, however, they are not very intuitively mapped to each other. Here is the mapping for reference:Since Java 8 new feature Optional you should not use @Nullable or @Notnull in your own code anymore. Take the example below:
public void printValue(@Nullable myValue) {
if (myValue != null) {
System.out.print(myValue);
} else {
System.out.print("I dont have a value");
}
It could be rewritten with:
public void printValue(Optional<String> myValue) {
if (myValue.ifPresent) {
System.out.print(myValue.get());
} else {
System.out.print("I dont have a value");
}
Using an optional forces you to check for null value. In the code above, you can only access the value by calling the get
method.
Another advantage is that the code get more readable. With the addition of Java 9 ifPresentOrElse, the function could even be written as:
public void printValue(Optional<String> myValue) {
myValue.ifPresentOrElse(
v -> System.out.print(v),
() -> System.out.print("I dont have a value"),
)
}
From the Javadoc for Date.getHours
As of JDK version 1.1, replaced by Calendar.get(Calendar.HOUR_OF_DAY)
So use
Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR_OF_DAY);
and the equivalent for getMinutes.
Here my 2 cents from Java world:
From a Spark Scala console, with Java 8:
scala> new java.net.URI("spark://spark_master").getHost
res10: String = null
scala> new java.net.URI("spark://spark-master").getHost
res11: String = spark-master
scala> new java.net.URI("spark://spark_master.google.fr").getHost
res12: String = null
scala> new java.net.URI("spark://spark.master.google.fr").getHost
res13: String = spark.master.google.fr
scala> new java.net.URI("spark://spark-master.google.fr:3434").getHost
res14: String = spark-master.google.fr
scala> new java.net.URI("spark://spark-master.goo_gle.fr:3434").getHost
res15: String = null
It's definitely a bad idea ^^
In this case, where you want to output plain text and a variable, you could do it like this:
http://{{ app.request.host }}
If you want to concatenate some variables, alessandro1997's solution would be much better.
Temporarily update the retention time on the topic to one second:
kafka-topics.sh --zookeeper <zkhost>:2181 --alter --topic <topic name> --config retention.ms=1000
And in newer Kafka releases, you can also do it with kafka-configs --entity-type topics
kafka-configs.sh --zookeeper <zkhost>:2181 --entity-type topics --alter --entity-name <topic name> --add-config retention.ms=1000
then wait for the purge to take effect (about one minute). Once purged, restore the previous retention.ms
value.
If it doesn't show up in your package manager (i.e. apt-cache search texinfo
) and even apt-file search bin/makeinfo
is no help, you may have to enable non-free/restricted packages for your package manager.
For ubuntu, sudo $EDITOR /etc/apt/sources.list
and add restricted
.
deb http://archive.ubuntu.com/ubuntu bionic main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu bionic-security main
deb http://archive.ubuntu.com/ubuntu bionic-updates main
For debian, sudo $EDITOR /etc/apt/sources.list
and add non-free
. You can even have preferences on package level if you don't want to clutter the package db with non-free stuff.
After a sudo apt-get udpate
you should find the required package.
You can use JSON.stringify
, and get some nice indentation as well as perhaps easier to remember syntax.
console.log(JSON.stringify(myObject, null, 4));
{
"a": "a",
"b": {
"c": "c",
"d": {
"e": "e",
"f": {
"g": "g",
"h": {
"i": "i"
}
}
}
}
}
The third argument sets the indentation level, so you can adjust that as desired.
More detail here if needed:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
The high scoring answer above nailed it.
First you were mixing base 2 and base 10 in your question, then when you put a number on the right side that is not divisible into the base you get problems. Like 1/3 in decimal because 3 doesnt go into a power of 10 or 1/5 in binary which doesnt go into a power of 2.
Another comment though NEVER use equal with floating point numbers, period. Even if it is an exact representation there are some numbers in some floating point systems that can be accurately represented in more than one way (IEEE is bad about this, it is a horrible floating point spec to start with, so expect headaches). No different here 1/3 is not EQUAL to the number on your calculator 0.3333333, no matter how many 3's there are to the right of the decimal point. It is or can be close enough but is not equal. so you would expect something like 2*1/3 to not equal 2/3 depending on the rounding. Never use equal with floating point.
You could also use a static class, such as a Config class or something along those lines...
public static class Config
{
public static readonly string SomeValue = "blah";
}
You can use this:
Collections.sort(list, org.joda.time.DateTimeComparator.getInstance());
Update with string interpolation in ES2015.
const num = 07734;
let numStringArr = `${num}`.split('').map(el => parseInt(el)); // [0, 7, 7, 3, 4]
One way to do it (may not be the best) is to create another array with the new elements and do column_stack. i.e.
>>>a = array([[1,3,4],[1,2,3]...[1,2,1]])
[[1 3 4]
[1 2 3]
[1 2 1]]
>>>b = array([1,2,3])
>>>column_stack((a,b))
array([[1, 3, 4, 1],
[1, 2, 3, 2],
[1, 2, 1, 3]])
To complement @Joe's answer:
Hamcrest provides you with three main methods to match a list:
contains
Checks for matching all the elements taking in count the order, if the list has more or less elements, it will fail
containsInAnyOrder
Checks for matching all the elements and it doesn't matter the order, if the list has more or less elements, will fail
hasItems
Checks just for the specified objects it doesn't matter if the list has more
hasItem
Checks just for one object it doesn't matter if the list has more
All of them can receive a list of objects and use equals
method for comparation or can be mixed with other matchers like @borjab mentioned:
assertThat(myList , contains(allOf(hasProperty("id", is(7L)),
hasProperty("name", is("testName1")),
hasProperty("description", is("testDesc1"))),
allOf(hasProperty("id", is(11L)),
hasProperty("name", is("testName2")),
hasProperty("description", is("testDesc2")))));
http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#contains(E...) http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#containsInAnyOrder(java.util.Collection) http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#hasItems(T...)
Use a cast:
public enum MyEnum : int {
A = 0,
B = 1,
AB = 2,
}
int val = (int)MyEnum.A;
Note
In order to run apache server after upgradation PHP 7.4.x requires Microsoft Visual C++ Redistributable for Visual Studio 2019 which can be downloaded here under the heading Other Tools and Frameworks. otherwise apache server won't start.
You can search for "Ajax Behavior Events" in PrimeFaces User's Guide, and you will find plenty of them for all supported components. That's also what PrimeFaces lead Optimus Prime suggest to do in this related question at the PrimeFaces forum <p:ajax>
event list?
There is no onblur
event, that's the HTML attribute name, but there is a blur
event. It's just without the "on" prefix like as the HTML attribute name. You can also look at all "on*" attributes of the tag documentation of the component in question to see which are all available, e.g. <p:inputText>
.
The compiler doesn't know that Environment.Exit() does not return. Why not just "return" from Main()?
You should use datetime
object, not str
.
>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'
To get the datetime object from the string, use datetime.datetime.strptime
:
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'
Callee vs caller saved is a convention for who is responsible for saving and restoring the value in a register across a call. ALL registers are "global" in that any code anywhere can see (or modify) a register and those modifications will be seen by any later code anywhere. The point of register saving conventions is that code is not supposed to modify certain registers, as other code assumes that the value is not modified.
In your example code, NONE of the registers are callee save, as it makes no attempt to save or restore the register values. However, it would seem to not be an entire procedure, as it contains a branch to an undefined label (l$loop
). So it might be a fragment of code from the middle of a procedure that treats some registers as callee save; you're just missing the save/restore instructions.
Tarkus's answer works well. However, I would suggest replacing VIEWSTATE with SESSION.
The current page's VIEWSTATE only works while the current page posts back to itself and is gone once the user is redirected away to another page. SESSION persists the sort order on more than just the current page's post-back. It persists it across the entire duration of the session. This means that the user can surf around to other pages, and when he comes back to the given page, the sort order he last used still remains. This is usually more convenient.
There are other methods, too, such as persisting user profiles.
I recommend this article for a very good explanation of ViewState and how it works with a web page's life cycle: https://msdn.microsoft.com/en-us/library/ms972976.aspx
To understand the difference between VIEWSTATE, SESSION and other ways of persisting variables, I recommend this article: https://msdn.microsoft.com/en-us/library/75x4ha6s.aspx
Use a JSON library to parse the string and retrieve the value.
The following very basic example uses the built-in JSON parser from Android.
String jsonString = "{ \"name\" : \"John\", \"age\" : \"20\", \"address\" : \"some address\" }";
JSONObject jsonObject = new JSONObject(jsonString);
int age = jsonObject.getInt("age");
More advanced JSON libraries, such as jackson, google-gson, json-io or genson, allow you to convert JSON objects to Java objects directly.
The dash type of a linestyle
is given by the linetype
, which does also select the line color unless you explicitely set an other one with linecolor
.
However, the support for dashed lines depends on the selected terminal:
png
(uses libgd
)pngcairo
, support dashed lines, but it is disables by default. To enable it, use set termoption dashed
, or set terminal pngcairo dashed ...
.linetype
, use the test
command:Running
set terminal pngcairo dashed
set output 'test.png'
test
set output
gives:
whereas, the postscript
terminal shows different dash patterns:
set terminal postscript eps color colortext
set output 'test.eps'
test
set output
Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:
A new dashtype
parameter was introduced:
To get the predefined dash patterns, use e.g.
plot x dashtype 2
You can also specify custom dash patterns like
plot x dashtype (3,5,10,5),\
2*x dashtype '.-_'
The terminal options dashed
and solid
are ignored. By default all lines are solid. To change them to dashed, use e.g.
set for [i=1:8] linetype i dashtype i
The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic
:
You need to make sure that your project is set to target the AVD that you want to launch.
Right click (ctrl-click MAC) on the project folder in Eclipse. Then click on Properties. In the window that shows up, click on "Android" and then click on the build target you want to launch. Hope that helps.
Try this,
DELETE posts.*
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id
Navigate to your "/install/hadoop/datanode/bin" folder or path where you could execute your hadoop commands:
To place the files in HDFS: Format: hadoop fs -put "Local system path"/filename.csv "HDFS destination path"
eg)./hadoop fs -put /opt/csv/load.csv /user/load
Here the /opt/csv/load.csv is source file path from my local linux system.
/user/load means HDFS cluster destination path in "hdfs://hacluster/user/load"
To get the files from HDFS to local system: Format : hadoop fs -get "/HDFSsourcefilepath" "/localpath"
eg)hadoop fs -get /user/load/a.csv /opt/csv/
After executing the above command, a.csv from HDFS would be downloaded to /opt/csv folder in local linux system.
This uploaded files could also be seen through HDFS NameNode web UI.
maybe there are some unmerged paths in your git repository that you have to resolve before stashing.
For IntelliJ in Mac
View -> Quick Switch theme (^`)-> color schema
according to dr. hipp in a recent list post:
CREATE TABLE whatever(
....
timestamp DATE DEFAULT (datetime('now','localtime')),
...
);
According to MSDN, timestamp
Is a data type that exposes automatically generated, unique binary numbers within a database. timestamp is generally used as a mechanism for version-stamping table rows. The storage size is 8 bytes. The timestamp data type is just an incrementing number and does not preserve a date or a time. To record a date or time, use a datetime data type.
You're probably looking for the datetime
data type instead.
In PHP >= 5.3 it can be done like this:
$offerArray = array_map(function($value) {
return $value[4];
}, $offer);
Content Security Policy headers for me! You can quickly rule out this possibility by checking the Chrome Dev Tools Console, if it's CSP problems there will be errors showing in the console. In .Net you can fix this either by adding headers in the web.config file or in code.
Refused to send form data to 'https://www.mysite.mydomain/' because it violates the following Content Security Policy directive: "form-action 'self' *.otherdomain www.thirdparty.co.uk".
Here's the web.config fix for the above error:
<cspConfiguration>
<directives>
<directive name="form-action" allowedSources="'self' *.mydomain>
</directive>
</directives>
</cspConfiguration>
_x000D_
sounds like you downloaded the german xampp package instead of the english xampp package (yes, it's another download-link) where the language is set according to the package you loaded. to change the language afterwards, simply edit the config.inc.php
and set:
$cfg['Lang'] = 'en-utf-8';
The Print statement in TSQL is a misunderstood creature, probably because of its name. It actually sends a message to the error/message-handling mechanism that then transfers it to the calling application. PRINT is pretty dumb. You can only send 8000 characters (4000 unicode chars). You can send a literal string, a string variable (varchar or char) or a string expression. If you use RAISERROR, then you are limited to a string of just 2,044 characters. However, it is much easier to use it to send information to the calling application since it calls a formatting function similar to the old printf in the standard C library. RAISERROR can also specify an error number, a severity, and a state code in addition to the text message, and it can also be used to return user-defined messages created using the sp_addmessage system stored procedure. You can also force the messages to be logged.
Your error-handling routines won’t be any good for receiving messages, despite messages and errors being so similar. The technique varies, of course, according to the actual way you connect to the database (OLBC, OLEDB etc). In order to receive and deal with messages from the SQL Server Database Engine, when you’re using System.Data.SQLClient, you’ll need to create a SqlInfoMessageEventHandler delegate, identifying the method that handles the event, to listen for the InfoMessage event on the SqlConnection class. You’ll find that message-context information such as severity and state are passed as arguments to the callback, because from the system perspective, these messages are just like errors.
It is always a good idea to have a way of getting these messages in your application, even if you are just spooling to a file, because there is always going to be a use for them when you are trying to chase a really obscure problem. However, I can’t think I’d want the end users to ever see them unless you can reserve an informational level that displays stuff in the application.
A late answer here, but I've used
DECIMAL(13,2)
which I'm right in thinking should allow upto 99,999,999,999.99.
A good way to do this is using $state.go('statename', {params...}) is faster and more friendly for user experience in cases when you don't have to reload and bootsraping whole app config and stuff
(function() {
'use strict';
angular
.module('app.appcode')
.controller('YourController', YourController);
YourController.$inject = ['rootURL', '$scope', '$state', '$http'];
function YourController(rootURL, $scope, $state, $http) {
$http({
url: rootURL + 'app-code/common.service.php',
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
dataType: 'json',
data:data + '&method=signin'
}).success(function (response) {
if (response['code'] == '420') {
$scope.message = response['message'];
$scope.loginPassword = '';
} else if (response['code'] != '200') {
$scope.message = response['message'];
$scope.loginPassword = '';
} else {
// $state.go('home'); // select here the route that you want to redirect
$state.go(response['state']); // response['state'] should be a route on your app.routes
}
})
}
});
// routes
(function() {
'use strict';
angular
.module('app')
.config(routes);
routes.$inject = [
'$stateProvider',
'$urlRouterProvider'
];
function routes($stateProvider, $urlRouterProvider) {
/**
* Default path for any unmatched url
*/
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: '/app/home/home.html',
controller: 'Home'
})
.state('login', {
url: '/login',
templateUrl: '/app/login/login.html',
controller: 'YourController'
})
// ... more routes .state
}
})();
Since the hosts is blocked. try connect it from other host and execute the mysqladmin flush-hosts command.
mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
You'd better build application with one entrance point, i.e. all files should be reached from index.php
Place this in index.php
define(A,true);
This check should run in each linked file (via require or include)
defined('A') or die(header('HTTP/1.0 403 Forbidden'));
ConcurrentLinkedQueue
If you don't care about having index-based access and just want the insertion-order-preserving characteristics of a List, you could consider a java.util.concurrent.ConcurrentLinkedQueue
. Since it implements Iterable, once you've finished adding all the items, you can loop over the contents using the enhanced for syntax:
Queue<String> globalQueue = new ConcurrentLinkedQueue<String>();
//Multiple threads can safely call globalQueue.add()...
for (String href : globalQueue) {
//do something with href
}
You can use this
declare @i int = 1
while Exists(Select(Substring(@Script,@i,4000))) and (@i < LEN(@Script))
begin
print Substring(@Script,@i,4000)
set @i = @i+4000
end
It is correct that rm –rf .
will remove everything in the current directly including any subdirectories and their content. The single dot (.
) means the current directory. be carefull not to do rm -rf ..
since the double dot (..
) means the previous directory.
This being said, if you are like me and have multiple terminal windows open at the same time, you'd better be safe and use rm -ir .
Lets look at the command arguments to understand why.
First, if you look at the rm
command man page (man rm
under most Unix) you notice that –r
means "remove the contents of directories recursively". So, doing rm -r .
alone would delete everything in the current directory and everything bellow it.
In rm –rf .
the added -f means "ignore nonexistent files, never prompt". That command deletes all the files and directories in the current directory and never prompts you to confirm you really want to do that. -f
is particularly dangerous if you run the command under a privilege user since you could delete the content of any directory without getting a chance to make sure that's really what you want.
On the otherhand, in rm -ri .
the -i
that replaces the -f
means "prompt before any removal". This means you'll get a chance to say "oups! that's not what I want" before rm goes happily delete all your files.
In my early sysadmin days I did an rm -rf /
on a system while logged with full privileges (root). The result was two days passed a restoring the system from backups. That's why I now employ rm -ri
now.
Code coverage has been explained well in the previous answers. So this is more of an answer to the second part of the question.
We've used three tools to determine code coverage.
We use these tools to
this.$http.get('https://pokeapi.co/api/v2/pokemon')
.then(response => {
if(response.status === 200)
{
this.usuarios = response.data.results.map(usuario => {
return { name: usuario.name, url: usuario.url, captched: false } })
}
})
.catch( error => { console.log("Error al Cargar los Datos: " + error ) } )
Here's how i do it in CoffeeScript on Node.JS:
blobService.createBlockBlobFromText 'containerName', (path + '$$$.$$$'), '', (err, result)->
if err
console.log 'failed to create path', err
else
console.log 'created path', path, result
Deadlock occurs when a thread is waiting for other thread to finish and vice versa.
How to avoid?
- Avoid Nested Locks
- Avoid Unnecessary Locks
- Use thread join()
How do you detect it?
run this command in cmd:
jcmd $PID Thread.print
reference : geeksforgeeks
string _connString = "metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=DATABASE;persist security info=True;user id=sa;password=YourPassword;multipleactiveresultsets=True;App=EntityFramework"";
EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder(_connString);
ctx = new Entities(_connString);
You can get the connection string from the web.config, and just set that in the EntityConnectionStringBuilder constructor, and use the EntityConnectionStringBuilder as an argument in the constructor for the context.
Cache the connection string by username. Simple example using a couple of generic methods to handle adding/retrieving from cache.
private static readonly ObjectCache cache = MemoryCache.Default;
// add to cache
AddToCache<string>(username, value);
// get from cache
string value = GetFromCache<string>(username);
if (value != null)
{
// got item, do something with it.
}
else
{
// item does not exist in cache.
}
public void AddToCache<T>(string token, T item)
{
cache.Add(token, item, DateTime.Now.AddMinutes(1));
}
public T GetFromCache<T>(string cacheKey) where T : class
{
try
{
return (T)cache[cacheKey];
}
catch
{
return null;
}
}
have a try with Flex Paper http://flexpaper.devaldi.com/
it works like scribd
Two Solutions:
I will first say that having a favicon in a Web page is a good thing (normally).
However it is not always desired and sometime developers need a way to avoid the extra payload. For example an IFRAME would request a favicon without showing it. Worst yet, in Chrome and Android an IFRAME will generate 3 requests for favicons:
"GET /favicon.ico HTTP/1.1" 404 183
"GET /apple-touch-icon-precomposed.png HTTP/1.1" 404 197
"GET /apple-touch-icon.png HTTP/1.1" 404 189
The following uses data URI and can be used to avoid fake favicon requests:
<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
For references see here:
UPDATE 1:
From the comments (jpic) it looks like Firefox >= 25 doesn't like the above syntax anymore. I tested on Firefox 27 and it doesn't work while it still work on Webkit/Chrome.
So here is the new one that should cover all recent browsers. I tested Safari, Chrome and Firefox:
<link rel="icon" href="data:;base64,=">
I left out the "shortcut" name from the "rel" attribute value since that's only for older IE and versions of IE < 8 doesn't like dataURIs either. Not tested on IE8.
UPDATE 2:
If you need your document to validate against HTML5 use this instead:
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
we can disable using this technique.
<select class="form-control" name="option_select">
<option selected="true" disabled="disabled">Select option </option>
<option value="Option A">Option A</option>
<option value="Option B">Option B</option>
<option value="Option C">Option C</option>
</select>
The method to get the rendered HTML I prefer is the following:
driver.get("http://www.google.com")
body_html = driver.find_element_by_xpath("/html/body")
print body_html.text
However, the above method removes all the tags (yes, the nested tags as well) and returns only text content. If you interested in getting the HTML markup as well, then use the method below.
print body_html.getAttribute("innerHTML")
One way is (this is with Bash)
grep -P '\t'
-P
turns on Perl regular expressions so \t will work.
As user unwind says, it may be specific to GNU grep. The alternative is to literally insert a tab in there if the shell, editor or terminal will allow it.
In addition to the accepted answer. You can use a lambda
instead of regex
:
from bs4 import BeautifulSoup
html = """<p>test python</p>"""
soup = BeautifulSoup(html, "html.parser")
print(soup(text="python"))
print(soup(text=lambda t: "python" in t))
Output:
[]
['test python']
In addition (or in replacement) to the HTML5's <a download
attribute already mentioned,
the browser's download to disk behavior can also be triggered by the following http response header:
Content-Disposition: attachment; filename=ProposedFileName.txt;
This was the way to do before HTML5 (and still works with browsers supporting HTML5).
It looks like that's an "unhandled exception", meaning the cmdlet itself hasn't been coded to recognize and handle that exception. It blew up without ever getting to run it's internal error handling, so the -ErrorAction setting on the cmdlet never came into play.
One other option would be to use something like this
SELECT *
FROM table t INNER JOIN
(
SELECT 'Text%' Col
UNION SELECT 'Link%'
UNION SELECT 'Hello%'
UNION SELECT '%World%'
) List ON t.COLUMN LIKE List.Col
This is a bit dated but there may be others looking for answers to the same question. You should think about what protection spaces make sense for your APIs. For example, you may want to identify and authenticate client application access to your APIs to restrict their use to known, registered client applications. In this case, you can use the Basic
authentication scheme with the client identifier as the user-id and client shared secret as the password. You don't need proprietary authentication schemes just clearly identify the one(s) to be used by clients for each protection space. I prefer only one for each protection space but the HTTP standards allow both multiple authentication schemes on each WWW-Authenticate header response and multiple WWW-Authenticate headers in each response; this will be confusing for API clients which options to use. Be consistent and clear then your APIs will be used.
The same thing happened to me before when I created a new git branch while not pushing it to origin.
Try to execute those two lines first:
git checkout -b name_of_new_branch # create the new branch
git push origin name_of_new_branch # push the branch to github
Then:
git pull origin name_of_new_branch
It should be fine now!
Best way to add schema to your existing table: Right click on the specific table-->Design --> Under the management studio Right sight see the Properties window and select the schema and click it, see the drop down list and select your schema. After the change the schema save it. Then will see it will chage your schema.
You can have only one public class in a file else you will get the error what you are getting now and name of file must be the name of public class
This is fast and works for small and (arbitrary) large ints:
def Dump(n):
s = '%x' % n
if len(s) & 1:
s = '0' + s
return s.decode('hex')
print repr(Dump(1245427)) #: '\x13\x00\xf3'
Take a look at this tutorial for how to use SQL inside VBA:
http://www.ehow.com/how_7148832_access-vba-query-results.html
For a query that won't return results, use (reference here):
DoCmd.RunSQL
For one that will, use (reference here):
Dim dBase As Database
dBase.OpenRecordset
I think you meant to do url[i] <- paste(...
instead of url[i] = paste(...
. If so replace =
with <-
.
Not sure where you get your legends from but:
<button>
As with:
<button type="submit">(html content)</button>
IE6 will submit all text for this button between the tags, other browsers will only submit the value. Using <button>
gives you more layout freedom over the design of the button. In all its intents and purposes, it seemed excellent at first, but various browser quirks make it hard to use at times.
In your example, IE6 will send text
to the server, while most other browsers will send nothing. To make it cross-browser compatible, use <button type="submit" value="text">text</button>
. Better yet: don't use the value, because if you add HTML it becomes rather tricky what is received on server side. Instead, if you must send an extra value, use a hidden field.
<input>
As with:
<input type="button" />
By default, this does next to nothing. It will not even submit your form. You can only place text on the button and give it a size and a border by means of CSS. Its original (and current) intent was to execute a script without the need to submit the form to the server.
<input>
As with:
<input type="submit" />
Like the former, but actually submits the surrounding form.
<input>
As with:
<input type="image" />
Like the former (submit), it will also submit a form, but you can use any image. This used to be the preferred way to use images as buttons when a form needed submitting. For more control, <button>
is now used. This can also be used for server side image maps but that's a rarity these days. When you use the usemap
-attribute and (with or without that attribute), the browser will send the mouse-pointer X/Y coordinates to the server (more precisely, the mouse-pointer location inside the button of the moment you click it). If you just ignore these extras, it is nothing more than a submit button disguised as an image.
There are some subtle differences between browsers, but all will submit the value-attribute, except for the <button>
tag as explained above.
base64.b16encode
and base64.b16decode
convert bytes to and from hex and work across all Python versions. The codecs approach also works, but is less straightforward in Python 3.
You may checkout this code:
var today = new Date();_x000D_
var Christmas = new Date("2012-12-25");_x000D_
var diffMs = (Christmas - today); // milliseconds between now & Christmas_x000D_
var diffDays = Math.floor(diffMs / 86400000); // days_x000D_
var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours_x000D_
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes_x000D_
alert(diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes until Christmas 2009 =)");
_x000D_
or var diffMins = Math.floor((...
to discard seconds if you don't want to round minutes.
check all the variables names in both of the combined files. Name of variables of both files to be combines should be exact same or else it will produce the above mentioned errors. I was facing the same problem as well, and after making all names same in both the file, rbind works accurately.
Thanks
How can I programatically (C#) ZIP a file (in Windows) without using any third party libraries?
If using the 4.5+ Framework, there is now the ZipArchive and ZipFile classes.
using (ZipArchive zip = ZipFile.Open("test.zip", ZipArchiveMode.Create))
{
zip.CreateEntryFromFile(@"c:\something.txt", "data/path/something.txt");
}
You need to add references to:
For .NET Core targeting net46, you need to add dependencies for
Example project.json:
"dependencies": {
"System.IO.Compression": "4.1.0",
"System.IO.Compression.ZipFile": "4.0.1"
},
"frameworks": {
"net46": {}
}
For .NET Core 2.0, just adding a simple using statement is all that is needed:
First of all, from __future__ import print_function
needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print
as a function now. That's the whole point of from __future__ import print_function
; to bring the print
function from Python 3 into Python 2.6+.
from __future__ import print_function
import sys, os, time
for x in range(0,10):
print(x, sep=' ', end='') # No need for sep here, but okay :)
time.sleep(1)
__future__
statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:
A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.
The documentation also mentions that the only things that can precede a __future__
statement are the module docstring, comments, blank lines, and other future statements.
For npm
npm install --save core-js@^3
for yarn
yarn add core-js@^3
You have to drop it and recreate it, but you don't have to incur the cost of revalidating the data if you don't want to.
alter table t drop constraint ck ;
alter table t add constraint ck check (n < 0) enable novalidate;
The enable novalidate
clause will force inserts or updates to have the constraint enforced, but won't force a full table scan against the table to verify all rows comply.
as explained here
With help from numpy one can calculate for example a linear fitting.
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])
Go simply with Zoo, it will simply replace all NA values with mean of the column values:
library(zoo)
na.aggregate(data)
Arrays can only be passed by reference, actually:
void foo(double (&bar)[10])
{
}
This prevents you from doing things like:
double arr[20];
foo(arr); // won't compile
To be able to pass an arbitrary size array to foo
, make it a template and capture the size of the array at compile time:
template<typename T, size_t N>
void foo(T (&bar)[N])
{
// use N here
}
You should seriously consider using std::vector
, or if you have a compiler that supports c++11, std::array
.
If you want to do it dynamically, for example, you have an array which you want to apply as a key to JSON object:
your Array will be like :
var keys = ["id", "name","Address","Phone"] // The array size should be same as JSON Object keys size
Now you have a JSON Array like:
var jArray = [
{
"_id": 1,
"_name": "Asna",
"Address": "NY",
"Phone": 123
},
{
"_id": 2,
"_name": "Euphoria",
"Address": "Monaco",
"Phone": 124
},
{
"_id": 3,
"_name": "Ahmed",
"Address": "Mumbai",
"Phone": 125
}
]
$.each(jArray ,function(pos,obj){
var counter = 0;
$.each(obj,function(key,value){
jArray [pos][keys[counter]] = value;
delete jArray [pos][key];
counter++;
})
})
Your resultant JSON Array will be like :
[
{
"id": 1,
"name": "Asna",
"Address": "NY",
"Phone": 123
},
{
"id": 2,
"name": "Euphoria",
"Address": "Monaco",
"Phone": 124
},
{
"id": 3,
"name": "Ahmed",
"Address": "Mumbai",
"Phone": 125
}
]
You might want to consider using console.log
with the built-in "arguments" object:
console.log(arguments); // would have shown you [0] null, [1] yourResult
This will always output all of your arguments, no matter how many arguments you have.
Ternary, conditional; tomato, tomatoh. What it's really valuable for is variable initialization. If (like me) you're fond of initializing variables where they are defined, the conditional ternary operator (for it is both) permits you to do that in cases where there is conditionality about its value. Particularly notable in final fields, but useful elsewhere, too.
e.g.:
public class Foo {
final double value;
public Foo(boolean positive, double value) {
this.value = positive ? value : -value;
}
}
Without that operator - by whatever name - you would have to make the field non-final or write a function simply to initialize it. Actually, that's not right - it can still be initialized using if/else, at least in Java. But I find this cleaner.
Why not just use the WordPress get_query_var()
function? WordPress Code Reference
// Test if the query exists at the URL
if ( get_query_var('ppc') ) {
// If so echo the value
echo get_query_var('ppc');
}
Since get_query_var can only access query parameters available to WP_Query, in order to access a custom query var like 'ppc', you will also need to register this query variable within your plugin or functions.php
by adding an action during initialization:
add_action('init','add_get_val');
function add_get_val() {
global $wp;
$wp->add_query_var('ppc');
}
Or by adding a hook to the query_vars filter:
function add_query_vars_filter( $vars ){
$vars[] = "ppc";
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
Well my problem was that i used the code from the answer, which is checked as a solution here, but after the replacement was executed, the first layer was still visible and functionating under just opened fragment. My solution was simmple, i added
.remove(CourseListFragment.this)
the CourseListFragment is a class file for the fragment i tried to close. (MainActivity.java, but for specific section (navigation drawer fragment), if it makes more sense to you) so my code looks like this now :
LecturesFragment nextFrag= new LecturesFragment();
getActivity().getSupportFragmentManager().beginTransaction()
.remove(CourseListFragment.this)
.replace(((ViewGroup)getView().getParent()).getId(), nextFrag, "findThisFragment")
.addToBackStack(null)
.commit();
And it works like a charm for me.
Using pandas:
import pandas as pd
xls = pd.ExcelFile(r"yourfilename.xls") #use r before absolute file path
sheetX = xls.parse(2) #2 is the sheet number+1 thus if the file has only 1 sheet write 0 in paranthesis
var1 = sheetX['ColumnName']
print(var1[1]) #1 is the row number...
Referring to the bible:
You need to use the SUBTOTAL function. The SUBTOTAL function ignores rows that have been excluded by a filter.
The formula would look like this:
=SUBTOTAL(9,B1:B20)
The function number 9, tells it to use the SUM function on the data range B1:B20.
If you are 'filtering' by hiding rows, the function number should be updated to 109.
=SUBTOTAL(109,B1:B20)
The function number 109 is for the SUM function as well, but hidden rows are ignored.
Shorter version
that works perfect for me that is as follow:
document.querySelector('#fileUpload').value = "";
Ensure you have Project | Build Automatically flagged. I ran into this issue too and turning that on fixed the problem.
Use a Func<T1, T2, TResult>
delegate as the parameter type and pass it in to your Query
:
public List<IJob> getJobs(Func<FullTimeJob, Student, FullTimeJob> lambda)
{
using (SqlConnection connection = new SqlConnection(getConnectionString())) {
connection.Open();
return connection.Query<FullTimeJob, Student, FullTimeJob>(sql,
lambda,
splitOn: "user_id",
param: parameters).ToList<IJob>();
}
}
You would call it:
getJobs((job, student) => {
job.Student = student;
job.StudentId = student.Id;
return job;
});
Or assign the lambda to a variable and pass it in.
It refers to which filegroup the object you are creating resides on. So your Primary filegroup could reside on drive D:\ of your server. you could then create another filegroup called Indexes. This filegroup could reside on drive E:\ of your server.
Here is a simple one liner function
//ECHMA5
function GetMonth(anyDate) {
return 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(',')[anyDate.getMonth()];
}
//
// ECMA6
var GetMonth = (anyDate) => 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(',')[anyDate.getMonth()];
queryString = "SELECT name FROM user WHERE id=" & Worksheets("Sheet1").Range("D4").Value
Since an ounce of experience is worth a ton of theory, I tried a little test program for MULTILINE
:
#define MULTILINE(...) #__VA_ARGS__
const char *mstr[] =
{
MULTILINE(1, 2, 3), // "1, 2, 3"
MULTILINE(1,2,3), // "1,2,3"
MULTILINE(1 , 2 , 3), // "1 , 2 , 3"
MULTILINE( 1 , 2 , 3 ), // "1 , 2 , 3"
MULTILINE((1, 2, 3)), // "(1, 2, 3)"
MULTILINE(1
2
3), // "1 2 3"
MULTILINE(1\n2\n3\n), // "1\n2\n3\n"
MULTILINE(1\n
2\n
3\n), // "1\n 2\n 3\n"
MULTILINE(1, "2" \3) // "1, \"2\" \3"
};
Compile this fragment with cpp -P -std=c++11 filename
to reproduce.
The trick behind #__VA_ARGS__
is that __VA_ARGS__
does not process the comma separator. So you can pass it to the stringizing operator. Leading and trailing spaces are trimmed, and spaces (including newlines) between words are compressed to a single space then. Parentheses need to be balanced. I think these shortcomings explain why the designers of C++11, despite #__VA_ARGS__
, saw the need for raw string literals.
Like this:
numrows = len(input) # 3 rows in your example
numcols = len(input[0]) # 2 columns in your example
Assuming that all the sublists have the same length (that is, it's not a jagged array).
CSV files have no limit of rows you can add to them. Excel won't hold more that the 1 million lines of data if you import a CSV file having more lines.
Excel will actually ask you whether you want to proceed when importing more than 1 million data rows. It suggests to import the remaining data by using the text import wizard again - you will need to set the appropriate line offset.
Having /A without additional parameters other than the filename didn't work for me, but the following code worked fine with /n
string sfile = @".\help\delta-pqca-400-100-300-fc4-user-manual.pdf";
Process myProcess = new Process();
myProcess.StartInfo.FileName = "AcroRd32.exe";
myProcess.StartInfo.Arguments = " /n " + "\"" + sfile + "\"";
myProcess.Start();
strInputString = strInputString.replace(/'/g, "''");
Install it locally rather installing it globally. Then your project may be run on any machine without any error.I think its better.
npm install express --save
npm install ejs --save
To concatenate strings, use the +
operator.
To insert data into a URI, encode it for URIs.
Bad:
var url = "http://localhost:8080/login?cid='username'&pwd='password'"
Good:
var url_safe_username = encodeURIComponent(username);
var url_safe_password = encodeURIComponent(password);
var url = "http://localhost:8080/login?cid=" + url_safe_username + "&pwd=" + url_safe_password;
The server will have to process the query string to make use of the data. You can't assign to arbitrary form fields.
… but don't trigger new windows or pass credentials in the URI (where they are exposed to over the shoulder attacks and may be logged).
$(document).ready(function() {
$('#example').DataTable( {
"columnDefs": [
{
"targets": [ 2 ],
"visible": false,
"searchable": false
},
{
"targets": [ 3 ],
"visible": false
}
]
});});
Here is a simple way of running MySQL queries in the bash shell
mysql -u [database_username] -p [database_password] -D [database_name] -e "SELECT * FROM [table_name]"
You can make Liquinaut's answer responsive to window size changes by adding a callback that sets the height back to auto.
$("#first").animate({height: $("#first").get(0).scrollHeight}, 1000, function() {$("#first").css({height: "auto"});});
equal_freq
from funModeling
takes a vector and the number of bins (based on equal frequency):
das <- data.frame(anim=1:15,
wt=c(181,179,180.5,201,201.5,245,246.4,
189.3,301,354,369,205,199,394,231.3))
das$wt_bin=funModeling::equal_freq(das$wt, 3)
table(das$wt_bin)
#[179,201) [201,246) [246,394]
# 5 5 5
>>> a = 255556
>>> a == 255556
True
>>> a is 255556
False
I think that should answer it ;-)
The reason is that some often-used objects, such as the booleans True and False, all 1-letter strings and short numbers are allocated once by the interpreter, and each variable containing that object refers to it. Other numbers and larger strings are allocated on demand. The 255556 for instance is allocated three times, every time a different object is created. And therefore, according to is
, they are not the same.
var cumulativeOffset = function(element) {
var top = 0, left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
return {
top: top,
left: left
};
};
(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)
Test castEnum = static_cast<Test>(a-1);
will cast a
to A
. If you don't want to substruct 1, you can redefine the enum
:
enum Test
{
A:1, B
};
In this case Test castEnum = static_cast<Test>(a);
could be used to cast a
to A
.
I just had the same problem as you, but found out about the toDataURL method, which proved useful.
The gist of it is to turn your current canvas into a dataURL, change your canvas size, and then draw what you had back into your canvas from the dataURL you saved.
So here's my code:
var oldCanvas = canvas.toDataURL("image/png");
var img = new Image();
img.src = oldCanvas;
img.onload = function (){
canvas.height += 100;
ctx.drawImage(img, 0, 0);
}
select count(*) from dbo.tablename where address_line_1 LIKE '%[\'']%' {eSCAPE'\'}
You can't have HTML code inside the options, they can only contain text, but you can apply the class to the option instead:
<option selected="selected" class="grey_color">select one option</option>
Demo: http://jsfiddle.net/Guffa/hUpAB/9/
Note:
html
and head
tags in the HTML code in jsfiddle.TreeSet would not work because they do not allow duplicates plus they do not provide method to fetch element at specific position. PriorityQueue would not work because it does not allow fetching elements at specific position which is a basic requirement for a list. I think you need to implement your own algorithm to maintain a sorted list in Java with O(logn) insert time, unless you do not need duplicates. Maybe a solution could be using a TreeMap where the key is a subclass of the item overriding the equals method so that duplicates are allowed.
That is the textarea
's job - for multiline text input. The input
won't do it; it wasn't designed to do it.
So use a textarea
. Besides their visual differences, they are accessed via JavaScript the same way (use value
property).
You can prevent newlines being entered via the input
event and simply using a replace(/\n/g, '')
.
You need to pass your data in the request body as a raw string rather than FormUrlEncodedContent
. One way to do so is to serialize it into a JSON string:
var json = JsonConvert.SerializeObject(data); // or JsonSerializer.Serialize if using System.Text.Json
Now all you need to do is pass the string to the post method.
var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json"); // use MediaTypeNames.Application.Json in Core 3.0+ and Standard 2.1+
var client = new HttpClient();
var response = await client.PostAsync(uri, stringContent);
tableColumns
null
for all columns as in SELECT * FROM ...
new String[] { "column1", "column2", ... }
for specific columns as in SELECT column1, column2 FROM ...
- you can also put complex expressions here:new String[] { "(SELECT max(column1) FROM table1) AS max" }
would give you a column named max
holding the max value of column1
whereClause
WHERE
without that keyword, e.g. "column1 > 5"
?
for things that are dynamic, e.g. "column1=?"
-> see whereArgs
whereArgs
?
in whereClause
in the order they appearthe others
whereClause
the statement after the keyword or null
if you don't use it.Example
String[] tableColumns = new String[] {
"column1",
"(SELECT max(column1) FROM table2) AS max"
};
String whereClause = "column1 = ? OR column1 = ?";
String[] whereArgs = new String[] {
"value1",
"value2"
};
String orderBy = "column1";
Cursor c = sqLiteDatabase.query("table1", tableColumns, whereClause, whereArgs,
null, null, orderBy);
// since we have a named column we can do
int idx = c.getColumnIndex("max");
is equivalent to the following raw query
String queryString =
"SELECT column1, (SELECT max(column1) FROM table1) AS max FROM table1 " +
"WHERE column1 = ? OR column1 = ? ORDER BY column1";
sqLiteDatabase.rawQuery(queryString, whereArgs);
By using the Where/Bind -Args version you get automatically escaped values and you don't have to worry if input-data contains '
.
Unsafe: String whereClause = "column1='" + value + "'";
Safe: String whereClause = "column1=?";
because if value contains a '
your statement either breaks and you get exceptions or does unintended things, for example value = "XYZ'; DROP TABLE table1;--"
might even drop your table since the statement would become two statements and a comment:
SELECT * FROM table1 where column1='XYZ'; DROP TABLE table1;--'
using the args version XYZ'; DROP TABLE table1;--
would be escaped to 'XYZ''; DROP TABLE table1;--'
and would only be treated as a value. Even if the '
is not intended to do bad things it is still quite common that people have it in their names or use it in texts, filenames, passwords etc. So always use the args version. (It is okay to build int
and other primitives directly into whereClause
though)
From the description and from the reference to the search box in the Ubuntu site, I gather that you actually want an arrowhead character pointing to the right. There are no Unicode characters designed to be used as arrowheads, but some of them may visually resemble an arrowhead.
In particular, if you draw your idea of the character at Shapecatcher.com, you will find many suggestions, such as “>” RIGHT-POINTING ANGLE BRACKET' (U+232A) and “?” MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT (U+276D).
Such characters generally have limited support in fonts, so you would need to carefully write a longish font-family
list or to use a downloadable font. See my Guide to using special characters in HTML.
Especially if the intended use is as a symbol in a search box, as the reference to the Ubuntu page suggests, it is questionable whether you should use a character at all. It’s not really an element of text here; rather, a graphic symbol that accompanies text but isn’t a part of it. So why take all the trouble with using a character (safely), when it isn’t really a character?
I have a visual Basic program with Visual Studio 2008 that uses an Access 2007 database and was receiving the same error. I found some threads that advised changing the advanced compile configuration to x86 found in the programs properties if you're running a 64 bit system. So far I haven't had any problems with my program since.
I find that the most convenient way to rename a single column is using dplyr::rename_at
:
library(dplyr)
cars %>% rename_at("speed",~"new") %>% head
cars %>% rename_at(vars(speed),~"new") %>% head
cars %>% rename_at(1,~"new") %>% head
# new dist
# 1 4 2
# 2 4 10
# 3 7 4
# 4 7 22
# 5 8 16
# 6 9 10
You can wrap the following in a DIV:
<div class="your-class">
<label for="First_Name">First Name:</label>
<input name="first_name" id="First_Name" type="text" />
<label for="Name">Last Name:</label>
<input name="last_name" id="Last_Name" type="text" />
</div>
Give each input float:left
in your CSS:
.your-class input{
float:left;
}
example only
You might have to adjust margins.
Remember to apply clear:left
or both to whatever comes after ".your-class"