How to draw interactive Polyline on route google maps v2 android
Instead of creating too many short Polyline
s just create one like here:
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
line = myMap.addPolyline(options);
I'm also not sure you should use geodesic
when your points are so close to each other.
Get driving directions using Google Maps API v2
This is what I am using,
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr="+latitude_cur+","+longitude_cur+"&daddr="+latitude+","+longitude));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_LAUNCHER );
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
Remove grid, background color, and top and right borders from ggplot2
An alternative to theme_classic()
is the theme that comes with the cowplot package, theme_cowplot()
(loaded automatically with the package). It looks similar to theme_classic()
, with a few subtle differences. Most importantly, the default label sizes are larger, so the resulting figures can be used in publications without further modifications needed (in particular if you save them with save_plot()
instead of ggsave()
). Also, the background is transparent, not white, which may be useful if you want to edit the figure in illustrator. Finally, faceted plots look better, in my opinion.
Example:
library(cowplot)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))
p <- ggplot(df, aes(x = a, y = b)) + geom_point()
save_plot('plot.png', p) # alternative to ggsave, with default settings that work well with the theme
This is what the file plot.png
produced by this code looks like:
Disclaimer: I'm the package author.
Random color generator
function randomColor(format = 'hex') {
const rnd = Math.random().toString(16).slice(-6);
if (format === 'hex') {
return '#' + rnd;
}
if (format === 'rgb') {
const [r, g, b] = rnd.match(/.{2}/g).map(c=>parseInt(c, 16));
return `rgb(${r}, ${g}, ${b})`;
}
}
Node.js: How to read a stream into a buffer?
I suggest loganfsmyths method, using an array to hold the data.
var bufs = [];
stdout.on('data', function(d){ bufs.push(d); });
stdout.on('end', function(){
var buf = Buffer.concat(bufs);
}
IN my current working example, i am working with GRIDfs and npm's Jimp.
var bucket = new GridFSBucket(getDBReference(), { bucketName: 'images' } );
var dwnldStream = bucket.openDownloadStream(info[0]._id);// original size
dwnldStream.on('data', function(chunk) {
data.push(chunk);
});
dwnldStream.on('end', function() {
var buff =Buffer.concat(data);
console.log("buffer: ", buff);
jimp.read(buff)
.then(image => {
console.log("read the image!");
IMAGE_SIZES.forEach( (size)=>{
resize(image,size);
});
});
I did some other research
with a string method but that did not work, per haps because i was reading from an image file, but the array method did work.
const DISCLAIMER = "DONT DO THIS";
var data = "";
stdout.on('data', function(d){
bufs+=d;
});
stdout.on('end', function(){
var buf = Buffer.from(bufs);
//// do work with the buffer here
});
When i did the string method i got this error from npm jimp
buffer: <Buffer 00 00 00 00 00>
{ Error: Could not find MIME for Buffer <null>
basically i think the type coersion from binary to string didnt work so well.
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
How to run mysql command on bash?
This one worked, double quotes when $user and $password are outside single quotes. Single quotes when inside a single quote statement.
mysql --user="$user" --password="$password" --database="$user" --execute='DROP DATABASE '$user'; CREATE DATABASE '$user';'
How do I add a .click() event to an image?
You can't bind an event to the element before it exists, so you should do it in the onload
event:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
document.getElementById('foo').addEventListener('click', function (e) {
var img = document.createElement('img');
img.setAttribute('src', 'http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png');
e.target.appendChild(img);
});
};
</script>
</head>
<body>
<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
</body>
</html>
Bootstrap modal opening on page load
I found the problem.
This code was placed in a separate file that was added with a php include() function.
And this include was happening before the Bootstrap files were loaded. So the Bootstrap JS file was not loaded yet, causing this modal to not do anything.
With the above code sample is nothing wrong and works as intended when placed in the body part of a html page.
<script type="text/javascript">
$('#memberModal').modal('show');
</script>
builder for HashMap
Underscore-java can build hashmap.
Map<String, Object> value = U.objectBuilder()
.add("firstName", "John")
.add("lastName", "Smith")
.add("age", 25)
.add("address", U.arrayBuilder()
.add(U.objectBuilder()
.add("streetAddress", "21 2nd Street")
.add("city", "New York")
.add("state", "NY")
.add("postalCode", "10021")))
.add("phoneNumber", U.arrayBuilder()
.add(U.objectBuilder()
.add("type", "home")
.add("number", "212 555-1234"))
.add(U.objectBuilder()
.add("type", "fax")
.add("number", "646 555-4567")))
.build();
// {firstName=John, lastName=Smith, age=25, address=[{streetAddress=21 2nd Street,
// city=New York, state=NY, postalCode=10021}], phoneNumber=[{type=home, number=212 555-1234},
// {type=fax, number=646 555-4567}]}
Is there a limit to the length of a GET request?
Not in the RFC, no, but there are practical limits.
The HTTP protocol does not place any a priori limit on the length of
a URI. Servers MUST be able to handle the URI of any resource they
serve, and SHOULD be able to handle URIs of unbounded length if they
provide GET-based forms that could generate such URIs. A server
SHOULD return 414 (Request-URI Too Long) status if a URI is longer
than the server can handle (see section 10.4.15).
Note: Servers should be cautious about depending on URI lengths
above 255 bytes, because some older client or proxy implementations
may not properly support these lengths.
How to use the divide function in the query?
Try something like this
select Cast((SPGI09_EARLY_OVER_T – (SPGI09_OVER_WK_EARLY_ADJUST_T) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T + SPGR99_ON_TIME_Q)) as varchar(20) + '%' as percentageAmount
from CSPGI09_OVERSHIPMENT
I presume the value is a representation in percentage - if not convert it to a valid percentage total, then add the % sign and convert the column to varchar.
iOS: present view controller programmatically
If you are using Storyboard and your "add" viewController is in storyboard then set an identifier for your "add" viewcontroller in settings so you can do something like this:
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"NameOfYourStoryBoard"
bundle:nil];
AddTaskViewController *add =
[storyboard instantiateViewControllerWithIdentifier:@"viewControllerIdentifier"];
[self presentViewController:add
animated:YES
completion:nil];
if you do not have your "add" viewController in storyboard or a nib file and want to create the whole thing programmaticaly then appDocs says:
If you cannot define your views in a storyboard or a nib file, override the loadView method to manually instantiate a view hierarchy and assign it to the view property.
How to implement an android:background that doesn't stretch?
Simply using ImageButton
instead of Button
fixes the problem.
<ImageButton android:layout_width="30dp"
android:layout_height="30dp"
android:src="@drawable/bgimage" />
and you can set
android:background="@null"
to remove button background if you want.
Quick Fix !! :-)
AngularJS : Prevent error $digest already in progress when calling $scope.$apply()
The digest cycle is a synchronous call. It won't yield control to the browser's event loop until it is done. There are a few ways to deal with this. The easiest way to deal with this is to use the built in $timeout, and a second way is if you are using underscore or lodash (and you should be), call the following:
$timeout(function(){
//any code in here will automatically have an apply run afterwards
});
or if you have lodash:
_.defer(function(){$scope.$apply();});
We tried several workarounds, and we hated injecting $rootScope into all of our controllers, directives, and even some factories. So, the $timeout and _.defer have been our favorite so far. These methods successfully tell angular to wait until the next animation loop, which will guarantee that the current scope.$apply is over.
How to dynamically set bootstrap-datepicker's date value?
Use Code:
var startDate = "2019-03-12"; //Date Format YYYY-MM-DD
$('#datepicker').val(startDate).datepicker("update");
Explanation:
Datepicker(input field) Selector #datepicker.
Update input field.
Call datepicker with option update.
Top 1 with a left join
The key to debugging situations like these is to run the subquery/inline view on its' own to see what the output is:
SELECT TOP 1
dm.marker_value,
dum.profile_id
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
ORDER BY dm.creation_date
Running that, you would see that the profile_id
value didn't match the u.id
value of u162231993
, which would explain why any mbg
references would return null
(thanks to the left join; you wouldn't get anything if it were an inner join).
You've coded yourself into a corner using TOP
, because now you have to tweak the query if you want to run it for other users. A better approach would be:
SELECT u.id,
x.marker_value
FROM DPS_USER u
LEFT JOIN (SELECT dum.profile_id,
dm.marker_value,
dm.creation_date
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
) x ON x.profile_id = u.id
JOIN (SELECT dum.profile_id,
MAX(dm.creation_date) 'max_create_date'
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
GROUP BY dum.profile_id) y ON y.profile_id = x.profile_id
AND y.max_create_date = x.creation_date
WHERE u.id = 'u162231993'
With that, you can change the id
value in the where
clause to check records for any user in the system.
Android Layout Weight
It doesn't work because you are using fill_parent as the width. The weight is used to distribute the remaining empty space or take away space when the total sum is larger than the LinearLayout. Set your widths to 0dip instead and it will work.
How to change the status bar background color and text color on iOS 7?
If you're using a UINavigationController
, you can use an extension like this:
extension UINavigationController {
private struct AssociatedKeys {
static var navigationBarBackgroundViewName = "NavigationBarBackground"
}
var navigationBarBackgroundView: UIView? {
get {
return objc_getAssociatedObject(self,
&AssociatedKeys.navigationBarBackgroundViewName) as? UIView
}
set(newValue) {
objc_setAssociatedObject(self,
&AssociatedKeys.navigationBarBackgroundViewName,
newValue,
.OBJC_ASSOCIATION_RETAIN)
}
}
func setNavigationBar(hidden isHidden: Bool, animated: Bool = false) {
if animated {
UIView.animate(withDuration: 0.3) {
self.navigationBarBackgroundView?.isHidden = isHidden
}
} else {
navigationBarBackgroundView?.isHidden = isHidden
}
}
func setNavigationBarBackground(color: UIColor, includingStatusBar: Bool = true, animated: Bool = false) {
navigationBarBackgroundView?.backgroundColor = UIColor.clear
navigationBar.backgroundColor = UIColor.clear
navigationBar.barTintColor = UIColor.clear
let setupOperation = {
if includingStatusBar {
self.navigationBarBackgroundView?.isHidden = false
if self.navigationBarBackgroundView == nil {
self.setupBackgroundView()
}
self.navigationBarBackgroundView?.backgroundColor = color
} else {
self.navigationBarBackgroundView?.isHidden = true
self.navigationBar.backgroundColor = color
}
}
if animated {
UIView.animate(withDuration: 0.3) {
setupOperation()
}
} else {
setupOperation()
}
}
private func setupBackgroundView() {
var frame = navigationBar.frame
frame.origin.y = 0
frame.size.height = 64
navigationBarBackgroundView = UIView(frame: frame)
navigationBarBackgroundView?.translatesAutoresizingMaskIntoConstraints = true
navigationBarBackgroundView?.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
navigationBarBackgroundView?.isUserInteractionEnabled = false
view.insertSubview(navigationBarBackgroundView!, aboveSubview: navigationBar)
}
}
It basically makes the navigation bar background transparent and uses another UIView as the background. You can call the setNavigationBarBackground
method of your navigation controller to set the navigation bar background color together with the status bar.
Keep in mind that you have to then use the setNavigationBar(hidden: Bool, animated: Bool)
method in the extension when you want to hide the navigation bar otherwise the view that was used as the background will still be visible.
Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?
Wild stab in the dark: You're on a machine with an IPv6 resolver where localhost
defaults to the IPv6 address ::1
, but listen_addresses
in postgresql.conf
is set to 127.0.0.1
or 0.0.0.0
not *
or you're using an older PostgreSQL built with a C library that doesn't have transparent IPv6 support.
Change listen_addresses
to localhost
and make sure localhost
resolves to both the IPv4 and IPv6 addresses, or set it to ::1, 127.0.0.1
to explicitly specify both IPv4 and IPv6. Or just set it to *
to listen on all interfaces. Alternately, if you don't care about IPv6, connect to 127.0.0.1
instead of localhost
.
See this Google search or this Stack Overflow search for more information.
(Posting despite my close-vote because I voted the question for migration).
Composer could not find a composer.json
To install composer and add to your global path:
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
run these in terminal. It does say if you get an error that usr doesn't exist, you do need to manually make it. I know an answer was selected, so this is for anyone who may see this in the future, as i am sometimes, and don't want to be advised to visit yet another site. Its simple just two lines, might have to be in sudo if you have permission error
setState() inside of componentDidUpdate()
This example will help you to understand the React Life Cycle Hooks.
You can setState
in getDerivedStateFromProps
method i.e. static
and trigger the method after props change in componentDidUpdate
.
In componentDidUpdate
you will get 3rd param which returns from getSnapshotBeforeUpdate
.
You can check this codesandbox link
_x000D_
_x000D_
// Child component_x000D_
class Child extends React.Component {_x000D_
// First thing called when component loaded_x000D_
constructor(props) {_x000D_
console.log("constructor");_x000D_
super(props);_x000D_
this.state = {_x000D_
value: this.props.value,_x000D_
color: "green"_x000D_
};_x000D_
}_x000D_
_x000D_
// static method_x000D_
// dont have access of 'this'_x000D_
// return object will update the state_x000D_
static getDerivedStateFromProps(props, state) {_x000D_
console.log("getDerivedStateFromProps");_x000D_
return {_x000D_
value: props.value,_x000D_
color: props.value % 2 === 0 ? "green" : "red"_x000D_
};_x000D_
}_x000D_
_x000D_
// skip render if return false_x000D_
shouldComponentUpdate(nextProps, nextState) {_x000D_
console.log("shouldComponentUpdate");_x000D_
// return nextState.color !== this.state.color;_x000D_
return true;_x000D_
}_x000D_
_x000D_
// In between before real DOM updates (pre-commit)_x000D_
// has access of 'this'_x000D_
// return object will be captured in componentDidUpdate_x000D_
getSnapshotBeforeUpdate(prevProps, prevState) {_x000D_
console.log("getSnapshotBeforeUpdate");_x000D_
return { oldValue: prevState.value };_x000D_
}_x000D_
_x000D_
// Calls after component updated_x000D_
// has access of previous state and props with snapshot_x000D_
// Can call methods here_x000D_
// setState inside this will cause infinite loop_x000D_
componentDidUpdate(prevProps, prevState, snapshot) {_x000D_
console.log("componentDidUpdate: ", prevProps, prevState, snapshot);_x000D_
}_x000D_
_x000D_
static getDerivedStateFromError(error) {_x000D_
console.log("getDerivedStateFromError");_x000D_
return { hasError: true };_x000D_
}_x000D_
_x000D_
componentDidCatch(error, info) {_x000D_
console.log("componentDidCatch: ", error, info);_x000D_
}_x000D_
_x000D_
// After component mount_x000D_
// Good place to start AJAX call and initial state_x000D_
componentDidMount() {_x000D_
console.log("componentDidMount");_x000D_
this.makeAjaxCall();_x000D_
}_x000D_
_x000D_
makeAjaxCall() {_x000D_
console.log("makeAjaxCall");_x000D_
}_x000D_
_x000D_
onClick() {_x000D_
console.log("state: ", this.state);_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<div style={{ border: "1px solid red", padding: "0px 10px 10px 10px" }}>_x000D_
<p style={{ color: this.state.color }}>Color: {this.state.color}</p>_x000D_
<button onClick={() => this.onClick()}>{this.props.value}</button>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
// Parent component_x000D_
class Parent extends React.Component {_x000D_
constructor(props) {_x000D_
super(props);_x000D_
this.state = { value: 1 };_x000D_
_x000D_
this.tick = () => {_x000D_
this.setState({_x000D_
date: new Date(),_x000D_
value: this.state.value + 1_x000D_
});_x000D_
};_x000D_
}_x000D_
_x000D_
componentDidMount() {_x000D_
setTimeout(this.tick, 2000);_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<div style={{ border: "1px solid blue", padding: "0px 10px 10px 10px" }}>_x000D_
<p>Parent</p>_x000D_
<Child value={this.state.value} />_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
function App() {_x000D_
return (_x000D_
<React.Fragment>_x000D_
<Parent />_x000D_
</React.Fragment>_x000D_
);_x000D_
}_x000D_
_x000D_
const rootElement = document.getElementById("root");_x000D_
ReactDOM.render(<App />, rootElement);
_x000D_
<div id="root"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
_x000D_
_x000D_
_x000D_
How can I set the PATH variable for javac so I can manually compile my .java works?
You don't need to do any complex command-line stuff or edit any system code.
You simply have to open Computer, showing all of your disks and open properties.
From there, go to Advanced System Settings and click Environment Variables.
Scroll down in the lower list box and edit Path.
Do not erase anything already there. Put a ; after it and then type in your path. To test, open command prompt and do "javac", it should list around 20 programs.
You would be finished at that point.
By the way, the command to compile is javac -g
not just javac
.
Happy coding!
Darken background image on hover
If you have to use the current image and get a darker image then you need to create a new one. Else you can simply reduce the opacity of the .image class and the in the .image:hover you can put a higher value for opacity. But then the image without hover would look pale.
The best way would be to create two images and add the following :
.image {
background: url('http://cdn1.iconfinder.com/data/icons/round-simple-social-icons/58/facebook.png');
width: 58px;
height: 58px;
opacity:0.9;
}
.image:hover{
background: url('http://cdn1.iconfinder.com/data/icons/round-simple-social-icons/58/facebook_hover.png');
}
}
positional argument follows keyword argument
The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
Specifically, a keyword argument looks like this: tag='insider trading!'
while a positional argument looks like this: ..., exchange, ...
. The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.
Also, when an argument has a default value, such as price=None
, that means you don't have to provide it. If you don't provide it, it will use the default value instead.
To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity)
# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)
# Some positional, some keyword (all keywords at end):
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity, tag='insider trading!')
is there a require for json in node.js
Two of the most common
First way :
let jsonData = require('./JsonFile.json')
let jsonData = require('./JsonFile')
// if we omitting .json also works
OR
import jsonData from ('./JsonFile.json')
Second way :
1) synchronously
const fs = require('fs')
let jsonData = JSON.parse(fs.readFileSync('JsonFile.json', 'utf-8'))
2) asynchronously
const fs = require('fs')
let jsonData = {}
fs.readFile('JsonFile.json', 'utf-8', (err, data) => {
if (err) throw err
jsonData = JSON.parse(data)
})
Note:
1) if we JsonFile.json is changed, we not get the new data, even if we re run require('./JsonFile.json')
2) The fs.readFile or fs.readFileSync will always re read the file, and get changes
(WAMP/XAMP) send Mail using SMTP localhost
If any one of you are getting error like following after following answer given by Afwe Wef
Warning: mail() [<a href='function.mail'>function.mail</a>]: SMTP server response:
550 The address is not valid. in c:\wamp\www\email.php
Go to php.ini
; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = [email protected]
Enter [email protected] as your email id which you used to configure the hMailserver in front of sendmail_from .
your problem will be solved.
Tested on Wamp server2.2(Apache 2.2.22, php 5.3.13) on windows 8
If you are also getting following error
"APPLICATION" 6364 "2014-03-24 13:13:33.979" "SMTPDeliverer - Message 2: Relaying to host smtp.gmail.com."
"APPLICATION" 6364 "2014-03-24 13:13:34.415" "SMTPDeliverer - Message 2: Message could not be delivered. Scheduling it for later delivery in 60 minutes."
"APPLICATION" 6364 "2014-03-24 13:13:34.430" "SMTPDeliverer - Message 2: Message delivery thread completed."
You might have forgot to change the port from 25 to 465
How do search engines deal with AngularJS applications?
Use PushState and Precomposition
The current (2015) way to do this is using the JavaScript pushState method.
PushState changes the URL in the top browser bar without reloading the page. Say you have a page containing tabs. The tabs hide and show content, and the content is inserted dynamically, either using AJAX or by simply setting display:none and display:block to hide and show the correct tab content.
When the tabs are clicked, use pushState to update the url in the address bar. When the page is rendered, use the value in the address bar to determine which tab to show. Angular routing will do this for you automatically.
Precomposition
There are two ways to hit a PushState Single Page App (SPA)
- Via PushState, where the user clicks a PushState link and the content is AJAXed in.
- By hitting the URL directly.
The initial hit on the site will involve hitting the URL directly. Subsequent hits will simply AJAX in content as the PushState updates the URL.
Crawlers harvest links from a page then add them to a queue for later processing. This means that for a crawler, every hit on the server is a direct hit, they don't navigate via Pushstate.
Precomposition bundles the initial payload into the first response from the server, possibly as a JSON object. This allows the Search Engine to render the page without executing the AJAX call.
There is some evidence to suggest that Google might not execute AJAX requests. More on this here:
https://web.archive.org/web/20160318211223/http://www.analog-ni.co/precomposing-a-spa-may-become-the-holy-grail-to-seo
Search Engines can read and execute JavaScript
Google has been able to parse JavaScript for some time now, it's why they originally developed Chrome, to act as a full featured headless browser for the Google spider. If a link has a valid href attribute, the new URL can be indexed. There's nothing more to do.
If clicking a link in addition triggers a pushState call, the site can be navigated by the user via PushState.
Search Engine Support for PushState URLs
PushState is currently supported by Google and Bing.
Google
Here's Matt Cutts responding to Paul Irish's question about PushState for SEO:
http://youtu.be/yiAF9VdvRPw
Here is Google announcing full JavaScript support for the spider:
http://googlewebmastercentral.blogspot.de/2014/05/understanding-web-pages-better.html
The upshot is that Google supports PushState and will index PushState URLs.
See also Google webmaster tools' fetch as Googlebot. You will see your JavaScript (including Angular) is executed.
Bing
Here is Bing's announcement of support for pretty PushState URLs dated March 2013:
http://blogs.bing.com/webmaster/2013/03/21/search-engine-optimization-best-practices-for-ajax-urls/
Don't use HashBangs #!
Hashbang urls were an ugly stopgap requiring the developer to provide a pre-rendered version of the site at a special location. They still work, but you don't need to use them.
Hashbang URLs look like this:
domain.com/#!path/to/resource
This would be paired with a metatag like this:
<meta name="fragment" content="!">
Google will not index them in this form, but will instead pull a static version of the site from the _escaped_fragments_ URL and index that.
Pushstate URLs look like any ordinary URL:
domain.com/path/to/resource
The difference is that Angular handles them for you by intercepting the change to document.location dealing with it in JavaScript.
If you want to use PushState URLs (and you probably do) take out all the old hash style URLs and metatags and simply enable HTML5 mode in your config block.
Testing your site
Google Webmaster tools now contains a tool which will allow you to fetch a URL as google, and render JavaScript as Google renders it.
https://www.google.com/webmasters/tools/googlebot-fetch
Generating PushState URLs in Angular
To generate real URLs in Angular, rather than # prefixed ones, set HTML5 mode on your $locationProvider object.
$locationProvider.html5Mode(true);
Server Side
Since you are using real URLs, you will need to ensure the same template (plus some precomposed content) gets shipped by your server for all valid URLs. How you do this will vary depending on your server architecture.
Sitemap
Your app may use unusual forms of navigation, for example hover or scroll. To ensure Google is able to drive your app, I would probably suggest creating a sitemap, a simple list of all the urls your app responds to. You can place this at the default location (/sitemap or /sitemap.xml), or tell Google about it using webmaster tools.
It's a good idea to have a sitemap anyway.
Browser support
Pushstate works in IE10. In older browsers, Angular will automatically fall back to hash style URLs
A demo page
The following content is rendered using a pushstate URL with precomposition:
http://html5.gingerhost.com/london
As can be verified, at this link, the content is indexed and is appearing in Google.
Serving 404 and 301 Header status codes
Because the search engine will always hit your server for every request, you can serve header status codes from your server and expect Google to see them.
get the value of DisplayName attribute
If instead
[DisplayName("Something To Name")]
you use
[Display(Name = "Something To Name")]
Just do this:
private string GetDisplayName(Class1 class1)
{
string displayName = string.Empty;
string propertyName = class1.Name.GetType().Name;
CustomAttributeData displayAttribute = class1.GetType().GetProperty(propertyName).CustomAttributes.FirstOrDefault(x => x.AttributeType.Name == "DisplayAttribute");
if (displayAttribute != null)
{
displayName = displayAttribute.NamedArguments.FirstOrDefault().TypedValue.Value;
}
return displayName;
}
How can I pass a parameter in Action?
Dirty trick: You could as well use lambda expression to pass any code you want including the call with parameters.
this.Include(includes, () =>
{
_context.Cars.Include(<parameters>);
});
How to get the unique ID of an object which overrides hashCode()?
Just to augment the other answers from a different angle.
If you want to reuse hashcode(s) from 'above' and derive new ones using your class' immutatable state, then a call to super will work. While this may/may not cascade all the way up to Object (i.e. some ancestor may not call super), it will allow you to derive hashcodes by reuse.
@Override
public int hashCode() {
int ancestorHash = super.hashCode();
// now derive new hash from ancestorHash plus immutable instance vars (id fields)
}
GDB: break if variable equal value
There are hardware and software watchpoints. They are for reading and for writing a variable. You need to consult a tutorial:
http://www.unknownroad.com/rtfm/gdbtut/gdbwatch.html
To set a watchpoint, first you need to break the code into a place where the varianle i is present in the environment, and set the watchpoint.
watch
command is used to set a watchpoit for writing, while rwatch
for reading, and awatch
for reading/writing.
Allow click on twitter bootstrap dropdown toggle link?
I'm not sure about the issue for making the top level anchor element a clickable anchor but here's the simplest solution for making desktop views have the hover effect, and mobile views maintaining their click-ability.
// Medium screens and up only
@media only screen and (min-width: $screen-md-min) {
// Enable menu hover for bootstrap
// dropdown menus
.dropdown:hover .dropdown-menu {
display: block;
}
}
This way the mobile menu still behaves as it should, while the desktop menu will expand on hover instead of on a click.
How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting
A problem I had on my Mac using rbenv was that when I first set it up, it loaded a bunch of ruby executables in /usr/local/bin - these executables loaded the system ruby, rather than the current version.
If you run
which bundle
And it shows /usr/local/bin/bundle you may have this issue.
Search through /usr/local/bin and delete any files that start with #!/user/bin ruby
Then run
rbenv rehash
matplotlib: Group boxplots
Here's a function I wrote that takes Molly's code and some other code I've found on the internet to make slightly fancier grouped boxplots:
import numpy as np
import matplotlib.pyplot as plt
def custom_legend(colors, labels, linestyles=None):
""" Creates a list of matplotlib Patch objects that can be passed to the legend(...) function to create a custom
legend.
:param colors: A list of colors, one for each entry in the legend. You can also include a linestyle, for example: 'k--'
:param labels: A list of labels, one for each entry in the legend.
"""
if linestyles is not None:
assert len(linestyles) == len(colors), "Length of linestyles must match length of colors."
h = list()
for k,(c,l) in enumerate(zip(colors, labels)):
clr = c
ls = 'solid'
if linestyles is not None:
ls = linestyles[k]
patch = patches.Patch(color=clr, label=l, linestyle=ls)
h.append(patch)
return h
def grouped_boxplot(data, group_names=None, subgroup_names=None, ax=None, subgroup_colors=None,
box_width=0.6, box_spacing=1.0):
""" Draws a grouped boxplot. The data should be organized in a hierarchy, where there are multiple
subgroups for each main group.
:param data: A dictionary of length equal to the number of the groups. The key should be the
group name, the value should be a list of arrays. The length of the list should be
equal to the number of subgroups.
:param group_names: (Optional) The group names, should be the same as data.keys(), but can be ordered.
:param subgroup_names: (Optional) Names of the subgroups.
:param subgroup_colors: A list specifying the plot color for each subgroup.
:param ax: (Optional) The axis to plot on.
"""
if group_names is None:
group_names = data.keys()
if ax is None:
ax = plt.gca()
plt.sca(ax)
nsubgroups = np.array([len(v) for v in data.values()])
assert len(np.unique(nsubgroups)) == 1, "Number of subgroups for each property differ!"
nsubgroups = nsubgroups[0]
if subgroup_colors is None:
subgroup_colors = list()
for k in range(nsubgroups):
subgroup_colors.append(np.random.rand(3))
else:
assert len(subgroup_colors) == nsubgroups, "subgroup_colors length must match number of subgroups (%d)" % nsubgroups
def _decorate_box(_bp, _d):
plt.setp(_bp['boxes'], lw=0, color='k')
plt.setp(_bp['whiskers'], lw=3.0, color='k')
# fill in each box with a color
assert len(_bp['boxes']) == nsubgroups
for _k,_box in enumerate(_bp['boxes']):
_boxX = list()
_boxY = list()
for _j in range(5):
_boxX.append(_box.get_xdata()[_j])
_boxY.append(_box.get_ydata()[_j])
_boxCoords = zip(_boxX, _boxY)
_boxPolygon = plt.Polygon(_boxCoords, facecolor=subgroup_colors[_k])
ax.add_patch(_boxPolygon)
# draw a black line for the median
for _k,_med in enumerate(_bp['medians']):
_medianX = list()
_medianY = list()
for _j in range(2):
_medianX.append(_med.get_xdata()[_j])
_medianY.append(_med.get_ydata()[_j])
plt.plot(_medianX, _medianY, 'k', linewidth=3.0)
# draw a black asterisk for the mean
plt.plot([np.mean(_med.get_xdata())], [np.mean(_d[_k])], color='w', marker='*',
markeredgecolor='k', markersize=12)
cpos = 1
label_pos = list()
for k in group_names:
d = data[k]
nsubgroups = len(d)
pos = np.arange(nsubgroups) + cpos
label_pos.append(pos.mean())
bp = plt.boxplot(d, positions=pos, widths=box_width)
_decorate_box(bp, d)
cpos += nsubgroups + box_spacing
plt.xlim(0, cpos-1)
plt.xticks(label_pos, group_names)
if subgroup_names is not None:
leg = custom_legend(subgroup_colors, subgroup_names)
plt.legend(handles=leg)
You can use the function(s) like this:
data = { 'A':[np.random.randn(100), np.random.randn(100) + 5],
'B':[np.random.randn(100)+1, np.random.randn(100) + 9],
'C':[np.random.randn(100)-3, np.random.randn(100) -5]
}
grouped_boxplot(data, group_names=['A', 'B', 'C'], subgroup_names=['Apples', 'Oranges'], subgroup_colors=['#D02D2E', '#D67700'])
plt.show()
Picking a random element from a set
If you don't mind a 3rd party library, the Utils library has a IterableUtils that has a randomFrom(Iterable iterable) method that will take a Set and return a random element from it
Set<Object> set = new HashSet<>();
set.add(...);
...
Object random = IterableUtils.randomFrom(set);
It is in the Maven Central Repository at:
<dependency>
<groupId>com.github.rkumsher</groupId>
<artifactId>utils</artifactId>
<version>1.3</version>
</dependency>
Java - sending HTTP parameters via POST method easily
This answer covers the specific case of the POST Call using a Custom Java POJO.
Using maven dependency for Gson to serialize our Java Object to JSON.
Install Gson using the dependency below.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
<scope>compile</scope>
</dependency>
For those using gradle can use the below
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
Other imports used:
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.*;
import org.apache.http.impl.client.CloseableHttpClient;
import com.google.gson.Gson;
Now, we can go ahead and use the HttpPost provided by Apache
private CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://example.com");
Product product = new Product(); //custom java object to be posted as Request Body
Gson gson = new Gson();
String client = gson.toJson(product);
httppost.setEntity(new StringEntity(client, ContentType.APPLICATION_JSON));
httppost.setHeader("RANDOM-HEADER", "headervalue");
//Execute and get the response.
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (IOException e) {
throw new InternalServerErrorException("Post fails");
}
Response.Status responseStatus = Response.Status.fromStatusCode(response.getStatusLine().getStatusCode());
return Response.status(responseStatus).build();
The above code will return with the response code received from the POST Call
jQuery ajax error function
From jquery.com:
The jqXHR.success(), jqXHR.error(), and jqXHR.complete()
callback methods introduced injQuery 1.5 are deprecated
as of jQuery 1.8. To prepare your code for their eventual
removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
If you want global handlers you can use:
.ajaxStart(), .ajaxStop(),
.ajaxComplete(), .ajaxError(),
.ajaxSuccess(), .ajaxSend()
Determine whether a key is present in a dictionary
In terms of bytecode, in
saves a LOAD_ATTR
and replaces a CALL_FUNCTION
with a COMPARE_OP
.
>>> dis.dis(indict)
2 0 LOAD_GLOBAL 0 (name)
3 LOAD_GLOBAL 1 (d)
6 COMPARE_OP 6 (in)
9 POP_TOP
>>> dis.dis(haskey)
2 0 LOAD_GLOBAL 0 (d)
3 LOAD_ATTR 1 (haskey)
6 LOAD_GLOBAL 2 (name)
9 CALL_FUNCTION 1
12 POP_TOP
My feelings are that in
is much more readable and is to be preferred in every case that I can think of.
In terms of performance, the timing reflects the opcode
$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "'foo' in d"
10000000 loops, best of 3: 0.11 usec per loop
$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "d.has_key('foo')"
1000000 loops, best of 3: 0.205 usec per loop
in
is almost twice as fast.
What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?
If you need to write line by line from string builder
StringBuilder sb = new StringBuilder();
sb.AppendLine("New Line!");
using (var sw = new StreamWriter(@"C:\MyDir\MyNewTextFile.txt", true))
{
sw.Write(sb.ToString());
}
If you need to write all text as single line from string builder
StringBuilder sb = new StringBuilder();
sb.Append("New Text line!");
using (var sw = new StreamWriter(@"C:\MyDir\MyNewTextFile.txt", true))
{
sw.Write(sb.ToString());
}
Resizing a button
You should not use "width" and "height" attributes directly, use the style attribute like style="some css here"
if you want to use inline styling:
<div class="button" style="width:60px;height:30px;">This is a button</div>
Note, however, that inline styling should generally be avoided since it makes maintenance and style updates a nightmare. Personally, if I had a button styling like yours but also wanted to apply different sizes, I would work with multiple css classes for sizing, like this:
_x000D_
_x000D_
.button {_x000D_
background-color: #000000;_x000D_
color: #FFFFFF;_x000D_
padding: 10px;_x000D_
border-radius: 10px;_x000D_
-moz-border-radius: 10px;_x000D_
-webkit-border-radius: 10px;_x000D_
margin:10px_x000D_
}_x000D_
_x000D_
.small-btn {_x000D_
width: 50px;_x000D_
height: 25px;_x000D_
}_x000D_
_x000D_
.medium-btn {_x000D_
width: 70px;_x000D_
height: 30px;_x000D_
}_x000D_
_x000D_
.big-btn {_x000D_
width: 90px;_x000D_
height: 40px;_x000D_
}
_x000D_
<div class="button big-btn">This is a big button</div>_x000D_
<div class="button medium-btn">This is a medium button</div>_x000D_
<div class="button small-btn">This is a small button</div>_x000D_
_x000D_
_x000D_
_x000D_
jsFiddle example
Using this way of defining styles removes all style information from your HTML markup, which in will make it easier down the road if you want to change the size of all small buttons - you'll only have to change them once in the CSS.
Delete all documents from index/type without deleting type
I'm using elasticsearch 7.5 and when I use
curl -XPOST 'localhost:9200/materials/_delete_by_query?conflicts=proceed&pretty' -d'
{
"query": {
"match_all": {}
}
}'
which will throw below error.
{
"error" : "Content-Type header [application/x-www-form-urlencoded] is not supported",
"status" : 406
}
I also need to add extra -H 'Content-Type: application/json'
header in the request to make it works.
curl -XPOST 'localhost:9200/materials/_delete_by_query?conflicts=proceed&pretty' -H 'Content-Type: application/json' -d'
{
"query": {
"match_all": {}
}
}'
{
"took" : 465,
"timed_out" : false,
"total" : 2275,
"deleted" : 2275,
"batches" : 3,
"version_conflicts" : 0,
"noops" : 0,
"retries" : {
"bulk" : 0,
"search" : 0
},
"throttled_millis" : 0,
"requests_per_second" : -1.0,
"throttled_until_millis" : 0,
"failures" : [ ]
}
Can You Get A Users Local LAN IP Address Via JavaScript?
As it turns out, the recent WebRTC extension of HTML5 allows javascript to query the local client IP address. A proof of concept is available here: http://net.ipcalf.com
This feature is apparently by design, and is not a bug. However, given its controversial nature, I would be cautious about relying on this behaviour. Nevertheless, I think it perfectly and appropriately addresses your intended purpose (revealing to the user what their browser is leaking).
Failed to load JavaHL Library
maybe you can try this: change jdk version.
And I resolved this problem by change jdk from 1.6.0_37 to 1.6.0.45 .
BR!
Dynamically Add C# Properties at Runtime
you could deserialize your json string into a dictionary and then add new properties then serialize it.
var jsonString = @"{}";
var jsonDoc = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonString);
jsonDoc.Add("Name", "Khurshid Ali");
Console.WriteLine(JsonSerializer.Serialize(jsonDoc));
PHP array: count or sizeof?
I know this is old but just wanted to mention that I tried this with PHP 7.2:
<?php
//Creating array with 1 000 000 elements
$a = array();
for ($i = 0; $i < 1000000; ++$i)
{
$a[] = 100;
}
//Measure
$time = time();
for ($i = 0; $i < 1000000000; ++$i)
{
$b = count($a);
}
print("1 000 000 000 iteration of count() took ".(time()-$time)." sec\n");
$time = time();
for ($i = 0; $i < 1000000000; ++$i)
{
$b = sizeof($a);
}
print("1 000 000 000 iteration of sizeof() took ".(time()-$time)." sec\n");
?>
and the result was:
1 000 000 000 iteration of count() took 414 sec
1 000 000 000 iteration of sizeof() took 1369 sec
So just use count()
.
Removing duplicates from a list of lists
Strangely, the answers above removes the 'duplicates' but what if I want to remove the duplicated value also??
The following should be useful and does not create a new object in memory!
def dictRemoveDuplicates(self):
a=[[1,'somevalue1'],[1,'somevalue2'],[2,'somevalue1'],[3,'somevalue4'],[5,'somevalue5'],[5,'somevalue1'],[5,'somevalue1'],[5,'somevalue8'],[6,'somevalue9'],[6,'somevalue0'],[6,'somevalue1'],[7,'somevalue7']]
print(a)
temp = 0
position = -1
for pageNo, item in a:
position+=1
if pageNo != temp:
temp = pageNo
continue
else:
a[position] = 0
a[position - 1] = 0
a = [x for x in a if x != 0]
print(a)
and the o/p is:
[[1, 'somevalue1'], [1, 'somevalue2'], [2, 'somevalue1'], [3, 'somevalue4'], [5, 'somevalue5'], [5, 'somevalue1'], [5, 'somevalue1'], [5, 'somevalue8'], [6, 'somevalue9'], [6, 'somevalue0'], [6, 'somevalue1'], [7, 'somevalue7']]
[[2, 'somevalue1'], [3, 'somevalue4'], [7, 'somevalue7']]
Hide Button After Click (With Existing Form on Page)
Change the button to :
<button onclick="getElementById('hidden-div').style.display = 'block'; this.style.display = 'none'">Check Availability</button>
FIDDLE
Or even better, use a proper event handler by identifying the button :
<button id="show_button">Check Availability</button>
and a script
<script type="text/javascript">
var button = document.getElementById('show_button')
button.addEventListener('click',hideshow,false);
function hideshow() {
document.getElementById('hidden-div').style.display = 'block';
this.style.display = 'none'
}
</script>
FIDDLE
Find row number of matching value
For your first method change ws.Range("A")
to ws.Range("A:A")
which will search the entirety of column a, like so:
Sub Find_Bingo()
Dim wb As Workbook
Dim ws As Worksheet
Dim FoundCell As Range
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Const WHAT_TO_FIND As String = "Bingo"
Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
If Not FoundCell Is Nothing Then
MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
Else
MsgBox (WHAT_TO_FIND & " not found")
End If
End Sub
For your second method, you are using Bingo
as a variable instead of a string literal. This is a good example of why I add Option Explicit
to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.
Additionally, when you are using With...End With
you need a period .
before you reference Cells
, so Cells
should be .Cells
. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)
Change Bingo
to "Bingo"
and change Cells
to .Cells
With Sheet1
Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
If Not FoundCell Is Nothing Then
MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
MsgBox ("Bingo not found")
End If
Update
In my
With Sheet1
.....
End With
The Sheet1
refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1
. I can refer to that in code either with the code name of Sheet1
or I can refer to it with the index of Sheets("Sheet1")
. The advantage to using a codename is that it does not change if you change the name of the worksheet.
Continuing this example, let's say I renamed Sheet1
to Data
. Using Sheet1
would continue to work, as the code name doesn't change, but now using Sheets("Sheet1")
would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data")
.
In the VB Editor you would see something like this:
Notice how, even though I changed the name to Data
, there is still a Sheet1
to the left. That is what I mean by codename.
The Data
worksheet can be referenced in two ways:
Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name
Both should return Data
More discussion on worksheet code names can be found here.
PRINT statement in T-SQL
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.
Where are static methods and static variables stored in Java?
Prior to Java 8:
The static variables were stored in the permgen space(also called the method area).
PermGen Space is also known as Method Area
PermGen Space used to store 3 things
- Class level data (meta-data)
- interned strings
- static variables
From Java 8 onwards
The static variables are stored in the Heap itself.From Java 8 onwards the PermGen Space have been removed and new space named as MetaSpace is introduced which is not the part of Heap any more unlike the previous Permgen Space. Meta-Space is present on the native memory (memory provided by the OS to a particular Application for its own usage) and it now only stores the class meta-data.
The interned strings and static variables are moved into the heap itself.
For official information refer : JEP 122:Remove the Permanent Gen Space
How can I start InternetExplorerDriver using Selenium WebDriver
In the same way for Chrome Browser below are the things to be considered.
Step 1-->Import files Required for Chrome :
import org.openqa.selenium.chrome.*;
Step 2--> Set the Path and initialize the Chrome Driver:
System.setProperty("webdriver.chrome.driver","S:\\chromedriver_win32\\chromedriver.exe");
Note: In Step 2 the location should point the chromedriver.exe file's storage location in your system drive
step 3--> Create an instance of Chrome browser
WebDriver driver = new ChromeDriver();
Rest will be the same as...
'printf' with leading zeros in C
Your format specifier is incorrect. From the printf()
man page on my machine:
0
A zero '0
' character indicating that zero-padding should be used rather than blank-padding. A '-
' overrides a '0
' if both are used;
Field Width:
An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);
Precision: An optional period, '.
', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;
For your case, your format would be %09.3f
:
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%09.3f\n", 4917.24);
return 0;
}
Output:
$ make testapp
cc testapp.c -o testapp
$ ./testapp
04917.240
Note that this answer is conditional on your embedded system having a printf()
implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.
don't fail jenkins build if execute shell fails
On the (more general) question in title - to prevent Jenkins from failing you can prevent it from seeing exit code 1. Example for ping:
bash -c "ping 1.2.3.9999 -c 1; exit 0"
And now you can e.g. get output of ping:
output=`bash -c "ping 1.2.3.9999 -c 1; exit 0"`
Of course instead of ping ...
You can use any command(s) - including git commit
.
How to create a file with a given size in Linux?
You can do it programmatically:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int main() {
int fd = creat("/tmp/foo.txt", 0644);
ftruncate(fd, SIZE_IN_BYTES);
close(fd);
return 0;
}
This approach is especially useful to subsequently mmap the file into memory.
use the following command to check that the file has the correct size:
# du -B1 --apparent-size /tmp/foo.txt
Be careful:
# du /tmp/foo.txt
will probably print 0 because it is allocated as Sparse file if supported by your filesystem.
see also: man 2 open and man 2 truncate
How to properly add include directories with CMake
First, you use include_directories()
to tell CMake to add the directory as -I
to the compilation command line. Second, you list the headers in your add_executable()
or add_library()
call.
As an example, if your project's sources are in src
, and you need headers from include
, you could do it like this:
include_directories(include)
add_executable(MyExec
src/main.c
src/other_source.c
include/header1.h
include/header2.h
)
How to trim whitespace from a Bash variable?
I found that I needed to add some code from a messy sdiff
output in order to clean it up:
sdiff -s column1.txt column2.txt | grep -F '<' | cut -f1 -d"<" > c12diff.txt
sed -n 1'p' c12diff.txt | sed 's/ *$//g' | tr -d '\n' | tr -d '\t'
This removes the trailing spaces and other invisible characters.
Get Insert Statement for existing row in MySQL
With PDO you can do it this way.
$stmt = DB::getDB()->query("SELECT * FROM sometable", array());
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
$fields = array_keys($array[0]);
$statement = "INSERT INTO user_profiles_copy (".implode(",",$fields).") VALUES ";
$statement_values = null;
foreach ($array as $key => $post) {
if(isset($statement_values)) {
$statement_values .= ", \n";
}
$values = array_values($post);
foreach($values as $index => $value) {
$quoted = str_replace("'","\'",str_replace('"','\"', $value));
$values[$index] = (!isset($value) ? 'NULL' : "'" . $quoted."'") ;
}
$statement_values .= "(".implode(',',$values).")";
}
$statement .= $statement_values . ";";
echo $statement;
When do you use POST and when do you use GET?
Short Version
GET: Usually used for submitted search requests, or any request where you want the user to be able to pull up the exact page again.
Advantages of GET:
- URLs can be bookmarked safely.
- Pages can be reloaded safely.
Disadvantages of GET:
POST: Used for higher security requests where data may be used to alter a database, or a page that you don't want someone to bookmark.
Advantages of POST:
- Name-value pairs are not displayed in url. (Security += 1)
- Unlimited number of name-value pairs can be passed via POST. Reference.
Disadvantages of POST:
- Page that used POST data cannot be bookmark. (If you so desired.)
Longer Version
Directly from the Hypertext Transfer Protocol -- HTTP/1.1:
9.3 GET
The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process.
The semantics of the GET method change to a "conditional GET" if the request message includes an If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or If-Range header field. A conditional GET method requests that the entity be transferred only under the circumstances described by the conditional header field(s). The conditional GET method is intended to reduce unnecessary network usage by allowing cached entities to be refreshed without requiring multiple requests or transferring data already held by the client.
The semantics of the GET method change to a "partial GET" if the request message includes a Range header field. A partial GET requests that only part of the entity be transferred, as described in section 14.35. The partial GET method is intended to reduce unnecessary network usage by allowing partially-retrieved entities to be completed without transferring data already held by the client.
The response to a GET request is cacheable if and only if it meets the requirements for HTTP caching described in section 13.
See section 15.1.3 for security considerations when used for forms.
9.5 POST
The POST method is used to request that the origin server accept the
entity enclosed in the request as a new subordinate of the resource
identified by the Request-URI in the Request-Line. POST is designed
to allow a uniform method to cover the following functions:
Annotation of existing resources;
Posting a message to a bulletin board, newsgroup, mailing list,
or similar group of articles;
Providing a block of data, such as the result of submitting a
form, to a data-handling process;
Extending a database through an append operation.
The actual function performed by the POST method is determined by the
server and is usually dependent on the Request-URI. The posted entity
is subordinate to that URI in the same way that a file is subordinate
to a directory containing it, a news article is subordinate to a
newsgroup to which it is posted, or a record is subordinate to a
database.
The action performed by the POST method might not result in a
resource that can be identified by a URI. In this case, either 200
(OK) or 204 (No Content) is the appropriate response status,
depending on whether or not the response includes an entity that
describes the result.
How to post JSON to PHP with curl
You need to set a few extra flags so that curl sends the data as JSON.
command
$ curl -H "Content-Type: application/json" \
-X POST \
-d '{"JSON": "HERE"}' \
http://localhost:3000/api/url
flags
-H
: custom header, next argument is expected to be header
-X
: custom HTTP verb, next argument is expected to be verb
-d
: sends the next argument as data in an HTTP POST request
resources
In a bootstrap responsive page how to center a div
In bootstrap 4
to center the children horizontally, use bootstrap-4 class
justify-content-center
to center the children vertically, use bootstrap-4 class
align-items-center
but remember don't forget to use d-flex class with these
it's a bootstrap-4 utility class, like so
<div class="d-flex justify-content-center align-items-center" style="height:100px;">
<div class="bg-primary">MIDDLE</div>
</div>
Note: make sure to add bootstrap-4 utilities if this code does not work
How to echo shell commands as they are executed
According to TLDP's Bash Guide for Beginners: Chapter 2. Writing and debugging scripts:
2.3.1. Debugging on the entire script
$ bash -x script1.sh
...
There is now a full-fledged debugger for Bash, available at SourceForge. These debugging features are available in most modern versions of Bash, starting from 3.x.
2.3.2. Debugging on part(s) of the script
set -x # Activate debugging from here
w
set +x # Stop debugging from here
...
Table 2-1. Overview of set debugging options
Short | Long notation | Result
-------+---------------+--------------------------------------------------------------
set -f | set -o noglob | Disable file name generation using metacharacters (globbing).
set -v | set -o verbose| Prints shell input lines as they are read.
set -x | set -o xtrace | Print command traces before executing command.
...
Alternatively, these modes can be specified in the script itself, by
adding the desired options to the first line shell declaration.
Options can be combined, as is usually the case with UNIX commands:
#!/bin/bash -xv
Sort a List of objects by multiple fields
If you know in advance which fields to use to make the comparison, then other people gave right answers.
What you may be interested in is to sort your collection in case you don't know at compile-time which criteria to apply.
Imagine you have a program dealing with cities:
protected Set<City> cities;
(...)
Field temperatureField = City.class.getDeclaredField("temperature");
Field numberOfInhabitantsField = City.class.getDeclaredField("numberOfInhabitants");
Field rainfallField = City.class.getDeclaredField("rainfall");
program.showCitiesSortBy(temperatureField, numberOfInhabitantsField, rainfallField);
(...)
public void showCitiesSortBy(Field... fields) {
List<City> sortedCities = new ArrayList<City>(cities);
Collections.sort(sortedCities, new City.CityMultiComparator(fields));
for (City city : sortedCities) {
System.out.println(city.toString());
}
}
where you can replace hard-coded field names by field names deduced from a user request in your program.
In this example, City.CityMultiComparator<City>
is a static nested class of class City
implementing Comparator
:
public static class CityMultiComparator implements Comparator<City> {
protected List<Field> fields;
public CityMultiComparator(Field... orderedFields) {
fields = new ArrayList<Field>();
for (Field field : orderedFields) {
fields.add(field);
}
}
@Override
public int compare(City cityA, City cityB) {
Integer score = 0;
Boolean continueComparison = true;
Iterator itFields = fields.iterator();
while (itFields.hasNext() && continueComparison) {
Field field = itFields.next();
Integer currentScore = 0;
if (field.getName().equalsIgnoreCase("temperature")) {
currentScore = cityA.getTemperature().compareTo(cityB.getTemperature());
} else if (field.getName().equalsIgnoreCase("numberOfInhabitants")) {
currentScore = cityA.getNumberOfInhabitants().compareTo(cityB.getNumberOfInhabitants());
} else if (field.getName().equalsIgnoreCase("rainfall")) {
currentScore = cityA.getRainfall().compareTo(cityB.getRainfall());
}
if (currentScore != 0) {
continueComparison = false;
}
score = currentScore;
}
return score;
}
}
You may want to add an extra layer of precision, to specify, for each field, whether sorting should be ascendant or descendant. I guess a solution is to replace Field
objects by objects of a class you could call SortedField
, containing a Field
object, plus another field meaning ascendant or descendant.
Adding a view controller as a subview in another view controller
For Add and Remove ViewController
var secondViewController :SecondViewController?
// Adding
func add_ViewController() {
let controller = self.storyboard?.instantiateViewController(withIdentifier: "secondViewController")as! SecondViewController
controller.view.frame = self.view.bounds
self.view.addSubview(controller.view)
self.addChild(controller)
controller.didMove(toParent: self)
self.secondViewController = controller
}
// Removing
func remove_ViewController(secondViewController:SecondViewController?) {
if secondViewController != nil {
if self.view.subviews.contains(secondViewController!.view) {
secondViewController!.view.removeFromSuperview()
}
}
}
How to check whether a string contains a substring in Ruby
How to check whether a string contains a substring in Ruby?
When you say 'check', I assume you want a boolean returned in which case you may use String#match?
. match?
accepts strings or regexes as its first parameter, if it's the former then it's automatically converted to a regex. So your use case would be:
str = 'string'
str.match? 'strings' #=> false
str.match? 'string' #=> true
str.match? 'strin' #=> true
str.match? 'trin' #=> true
str.match? 'tri' #=> true
String#match?
has the added benefit of an optional second argument which specifies an index from which to search the string. By default this is set to 0
.
str.match? 'tri',0 #=> true
str.match? 'tri',1 #=> true
str.match? 'tri',2 #=> false
Converting any string into camel case
Reliable, working example that I've been using for years:
function camelize(text) {
text = text.replace(/[-_\s.]+(.)?/g, (_, c) => c ? c.toUpperCase() : '');
return text.substr(0, 1).toLowerCase() + text.substr(1);
}
Case-changing characters:
- hyphen
-
- underscore
_
- period
.
- space
What does '&' do in a C++ declaration?
The "&" denotes a reference instead of a pointer to an object (In your case a constant reference).
The advantage of having a function such as
foo(string const& myname)
over
foo(string const* myname)
is that in the former case you are guaranteed that myname is non-null, since C++ does not allow NULL references. Since you are passing by reference, the object is not copied, just like if you were passing a pointer.
Your second example:
const string &GetMethodName() { ... }
Would allow you to return a constant reference to, for example, a member variable. This is useful if you do not wish a copy to be returned, and again be guaranteed that the value returned is non-null. As an example, the following allows you direct, read-only access:
class A
{
public:
int bar() const {return someValue;}
//Big, expensive to copy class
}
class B
{
public:
A const& getA() { return mA;}
private:
A mA;
}
void someFunction()
{
B b = B();
//Access A, ability to call const functions on A
//No need to check for null, since reference is guaranteed to be valid.
int value = b.getA().bar();
}
You have to of course be careful to not return invalid references.
Compilers will happily compile the following (depending on your warning level and how you treat warnings)
int const& foo()
{
int a;
//This is very bad, returning reference to something on the stack. This will
//crash at runtime.
return a;
}
Basically, it is your responsibility to ensure that whatever you are returning a reference to is actually valid.
How do I fix a "Expected Primary-expression before ')' token" error?
showInventory(player); // I get the error here.
void showInventory(player& obj) { // By Johnny :D
this means that player is an datatype and showInventory expect an referance to an variable of type player.
so the correct code will be
void showInventory(player& obj) { // By Johnny :D
for(int i = 0; i < 20; i++) {
std::cout << "\nINVENTORY:\n" + obj.getItem(i);
i++;
std::cout << "\t\t\t" + obj.getItem(i) + "\n";
i++;
}
}
players myPlayers[10];
std::string toDo() //BY KEATON
{
std::string commands[5] = // This is the valid list of commands.
{"help", "inv"};
std::string ans;
std::cout << "\nWhat do you wish to do?\n>> ";
std::cin >> ans;
if(ans == commands[0]) {
helpMenu();
return NULL;
}
else if(ans == commands[1]) {
showInventory(myPlayers[0]); // or any other index,also is not necessary to have an array
return NULL;
}
}
What is the fastest way to transpose a matrix in C++?
If the size of the arrays are known prior then we could use the union to our help. Like this-
#include <bits/stdc++.h>
using namespace std;
union ua{
int arr[2][3];
int brr[3][2];
};
int main() {
union ua uav;
int karr[2][3] = {{1,2,3},{4,5,6}};
memcpy(uav.arr,karr,sizeof(karr));
for (int i=0;i<3;i++)
{
for (int j=0;j<2;j++)
cout<<uav.brr[i][j]<<" ";
cout<<'\n';
}
return 0;
}
DataGridView changing cell background color
If you are still intrested in why this didn't work for you at first:
The reason you don't see changes you've made to the cell's style is because you do these changes before the form was shown, and so they are disregarded.
Changing cell styles in the events suggested here will do the job, but they are called multiple times causing your style changes to happen more times than you wish, and so aren't very efficient.
To solve this, either change the style after the point in your code in which the form is shown, or subscribe to the Shown event, and place your changes there (this is event is called significantly less than the other events suggested).
Rounding a number to the nearest 5 or 10 or X
In VB, math.round has additional arguments to specify number of decimal places and rounding method. Math.Round(10.665, 2, MidpointRounding.AwayFromZero) will return 10.67 . If the number is a decimal or single data type, math.round returns a decimal data type. If it is double, it returns double data type. That might be important if option strict is on.
The result of (10.665).ToString("n2") rounds away from zero to give "10.67". without additional arguments math.round returns 10.66, which could lead to unwanted discrepancies.
@Value annotation type casting to Integer from String
If you are using @Configuation then instantiate below static bean. If not static @Configutation is instantiated very early and and the BeanPostProcessors responsible for resolving annotations like @Value, @Autowired etc, cannot act on it. Refer here
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
Can I use an HTML input type "date" to collect only a year?
You can do the following:
- Generate an Array of the years I'll be accepting,
- Use a select box.
- Use each item from your Array as an 'option' tag.
Example using PHP (you can do this in any language of your choice):
Server:
<?php $years = range(1900, strftime("%Y", time())); ?>
HTML
<select>
<option>Select Year</option>
<?php foreach($years as $year) : ?>
<option value="<?php echo $year; ?>"><?php echo $year; ?></option>
<?php endforeach; ?>
</select>
As an added benefit, this works has a browser compatibility of a 100% ;-)
Foreach value from POST from form
First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters
In addition, you don't have to use variable variable names (that sounds odd), instead:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'";
}
To ensure that you have only parameters beginning with 'item_name' you can check it like so:
$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
// do something
}
UITableViewCell Selected Background Color on Multiple Selection
Swift 3
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifier", for: indexPath)
cell.selectionStyle = .none
return cell
}
Swift 2
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "yourCellIdentifier", for: indexPath)
cell.selectionStyle = .None
return cell
}
Should I use 'has_key()' or 'in' on Python dicts?
There is one example where in
actually kills your performance.
If you use in
on a O(1) container that only implements __getitem__
and has_key()
but not __contains__
you will turn an O(1) search into an O(N) search (as in
falls back to a linear search via __getitem__
).
Fix is obviously trivial:
def __contains__(self, x):
return self.has_key(x)
How to add two edit text fields in an alert dialog
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.text_entry, null);
//text_entry is an Layout XML file containing two text field to display in alert dialog
final EditText input1 = (EditText) textEntryView.findViewById(R.id.EditText1);
final EditText input2 = (EditText) textEntryView.findViewById(R.id.EditText2);
input1.setText("DefaultValue", TextView.BufferType.EDITABLE);
input2.setText("DefaultValue", TextView.BufferType.EDITABLE);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setIcon(R.drawable.icon)
.setTitle("Enter the Text:")
.setView(textEntryView)
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i("AlertDialog","TextEntry 1 Entered "+input1.getText().toString());
Log.i("AlertDialog","TextEntry 2 Entered "+input2.getText().toString());
/* User clicked OK so do some stuff */
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
alert.show();
Bootstrap 3 collapsed menu doesn't close on click
All you need is data-target=".navbar-collapse" in the button, nothing else.
<button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
Setting up MySQL and importing dump within Dockerfile
Each RUN
instruction in a Dockerfile
is executed in a different layer (as explained in the documentation of RUN
).
In your Dockerfile
, you have three RUN
instructions. The problem is that MySQL server is only started in the first. In the others, no MySQL are running, that is why you get your connection error with mysql
client.
To solve this problem you have 2 solutions.
Solution 1: use a one-line RUN
RUN /bin/bash -c "/usr/bin/mysqld_safe --skip-grant-tables &" && \
sleep 5 && \
mysql -u root -e "CREATE DATABASE mydb" && \
mysql -u root mydb < /tmp/dump.sql
Solution 2: use a script
Create an executable script init_db.sh
:
#!/bin/bash
/usr/bin/mysqld_safe --skip-grant-tables &
sleep 5
mysql -u root -e "CREATE DATABASE mydb"
mysql -u root mydb < /tmp/dump.sql
Add these lines to your Dockerfile
:
ADD init_db.sh /tmp/init_db.sh
RUN /tmp/init_db.sh
Use Fieldset Legend with bootstrap
In bootstrap 4 it is much easier to have a border on the fieldset that blends with the legend. You don't need custom css to achieve it, it can be done like this:
<fieldset class="border p-2">
<legend class="w-auto">Your Legend</legend>
</fieldset>
which looks like this:
Can not deserialize instance of java.lang.String out of START_OBJECT token
This way I solved my problem. Hope it helps others.
In my case I created a class, a field, their getter & setter and then provide the object instead of string.
Use this
public static class EncryptedData {
private String encryptedData;
public String getEncryptedData() {
return encryptedData;
}
public void setEncryptedData(String encryptedData) {
this.encryptedData = encryptedData;
}
}
@PutMapping(value = MY_IP_ADDRESS)
public ResponseEntity<RestResponse> updateMyIpAddress(@RequestBody final EncryptedData encryptedData) {
try {
Path path = Paths.get(PUBLIC_KEY);
byte[] bytes = Files.readAllBytes(path);
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(base64.decode(bytes));
PrivateKey privateKey = KeyFactory.getInstance(CRYPTO_ALGO_RSA).generatePrivate(ks);
Cipher cipher = Cipher.getInstance(CRYPTO_ALGO_RSA);
cipher.init(Cipher.PRIVATE_KEY, privateKey);
String decryptedData = new String(cipher.doFinal(encryptedData.getEncryptedData().getBytes()));
String[] dataArray = decryptedData.split("|");
Method updateIp = Class.forName("com.cuanet.client.helper").getMethod("methodName", String.class,String.class);
updateIp.invoke(null, dataArray[0], dataArray[1]);
} catch (Exception e) {
LOG.error("Unable to update ip address for encrypted data: "+encryptedData, e);
}
return null;
Instead of this
@PutMapping(value = MY_IP_ADDRESS)
public ResponseEntity<RestResponse> updateMyIpAddress(@RequestBody final EncryptedData encryptedData) {
try {
Path path = Paths.get(PUBLIC_KEY);
byte[] bytes = Files.readAllBytes(path);
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(base64.decode(bytes));
PrivateKey privateKey = KeyFactory.getInstance(CRYPTO_ALGO_RSA).generatePrivate(ks);
Cipher cipher = Cipher.getInstance(CRYPTO_ALGO_RSA);
cipher.init(Cipher.PRIVATE_KEY, privateKey);
String decryptedData = new String(cipher.doFinal(encryptedData.getBytes()));
String[] dataArray = decryptedData.split("|");
Method updateIp = Class.forName("com.cuanet.client.helper").getMethod("methodName", String.class,String.class);
updateIp.invoke(null, dataArray[0], dataArray[1]);
} catch (Exception e) {
LOG.error("Unable to update ip address for encrypted data: "+encryptedData, e);
}
return null;
}
Debugging WebSocket in Google Chrome
Short answer for Chrome Version 29 and up:
- Open debugger, go to the tab "Network"
- Load page with websocket
- Click on the websocket request with upgrade response from server
- Select the tab "Frames" to see websocket frames
- Click on the websocket request again to refresh frames
Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches
As the error code says, "no alternative certificate subject name matches target host name" - so there is an issue with the SSL certificate.
The certificate should include SAN, and only SAN will be used. Some browsers ignore the deprecated Common Name.
RFC 2818 clearly states
"If a subjectAltName extension of type dNSName is present, that MUST
be used as the identity. Otherwise, the (most specific) Common Name
field in the Subject field of the certificate MUST be used. Although
the use of the Common Name is existing practice, it is deprecated and
Certification Authorities are encouraged to use the dNSName instead."
What is the correct way to free memory in C#
Let's answer your questions one by one.
- Yes, you make a new object whenever this statement is executed, however, it goes "out of scope" when you exit the method and it is eligible for garbage collection.
- Well this would be the same as #1, except that you've used a string type. A string type is immutable and you get a new object every time you make an assignment.
- Yes the garbage collector collects the out of scope objects, unless you assign the object to a variable with a large scope such as class variable.
- Yes.
- The using statement only applies to objects that implement the IDisposable interface. If that is the case, by all means using is best for objects within a method's scope. Don't put Foo o at a larger scope unless you have a good reason to do so. It is best to limit the scope of any variable to the smallest scope that makes sense.
How do I implement a progress bar in C#?
If you can't know the progress you should not fake it by abusing a progress bar, instead just display some sort of busy icon like en.wikipedia.org/wiki/Throbber#Spinning_wheel Show it when starting the task and hide it when it's finished. That would make for a more "honest" GUI.
Import existing Gradle Git project into Eclipse
I use another Eclipse plugin to import existing gradle projects.
You can install the Builship Gradle Gntegration 2.0 using the Eclipse Marketplace client.
Then you choose FIle ? Import ? Existing Gradle Project.
Finially, indicate your project root directory and click finish.
Row numbers in query result using Microsoft Access
MS-Access doesn't support ROW_NUMBER(). Use TOP 1:
SELECT TOP 1 *
FROM [MyTable]
ORDER BY [MyIdentityCOlumn]
If you need the 15th row - MS-Access has no simple, built-in, way to do this. You can simulate the rownumber by using reverse nested ordering to get this:
SELECT TOP 1 *
FROM (
SELECT TOP 15 *
FROM [MyTable]
ORDER BY [MyIdentityColumn] ) t
ORDER BY [MyIdentityColumn] DESC
Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction
If you really need to do it in separate transaction you need to use REQUIRES_NEW
and live with the performance overhead. Watch out for dead locks.
I'd rather do it the other way:
- Validate data on Java side.
- Run everyting in one transaction.
- If anything goes wrong on DB side -> it's a major error of DB or validation design. Rollback everything and throw critical top level error.
- Write good unit tests.
Replace image src location using CSS
you can use: content:url("image.jpg")
<style>
.your-class-name{
content: url("http://imgur.com/SZ8Cm.jpg");
}
</style>
<img class="your-class-name" src="..."/>
How to save data file into .RData?
There are three ways to save objects from your R session:
Saving all objects in your R session:
The save.image()
function will save all objects currently in your R session:
save.image(file="1.RData")
These objects can then be loaded back into a new R session using the load()
function:
load(file="1.RData")
Saving some objects in your R session:
If you want to save some, but not all objects, you can use the save()
function:
save(city, country, file="1.RData")
Again, these can be reloaded into another R session using the load()
function:
load(file="1.RData")
Saving a single object
If you want to save a single object you can use the saveRDS()
function:
saveRDS(city, file="city.rds")
saveRDS(country, file="country.rds")
You can load these into your R session using the readRDS()
function, but you will need to assign the result into a the desired variable:
city <- readRDS("city.rds")
country <- readRDS("country.rds")
But this also means you can give these objects new variable names if needed (i.e. if those variables already exist in your new R session but contain different objects):
city_list <- readRDS("city.rds")
country_vector <- readRDS("country.rds")
pycharm running way slow
In my case, it was very slow and i needed to change inspections settings, i tried everything, the only thing that worked was going from 2018.2 version to 2016.2, sometimes is better to be some updates behind...
React-Native: Application has not been registered error
In my case there's this line in MainActivity.java which was missed when I used react-native-rename
cli (from NPM)
protected String getMainComponentName() {
return "AwesomeApp";
}
Obviously ya gotta rename it to your app's name.
What does the exclamation mark do before the function?
! is a logical NOT operator, it's a boolean operator that will invert something to its opposite.
Although you can bypass the parentheses of the invoked function by using the BANG (!) before the function, it will still invert the return, which might not be what you wanted. As in the case of an IEFE, it would return undefined, which when inverted becomes the boolean true.
Instead, use the closing parenthesis and the BANG (!) if needed.
// I'm going to leave the closing () in all examples as invoking the function with just ! and () takes away from what's happening.
(function(){ return false; }());
=> false
!(function(){ return false; }());
=> true
!!(function(){ return false; }());
=> false
!!!(function(){ return false; }());
=> true
Other Operators that work...
+(function(){ return false; }());
=> 0
-(function(){ return false; }());
=> -0
~(function(){ return false; }());
=> -1
Combined Operators...
+!(function(){ return false; }());
=> 1
-!(function(){ return false; }());
=> -1
!+(function(){ return false; }());
=> true
!-(function(){ return false; }());
=> true
~!(function(){ return false; }());
=> -2
~!!(function(){ return false; }());
=> -1
+~(function(){ return false; }());
+> -1
Programmatically Install Certificate into Mozilla
Just wanted to add to an old thread to hopefully aid other people. I needed programmatically add a cert to the firefox database using a GPO, this was how I did it for Windows
1, First download and unzip the precompiled firefox NSS nss-3.13.5-nspr-4.9.1-compiled-x86.zip
2, Add the cert manually to firefox Options-->Advanced--Certificates-->Authorities-->Import
3, from the downloaded NSS package, run
certutil -L -d c:\users\[username]\appdata\roaming\mozilla\firefox\[profile].default
4, The above query will show you the certificate name and Trust Attributes e.g.
my company Ltd CT,C,C
5, Delete the certificate in step 2. Options-->Advanced--Certificates-->Authorities-->Delete
6, Create a powershell script using the information from step 4 as follows. This script will get the users profile path and add the certificate. This only works if the user has one firefox profile (need somehow to retrieve the users firefox folder profile name)
#Script adds Radius Certificate to independent Firefox certificate store since the browser does not use the Windows built in certificate store
#Get Firefox profile cert8.db file from users windows profile path
$ProfilePath = "C:\Users\" + $env:username + "\AppData\Roaming\Mozilla\Firefox\Profiles\"
$ProfilePath = $ProfilePath + (Get-ChildItem $ProfilePath | ForEach-Object { $_.Name }).ToString()
#Update firefox cert8.db file with Radius Certificate
certutil -A -n "UK my company" -t "CT,C,C" -i CertNameToAdd.crt -d $ProfilePath
7, Create GPO as a User Configuration to run the PowerShell script
Hope that helps save someone time
Simple way to find if two different lists contain exactly the same elements?
Check both lists are not nulls. If their sizes are different, then these lists are not equal. Build maps consisting of the lists' elements as keys and their repeats as values and compare the maps.
Assumptions, if both lists are nulls, I consider them equal.
private boolean compareLists(List<?> l1, List<?> l2) {
if (l1 == null && l2 == null) {
return true;
} else if (l1 == null || l2 == null) {
return false;
}
if (l1.size() != l2.size()) {
return false;
}
Map<?, Integer> m1 = toMap(l1);
Map<?, Integer> m2 = toMap(l2);
return m1.equals(m2);
}
private Map<Object, Integer> toMap(List<?> list) {
//Effective size, not to resize in the future.
int mapSize = (int) (list.size() / 0.75 + 1);
Map<Object, Integer> map = new HashMap<>(mapSize);
for (Object o : list) {
Integer count = map.get(o);
if (count == null) {
map.put(o, 1);
} else {
map.put(o, ++count);
}
}
System.out.println(map);
return map;
}
Please, note, method equals should be properly defined for these objects.
https://stackoverflow.com/a/24814634/4587961
Multiple Indexes vs Multi-Column Indexes
The multi-column index can be used for queries referencing all the columns:
SELECT *
FROM TableName
WHERE Column1=1 AND Column2=2 AND Column3=3
This can be looked up directly using the multi-column index. On the other hand, at most one of the single-column index can be used (it would have to look up all records having Column1=1, and then check Column2 and Column3 in each of those).
how to generate web service out of wsdl
This may be very late in answering. But might be helpful to needy:
How to convert WSDL to SVC :
- Assuming you are having .wsdl file at location "E:\" for ease in access further.
- Prepare the command for each .wsdl file as: E:\YourServiceFileName.wsdl
- Permissions: Assuming you are having the Administrative rights to perform permissions. Open directory : C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin
- Right click to amd64 => Security => Edit => Add User => Everyone Or Current User => Allow all permissions => OK.
- Prepare the Commands for each file in text editor as: wsdl.exe E:\YourServiceFileName.wsdl /l:CS /server.
- Now open Visual studio command prompt from : C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts\VS2013 x64 Native Tools Command Prompt.
- Execute above command.
Go to directory : C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\amd64, Where respective .CS file should be generated.
9.Move generated CS file to appropriate location.
How does strtok() split the string into tokens in C?
This is how i implemented strtok, Not that great but after working 2 hr on it finally got it worked. It does support multiple delimiters.
#include "stdafx.h"
#include <iostream>
using namespace std;
char* mystrtok(char str[],char filter[])
{
if(filter == NULL) {
return str;
}
static char *ptr = str;
static int flag = 0;
if(flag == 1) {
return NULL;
}
char* ptrReturn = ptr;
for(int j = 0; ptr != '\0'; j++) {
for(int i=0 ; filter[i] != '\0' ; i++) {
if(ptr[j] == '\0') {
flag = 1;
return ptrReturn;
}
if( ptr[j] == filter[i]) {
ptr[j] = '\0';
ptr+=j+1;
return ptrReturn;
}
}
}
return NULL;
}
int _tmain(int argc, _TCHAR* argv[])
{
char str[200] = "This,is my,string.test";
char *ppt = mystrtok(str,", .");
while(ppt != NULL ) {
cout<< ppt << endl;
ppt = mystrtok(NULL,", .");
}
return 0;
}
Create an empty data.frame
The most efficient way to do this is to use structure
to create a list that has the class "data.frame"
:
structure(list(Date = as.Date(character()), File = character(), User = character()),
class = "data.frame")
# [1] Date File User
# <0 rows> (or 0-length row.names)
To put this into perspective compared to the presently accepted answer, here's a simple benchmark:
s <- function() structure(list(Date = as.Date(character()),
File = character(),
User = character()),
class = "data.frame")
d <- function() data.frame(Date = as.Date(character()),
File = character(),
User = character(),
stringsAsFactors = FALSE)
library("microbenchmark")
microbenchmark(s(), d())
# Unit: microseconds
# expr min lq mean median uq max neval
# s() 58.503 66.5860 90.7682 82.1735 101.803 469.560 100
# d() 370.644 382.5755 523.3397 420.1025 604.654 1565.711 100
ORDER BY using Criteria API
This is what you have to do since sess.createCriteria is deprecated:
CriteriaBuilder builder = getSession().getCriteriaBuilder();
CriteriaQuery<User> q = builder.createQuery(User.class);
Root<User> usr = q.from(User.class);
ParameterExpression<String> p = builder.parameter(String.class);
q.select(usr).where(builder.like(usr.get("name"),p))
.orderBy(builder.asc(usr.get("name")));
TypedQuery<User> query = getSession().createQuery(q);
query.setParameter(p, "%" + Main.filterName + "%");
List<User> list = query.getResultList();
Finding the handle to a WPF window
If you want window handles for ALL of your application's Window
s for some reason, you can use the Application.Windows
property to get at all the Windows and then use WindowInteropHandler
to get at their handles as you have already demonstrated.
How do I block comment in Jupyter notebook?
I tried this on Mac OSX with Chrome 42.0.2311.90 (64-bit) and this works by using CMD + /
The version of the notebook server is 3.1.0-cbccb68 and is running on:
Python 2.7.9 |Anaconda 2.1.0 (x86_64)| (default, Dec 15 2014, 10:37:34)
[GCC 4.2.1 (Apple Inc. build 5577)]
Could it be a browser related problem? Did you try Firefox or IE?
using batch echo with special characters
Here's one more approach by using SET
and FOR /F
@echo off
set "var=<?xml version="1.0" encoding="utf-8" ?>"
for /f "tokens=1* delims==" %%a in ('set var') do echo %%b
and you can beautify it like:
@echo off
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "print{[=for /f "tokens=1* delims==" %%a in ('set " & set "]}=') do echo %%b"
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "xml_line.1=<?xml version="1.0" encoding="utf-8" ?>"
set "xml_line.2=<root>"
set "xml_line.3=</root>"
%print{[% xml_line %]}%
Angular 2 Routing run in new tab
Try this please, <a target="_blank" routerLink="/Page2">
Update1: Custom directives to the rescue! Full code is here: https://github.com/pokearound/angular2-olnw
import { Directive, ElementRef, HostListener, Input, Inject } from '@angular/core';
@Directive({ selector: '[olinw007]' })
export class OpenLinkInNewWindowDirective {
//@Input('olinwLink') link: string; //intro a new attribute, if independent from routerLink
@Input('routerLink') link: string;
constructor(private el: ElementRef, @Inject(Window) private win:Window) {
}
@HostListener('mousedown') onMouseEnter() {
this.win.open(this.link || 'main/default');
}
}
Notice, Window is provided and OpenLinkInNewWindowDirective declared below:
import { AppAboutComponent } from './app.about.component';
import { AppDefaultComponent } from './app.default.component';
import { PageNotFoundComponent } from './app.pnf.component';
import { OpenLinkInNewWindowDirective } from './olinw.directive';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
const appRoutes: Routes = [
{ path: '', pathMatch: 'full', component: AppDefaultComponent },
{ path: 'home', component: AppComponent },
{ path: 'about', component: AppAboutComponent },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
declarations: [
AppComponent, AppAboutComponent, AppDefaultComponent, PageNotFoundComponent, OpenLinkInNewWindowDirective
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(appRoutes)
],
providers: [{ provide: Window, useValue: window }],
bootstrap: [AppComponent]
})
export class AppModule { }
First link opens in new Window, second one will not:
<h1>
{{title}}
<ul>
<li><a routerLink="/main/home" routerLinkActive="active" olinw007> OLNW</a></li>
<li><a routerLink="/main/home" routerLinkActive="active"> OLNW - NOT</a></li>
</ul>
<div style="background-color:#eee;">
<router-outlet></router-outlet>
</div>
</h1>
Tada! ..and you are welcome =)
Update2: As of v2.4.10 <a target="_blank" routerLink="/Page2">
works
'gulp' is not recognized as an internal or external command
If you have mysql install in your windows 10 try uninstall every myqsl app from your computer. Its work for me. exactly when i installed the mysql in my computer gulp command and some other commands stop working and then i have tried everything but not nothing worked for me.
Storing a Key Value Array into a compact JSON string
To me, this is the most "natural" way to structure such data in JSON, provided that all of the keys are strings.
{
"keyvaluelist": {
"slide0001.html": "Looking Ahead",
"slide0008.html": "Forecast",
"slide0021.html": "Summary"
},
"otherdata": {
"one": "1",
"two": "2",
"three": "3"
},
"anotherthing": "thing1",
"onelastthing": "thing2"
}
I read this as
a JSON object with four elements
element 1 is a map of key/value pairs named "keyvaluelist",
element 2 is a map of key/value pairs named "otherdata",
element 3 is a string named "anotherthing",
element 4 is a string named "onelastthing"
The first element or second element could alternatively be described as objects themselves, of course, with three elements each.
CSS3 Fade Effect
You can't transition between two background images, as there's no way for the browser to know what you want to interpolate. As you've discovered, you can transition the background position. If you want the image to fade in on mouse over, I think the best way to do it with CSS transitions is to put the image on a containing element and then animate the background colour to transparent on the link itself:
span {
background: url(button.png) no-repeat 0 0;
}
a {
width: 32px;
height: 32px;
text-align: left;
background: rgb(255,255,255);
-webkit-transition: background 300ms ease-in 200ms; /* property duration timing-function delay */
-moz-transition: background 300ms ease-in 200ms;
-o-transition: background 300ms ease-in 200ms;
transition: background 300ms ease-in 200ms;
}
a:hover {
background: rgba(255,255,255,0);
}
Convert a python dict to a string and back
If you care about the speed use ujson (UltraJSON), which has the same API as json:
import ujson
ujson.dumps([{"key": "value"}, 81, True])
# '[{"key":"value"},81,true]'
ujson.loads("""[{"key": "value"}, 81, true]""")
# [{u'key': u'value'}, 81, True]
Class has been compiled by a more recent version of the Java Environment
Your JDK version: Java 8
Your JRE version: Java 9
Here your JRE version is different than the JDK version that's the case. Here you can compile all the java classes using JDK version 1.8. If you want to compile only one java class just change the *.java
into <yourclassname>.java
javac -source 1.8 -target 1.8 *.java
source: The version that your source code requires to compile.
target: The oldest JRE version you want to support.
Write to CSV file and export it?
Rom, you're doing it wrong. You don't want to write files to disk so that IIS can serve them up. That adds security implications as well as increases complexity. All you really need to do is save the CSV directly to the response stream.
Here's the scenario: User wishes to download csv. User submits a form with details about the csv they want. You prepare the csv, then provide the user a URL to an aspx page which can be used to construct the csv file and write it to the response stream. The user clicks the link. The aspx page is blank; in the page codebehind you simply write the csv to the response stream and end it.
You can add the following to the (I believe this is correct) Load event:
string attachment = "attachment; filename=MyCsvLol.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
var sb = new StringBuilder();
foreach(var line in DataToExportToCSV)
sb.AppendLine(TransformDataLineIntoCsv(line));
HttpContext.Current.Response.Write(sb.ToString());
writing to the response stream code ganked from here.
Difference between subprocess.Popen and os.system
When running python (cpython) on windows the <built-in function system>
os.system will execute under the curtains _wsystem while if you're using a non-windows os, it'll use system.
On contrary, Popen should use CreateProcess on windows and _posixsubprocess.fork_exec in posix-based operating-systems.
That said, an important piece of advice comes from os.system docs, which says:
The subprocess module provides more powerful facilities for spawning
new processes and retrieving their results; using that module is
preferable to using this function. See the Replacing Older Functions
with the subprocess Module section in the subprocess documentation for
some helpful recipes.
What does '<?=' mean in PHP?
Arrays in PHP are associative arrays (otherwise known as dictionaries or hashes) by default. If you don't explicitly assign a key to a value, the interpreter will silently do that for you. So, the expression you've got up there iterates through $user_list
, making the key available as $user
and the value available as $pass
as local variables in the body of the foreach
.
How to revert initial git commit?
Under the conditions stipulated in the question:
- The commit is the first commit in the repository.
- Which means there have been very few commands executed:
- a
git init
,
- presumably some
git add
operations,
- and a
git commit
,
- and that's all!
If those preconditions are met, then the simplest way to undo the initial commit would be:
rm -fr .git
from the directory where you did git init
. You can then redo the git init
to recreate the Git repository, and redo the additions with whatever changes are sensible that you regretted not making the first time, and redo the initial commit.
DANGER! This removes the Git repository directory.
It removes the Git repository directory permanently and irrecoverably, unless you've got backups somewhere. Under the preconditions, you've nothing you want to keep in the repository, so you're not losing anything.
All the files you added are still available in the working directories, assuming you have not modified them yet and have not deleted them, etc. However, doing this is safe only if you have nothing else in your repository at all. Under the circumstances described in the question 'commit repository first time — then regret it', it is safe. Very often, though, it is not safe.
It's also safe to do this to remove an unwanted cloned repository; it does no damage to the repository that it was cloned from. It throws away anything you've done in your copy, but doesn't affect the original repository otherwise.
Be careful, but it is safe and effective when the preconditions are met.
If you've done other things with your repository that you want preserved, then this is not the appropriate technique — your repository no longer meets the preconditions for this to be appropriate.
Generating a Random Number between 1 and 10 Java
This will work for generating a number 1 - 10. Make sure you import Random at the top of your code.
import java.util.Random;
If you want to test it out try something like this.
Random rn = new Random();
for(int i =0; i < 100; i++)
{
int answer = rn.nextInt(10) + 1;
System.out.println(answer);
}
Also if you change the number in parenthesis it will create a random number from 0 to that number -1 (unless you add one of course like you have then it will be from 1 to the number you've entered).
JPA - Returning an auto generated id after persist()
Another option compatible to 4.0:
Before committing the changes, you can recover the new CayenneDataObject
object(s) from the collection associated to the context, like this:
CayenneDataObject dataObjectsCollection = (CayenneDataObject)cayenneContext.newObjects();
then access the ObjectId
for each one in the collection, like:
ObjectId objectId = dataObject.getObjectId();
Finally you can iterate under the values, where usually the generated-id is going to be the first one of the values (for a single column key) in the Map returned by getIdSnapshot()
, it contains also the column name(s) associated to the PK as key(s):
objectId.getIdSnapshot().values()
How to fix C++ error: expected unqualified-id
Get rid of the semicolon after WordGame
.
You really should have discovered this problem when the class was a lot smaller. When you're writing code, you should be compiling about every time you add half a dozen lines.
How to parse a string into a nullable int
I felt I should share mine which is a bit more generic.
Usage:
var result = "123".ParseBy(int.Parse);
var result2 = "123".ParseBy<int>(int.TryParse);
Solution:
public static class NullableParse
{
public static Nullable<T> ParseBy<T>(this string input, Func<string, T> parser)
where T : struct
{
try
{
return parser(input);
}
catch (Exception exc)
{
return null;
}
}
public delegate bool TryParseDelegate<T>(string input, out T result);
public static Nullable<T> ParseBy<T>(this string input, TryParseDelegate<T> parser)
where T : struct
{
T t;
if (parser(input, out t)) return t;
return null;
}
}
First version is a slower since it requires a try-catch but it looks cleaner. If it won't be called many times with invalid strings, it is not that important.
If performance is an issue, please note that when using TryParse methods, you need to specify the type parameter of ParseBy as it can not be inferred by the compiler. I also had to define a delegate as out keyword can not be used within Func<>, but at least this time compiler does not require an explicit instance.
Finally, you can use it with other structs as well, i.e. decimal, DateTime, Guid, etc.
What Does 'zoom' do in CSS?
Zoom is not included in the CSS specification, but it is supported in IE, Safari 4, Chrome (and you can get a somewhat similar effect in Firefox with -moz-transform: scale(x)
since 3.5). See here.
So, all browsers
zoom: 2;
zoom: 200%;
will zoom your object in by 2, so it's like doubling the size. Which means if you have
a:hover {
zoom: 2;
}
On hover, the <a>
tag will zoom by 200%.
Like I say, in FireFox 3.5+ use -moz-transform: scale(x)
, it does much the same thing.
Edit: In response to the comment from thirtydot
, I will say that scale()
is not a complete replacement. It does not expand in line like zoom
does, rather it will expand out of the box and over content, not forcing other content out of the way. See this in action here. Furthermore, it seems that zoom
is not supported in Opera.
This post gives a useful insight into ways to work around incompatibilities with scale
and workarounds for it using jQuery.
Portable way to check if directory exists [Windows/Linux, C]
stat() works on Linux., UNIX and Windows as well:
#include <sys/types.h>
#include <sys/stat.h>
struct stat info;
if( stat( pathname, &info ) != 0 )
printf( "cannot access %s\n", pathname );
else if( info.st_mode & S_IFDIR ) // S_ISDIR() doesn't exist on my windows
printf( "%s is a directory\n", pathname );
else
printf( "%s is no directory\n", pathname );
SQL Server loop - how do I loop through a set of records
I think this is the easy way example to iterate item.
declare @cateid int
select CateID into [#TempTable] from Category where GroupID = 'STOCKLIST'
while (select count(*) from #TempTable) > 0
begin
select top 1 @cateid = CateID from #TempTable
print(@cateid)
--DO SOMETHING HERE
delete #TempTable where CateID = @cateid
end
drop table #TempTable
Why use $_SERVER['PHP_SELF'] instead of ""
Using an empty string is perfectly fine and actually much safer than simply using $_SERVER['PHP_SELF']
.
When using $_SERVER['PHP_SELF']
it is very easy to inject malicious data by simply appending /<script>...
after the whatever.php
part of the URL so you should not use this method and stop using any PHP tutorial that suggests it.
Post order traversal of binary tree without recursion
Here's a sample from wikipedia:
nonRecursivePostorder(rootNode)
nodeStack.push(rootNode)
while (! nodeStack.empty())
currNode = nodeStack.peek()
if ((currNode.left != null) and (currNode.left.visited == false))
nodeStack.push(currNode.left)
else
if ((currNode.right != null) and (currNode.right.visited == false))
nodeStack.push(currNode.right)
else
print currNode.value
currNode.visited := true
nodeStack.pop()
How can I render repeating React elements?
In the spirit of functional programming, let's make our components a bit easier to work with by using abstractions.
// converts components into mappable functions
var mappable = function(component){
return function(x, i){
return component({key: i}, x);
}
}
// maps on 2-dimensional arrays
var map2d = function(m1, m2, xss){
return xss.map(function(xs, i, arr){
return m1(xs.map(m2), i, arr);
});
}
var td = mappable(React.DOM.td);
var tr = mappable(React.DOM.tr);
var th = mappable(React.DOM.th);
Now we can define our render like this:
render: function(){
return (
<table>
<thead>{this.props.titles.map(th)}</thead>
<tbody>{map2d(tr, td, this.props.rows)}</tbody>
</table>
);
}
An alternative to our map2d would be a curried map function, but people tend to shy away from currying.
Save ArrayList to SharedPreferences
Why don't you stick your arraylist on an Application class? It only get's destroyed when the app is really killed, so, it will stick around for as long as the app is available.
Multiple try codes in one block
You could try a for loop
for func,args,kwargs in zip([a,b,c,d],
[args_a,args_b,args_c,args_d],
[kw_a,kw_b,kw_c,kw_d]):
try:
func(*args, **kwargs)
break
except:
pass
This way you can loop as many functions as you want without making the code look ugly
What is the difference between the kernel space and the user space?
Kernel Space and User Space are logical spaces.
Most of the modern processors are designed to run in different privileged mode. x86 machines can run in 4 different privileged modes.
And a particular machine instruction can be executed when in/above particular privileged mode.
Because of this design you are giving a system protection or sand-boxing the execution environment.
Kernel is a piece of code, which manages your hardware and provide system abstraction. So it needs to have access for all the machine instruction. And it is most trusted piece of software. So i should be executed with the highest privilege. And Ring level 0 is the most privileged mode. So Ring Level 0 is also called as Kernel Mode.
User Application are piece of software which comes from any third party vendor, and you can't completely trust them. Someone with malicious intent can write a code to crash your system if he had complete access to all the machine instruction. So application should be provided with access to limited set of instructions. And Ring Level 3 is the least privileged mode. So all your application run in that mode. Hence that Ring Level 3 is also called User Mode.
Note: I am not getting Ring Levels 1 and 2. They are basically modes with intermediate privilege. So may be device driver code are executed with this privilege. AFAIK, linux uses only Ring Level 0 and 3 for kernel code execution and user application respectively.
So any operation happening in kernel mode can be considered as kernel space.
And any operation happening in user mode can be considered as user space.
CREATE TABLE LIKE A1 as A2
Your attempt wasn't that bad. You have to do it with LIKE
, yes.
In the manual it says:
Use LIKE to create an empty table based on the definition of another
table, including any column attributes and indexes defined in the
original table.
So you do:
CREATE TABLE New_Users LIKE Old_Users;
Then you insert with
INSERT INTO New_Users SELECT * FROM Old_Users GROUP BY ID;
But you can not do it in one statement.
Why am I getting "Thread was being aborted" in ASP.NET?
For a web service hosted in ASP.NET, the configuration property is executionTimeout:
<configuration> <system.web>
<httpRuntime executionTimeout="360" />
</system.web>
</configuration>
Set this and the thread abort exception will go away :)
WCF Service , how to increase the timeout?
The best way is to change any setting you want in your code.
Check out the below example:
using(WCFServiceClient client = new WCFServiceClient ())
{
client.Endpoint.Binding.SendTimeout = new TimeSpan(0, 1, 30);
}
RegEx - Match Numbers of Variable Length
You can specify how many times you want the previous item to match by using {min,max}
.
{[0-9]{1,3}:[0-9]{1,3}}
Also, you can use \d
for digits instead of [0-9]
for most regex flavors:
{\d{1,3}:\d{1,3}}
You may also want to consider escaping the outer {
and }
, just to make it clear that they are not part of a repetition definition.
PHP add elements to multidimensional array with array_push
if you want to add the data in the increment order inside your associative array you can do this:
$newdata = array (
'wpseo_title' => 'test',
'wpseo_desc' => 'test',
'wpseo_metakey' => 'test'
);
// for recipe
$md_array["recipe_type"][] = $newdata;
//for cuisine
$md_array["cuisine"][] = $newdata;
this will get added to the recipe or cuisine depending on what was the last index.
Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this
array_push($md_array["cuisine"],$newdata);
How to place div side by side
If you're not tagetting IE6, then float the second <div>
and give it a margin equal to (or maybe a little bigger than) the first <div>
's fixed width.
HTML:
<div id="main-wrapper">
<div id="fixed-width"> lorem ipsum </div>
<div id="rest-of-space"> dolor sit amet </div>
</div>
CSS:
#main-wrapper {
100%;
background:red;
}
#fixed-width {
width:100px;
float:left
}
#rest-of-space {
margin-left:101px;
/* May have to increase depending on borders and margin of the fixd width div*/
background:blue;
}
The margin accounts for the possibility that the 'rest-of-space' <div>
may contain more content than the 'fixed-width' <div>
.
Don't give the fixed width one a background; if you need to visibly see these as different 'columns' then use the Faux Columns trick.
How do I remove background-image in css?
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #fff), color-stop(0.5, #fff));
background-image: -webkit-linear-gradient(center top, #fff 0%, #fff 50%);
background-image: -moz-linear-gradient(center top, #fff 0%, #fff 50%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#ffffff', GradientType=0);
background-image: linear-gradient(to bottom, #fff 0%, #fff 50%);
for older browsers.. if you have defined css in some framewokrk.css like select2.css in IE9 background-image: -webkit-gradient etc. and you want it via another .css rewrite with "background-image: none !important" not works. I used same color to color gradient like page background color.
Send FormData with other field in AngularJS
Here is the complete solution
html code,
create the text anf file upload fields as shown below
<div class="form-group">
<div>
<label for="usr">User Name:</label>
<input type="text" id="usr" ng-model="model.username">
</div>
<div>
<label for="pwd">Password:</label>
<input type="password" id="pwd" ng-model="model.password">
</div><hr>
<div>
<div class="col-lg-6">
<input type="file" file-model="model.somefile"/>
</div>
</div>
<div>
<label for="dob">Dob:</label>
<input type="date" id="dob" ng-model="model.dob">
</div>
<div>
<label for="email">Email:</label>
<input type="email"id="email" ng-model="model.email">
</div>
<button type="submit" ng-click="saveData(model)" >Submit</button>
directive code
create a filemodel directive to parse file
.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};}]);
Service code
append the file and fields to form data and do $http.post as shown below
remember to keep 'Content-Type': undefined
.service('fileUploadService', ['$http', function ($http) {
this.uploadFileToUrl = function(file, username, password, dob, email, uploadUrl){
var myFormData = new FormData();
myFormData.append('file', file);
myFormData.append('username', username);
myFormData.append('password', password);
myFormData.append('dob', dob);
myFormData.append('email', email);
$http.post(uploadUrl, myFormData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
In controller
Now in controller call the service by sending required data to be appended in parameters,
$scope.saveData = function(model){
var file = model.myFile;
var uploadUrl = "/api/createUsers";
fileUpload.uploadFileToUrl(file, model.username, model.password, model.dob, model.email, uploadUrl);
};
Backbone.js fetch with parameters
changing:
collection.fetch({ data: { page: 1} });
to:
collection.fetch({ data: $.param({ page: 1}) });
So with out over doing it, this is called with your {data: {page:1}}
object as options
Backbone.sync = function(method, model, options) {
var type = methodMap[method];
// Default JSON-request options.
var params = _.extend({
type: type,
dataType: 'json',
processData: false
}, options);
// Ensure that we have a URL.
if (!params.url) {
params.url = getUrl(model) || urlError();
}
// Ensure that we have the appropriate request data.
if (!params.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model.toJSON());
}
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (Backbone.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.processData = true;
params.data = params.data ? {model : params.data} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (Backbone.emulateHTTP) {
if (type === 'PUT' || type === 'DELETE') {
if (Backbone.emulateJSON) params.data._method = type;
params.type = 'POST';
params.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
};
}
}
// Make the request.
return $.ajax(params);
};
So it sends the 'data' to jQuery.ajax which will do its best to append whatever params.data
is to the URL.
Display text from .txt file in batch file
Try this: use Find to iterate through all lines with "Current date/time", and write each line to the same file:
for /f "usebackq delims==" %i in (`find "Current date" log.txt`) do (echo %i > log-time.txt)
type log-time.txt
Set delims= to a character not relevant in the date/time lines. Use %%i in batch files.
Explanation (update):
Find extracts all lines from log.txt containing the search string.
For /f loops through each line the command inside (...
) generates.
As echo > log-time.txt (single > !) overwrites log-time.txt every time it's executed, only the last matching line remains in log-time.txt
Automatic login script for a website on windows machine?
From the term "automatic login" I suppose security (password protection) is not of key importance here.
The guidelines for solution could be to use a JavaScript bookmark (idea borrowed form a nice game published on M&M's DK site).
The idea is to create a javascript file and store it locally. It should do the login data entering depending on current site address. Just an example using jQuery:
// dont forget to include jQuery code
// preferably with .noConflict() in order not to break the site scripts
if (window.location.indexOf("mail.google.com") > -1) {
// Lets login to Gmail
jQuery("#Email").val("[email protected]");
jQuery("#Passwd").val("superSecretPassowrd");
jQuery("#gaia_loginform").submit();
}
Now save this as say login.js
Then create a bookmark (in any browser) with this (as an) url:
javascript:document.write("<script type='text/javascript' src='file:///path/to/login.js'></script>");
Now when you go to Gmail and click this bookmark you will get automatically logged in by your script.
Multiply the code blocks in your script, to add more sites in the similar manner. You could even combine it with window.open(...)
functionality to open more sites, but that may get the script inclusion more complicated.
Note: This only illustrates an idea and needs lots of further work, it's not a complete solution.
console.log not working in Angular2 Component (Typescript)
It's not working because console.log() it's not in a "executable area" of the class "App".
A class is a structure composed by attributes and methods.
The only way to have your code executed is to place it inside a method that is going to be executed. For instance: constructor()
_x000D_
_x000D_
console.log('It works here')_x000D_
_x000D_
@Component({..)_x000D_
export class App {_x000D_
s: string = "Hello2";_x000D_
_x000D_
constructor() {_x000D_
console.log(this.s) _x000D_
} _x000D_
}
_x000D_
_x000D_
_x000D_
Think of class like a plain javascript object.
Would it make sense to expect this to work?
_x000D_
_x000D_
class: {_x000D_
s: string,_x000D_
console.log(s)_x000D_
}
_x000D_
_x000D_
_x000D_
If you still unsure, try the typescript playground where you can see your typescript code generated into plain javascript.
https://www.typescriptlang.org/play/index.html
Is there a command line command for verifying what version of .NET is installed
you can check installed c# compilers and the printed version of the .net:
@echo off
for /r "%SystemRoot%\Microsoft.NET\Framework\" %%# in ("*csc.exe") do (
set "l="
for /f "skip=1 tokens=2 delims=k" %%$ in ('"%%# #"') do (
if not defined l (
echo Installed: %%$
set l=%%$
)
)
)
echo latest installed .NET %l%
the csc.exe
does not have a -version
switch but it prints the .net version in its logo. You can also try with msbuild.exe but .net framework 1.* does not have msbuild.
Converting Swagger specification JSON to HTML documentation
There's a small Java program which generates docs (adoc or md) from a yaml file.
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.ASCIIDOC)
.withSwaggerMarkupLanguage(MarkupLanguage.ASCIIDOC)
.withOutputLanguage(Language.DE)
.build();
Swagger2MarkupConverter builder = Swagger2MarkupConverter.from(yamlFileAsString).withConfig(config).build();
return builder.toFileWithoutExtension(outFile);
Unfortunately it only supports OpenAPI 2.0 but not OpenAPI 3.0.