I had the same problem, but it was because in my buttons layout_width/height I forgot to put dp at the end when editing them. Added dp and problem fixed :/
I was trying to install fancyimpute package for imputation but there was not luck. But when i tried below commands, it got installed: Commands:
conda update conda
conda update anaconda
pip install fancyimpute
(here i was trying to give command conda install fancyimpute which did't work)
According @noraj's answer and @Niels Kristian's comment, the following command should do the job.
gem update --system
bundle install
I wrote this in case someone gets into an issue like mine.
gem install bundler
shows that everythings installs well.
Fetching: bundler-1.16.0.gem (100%)
Successfully installed bundler-1.16.0
Parsing documentation for bundler-1.16.0
Installing ri documentation for bundler-1.16.0
Done installing documentation for bundler after 7 seconds
1 gem installed
When I typed bundle
there was an error:
/Users/nikkov/.rvm/gems/ruby-2.4.0/bin/bundle:23:in `load': cannot load such file -- /Users/nikkov/.rvm/rubies/ruby-2.4.0/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/exe/bundle (LoadError)
from /Users/nikkov/.rvm/gems/ruby-2.4.0/bin/bundle:23:in `<main>'
from /Users/nikkov/.rvm/gems/ruby-2.4.0/bin/ruby_executable_hooks:15:in `eval'
from /Users/nikkov/.rvm/gems/ruby-2.4.0/bin/ruby_executable_hooks:15:in `<main>'
And in the folder /Users/nikkov/.rvm/rubies/ruby-2.4.0/lib/ruby/gems/2.4.0/gems/
there wasn't a bundler-1.16.0
folder.
I fixed this with sudo gem install bundler
ng g c component-name
For specify custom location: ng g c specific-folder/component-name
here component-name
will be created inside specific-folder.
Similarl approach can be used for generating other components like directive
, pipe
, service
, class
, guard
, interface
, enum
, module
, etc.
You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance
before trying to spy on the method.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const instance = app.instance()
const spy = jest.spyOn(instance, 'myClickFunc')
instance.forceUpdate();
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html
cd path/to/project
ssh-keygen
cat ~/.ssh/id_rsa.pub
in terminalGitlab/Settings/SSH-KEYS
This worked for me like a charm!
If using integers as targets, makes sure they aren't symmetrical at 0.
I.e., don't use classes -1, 0, 1. Use instead 0, 1, 2.
The right way to do it:
In .NET Core you can inject the IConfiguration
as a parameter into your Class constructor, and it will be available.
public class MyClass
{
private IConfiguration configuration;
public MyClass(IConfiguration configuration)
{
ConnectionString = new configuration.GetValue<string>("ConnectionString");
}
Now, when you want to create an instance of your class, since your class gets injected the IConfiguration
, you won't be able to just do new MyClass()
, because it needs a IConfiguration
parameter injected into the constructor, so, you will need to inject your class as well to the injecting chain, which means two simple steps:
1) Add your Class/es - where you want to use the IConfiguration
, to the IServiceCollection
at the ConfigureServices()
method in Startup.cs
services.AddTransient<MyClass>();
2) Define an instance - let's say in the Controller
, and inject it using the constructor:
public class MyController : ControllerBase
{
private MyClass _myClass;
public MyController(MyClass myClass)
{
_myClass = myClass;
}
Now you should be able to enjoy your _myClass.configuration
freely...
Another option:
If you are still looking for a way to have it available without having to inject the classes into the controller, then you can store it in a static class
, which you will configure in the Startup.cs
, something like:
public static class MyAppData
{
public static IConfiguration Configuration;
}
And your Startup
constructor should look like this:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
MyAppData.Configuration = configuration;
}
Then use MyAppData.Configuration
anywhere in your program.
Don't confront me why the first option is the right way, I can just see experienced developers always avoid garbage data along their way, and it's well understood that it's not the best practice to have loads of data available in memory all the time, neither is it good for performance and nor for development, and perhaps it's also more secure to only have with you what you need.
Below is a relevant code example for Angular 4/5 with the new HttpClient.
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
public removeItem(item) {
let options = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
body: item,
};
return this._http
.delete('/api/menu-items', options)
.map((response: Response) => response)
.toPromise()
.catch(this.handleError);
}
Export the store from the module you called createStore
with. Then you are assured it will both be created and will not pollute the global window space.
const store = createStore(myReducer);
export store;
or
const store = createStore(myReducer);
export default store;
import {store} from './MyStore'
store.dispatch(...)
or if you used default
import store from './MyStore'
store.dispatch(...)
If you need multiple instances of a store, export a factory function.
I would recommend making it async
(returning a promise
).
async function getUserStore (userId) {
// check if user store exists and return or create it.
}
export getUserStore
On the client (in an async
block)
import {getUserStore} from './store'
const joeStore = await getUserStore('joe')
For me it was not an option to use the graphical components of React Router. I prefer programmatically navigate using React Router.
React Router v5.1.0 with hooks
There is a new useHistory
hook in React Router >5.1.0 if you are using React >16.8.0 and functional components.
import { useHistory } from "react-router-dom";
function HomeButton() {
const history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
I think the main difference I can describe relates to record oriented vs. column oriented formats. Record oriented formats are what we're all used to -- text files, delimited formats like CSV, TSV. AVRO is slightly cooler than those because it can change schema over time, e.g. adding or removing columns from a record. Other tricks of various formats (especially including compression) involve whether a format can be split -- that is, can you read a block of records from anywhere in the dataset and still know it's schema? But here's more detail on columnar formats like Parquet.
Parquet, and other columnar formats handle a common Hadoop situation very efficiently. It is common to have tables (datasets) having many more columns than you would expect in a well-designed relational database -- a hundred or two hundred columns is not unusual. This is so because we often use Hadoop as a place to denormalize data from relational formats -- yes, you get lots of repeated values and many tables all flattened into a single one. But it becomes much easier to query since all the joins are worked out. There are other advantages such as retaining state-in-time data. So anyway it's common to have a boatload of columns in a table.
Let's say there are 132 columns, and some of them are really long text fields, each different column one following the other and use up maybe 10K per record.
While querying these tables is easy with SQL standpoint, it's common that you'll want to get some range of records based on only a few of those hundred-plus columns. For example, you might want all of the records in February and March for customers with sales > $500.
To do this in a row format the query would need to scan every record of the dataset. Read the first row, parse the record into fields (columns) and get the date and sales columns, include it in your result if it satisfies the condition. Repeat. If you have 10 years (120 months) of history, you're reading every single record just to find 2 of those months. Of course this is a great opportunity to use a partition on year and month, but even so, you're reading and parsing 10K of each record/row for those two months just to find whether the customer's sales are > $500.
In a columnar format, each column (field) of a record is stored with others of its kind, spread all over many different blocks on the disk -- columns for year together, columns for month together, columns for customer employee handbook (or other long text), and all the others that make those records so huge all in their own separate place on the disk, and of course columns for sales together. Well heck, date and months are numbers, and so are sales -- they are just a few bytes. Wouldn't it be great if we only had to read a few bytes for each record to determine which records matched our query? Columnar storage to the rescue!
Even without partitions, scanning the small fields needed to satisfy our query is super-fast -- they are all in order by record, and all the same size, so the disk seeks over much less data checking for included records. No need to read through that employee handbook and other long text fields -- just ignore them. So, by grouping columns with each other, instead of rows, you can almost always scan less data. Win!
But wait, it gets better. If your query only needed to know those values and a few more (let's say 10 of the 132 columns) and didn't care about that employee handbook column, once it had picked the right records to return, it would now only have to go back to the 10 columns it needed to render the results, ignoring the other 122 of the 132 in our dataset. Again, we skip a lot of reading.
(Note: for this reason, columnar formats are a lousy choice when doing straight transformations, for example, if you're joining all of two tables into one big(ger) result set that you're saving as a new table, the sources are going to get scanned completely anyway, so there's not a lot of benefit in read performance, and because columnar formats need to remember more about the where stuff is, they use more memory than a similar row format).
One more benefit of columnar: data is spread around. To get a single record, you can have 132 workers each read (and write) data from/to 132 different places on 132 blocks of data. Yay for parallelization!
And now for the clincher: compression algorithms work much better when it can find repeating patterns. You could compress AABBBBBBCCCCCCCCCCCCCCCC
as 2A6B16C
but ABCABCBCBCBCCCCCCCCCCCCCC
wouldn't get as small (well, actually, in this case it would, but trust me :-) ). So once again, less reading. And writing too.
So we read a lot less data to answer common queries, it's potentially faster to read and write in parallel, and compression tends to work much better.
Columnar is great when your input side is large, and your output is a filtered subset: from big to little is great. Not as beneficial when the input and outputs are about the same.
But in our case, Impala took our old Hive queries that ran in 5, 10, 20 or 30 minutes, and finished most in a few seconds or a minute.
Hope this helps answer at least part of your question!
Well this is not a right answer but can be consider as a quick workaround. Right answer is turn off Strict SSL.
I am having the same error
PhantomJS not found on PATH
Downloading https://github.com/Medium/phantomjs/releases/download/v2.1.1/phantomjs-2.1.1-windows.zip
Saving to C:\Users\Sam\AppData\Local\Temp\phantomjs\phantomjs-2.1.1-windows.zip
Receiving...
Error making request.
Error: unable to get local issuer certificate
at TLSSocket. (_tls_wrap.js:1105:38)
at emitNone (events.js:106:13)
at TLSSocket.emit (events.js:208:7)
at TLSSocket._finishInit (_tls_wrap.js:639:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:469:38)
So the after reading the error.
Just downloaded the file manually and placed it on the required path. i.e
C:\Users\Sam\AppData\Local\Temp\phantomjs\
This solved my problem.
PhantomJS not found on PATH
Download already available at C:\Users\sam\AppData\Local\Temp\phantomjs\phantomjs-2.1.1-windows.zip
Verified checksum of previously downloaded file
Extracting zip contents
OP here (I am answering this question after two years, the post made by Daniel Cerecedo was not bad at a time, but the web services are developing very fast)
After three years of full-time software development (with focus also on software architecture, project management and microservice architecture) I definitely choose the second way (but with one general endpoint) as the best one.
If you have a special endpoint for images, it gives you much more power over handling those images.
We have the same REST API (Node.js) for both - mobile apps (iOS/android) and frontend (using React). This is 2017, therefore you don't want to store images locally, you want to upload them to some cloud storage (Google cloud, s3, cloudinary, ...), therefore you want some general handling over them.
Our typical flow is, that as soon as you select an image, it starts uploading on background (usually POST on /images endpoint), returning you the ID after uploading. This is really user-friendly, because user choose an image and then typically proceed with some other fields (i.e. address, name, ...), therefore when he hits "send" button, the image is usually already uploaded. He does not wait and watching the screen saying "uploading...".
The same goes for getting images. Especially thanks to mobile phones and limited mobile data, you don't want to send original images, you want to send resized images, so they do not take that much bandwidth (and to make your mobile apps faster, you often don't want to resize it at all, you want the image that fits perfectly into your view). For this reason, good apps are using something like cloudinary (or we do have our own image server for resizing).
Also, if the data are not private, then you send back to app/frontend just URL and it downloads it from cloud storage directly, which is huge saving of bandwidth and processing time for your server. In our bigger apps there are a lot of terabytes downloaded every month, you don't want to handle that directly on each of your REST API server, which is focused on CRUD operation. You want to handle that at one place (our Imageserver, which have caching etc.) or let cloud services handle all of it.
Cons : The only "cons" which you should think of is "not assigned images". User select images and continue with filling other fields, but then he says "nah" and turn off the app or tab, but meanwhile you successfully uploaded the image. This means you have uploaded an image which is not assigned anywhere.
There are several ways of handling this. The most easiest one is "I don't care", which is a relevant one, if this is not happening very often or you even have desire to store every image user send you (for any reason) and you don't want any deletion.
Another one is easy too - you have CRON and i.e. every week and you delete all unassigned images older than one week.
Another application that can be using the resources is apparently Android Studio's Kotlin REPL. I closed that, and then I could build again no problem.
In react-router v2.4.0
or above and before v4
there are several options
<Route
path="/home"
onEnter={ auth }
onLeave={ showConfirm }
component={ Home }
>
You can prevent a transition from happening or prompt the user before leaving a route with a leave hook.
const Home = withRouter(
React.createClass({
componentDidMount() {
this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave)
},
routerWillLeave(nextLocation) {
// return false to prevent a transition w/o prompting the user,
// or return a string to allow the user to decide:
// return `null` or nothing to let other hooks to be executed
//
// NOTE: if you return true, other hooks will not be executed!
if (!this.state.isSaved)
return 'Your work is not saved! Are you sure you want to leave?'
},
// ...
})
)
Note that this example makes use of the withRouter
higher-order component introduced in v2.4.0.
However these solution doesn't quite work perfectly when changing the route in URL manually
In the sense that
For react-router v4
using Prompt or custom history:
However in react-router v4
, its rather easier to implement with the help of Prompt
from'react-router
According to the documentation
Prompt
Used to prompt the user before navigating away from a page. When your application enters a state that should prevent the user from navigating away (like a form is half-filled out), render a
<Prompt>
.import { Prompt } from 'react-router' <Prompt when={formIsHalfFilledOut} message="Are you sure you want to leave?" />
message: string
The message to prompt the user with when they try to navigate away.
<Prompt message="Are you sure you want to leave?"/>
message: func
Will be called with the next location and action the user is attempting to navigate to. Return a string to show a prompt to the user or true to allow the transition.
<Prompt message={location => ( `Are you sure you want to go to ${location.pathname}?` )}/>
when: bool
Instead of conditionally rendering a
<Prompt>
behind a guard, you can always render it but passwhen={true}
orwhen={false}
to prevent or allow navigation accordingly.
In your render method you simply need to add this as mentioned in the documentation according to your need.
UPDATE:
In case you would want to have a custom action to take when user is leaving page, you can make use of custom history and configure your Router like
history.js
import createBrowserHistory from 'history/createBrowserHistory'
export const history = createBrowserHistory()
...
import { history } from 'path/to/history';
<Router history={history}>
<App/>
</Router>
and then in your component you can make use of history.block
like
import { history } from 'path/to/history';
class MyComponent extends React.Component {
componentDidMount() {
this.unblock = history.block(targetLocation => {
// take your action here
return false;
});
}
componentWillUnmount() {
this.unblock();
}
render() {
//component render here
}
}
If you have a strict content security policy that doesn't allow @vladimir-salguero's answer, you can use this (please make note of the script nonce
):
<script nonce="(your nonce)" async>
$(document).ready(function() {
$('link[media="none"]').each(function(a, t) {
var n = $(this).attr("data-async"),
i = $(this);
void 0 !== n && !1 !== n && ("true" == n || n) && i.attr("media", "all")
})
});
</script>
Just add the following to your stylesheet reference: media="none" data-async="true"
. Here's an example:
<link rel="stylesheet" href="../path/script.js" media="none" data-async="true" />
Example for jQuery:
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" type="text/css" media="none" data-async="true" crossorigin="anonymous" /><noscript><link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" type="text/css" /></noscript>
In 2020 Page Speed Insights user agents are: "Chrome-Lighthouse" for mobile and "Google Page Speed Insights" for desktop.
<?php if (!isset($_SERVER['HTTP_USER_AGENT']) || stripos($_SERVER['HTTP_USER_AGENT'], 'Chrome-Lighthouse') === false || stripos($_SERVER['HTTP_USER_AGENT'], 'Google Page Speed Insights') === false): ?>
// your google analytics code and other external script you want to hide from PageSpeed Insights here
<?php endif; ?>
This can occur on android too not just computers. Was browsing using Kiwi when the site I was on began to endlessly redirect so I cut net access to close it out and noticed my phone had DL'd something f.txt
in my downloaded files.
Deleted it and didn't open.
I had this problem and all I had to do is return true
from touchend and the warning went away.
Go to IDE:
STEP 1: Open the menu item: click on Help then click on Edit Custom Properties
STEP 2: Set the parameter:
idea.max.intellisense.filesize= 999999999
Here is the Python
/ numpy
implementation of the smoothed z-score algorithm (see answer above). You can find the gist here.
#!/usr/bin/env python
# Implementation of algorithm from https://stackoverflow.com/a/22640362/6029703
import numpy as np
import pylab
def thresholding_algo(y, lag, threshold, influence):
signals = np.zeros(len(y))
filteredY = np.array(y)
avgFilter = [0]*len(y)
stdFilter = [0]*len(y)
avgFilter[lag - 1] = np.mean(y[0:lag])
stdFilter[lag - 1] = np.std(y[0:lag])
for i in range(lag, len(y)):
if abs(y[i] - avgFilter[i-1]) > threshold * stdFilter [i-1]:
if y[i] > avgFilter[i-1]:
signals[i] = 1
else:
signals[i] = -1
filteredY[i] = influence * y[i] + (1 - influence) * filteredY[i-1]
avgFilter[i] = np.mean(filteredY[(i-lag+1):i+1])
stdFilter[i] = np.std(filteredY[(i-lag+1):i+1])
else:
signals[i] = 0
filteredY[i] = y[i]
avgFilter[i] = np.mean(filteredY[(i-lag+1):i+1])
stdFilter[i] = np.std(filteredY[(i-lag+1):i+1])
return dict(signals = np.asarray(signals),
avgFilter = np.asarray(avgFilter),
stdFilter = np.asarray(stdFilter))
Below is the test on the same dataset that yields the same plot as in the original answer for R
/Matlab
# Data
y = np.array([1,1,1.1,1,0.9,1,1,1.1,1,0.9,1,1.1,1,1,0.9,1,1,1.1,1,1,1,1,1.1,0.9,1,1.1,1,1,0.9,
1,1.1,1,1,1.1,1,0.8,0.9,1,1.2,0.9,1,1,1.1,1.2,1,1.5,1,3,2,5,3,2,1,1,1,0.9,1,1,3,
2.6,4,3,3.2,2,1,1,0.8,4,4,2,2.5,1,1,1])
# Settings: lag = 30, threshold = 5, influence = 0
lag = 30
threshold = 5
influence = 0
# Run algo with settings from above
result = thresholding_algo(y, lag=lag, threshold=threshold, influence=influence)
# Plot result
pylab.subplot(211)
pylab.plot(np.arange(1, len(y)+1), y)
pylab.plot(np.arange(1, len(y)+1),
result["avgFilter"], color="cyan", lw=2)
pylab.plot(np.arange(1, len(y)+1),
result["avgFilter"] + threshold * result["stdFilter"], color="green", lw=2)
pylab.plot(np.arange(1, len(y)+1),
result["avgFilter"] - threshold * result["stdFilter"], color="green", lw=2)
pylab.subplot(212)
pylab.step(np.arange(1, len(y)+1), result["signals"], color="red", lw=2)
pylab.ylim(-1.5, 1.5)
pylab.show()
If your server have a http service you can compress your directory and download the compressed file.
Compress:
tar -zcvf archive-name.tar.gz -C directory-name .
Download throught your browser:
If you don't have direct access to the server ip, do a ssh tunnel throught putty, and forward the 80 port in some local port, and you can download the file.
If [remote-path]
and [local-path]
are the same, you can do
$ git fetch origin master
$ git diff origin/master -- [local-path]
Note 1: The second command above will compare against the locally stored remote tracking branch. The fetch command is required to update the remote tracking branch to be in sync with the contents of the remote server. Alternatively, you can just do
$ git diff master:<path-or-file-name>
Note 2: master
can be replaced in the above examples with any branch name
Check again. Use debugger if must. My guess is that for some item in userResponseDetails this query finds no elements:
.Where(y => y.ResponseId.Equals(item.ResponseId))
so you can't call
.First()
on it. Maybe try
.FirstOrDefault()
if it solves the issue.
Do NOT return NULL value! This is purely so that you can see and diagnose where problem is. Handle these cases properly.
I was getting a similar issue from the Apache Lounge 32 bit version. After downloading the 64 bit version, the issue was resolved.
Here is an excellent video explain the steps involved: https://www.youtube.com/watch?v=17qhikHv5hY
This was for my own project and I'm sharing it here too.
This one had trouble after 3.2, so the one below may work better for you:
CSS
/* adjust body when menu is open */
body.slide-active {
overflow-x: hidden
}
/*first child of #page-content so it doesn't shift around*/
.no-margin-top {
margin-top: 0px!important
}
/*wrap the entire page content but not nav inside this div if not a fixed top, don't add any top padding */
#page-content {
position: relative;
padding-top: 70px;
left: 0;
}
#page-content.slide-active {
padding-top: 0
}
/* put toggle bars on the left :: not using button */
#slide-nav .navbar-toggle {
cursor: pointer;
position: relative;
line-height: 0;
float: left;
margin: 0;
width: 30px;
height: 40px;
padding: 10px 0 0 0;
border: 0;
background: transparent;
}
/* icon bar prettyup - optional */
#slide-nav .navbar-toggle > .icon-bar {
width: 100%;
display: block;
height: 3px;
margin: 5px 0 0 0;
}
#slide-nav .navbar-toggle.slide-active .icon-bar {
background: orange
}
.navbar-header {
position: relative
}
/* un fix the navbar when active so that all the menu items are accessible */
.navbar.navbar-fixed-top.slide-active {
position: relative
}
/* screw writing importants and shit, just stick it in max width since these classes are not shared between sizes */
@media (max-width:767px) {
#slide-nav .container {
margin: 0;
padding: 0!important;
}
#slide-nav .navbar-header {
margin: 0 auto;
padding: 0 15px;
}
#slide-nav .navbar.slide-active {
position: absolute;
width: 80%;
top: -1px;
z-index: 1000;
}
#slide-nav #slidemenu {
background: #f7f7f7;
left: -100%;
width: 80%;
min-width: 0;
position: absolute;
padding-left: 0;
z-index: 2;
top: -8px;
margin: 0;
}
#slide-nav #slidemenu .navbar-nav {
min-width: 0;
width: 100%;
margin: 0;
}
#slide-nav #slidemenu .navbar-nav .dropdown-menu li a {
min-width: 0;
width: 80%;
white-space: normal;
}
#slide-nav {
border-top: 0
}
#slide-nav.navbar-inverse #slidemenu {
background: #333
}
/* this is behind the navigation but the navigation is not inside it so that the navigation is accessible and scrolls*/
#slide-nav #navbar-height-col {
position: fixed;
top: 0;
height: 100%;
width: 80%;
left: -80%;
background: #eee;
}
#slide-nav.navbar-inverse #navbar-height-col {
background: #333;
z-index: 1;
border: 0;
}
#slide-nav .navbar-form {
width: 100%;
margin: 8px 0;
text-align: center;
overflow: hidden;
/*fast clearfixer*/
}
#slide-nav .navbar-form .form-control {
text-align: center
}
#slide-nav .navbar-form .btn {
width: 100%
}
}
@media (min-width:768px) {
#page-content {
left: 0!important
}
.navbar.navbar-fixed-top.slide-active {
position: fixed
}
.navbar-header {
left: 0!important
}
}
HTML
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation" id="slide-nav">
<div class="container">
<div class="navbar-header">
<a class="navbar-toggle">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="slidemenu">
<form class="navbar-form navbar-right" role="form">
<div class="form-group">
<input type="search" placeholder="search" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Search</button>
</form>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
<li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li class="dropdown-header">Nav header</li>
<li><a href="#">Separated link test long title goes here</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
jQuery
$(document).ready(function () {
//stick in the fixed 100% height behind the navbar but don't wrap it
$('#slide-nav.navbar .container').append($('<div id="navbar-height-col"></div>'));
// Enter your ids or classes
var toggler = '.navbar-toggle';
var pagewrapper = '#page-content';
var navigationwrapper = '.navbar-header';
var menuwidth = '100%'; // the menu inside the slide menu itself
var slidewidth = '80%';
var menuneg = '-100%';
var slideneg = '-80%';
$("#slide-nav").on("click", toggler, function (e) {
var selected = $(this).hasClass('slide-active');
$('#slidemenu').stop().animate({
left: selected ? menuneg : '0px'
});
$('#navbar-height-col').stop().animate({
left: selected ? slideneg : '0px'
});
$(pagewrapper).stop().animate({
left: selected ? '0px' : slidewidth
});
$(navigationwrapper).stop().animate({
left: selected ? '0px' : slidewidth
});
$(this).toggleClass('slide-active', !selected);
$('#slidemenu').toggleClass('slide-active');
$('#page-content, .navbar, body, .navbar-header').toggleClass('slide-active');
});
var selected = '#slidemenu, #page-content, body, .navbar, .navbar-header';
$(window).on("resize", function () {
if ($(window).width() > 767 && $('.navbar-toggle').is(':hidden')) {
$(selected).removeClass('slide-active');
}
});
});
You can filter the results based on formatted date using mysql (See here for Mysql/Mariadb help) and use something like this in laravel-5.4:
Model::selectRaw("COUNT(*) views, DATE_FORMAT(created_at, '%Y %m %e') date")
->groupBy('date')
->get();
I tried above answers and it didn't work in my project. My project was with maven
and openjfx
in Windows.
This solved the problem :
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("/main.fxml"));
root = fxmlLoader.load()
I spent a lot of time trying to figure this one out. Finally, I tried shutting down my development server and booting it up again. Frustratingly, this worked for me.
I came to the conclusion, that after editing the .env
file in Laravel 5, you have to exit the server, and run php artisan serve
again.
SELECT * INTO #TempTable
FROM SampleTable
WHERE...
SELECT * FROM #TempTable
DROP TABLE #TempTable
How about:
Supplier<Stream<Integer>> randomIntsStreamSupplier =
() -> (new Random()).ints(0, 2).boxed();
Stream<Integer> tails =
randomIntsStreamSupplier.get().filter(x->x.equals(0));
Stream<Integer> heads =
randomIntsStreamSupplier.get().filter(x->x.equals(1));
Bootstrap sets the height of the navbar automatically to 50px. The padding above and below links is set to 15px. I think that bootstrap is adding padding to your logo.
You can either remove some of the padding above and below your logo or you can add more padding above and below links.
Adding more padding should look something like this:
nav.navbar-inverse>li>a {
padding-top: 25px;
padding-bottom: 25px;
}
It would be the 32 bit version of eclipse , for instance if you are running the 32 bit version of eclipse in 64 bit JVM, this error will be the result.
To confirm this check for log in your configuration folder of the eclipse. Log will be as following java.lang.UnsatisfiedLinkError: Cannot load 32-bit SWT libraries on 64-bit JVM ...
try installing the either 64 bit eclipse or run in 32 bit jvm
In case someone being a beginner who tried all of the above and still didn't manage to get the project to work. Check your namespace. In an instance where you copy code from one project to another and you forget to change the namespace of the project then it will also give you this error.
Hope it helps someone.
Very old question, but I tried everything suggested above and still could not get it resolved.
Turns out that, I had after insert/update trigger for the main table which tracked the changes by inserting the record in history table having similar structure. I increased the size in the main table column but forgot to change the size of history table column and that created the problem.
I did similar changes in the other table and error is gone.
The 2019 optimal solution for this is HTTP/2 Server Push.
You do not need any hacky javascript solutions or inline styles. However, you do need a server that supports HTTP 2.0 (any modern server version will), which itself requires your server to run SSL. However, with Let's Encrypt there's no reason not to be using SSL anyway.
My site https://r.je/ has a 100/100 score for both mobile and desktop.
The reason for these errors is that the browser gets the HTML, then has to wait for the CSS to be downloaded before the page can be rendered. Using HTTP2 you can send both the HTML and the CSS at the same time.
You can use HTTP/2 push by setting the Link header.
Apache example (.htaccess):
Header add Link "</style.css>; as=style; rel=preload, </font.css>; as=style; rel=preload"
For NGINX you can add the header to your location tag in the server configuration:
location = / {
add_header Link "</style.css>; as=style; rel=preload, </font.css>; as=style; rel=preload";
}
With this header set, the browser receives the HTML and CSS at the same time which stops the CSS from blocking rendering.
You will want to tweak it so that the CSS is only sent on the first request, but the Link header is the most complete and least hacky solution to "Eliminate Render Blocking Javascript and CSS"
For a detailed discussion, take a look at my post here: Eliminate Render Blocking CSS using HTTP/2 Push
As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.
( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -
Replace backup.ab with the path to your file.
For those that could be facing the same problem and the solutions suggested above aren't working, for example in my case, I had installed mongodb-community, so you might wanna run the command below to restart your mongo server.
For those that installed mongodb-community using brew
brew services start mongodb-community
Using break
, just as practically any other language feature, can be a bad practice, within a specific context, where you are clearly misusing it. But some very important idioms cannot be coded without it, or at least would result in far less readable code. In those cases, break
is the way to go.
In other words, don't listen to any blanket, unqualified advice—about break
or anything else. It is not once that I've seen code totally emaciated just to literally enforce a "good practice".
Regarding your concern about performance overhead, there is absolutely none. At the bytecode level there are no explicit loop constructs anyway: all flow control is implemented in terms of conditional jumps.
This error comes for me in windows application while calling server dll from client. After system restart it works fine
The short version is: The efficient way to use readlines()
is to not use it. Ever.
I read some doc notes on
readlines()
, where people has claimed that thisreadlines()
reads whole file content into memory and hence generally consumes more memory compared to readline() or read().
The documentation for readlines()
explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list
full of str
ings out of those lines.
But the documentation for read()
likewise guarantees that it reads the whole file into memory, and builds a str
ing, so that doesn't help.
On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.
You can work around this in three ways:
readlines(sizehint)
, read(size)
, or readline()
.mmap
the file, which allows you to treat it as a giant string without first reading it in.For example, this has to read all of foo
at once:
with open('foo') as f:
lines = f.readlines()
for line in lines:
pass
But this only reads about 8K at a time:
with open('foo') as f:
while True:
lines = f.readlines(8192)
if not lines:
break
for line in lines:
pass
And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.
with open('foo') as f:
while True:
line = f.readline()
if not line:
break
pass
And this will do the exact same thing as the previous:
with open('foo') as f:
for line in f:
pass
Meanwhile:
but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?
Python doesn't make any such guarantees about garbage collection.
The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content
gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.
However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.
On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.
Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of malloc
s to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).
Putting it all together, here's how I'd write your program:
for filename in os.listdir(input_dir):
with open(filename, 'rb') as f:
if filename.endswith(".gz"):
f = gzip.open(fileobj=f)
words = (line.split(delimiter) for line in f)
... my logic ...
Or, maybe:
for filename in os.listdir(input_dir):
if filename.endswith(".gz"):
f = gzip.open(filename, 'rb')
else:
f = open(filename, 'rb')
with contextlib.closing(f):
words = (line.split(delimiter) for line in f)
... my logic ...
I wrote an add-on to overcome this issue in Firefox (Chrome, Opera version will have soon). It works with the latest Firefox version, with beautiful UI and support JS regex: https://addons.mozilla.org/en-US/firefox/addon/cross-domain-cors
In the START menu type "regedit" to open the Registry editor
Go to "HKEY_LOCAL_MACHINE" on the left-hand side registry explorer/tree menu
Click "SOFTWARE" within the "HKEY_LOCAL_MACHINE" registries
Click "JavaSoft" within the "SOFTWARE" registries
Click "Java Runtime Environment" within the "JavaSoft" list of registries here you can see different versions of installed java
Click "Java Runtime Environment"- On right hand side you will get 4-5 rows . Please select "CurrentVersion" and right Click( select modify option) Change version to "1.7"
Now the magic has been completed
Currently, there is no cross browser, script-free way of styling a native date picker.
As for what's going on inside WHATWG/W3C... If this functionality does emerge, it will likely be under the CSS-UI standard or some Shadow DOM-related standard. The CSS4-UI wiki page lists a few appearance-related things that were dropped from CSS3-UI, but to be honest, there doesn't seem to be a great deal of interest in the CSS-UI module.
I think your best bet for cross browser development right now, is to implement pretty controls with JavaScript based interface, and then disable the HTML5 native UI and replace it. I think in the future, maybe there will be better native control styling, but perhaps more likely will be the ability to swap out a native control for your own Shadow DOM "widget".
It is annoying that this isn't available, and petitioning for standard support is always worthwhile. Though it does seem like jQuery UI's lead has tried and was unsuccessful.
While this is all very discouraging, it's also worth considering the advantages of the HTML5 date picker, and also why custom styles are difficult and perhaps should be avoided. On some platforms, the datepicker looks extremely different and I personally can't think of any generic way of styling the native datepicker.
There is simple answer in the official guide:
What does it not do?
It does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, $window.location.href.
Although I've used Eclipse for years, this "answer" is only conjecture (which I'm going to try tonight). If it gets down-voted out of existence, then obviously I'm wrong.
Oracle relies on CMake to generate a Visual Studio "Solution" for their MySQL Connector C source code. Within the Solution are "Projects" that can be compiled individually or collectively (by the Solution). Each Project has its own makefile, compiling its portion of the Solution with settings that are different than the other Projects.
Similarly, I'm hoping an Eclipse Workspace can hold my related makefile Projects (Eclipse), with a master Project whose dependencies compile the various unique-makefile Projects as pre-requesites to building its "Solution". (My folder structure would be as @Rafael describes).
So I'm hoping a good way to use Workspaces is to emulate Visual Studio's ability to combine dissimilar Projects into a Solution.
Nevermind. I was making this way more complicated than it really needed to be.
This was all that I needed. The rename methods just generate a call to the sp_rename system stored procedure and I guess that took care of everything, including the foreign keys with the new column name.
public override void Up()
{
RenameTable("ReportSections", "ReportPages");
RenameTable("ReportSectionGroups", "ReportSections");
RenameColumn("ReportPages", "Group_Id", "Section_Id");
}
public override void Down()
{
RenameColumn("ReportPages", "Section_Id", "Group_Id");
RenameTable("ReportSections", "ReportSectionGroups");
RenameTable("ReportPages", "ReportSections");
}
The Expires entity-header field gives the date/time after which the response is considered stale.The Cache-control:maxage field gives the age value (in seconds) bigger than which response is consider stale.
Althought above header field give a mechanism to client to decide whether to send request to the server. In some condition, the client send a request to sever and the age value of response is bigger then the maxage value ,dose it means server needs to send the resource to client? Maybe the resource never changed.
In order to resolve this problem, HTTP1.1 gives last-modifided head. The server gives the last modified date of the response to client. When the client need this resource, it will send If-Modified-Since head field to server. If this date is before the modified date of the resouce, the server will sends the resource to client and gives 200 code.Otherwise,it will returns 304 code to client and this means client can use the resource it cached.
You're getting errors 'table liam does not exist' because the table's name is Liam
which is not the same as liam
. MySQL table names are case sensitive.
Why not simply use List#equals
?
assertEquals(argumentComponents, imapPathComponents);
two lists are defined to be equal if they contain the same elements in the same order.
One reason you get this error is that your local postgres database shuts down when you restart your computer. In a new terminal window, simply type:
$psql -h localhost
to restart the server.
Twitter Bootstrap assigns the active
class to the li
element that represents the active tab:
$("ul#sampleTabs li.active")
An alternative is to bind the shown
event of each tab, and save the active tab:
var activeTab = null;
$('a[data-toggle="tab"]').on('shown', function (e) {
activeTab = e.target;
})
The reason why Python3 lacks a function for directly getting a ranged list is because the original Python3 designer was quite novice in Python2. He only considered the use of range()
function in a for loop, thus, the list should never need to be expanded. In fact, very often we do need to use the range()
function to produce a list and pass into a function.
Therefore, in this case, Python3 is less convenient as compared to Python2 because:
xrange()
and range()
; range()
and list(range())
Nonetheless, you can still use list expansion in this way:
[*range(N)]
$user->data
is an array of objects. Each element in the array has a name
and value
property (as well as others).
Try putting the 2nd foreach
inside the 1st.
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
ALLOW-FROM is not supported in Chrome or Safari. See MDN article: https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options
You are already doing the work to make a custom header and send it with the correct data, can you not just exclude the header when you detect it is from a valid partner and add DENY to every other request? I don't see the benefit of AllowFrom when you are already dynamically building the logic up?
Q1) Here are couple things to read or google more :
Main differences between SOAP and RESTful web services in java http://www.ajaxonomy.com/2008/xml/web-services-part-1-soap-vs-rest
It's up to you what do you want to learn first. I'd recommend you take a look at the CXF framework. You can build both rest/soap services.
Q2) Here are couple of good tutorials for soap (I had them bookmarked) :
http://www.benmccann.com/blog/web-services-tutorial-with-apache-cxf/
http://www.mastertheboss.com/web-interfaces/337-apache-cxf-interceptors.html
Best way to learn is not just reading tutorials. But you would first go trough tutorials to get a basic idea so you can see that you're able to produce something(or not) and that would get you motivated.
SO is great way to learn particular technology (or more), people ask lot of wierd questions, and there are ever weirder answers. But overall you'll learn about ways to solve issues on other way. Maybe you didn't know of that way, maybe you couldn't thought of it by yourself.
Subscribe to couple of tags that are interesting to you and be persistent, ask good questions and try to give good answers and I guarantee you that you'll learn this as time passes (if you're persistent that is).
Q3) You will have to answer this one yourself. First by deciding what you're going to build, after all you will need to think of some mini project or something and take it from there.
If you decide to use CXF as your framework for building either REST/SOAP services I'd recommend you look up this book Apache CXF Web Service Development
.
It's fantastic, not hard to read and not too big either (win win).
You can also try this one if u need it in almost all places in the page.
U can configure it in a general way then just use it.
In this way u can also use HTML element and anything u want :)
$(document).ready(function()_x000D_
{_x000D_
var options =_x000D_
{_x000D_
placement: function (context, source)_x000D_
{_x000D_
var position = $(source).position();_x000D_
var content_width = 515; //Can be found from a JS function for more dynamic output_x000D_
var content_height = 110; //Can be found from a JS function for more dynamic output_x000D_
_x000D_
if (position.left > content_width)_x000D_
{_x000D_
return "left";_x000D_
}_x000D_
_x000D_
if (position.left < content_width)_x000D_
{_x000D_
return "right";_x000D_
}_x000D_
_x000D_
if (position.top < content_height)_x000D_
{_x000D_
return "bottom";_x000D_
}_x000D_
_x000D_
return "top";_x000D_
}_x000D_
, trigger: "hover"_x000D_
, animation: "true"_x000D_
, html:"true"_x000D_
};_x000D_
$('[data-toggle="popover"]').popover(options);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div class="container">_x000D_
<h3>Popover Example</h3>_x000D_
<a id="try_ppover" href="#" data-toggle="popover" title="Popover HTML Header" data-content="<div class='jumbotron'>Some HTML content inside the popover</div>">Toggle popover</a>_x000D_
</div>
_x000D_
For setting more options, u can go here.
Even more can be found here.
If u want the popup after click, u can change the JS option to trigger: "click"
like this-
return ..;
}
......
, trigger: "click"
......
};
U also can customize it in HTML ading data-trigger="click"
like this-
<a id="try_ppover" href="#" data-toggle="popover" data-trigger="click" title="Popover Header" data-content="<div class='jumbotron'>Some content inside the popover</div>">Toggle popover</a>
I think it will be more oriented code and more re-usable and more helpful to all :).
try
public void PrintGeneric<T>(T test) where T: ITest
{
Console.WriteLine("Generic : " + test.@var);
}
as @Ash Burlaczenko has said you cant name a variable after a keyword, if you reallllly want this prefix with @ symbol to escape the keyword
Running the following helped resolve the issue:
npm config set strict-ssl false
I cannot comment on whether it will cause any other issues at this point in time.
It sound like you'll need to use an array, where num[1] = "one"
, num[2] = "two"
, and so on. Then you can loop through each like you already are and
num = array(["one","two","three","four","five","six","seven","eight","nine","ten"])
for i in range(10,0,-1):
print num[i], "Bottles of beer on the wall,"
print num[i], "bottles of beer."
print "Take one down and pass it around,"
print num[i-1], "bottles of beer on the wall."
print ""
The Original Question
Why is one loop so much slower than two loops?
Conclusion:
Case 1 is a classic interpolation problem that happens to be an inefficient one. I also think that this was one of the leading reasons why many machine architectures and developers ended up building and designing multi-core systems with the ability to do multi-threaded applications as well as parallel programming.
Looking at it from this kind of an approach without involving how the hardware, OS, and compiler(s) work together to do heap allocations that involve working with RAM, cache, page files, etc.; the mathematics that is at the foundation of these algorithms shows us which of these two is the better solution.
We can use an analogy of a Boss
being a Summation
that will represent a For Loop
that has to travel between workers A
& B
.
We can easily see that Case 2 is at least half as fast if not a little more than Case 1 due to the difference in the distance that is needed to travel and the time taken between the workers. This math lines up almost virtually and perfectly with both the benchmark times as well as the number of differences in assembly instructions.
I will now begin to explain how all of this works below.
Assessing The Problem
The OP's code:
const int n=100000;
for(int j=0;j<n;j++){
a1[j] += b1[j];
c1[j] += d1[j];
}
And
for(int j=0;j<n;j++){
a1[j] += b1[j];
}
for(int j=0;j<n;j++){
c1[j] += d1[j];
}
The Consideration
Considering the OP's original question about the two variants of the for
loops and his amended question towards the behavior of caches along with many of the other excellent answers and useful comments; I'd like to try and do something different here by taking a different approach about this situation and problem.
The Approach
Considering the two loops and all of the discussion about cache and page filing I'd like to take another approach as to looking at this from a different perspective. One that doesn't involve the cache and page files nor the executions to allocate memory, in fact, this approach doesn't even concern the actual hardware or the software at all.
The Perspective
After looking at the code for a while it became quite apparent what the problem is and what is generating it. Let's break this down into an algorithmic problem and look at it from the perspective of using mathematical notations then apply an analogy to the math problems as well as to the algorithms.
What We Do Know
We know is that this loop will run 100,000 times. We also know that a1
, b1
, c1
& d1
are pointers on a 64-bit architecture. Within C++ on a 32-bit machine, all pointers are 4 bytes and on a 64-bit machine, they are 8 bytes in size since pointers are of a fixed length.
We know that we have 32 bytes in which to allocate for in both cases. The only difference is we are allocating 32 bytes or two sets of 2-8 bytes on each iteration wherein the second case we are allocating 16 bytes for each iteration for both of the independent loops.
Both loops still equal 32 bytes in total allocations. With this information let's now go ahead and show the general math, algorithms, and analogy of these concepts.
We do know the number of times that the same set or group of operations that will have to be performed in both cases. We do know the amount of memory that needs to be allocated in both cases. We can assess that the overall workload of the allocations between both cases will be approximately the same.
What We Don't Know
We do not know how long it will take for each case unless if we set a counter and run a benchmark test. However, the benchmarks were already included from the original question and from some of the answers and comments as well; and we can see a significant difference between the two and this is the whole reasoning for this proposal to this problem.
Let's Investigate
It is already apparent that many have already done this by looking at the heap allocations, benchmark tests, looking at RAM, cache, and page files. Looking at specific data points and specific iteration indices were also included and the various conversations about this specific problem have many people starting to question other related things about it. How do we begin to look at this problem by using mathematical algorithms and applying an analogy to it? We start off by making a couple of assertions! Then we build out our algorithm from there.
Our Assertions:
F1()
, F2()
, f(a)
, f(b)
, f(c)
and f(d)
.The Algorithms:
1st Case: - Only one summation but two independent function calls.
Sum n=1 : [1,100000] = F1(), F2();
F1() = { f(a) = f(a) + f(b); }
F2() = { f(c) = f(c) + f(d); }
2nd Case: - Two summations but each has its own function call.
Sum1 n=1 : [1,100000] = F1();
F1() = { f(a) = f(a) + f(b); }
Sum2 n=1 : [1,100000] = F1();
F1() = { f(c) = f(c) + f(d); }
If you noticed F2()
only exists in Sum
from Case1
where F1()
is contained in Sum
from Case1
and in both Sum1
and Sum2
from Case2
. This will be evident later on when we begin to conclude that there is an optimization that is happening within the second algorithm.
The iterations through the first case Sum
calls f(a)
that will add to its self f(b)
then it calls f(c)
that will do the same but add f(d)
to itself for each 100000
iterations. In the second case, we have Sum1
and Sum2
that both act the same as if they were the same function being called twice in a row.
In this case we can treat Sum1
and Sum2
as just plain old Sum
where Sum
in this case looks like this: Sum n=1 : [1,100000] { f(a) = f(a) + f(b); }
and now this looks like an optimization where we can just consider it to be the same function.
Summary with Analogy
With what we have seen in the second case it almost appears as if there is optimization since both for loops have the same exact signature, but this isn't the real issue. The issue isn't the work that is being done by f(a)
, f(b)
, f(c)
, and f(d)
. In both cases and the comparison between the two, it is the difference in the distance that the Summation has to travel in each case that gives you the difference in execution time.
Think of the for
loops as being the summations that does the iterations as being a Boss
that is giving orders to two people A
& B
and that their jobs are to meat C
& D
respectively and to pick up some package from them and return it. In this analogy, the for loops or summation iterations and condition checks themselves don't actually represent the Boss
. What actually represents the Boss
is not from the actual mathematical algorithms directly but from the actual concept of Scope
and Code Block
within a routine or subroutine, method, function, translation unit, etc. The first algorithm has one scope where the second algorithm has two consecutive scopes.
Within the first case on each call slip, the Boss
goes to A
and gives the order and A
goes off to fetch B's
package then the Boss
goes to C
and gives the orders to do the same and receive the package from D
on each iteration.
Within the second case, the Boss
works directly with A
to go and fetch B's
package until all packages are received. Then the Boss
works with C
to do the same for getting all of D's
packages.
Since we are working with an 8-byte pointer and dealing with heap allocation let's consider the following problem. Let's say that the Boss
is 100 feet from A
and that A
is 500 feet from C
. We don't need to worry about how far the Boss
is initially from C
because of the order of executions. In both cases, the Boss
initially travels from A
first then to B
. This analogy isn't to say that this distance is exact; it is just a useful test case scenario to show the workings of the algorithms.
In many cases when doing heap allocations and working with the cache and page files, these distances between address locations may not vary that much or they can vary significantly depending on the nature of the data types and the array sizes.
The Test Cases:
First Case: On first iteration the Boss
has to initially go 100 feet to give the order slip to A
and A
goes off and does his thing, but then the Boss
has to travel 500 feet to C
to give him his order slip. Then on the next iteration and every other iteration after the Boss
has to go back and forth 500 feet between the two.
Second Case: The Boss
has to travel 100 feet on the first iteration to A
, but after that, he is already there and just waits for A
to get back until all slips are filled. Then the Boss
has to travel 500 feet on the first iteration to C
because C
is 500 feet from A
. Since this Boss( Summation, For Loop )
is being called right after working with A
he then just waits there as he did with A
until all of C's
order slips are done.
The Difference In Distances Traveled
const n = 100000
distTraveledOfFirst = (100 + 500) + ((n-1)*(500 + 500);
// Simplify
distTraveledOfFirst = 600 + (99999*100);
distTraveledOfFirst = 600 + 9999900;
distTraveledOfFirst = 10000500;
// Distance Traveled On First Algorithm = 10,000,500ft
distTraveledOfSecond = 100 + 500 = 600;
// Distance Traveled On Second Algorithm = 600ft;
The Comparison of Arbitrary Values
We can easily see that 600 is far less than 10 million. Now, this isn't exact, because we don't know the actual difference in distance between which address of RAM or from which cache or page file each call on each iteration is going to be due to many other unseen variables. This is just an assessment of the situation to be aware of and looking at it from the worst-case scenario.
From these numbers it would almost appear as if algorithm one should be 99%
slower than algorithm two; however, this is only the Boss's
part or responsibility of the algorithms and it doesn't account for the actual workers A
, B
, C
, & D
and what they have to do on each and every iteration of the Loop. So the boss's job only accounts for about 15 - 40% of the total work being done. The bulk of the work that is done through the workers has a slightly bigger impact towards keeping the ratio of the speed rate differences to about 50-70%
The Observation: - The differences between the two algorithms
In this situation, it is the structure of the process of the work being done. It goes to show that Case 2 is more efficient from both the partial optimization of having a similar function declaration and definition where it is only the variables that differ by name and the distance traveled.
We also see that the total distance traveled in Case 1 is much farther than it is in Case 2 and we can consider this distance traveled our Time Factor between the two algorithms. Case 1 has considerable more work to do than Case 2 does.
This is observable from the evidence of the assembly instructions that were shown in both cases. Along with what was already stated about these cases, this doesn't account for the fact that in Case 1 the boss will have to wait for both A
& C
to get back before he can go back to A
again for each iteration. It also doesn't account for the fact that if A
or B
is taking an extremely long time then both the Boss
and the other worker(s) are idle waiting to be executed.
In Case 2 the only one being idle is the Boss
until the worker gets back. So even this has an impact on the algorithm.
The OP's Amended Question(s)
EDIT: The question turned out to be of no relevance, as the behavior severely depends on the sizes of the arrays (n) and the CPU cache. So if there is further interest, I rephrase the question:
Could you provide some solid insight into the details that lead to the different cache behaviors as illustrated by the five regions on the following graph?
It might also be interesting to point out the differences between CPU/cache architectures, by providing a similar graph for these CPUs.
Regarding These Questions
As I have demonstrated without a doubt, there is an underlying issue even before the Hardware and Software becomes involved.
Now as for the management of memory and caching along with page files, etc. which all work together in an integrated set of systems between the following:
We can already see that there is a bottleneck that is happening within the first algorithm before we even apply it to any machine with any arbitrary architecture, OS, and programmable language compared to the second algorithm. There already existed a problem before involving the intrinsics of a modern computer.
The Ending Results
However; it is not to say that these new questions are not of importance because they themselves are and they do play a role after all. They do impact the procedures and the overall performance and that is evident with the various graphs and assessments from many who have given their answer(s) and or comment(s).
If you paid attention to the analogy of the Boss
and the two workers A
& B
who had to go and retrieve packages from C
& D
respectively and considering the mathematical notations of the two algorithms in question; you can see without the involvement of the computer hardware and software Case 2
is approximately 60%
faster than Case 1
.
When you look at the graphs and charts after these algorithms have been applied to some source code, compiled, optimized, and executed through the OS to perform their operations on a given piece of hardware, you can even see a little more degradation between the differences in these algorithms.
If the Data
set is fairly small it may not seem all that bad of a difference at first. However, since Case 1
is about 60 - 70%
slower than Case 2
we can look at the growth of this function in terms of the differences in time executions:
DeltaTimeDifference approximately = Loop1(time) - Loop2(time)
//where
Loop1(time) = Loop2(time) + (Loop2(time)*[0.6,0.7]) // approximately
// So when we substitute this back into the difference equation we end up with
DeltaTimeDifference approximately = (Loop2(time) + (Loop2(time)*[0.6,0.7])) - Loop2(time)
// And finally we can simplify this to
DeltaTimeDifference approximately = [0.6,0.7]*Loop2(time)
This approximation is the average difference between these two loops both algorithmically and machine operations involving software optimizations and machine instructions.
When the data set grows linearly, so does the difference in time between the two. Algorithm 1 has more fetches than algorithm 2 which is evident when the Boss
has to travel back and forth the maximum distance between A
& C
for every iteration after the first iteration while algorithm 2 the Boss
has to travel to A
once and then after being done with A
he has to travel a maximum distance only one time when going from A
to C
.
Trying to have the Boss
focusing on doing two similar things at once and juggling them back and forth instead of focusing on similar consecutive tasks is going to make him quite angry by the end of the day since he had to travel and work twice as much. Therefore do not lose the scope of the situation by letting your boss getting into an interpolated bottleneck because the boss's spouse and children wouldn't appreciate it.
Amendment: Software Engineering Design Principles
-- The difference between local Stack and heap allocated computations within iterative for loops and the difference between their usages, their efficiencies, and effectiveness --
The mathematical algorithm that I proposed above mainly applies to loops that perform operations on data that is allocated on the heap.
So when you are working with data that needs to be on the heap and you are traversing through them in loops, it is more efficient to keep each data set and its corresponding algorithms within its own single loop. You will get better optimizations compared to trying to factor out consecutive loops by putting multiple operations of different data sets that are on the heap into a single loop.
It is okay to do this with data that is on the stack since they are frequently cached, but not for data that has to have its memory address queried every iteration.
This is where software engineering and software architecture design comes into play. It is the ability to know how to organize your data, knowing when to cache your data, knowing when to allocate your data on the heap, knowing how to design and implement your algorithms, and knowing when and where to call them.
You might have the same algorithm that pertains to the same data set, but you might want one implementation design for its stack variant and another for its heap-allocated variant just because of the above issue that is seen from its O(n)
complexity of the algorithm when working with the heap.
From what I've noticed over the years, many people do not take this fact into consideration. They will tend to design one algorithm that works on a particular data set and they will use it regardless of the data set being locally cached on the stack or if it was allocated on the heap.
If you want true optimization, yes it might seem like code duplication, but to generalize it would be more efficient to have two variants of the same algorithm. One for stack operations, and the other for heap operations that are performed in iterative loops!
Here's a pseudo example: Two simple structs, one algorithm.
struct A {
int data;
A() : data{0}{}
A(int a) : data{a}{}
};
struct B {
int data;
B() : data{0}{}
A(int b) : data{b}{}
}
template<typename T>
void Foo( T& t ) {
// Do something with t
}
// Some looping operation: first stack then heap.
// Stack data:
A dataSetA[10] = {};
B dataSetB[10] = {};
// For stack operations this is okay and efficient
for (int i = 0; i < 10; i++ ) {
Foo(dataSetA[i]);
Foo(dataSetB[i]);
}
// If the above two were on the heap then performing
// the same algorithm to both within the same loop
// will create that bottleneck
A* dataSetA = new [] A();
B* dataSetB = new [] B();
for ( int i = 0; i < 10; i++ ) {
Foo(dataSetA[i]); // dataSetA is on the heap here
Foo(dataSetB[i]); // dataSetB is on the heap here
} // this will be inefficient.
// To improve the efficiency above, put them into separate loops...
for (int i = 0; i < 10; i++ ) {
Foo(dataSetA[i]);
}
for (int i = 0; i < 10; i++ ) {
Foo(dataSetB[i]);
}
// This will be much more efficient than above.
// The code isn't perfect syntax, it's only psuedo code
// to illustrate a point.
This is what I was referring to by having separate implementations for stack variants versus heap variants. The algorithms themselves don't matter too much, it's the looping structures that you will use them in that do.
As of iOS8 you can open the built-in Settings app with:
NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
The actual URL string is @"app-settings:"
. I tried appending different sections to the string ("Bluetooth", "GENERAL", etc.) but seems only linking to the main Settings screen works. Post a reply if you find out otherwise.
They all do different things, since matplotlib uses a hierarchical order in which a figure window contains a figure which may consist of many axes. Additionally, there are functions from the pyplot interface and there are methods on the Figure
class. I will discuss both cases below.
pyplot
is a module that collects a couple of functions that allow matplotlib to be used in a functional manner. I here assume that pyplot
has been imported as import matplotlib.pyplot as plt
.
In this case, there are three different commands that remove stuff:
plt.cla()
clears an axes, i.e. the currently active axes in the current figure. It leaves the other axes untouched.
plt.clf()
clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots.
plt.close()
closes a window, which will be the current window, if not specified otherwise.
Which functions suits you best depends thus on your use-case.
The close()
function furthermore allows one to specify which window should be closed. The argument can either be a number or name given to a window when it was created using figure(number_or_name)
or it can be a figure instance fig
obtained, i.e., usingfig = figure()
. If no argument is given to close()
, the currently active window will be closed. Furthermore, there is the syntax close('all')
, which closes all figures.
Additionally, the Figure
class provides methods for clearing figures.
I'll assume in the following that fig
is an instance of a Figure
:
fig.clf()
clears the entire figure. This call is equivalent to plt.clf()
only if fig
is the current figure.
fig.clear()
is a synonym for fig.clf()
Note that even del fig
will not close the associated figure window. As far as I know the only way to close a figure window is using plt.close(fig)
as described above.
You may use:
To create array of objects:
var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
Or if you wants to create a single object from values of arrays:
var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
The solution from the comments deserves it's own answer:
redis-cli --bigkeys
Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors.
It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\
What you posted has a syntax error, but it makes no difference as you cannot pass HTTP headers via $.post()
.
Provided you're on jQuery version >= 1.5, switch to $.ajax()
and pass the headers
(docs) option. (If you're on an older version of jQuery, I will show you how to do it via the beforeSend
option.)
$.ajax({
url: 'https://url.com',
type: 'post',
data: {
access_token: 'XXXXXXXXXXXXXXXXXXX'
},
headers: {
Header_Name_One: 'Header Value One', //If your header name has spaces or any other char not appropriate
"Header Name Two": 'Header Value Two' //for object property name, use quoted notation shown in second
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
A slightly modified version of @sidanmor 's code. The main point is, not every webpage is purely ASCII, user should be able to handle the decoding manually (even encode into base64)
function httpGet(url) {
return new Promise((resolve, reject) => {
const http = require('http'),
https = require('https');
let client = http;
if (url.toString().indexOf("https") === 0) {
client = https;
}
client.get(url, (resp) => {
let chunks = [];
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
chunks.push(chunk);
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
resolve(Buffer.concat(chunks));
});
}).on("error", (err) => {
reject(err);
});
});
}
(async(url) => {
var buf = await httpGet(url);
console.log(buf.toString('utf-8'));
})('https://httpbin.org/headers');
I think you mean to update it back to the OLD
password, when the NEW one is not supplied.
DROP TRIGGER IF EXISTS upd_user;
DELIMITER $$
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
IF (NEW.password IS NULL OR NEW.password = '') THEN
SET NEW.password = OLD.password;
ELSE
SET NEW.password = Password(NEW.Password);
END IF;
END$$
DELIMITER ;
However, this means a user can never blank out a password.
DELIMITER $$
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN
SET NEW.password = OLD.password;
ELSE
SET NEW.password = Password(NEW.Password);
END IF;
END$$
DELIMITER ;
If you have a class Car
public class Car {
private Color externalColor;
}
And the property Color is a class
@Data
public class Color {
private Integer id;
private String name;
}
And you want to convert Color to an Enum
public class CarDTO {
private ColorEnum externalColor;
}
Simply add a method in Color class to convert Color in ColorEnum
@Data
public class Color {
private Integer id;
private String name;
public ColorEnum getEnum(){
ColorEnum.getById(id);
}
}
and inside ColorEnum implements the method getById()
public enum ColorEnum {
...
public static ColorEnum getById(int id) {
for(ColorEnum e : values()) {
if(e.id==id)
return e;
}
}
}
Now you can use a classMap
private MapperFactory factory = new DefaultMapperFactory.Builder().build();
...
factory.classMap(Car.class, CarDTO.class)
.fieldAToB("externalColor.enum","externalColor")
.byDefault()
.register();
...
CarDTO dto = mapper.map(car, CarDTO.class);
You can pass PHP arrays to JavaScript using json_encode
PHP function.
<?php
$phpArray = array(
0 => "Mon",
1 => "Tue",
2 => "Wed",
3 => "Thu",
4 => "Fri",
5 => "Sat",
6 => "Sun",
)
?>
<script type="text/javascript">
var jArray = <?php echo json_encode($phpArray); ?>;
for(var i=0; i<jArray.length; i++){
alert(jArray[i]);
}
</script>
You can pass a format string to the ToString method, like so:
ToString("N4"); // 4 decimal points Number
If you want to see more modifiers, take a look at MSDN - Standard Numeric Format Strings
As of this time, the latest draft of the HTTPbis specification, which is intended to replace and make RFC 2616 obsolete, states:
The 400 (Bad Request) status code indicates that the server cannot or will not process the request because the received syntax is invalid, nonsensical, or exceeds some limitation on what the server is willing to process.
This definition, while of course still subject to change, ratifies the widely used practice of responding to logical errors with a 400.
I came across another performance comparison(latest update 10 April 2014). It compares the following:
Here is a quick summary from the post:
Conclusion
Ninject is definitely the slowest container.
MEF, LinFu and Spring.NET are faster than Ninject, but still pretty slow. AutoFac, Catel and Windsor come next, followed by StructureMap, Unity and LightCore. A disadvantage of Spring.NET is, that can only be configured with XML.
SimpleInjector, Hiro, Funq, Munq and Dynamo offer the best performance, they are extremely fast. Give them a try!
Especially Simple Injector seems to be a good choice. It's very fast, has a good documentation and also supports advanced scenarios like interception and generic decorators.
You can also try using the Common Service Selector Library and hopefully try multiple options and see what works best for you.
Some informtion about Common Service Selector Library from the site:
The library provides an abstraction over IoC containers and service locators. Using the library allows an application to indirectly access the capabilities without relying on hard references. The hope is that using this library, third-party applications and frameworks can begin to leverage IoC/Service Location without tying themselves down to a specific implementation.
13.09.2011: Funq and Munq were added to the list of contestants. The charts were also updated, and Spring.NET was removed due to it's poor performance.
04.11.2011: "added Simple Injector, the performance is the best of all contestants".
Suppose you are going to create a test-context.xml which is independent from app-context.xml for testing, put test-context.xml under /src/test/resources. In the test class, have the @ContextConfiguration annotation on top of the class definition.
@ContextConfiguration(locations = "/test-context.xml")
public class MyTests {
...
}
Spring document Context management
UPDATE:
Post.find().sort({'updatedAt': -1}).all((posts) => {
// do something with the array of posts
});
Try:
Post.find().sort([['updatedAt', 'descending']]).all((posts) => {
// do something with the array of posts
});
Now in HTML5/CSS3 we have better solution for the problem. In my opinion this purely CSS solution is recommended:
table.fixed {table-layout:fixed; width:90px;}/*Setting the table width is important!*/_x000D_
table.fixed td {overflow:hidden;}/*Hide text outside the cell.*/_x000D_
table.fixed td:nth-of-type(1) {width:20px;}/*Setting the width of column 1.*/_x000D_
table.fixed td:nth-of-type(2) {width:30px;}/*Setting the width of column 2.*/_x000D_
table.fixed td:nth-of-type(3) {width:40px;}/*Setting the width of column 3.*/
_x000D_
<table class="fixed">_x000D_
<tr>_x000D_
<td>Veryverylongtext</td>_x000D_
<td>Actuallythistextismuchlongeeeeeer</td>_x000D_
<td>We should use spaces tooooooooooooo</td>_x000D_
</tr>_x000D_
</table>
_x000D_
You need to set the table's width
even in haunter's solution. Otherwise it doesn't work.
Also a new CSS3 feature that vsync suggested is: word-break:break-all;
. This will break the words without spaces in them to multiple lines too. Just modify the code like this:
table.fixed { table-layout:fixed; width:90px; word-break:break-all;}
Since iOS 11, you can use the native framework called PDFKit for displaying and manipulating PDFs.
After importing PDFKit, you should initialize a PDFView
with a local or a remote URL and display it in your view.
if let url = Bundle.main.url(forResource: "example", withExtension: "pdf") {
let pdfView = PDFView(frame: view.frame)
pdfView.document = PDFDocument(url: url)
view.addSubview(pdfView)
}
Read more about PDFKit in the Apple Developer documentation.
I tried a few of these things until I got one to work in both Firefox and IE. This is what I came up with.
$("#my-Select").val($("#my-Select" + " option").filter(function() { return this.text == myText }).val());
another way of writing it in a more readable fasion:
var valofText = $("#my-Select" + " option").filter(function() {
return this.text == myText
}).val();
$(ElementID).val(valofText);
Pseudocode:
$("#my-Select").val( getValOfText( myText ) );
Data elements (e.g. members of classes and structs) are typically aligned on WORD or DWORD boundaries for current generation processors in order to improve access times. Retrieving a DWORD at an address which isn't divisible by 4 requires at least one extra CPU cycle on a 32 bit processor. So, if you have e.g. three char members char a, b, c;
, they actually tend to take 6 or 12 bytes of storage.
#pragma
allows you to override this to achieve more efficient space usage, at the expense of access speed, or for consistency of stored data between different compiler targets. I had a lot of fun with this transitioning from 16 bit to 32 bit code; I expect porting to 64 bit code will cause the same kinds of headaches for some code.
Let's give an example for int(10) one with zerofill keyword, one not, the table likes that:
create table tb_test_int_type(
int_10 int(10),
int_10_with_zf int(10) zerofill,
unit int unsigned
);
Let's insert some data:
insert into tb_test_int_type(int_10, int_10_with_zf, unit)
values (123456, 123456,3147483647), (123456, 4294967291,3147483647)
;
Then
select * from tb_test_int_type;
# int_10, int_10_with_zf, unit
'123456', '0000123456', '3147483647'
'123456', '4294967291', '3147483647'
We can see that
with keyword zerofill
, num less than 10 will fill 0, but without zerofill
it won't
Secondly with keyword zerofill
, int_10_with_zf becomes unsigned int type, if you insert a minus you will get error Out of range value for column.....
. But you can insert minus to int_10. Also if you insert 4294967291 to int_10 you will get error Out of range value for column.....
Conclusion:
int(X) without keyword zerofill
, is equal to int range -2147483648~2147483647
int(X) with keyword zerofill
, the field is equal to unsigned int range 0~4294967295, if num's length is less than X it will fill 0 to the left
I have recently faced the same issue. I wrote the following code:
$('html').click(function(e) {
var a = e.target;
if ($(a).parents('.menu_container').length === 0) {
$('.ofSubLevelLinks').removeClass('active'); //hide menu item
$('.menu_container li > img').hide(); //hide dropdown image, if any
}
});
It has worked for me perfectly.
PowerShell is a good choice ;) It is very easy to enumerate files in given directory, read them and process.
The script could look like this:
Get-ChildItem C:\Projects *.config -recurse |
Foreach-Object {
$c = ($_ | Get-Content)
$c = $c -replace '<add key="Environment" value="Dev"/>','<add key="Environment" value="Demo"/>'
[IO.File]::WriteAllText($_.FullName, ($c -join "`r`n"))
}
I split the code to more lines to be readable for you.
Note that you could use Set-Content instead of [IO.File]::WriteAllText
, but it adds new line at the end. With WriteAllText
you can avoid it.
Otherwise the code could look like this: $c | Set-Content $_.FullName
.
I think what you're seeing is the hiding and showing of scrollbars. Here's a quick demo showing the width change.
As an aside: do you need to poll constantly? You might be able to optimize your code to run on the resize event, like this:
$(window).resize(function() {
//update stuff
});
public class MyObject implements Cloneable, Serializable{
@Override
@SuppressWarnings(value = "unchecked")
protected MyObject clone(){
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
ByteArrayOutputStream bOs = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bOs);
oos.writeObject(this);
ois = new ObjectInputStream(new ByteArrayInputStream(bOs.toByteArray()));
return (MyObject)ois.readObject();
} catch (Exception e) {
//Some seriouse error :< //
return null;
}finally {
if (oos != null)
try {
oos.close();
} catch (IOException e) {
}
if (ois != null)
try {
ois.close();
} catch (IOException e) {
}
}
}
}
The behaviour is not really that strange. Looking into the implementation of the classes, it is caused by:
Charset.defaultCharset()
is not caching the determined character set in Java 5.Charset.defaultCharset()
again causes a second evaluation of the system property, no character set with the name "Latin-1" is found, so Charset.defaultCharset()
defaults to "UTF-8".OutputStreamWriter
is however caching the default character set and is probably used already during VM initialization, so that its default character set diverts from Charset.defaultCharset()
if the system property "file.encoding" has been changed at runtime.As already pointed out, it is not documented how the VM must behave in such a situation. The Charset.defaultCharset()
API documentation is not very precise on how the default character set is determined, only mentioning that it is usually done on VM startup, based on factors like the OS default character set or default locale.
If you're trying to get data out of the request body, the code above works. But, I think you are having the same problem I was..
If the data in the body is in JSON form, and you want it as a Java object, you'll need to parse it yourself, or use a library like google-gson to handle it for you. You should look at the docs and examples at the project's website to know how to use it. It's fairly simple.
Maybe I am missing something here, but did you allocate any memory for that PString before you accessed it?
PString * initializeString() {
PString *str;
str = (PString *) malloc(sizeof(PString));
str->length = &length;
return str;
}
When you're launching tomcat server from netbeans IDE you need to check in menu "tools->servers" on connection tab for tomcat server - there is catalina base directory. And you need to include something like:
<role rolename="manager"/>
<user username="admin" password="admin" roles="manager"/>
at file
\CATALINA_BASE\conf\tomcat-users.xml
or use username automatically generated by IDE with description already placed in this file or on connection tab
For Manager Apps : GUI access:
<role rolename="manager-gui"/>
<user username="tomcat" password="s3cret" roles="manager-gui"/>
I ran into the same issue, but I had to go up one level and give full access to everyone to the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\ key, instead of going down to security, that cleared up the issue for me.
When setting with JQM
, don't forget to update the UI
:
$('#selectId').val('newValue').selectmenu('refresh', true);
SSL certificates are bound to a 'common name', which is usually a fully qualified domain name but can be a wildcard name (eg. *.domain.com) or even an IP address, but it usually isn't.
In your case, you are accessing your LDAP server by a hostname and it sounds like your two LDAP servers have different SSL certificates installed. Are you able to view (or download and view) the details of the SSL certificate? Each SSL certificate will have a unique serial numbers and fingerprint which will need to match. I assume the certificate is being rejected as these details don't match with what's in your certificate store.
Your solution will be to ensure that both LDAP servers have the same SSL certificate installed.
BTW - you can normally override DNS entries on your workstation by editing a local 'hosts' file, but I wouldn't recommend this.
A Grid is a hardware and software infrastructure that clusters and integrates high-end computers, networks, databases, and scientific instruments from multiple sources to form a virtual supercomputer on which users can work collaboratively within virtual organisations
Grid is Mostly free used by academic research etc.
Clouds are a large pool of easily usable and accessible virtualized resources (such as hardware, development platforms and/or services). These resources can be dynamically reconfigured to adjust to a variable load (scale), allowing also for an optimum resource utilization. This pool of resources is typically exploited by a pay peruse model in which guarantees are offered by the Infrastructure Provider by customized service level agreements.
Cloud is not free. It is a service, provided by different service providers and they charge according to your work done.
Scott Gu's quoted blog post explains it nicely.
For me, the answer to the question is in the following statement in that post:
Note how the static method above has a "this" keyword before the first parameter argument of type string. This tells the compiler that this particular Extension Method should be added to objects of type "string". Within the IsValidEmailAddress() method implementation I can then access all of the public properties/methods/events of the actual string instance that the method is being called on, and return true/false depending on whether it is a valid email or not.
To specify a variable is an array of objects:
$needles = getAllNeedles();
/* @var $needles Needle[] */
$needles[1]->... //codehinting works
This works in Netbeans 7.2 (I'm using it)
Works also with:
$needles = getAllNeedles();
/* @var $needles Needle[] */
foreach ($needles as $needle) {
$needle->... //codehinting works
}
Therefore use of declaration inside the foreach
is not necessary.
In IOS 7 and 8, you can change the Title's color to let's say green
self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor greenColor] forKey:NSForegroundColorAttributeName];
Drag the variable from Variables pane to Watch pane and voila!
well, there are many ways. I have made use of lists to solve this probelm.. below is the working code... feel free to comment if any feedback
def fib(n):
if n == 0: #to start fibonacci seraries value must be >= 1
print('Enter postive integer')
elif n ==1:
print(0)
else:
li = [0, 1]
for i in range(2, n): # start the loop from second index as 'li' is assigned for 0th and 1st index
li.append(li[-1] + li[-2])
i += 1
print(*li) # '*' is used to print elements from list in single line with spaces
n = int(input('Enter the number for which you want to generate fibonacci series\n'))
fib(n)
I think this part of code make changes to the context.
Page page = BuildManager.CreateInstanceFromVirtualPath(
m_VirtualPath,
typeof(Page)) as Page;// IHttpHandler;
Also this part of code is useless:
if (page != null)
{
return page;
}
return page;
It will always return the page wither it's null or not.
There's a general point to be made about such optimizations.
The optimization you get is proportional to the amount of time the program counter is actually in that code.
If you sample the program counter, you will find out where it spends its time, and that is usually in a tiny part of the code, and often in library routines you have no control over.
Only if you find it spending much time in the heap-allocation of your objects will it be noticeably faster to stack-allocate them.
As a C newbie, I found the slides called Test driven development in C very helpful. Basically, it uses the standard assert()
together with &&
to deliver a message, without any external dependencies. If someone is used to a full stack testing framework, this probably won't do :)
You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:
{el1, el2, {el31, el32, el33}, {el41, el42}}
var MainObj = {_x000D_
_x000D_
prop1: "prop1MainObj",_x000D_
_x000D_
Obj1: {_x000D_
prop1: "prop1Obj1",_x000D_
prop2: "prop2Obj1", _x000D_
Obj2: {_x000D_
prop1: "hey you",_x000D_
prop2: "prop2Obj2"_x000D_
}_x000D_
},_x000D_
_x000D_
Obj3: {_x000D_
prop1: "prop1Obj3",_x000D_
prop2: "prop2Obj3"_x000D_
},_x000D_
_x000D_
Obj4: {_x000D_
prop1: true,_x000D_
prop2: 3_x000D_
} _x000D_
};_x000D_
_x000D_
console.log(MainObj.Obj1.Obj2.prop1);
_x000D_
In my case, the database was related to an old Sharepoint install. Stopping and disabling related services in the server manager "unhung" the take offline action, which had been running for 40 minutes, and it completed immediately.
You may wish to check if any services are currently utilizing the database.
Even when the question is regarding Java 7, I think it adds value to know that from Java 11 onward, there is a static method in Path
class that allows to do this straight away:
With all the path in one String:
Path.of("/tmp/foo");
With the path broken down in several Strings:
Path.of("/tmp","foo");
To give a complete answer: yield
is working similar to return
, but in a generator.
As for the commonly given example, this works as follows:
function *squareGen(x) {
var i;
for (i = 0; i < x; i++) {
yield i*i;
}
}
var gen = squareGen(3);
console.log(gen.next().value); // prints 0
console.log(gen.next().value); // prints 1
console.log(gen.next().value); // prints 4
But theres also a second purpose of the yield keyword. It can be used to send values to the generator.
To clarify, a small example:
function *sendStuff() {
y = yield (0);
yield y*y;
}
var gen = sendStuff();
console.log(gen.next().value); // prints 0
console.log(gen.next(2).value); // prints 4
This works, as the value 2
is assigned to y
, by sending it to the generator, after it stopped at the first yield (which returned 0
).
This enables us to to some really funky stuff. (look up coroutine)
You can also, do this.
$(window).on("scroll", function () {
if ($(this).scrollTop() > 800) {
#code here
} else {
#code here
}
});
If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.
You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar
):
openssl genrsa -aes128 -passout pass:foobar 3072
However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.
A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:
openssl genrsa -aes128 -passout file:passphrase.txt 3072
Or supply the passphrase on standard input:
openssl genrsa -aes128 -passout stdin 3072
You can also used a named pipe with the file:
option, or a file descriptor.
To then obtain the matching public key, you need to use openssl rsa
, supplying the same passphrase with the -passin
parameter as was used to encrypt the private key:
openssl rsa -passin file:passphrase.txt -pubout
(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>
).
Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar
:
openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub
Try just =COUNTIF(A2:A51,"iPad")
That is the timeout to create the connection, NOT a timeout for commands executed over that connection.
See for instance http://www.connectionstrings.com/all-sql-server-connection-string-keywords/ (note that the property is "Connect Timeout" (or "Connection Timeout"), not just "Timeout")
From the comments:
It is not possible to set the command timeout through the connection string. However, the SqlCommand has a CommandTimeout property (derived from DbCommand) where you can set a timeout (in seconds) per command.
Do note that when you loop over query results with Read()
, the timeout is reset on every read. The timeout is for each network request, not for the total connection.
It will redirect your store page to your contact page
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
Redirect 301 /storepage /contactpage
</IfModule>
The changes to the rcParams
are very granular, most of the time all you want is just scaling all of the font sizes so they can be seen better in your figure. The figure size is a good trick but then you have to carry it for all of your figures. Another way (not purely matplotlib, or maybe overkill if you don't use seaborn) is to just set the font scale with seaborn:
sns.set_context('paper', font_scale=1.4)
DISCLAIMER: I know, if you only use matplotlib then probably you don't want to install a whole module for just scaling your plots (I mean why not) or if you use seaborn, then you have more control over the options. But there's the case where you have the seaborn in your data science virtual env but not using it in this notebook. Anyway, yet another solution.
Here is one way of doing it:
<%
Dim message
message = "This is my message"
Response.Write("<script language=VBScript>MsgBox """ + message + """</script>")
%>
There are MYSQL functions you can use. Like this one that resolves the user:
SELECT USER();
This will return something like root@localhost
so you get the host and the user.
To get the current database run this statement:
SELECT DATABASE();
Other useful functions can be found here: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html
I assume it is something in the lines of:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ChromeConsoleLogging {
private WebDriver driver;
@BeforeMethod
public void setUp() {
System.setProperty("webdriver.chrome.driver", "c:\\path\\to\\chromedriver.exe");
DesiredCapabilities caps = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(caps);
}
@AfterMethod
public void tearDown() {
driver.quit();
}
public void analyzeLog() {
LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
for (LogEntry entry : logEntries) {
System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
//do something useful with the data
}
}
@Test
public void testMethod() {
driver.get("http://mypage.com");
//do something on page
analyzeLog();
}
}
Source : Get chrome's console log
Cloud 9 IDE. Storage is cloud+local, it offers autocompletion, it provides explicit support for node.js development, offers real-time collaboration, and you get bash into the deal with all its most popular tools (gcc included). All without having to open anything other than your browser.
I think that's Pretty Awesome.
EDIT Q3 2013 I would also suggest JetBrains WebStorm. It has autocompletion and solid refactoring features for HTML5, CSS3, JS. And it is very responsive.
keyup event input jquery
$(document).ready(function(){ _x000D_
$("#tutsmake").keydown(function(){ _x000D_
$("#tutsmake").css("background-color", "green"); _x000D_
}); _x000D_
$("#tutsmake").keyup(function(){ _x000D_
$("#tutsmake").css("background-color", "yellow"); _x000D_
}); _x000D_
});
_x000D_
<!DOCTYPE html> _x000D_
<html> _x000D_
<title> jQuery keyup Event Example </title>_x000D_
<head> _x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>_x000D_
</head> _x000D_
<body> _x000D_
Fill the Input Box: <input type="text" id="tutsmake"> _x000D_
</body> _x000D_
</html>
_x000D_
Here's a code excerpt we're using in our app to set request headers. You'll note we set the CONTENT_TYPE header only on a POST or PUT, but the general method of adding headers (via a request interceptor) is used for GET as well.
/**
* HTTP request types
*/
public static final int POST_TYPE = 1;
public static final int GET_TYPE = 2;
public static final int PUT_TYPE = 3;
public static final int DELETE_TYPE = 4;
/**
* HTTP request header constants
*/
public static final String CONTENT_TYPE = "Content-Type";
public static final String ACCEPT_ENCODING = "Accept-Encoding";
public static final String CONTENT_ENCODING = "Content-Encoding";
public static final String ENCODING_GZIP = "gzip";
public static final String MIME_FORM_ENCODED = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN = "text/plain";
private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
final Map<String, String> headers, final Map<String, String> params, final int requestType)
throws IOException {
DefaultHttpClient client = HTTPClientFactory.newClient();
client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);
// add user and pass to client credentials if present
if ((user != null) && (pass != null)) {
client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
}
// process headers using request interceptor
final Map<String, String> sendHeaders = new HashMap<String, String>();
if ((headers != null) && (headers.size() > 0)) {
sendHeaders.putAll(headers);
}
if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
}
// request gzip encoding for response
sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);
if (sendHeaders.size() > 0) {
client.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(final HttpRequest request, final HttpContext context) throws HttpException,
IOException {
for (String key : sendHeaders.keySet()) {
if (!request.containsHeader(key)) {
request.addHeader(key, sendHeaders.get(key));
}
}
}
});
}
//.... code omitted ....//
}
You could serialize the image into a Data URI. There's a tutorial in this blog post. That will produce a string you can store in local storage. Then on the next page, use the data uri as the source of the image.
A simple comparison between del and pop():
import timeit
code = """
results = {'A': 1, 'B': 2, 'C': 3}
del results['A']
del results['B']
"""
print timeit.timeit(code, number=100000)
code = """
results = {'A': 1, 'B': 2, 'C': 3}
results.pop('A')
results.pop('B')
"""
print timeit.timeit(code, number=100000)
result:
0.0329667857143
0.0451040902256
So, del is faster than pop().
For those of you who need to convert hexadecimal representation of a signed byte from two-character String into byte (which in Java is always signed), there is an example. Parsing a hexadecimal string never gives negative number, which is faulty, because 0xFF is -1 from some point of view (two's complement coding). The principle is to parse the incoming String as int, which is larger than byte, and then wrap around negative numbers. I'm showing only bytes, so that example is short enough.
String inputTwoCharHex="FE"; //whatever your microcontroller data is
int i=Integer.parseInt(inputTwoCharHex,16);
//negative numbers is i now look like 128...255
// shortly i>=128
if (i>=Integer.parseInt("80",16)){
//need to wrap-around negative numbers
//we know that FF is 255 which is -1
//and FE is 254 which is -2 and so on
i=-1-Integer.parseInt("FF",16)+i;
//shortly i=-256+i;
}
byte b=(byte)i;
//b is now surely between -128 and +127
This can be edited to process longer numbers. Just add more FF's or 00's respectively. For parsing 8 hex-character signed integers, you need to use Long.parseLong, because FFFF-FFFF, which is integer -1, wouldn't fit into Integer when represented as a positive number (gives 4294967295). So you need Long to store it. After conversion to negative number and casting back to Integer, it will fit. There is no 8 character hex string, that wouldn't fit integer in the end.
If the response is in json then it would be like:
alert(response.id);
Otherwise
var str='{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';
An easy workaround might be to simply mount the volume (using the -v or --mount flag) to the container when you run it and access the files that way.
example:
docker run -v /path/to/file/on/host:/desired/path/to/file/in/container/ image_name
for more see: https://docs.docker.com/storage/volumes/
Standard PHP objects
The best way to provide PHP variables to JavaScript is json_encode
. When using Blade you can do it like following:
<script>
var bool = {!! json_encode($bool) !!};
var int = {!! json_encode($int) !!};
/* ... */
var array = {!! json_encode($array_without_keys) !!};
var object = {!! json_encode($array_with_keys) !!};
var object = {!! json_encode($stdClass) !!};
</script>
There is also a Blade directive for decoding to JSON
. I'm not sure since which version of Laravel but in 5.5 it is available. Use it like following:
<script>
var array = @json($array);
</script>
Jsonable's
When using Laravel objects e.g. Collection
or Model
you should use the ->toJson()
method. All those classes that implements the \Illuminate\Contracts\Support\Jsonable
interface supports this method call. The call returns automatically JSON
.
<script>
var collection = {!! $collection->toJson() !!};
var model = {!! $model->toJson() !!};
</script>
When using Model
class you can define the $hidden
property inside the class
and those will be filtered in JSON
. The $hidden
property, as its name describs, hides sensitive content. So this mechanism is the best for me. Do it like following:
class User extends Model
{
/* ... */
protected $hidden = [
'password', 'ip_address' /* , ... */
];
/* ... */
}
And somewhere in your view
<script>
var user = {!! $user->toJson() !!};
</script>
How To Read XML Data into a DataSet by Using Visual C# .NET contains some details. Basically, you can use the overloaded DataSet method ReadXml to get the data into a DataSet. Your XML data will be in the first DataTable there.
There is also a DataTable.ReadXml method.
As Tmdean correctly pointed out you can use the Mid()
function. The MSDN Library also has a great reference section on VBScript which you can find here:
Like this:
yourString = yourString.replaceAll("\\s+", " ");
For example
System.out.println("lorem ipsum dolor \n sit.".replaceAll("\\s+", " "));
outputs
lorem ipsum dolor sit.
What does that \s+
mean?
\s+
is a regular expression. \s
matches a space, tab, new line, carriage return, form feed or vertical tab, and +
says "one or more of those". Thus the above code will collapse all "whitespace substrings" longer than one character, with a single space character.
toBe()
versus toEqual()
: toEqual()
checks equivalence. toBe()
, on the other hand, makes sure that they're the exact same object.
I would say use toBe()
when comparing values, and toEqual()
when comparing objects.
When comparing primitive types, toEqual()
and toBe()
will yield the same result. When comparing objects, toBe()
is a stricter comparison, and if it is not the exact same object in memory this will return false. So unless you want to make sure it's the exact same object in memory, use toEqual()
for comparing objects.
Check this link out for more info : http://evanhahn.com/how-do-i-jasmine/
Now when looking at the difference between toBe()
and toEqual()
when it comes to numbers, there shouldn't be any difference so long as your comparison is correct. 5
will always be equivalent to 5
.
A nice place to play around with this to see different outcomes is here
An easy way to look at toBe()
and toEqual()
is to understand what exactly they do in JavaScript. According to Jasmine API, found here:
toEqual() works for simple literals and variables, and should work for objects
toBe() compares with
===
Essentially what that is saying is toEqual()
and toBe()
are similar Javascripts ===
operator except toBe()
is also checking to make sure it is the exact same object, in that for the example below objectOne === objectTwo //returns false
as well. However, toEqual()
will return true in that situation.
Now, you can at least understand why when given:
var objectOne = {
propertyOne: str,
propertyTwo: num
}
var objectTwo = {
propertyOne: str,
propertyTwo: num
}
expect(objectOne).toBe(objectTwo); //returns false
That is because, as stated in this answer to a different, but similar question, the ===
operator actually means that both operands reference the same object, or in case of value types, have the same value.
What you need to add is a custom HostnameVerifier
class bypasses certificate verification and returns true
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
This needs to be placed appropriately in your code.
You can simply do:
double approxRollingAverage (double avg, double new_sample) {
avg -= avg / N;
avg += new_sample / N;
return avg;
}
Where N
is the number of samples where you want to average over.
Note that this approximation is equivalent to an exponential moving average.
See: Calculate rolling / moving average in C++
exp(x) = e^x where e= 2.718281(approx)
import numpy as np
ar=np.array([1,2,3])
ar=np.exp(ar)
print ar
outputs:
[ 2.71828183 7.3890561 20.08553692]
$('input[type="text"]').get().some(item => item.value !== '');
The answer by Kleist certainly works, but there is an important caveat:
When you write a Makefile
manually, you might generate a SRCS
variable using a function to select all .cpp
and .h
files. If a source file is later added, re-running make
will include it.
However, CMake (with a command like file(GLOB ...)
) will explicitly generate a file list and place it in the auto-generated Makefile
. If you have a new source file, you will need to re-generate the Makefile
by re-running cmake
.
edit: No need to remove the Makefile.
Use .children
instead:
from bs4 import NavigableString, Comment
print ''.join(unicode(child) for child in hit.children
if isinstance(child, NavigableString) and not isinstance(child, Comment))
Yes, this is a bit of a dance.
Output:
>>> for hit in soup.findAll(attrs={'class' : 'MYCLASS'}):
... print ''.join(unicode(child) for child in hit.children
... if isinstance(child, NavigableString) and not isinstance(child, Comment))
...
THIS IS MY TEXT
Or you can use the more obvious solution, right in the GUI: Tools -> Messages (set verbosity to 2)...
Are you concerned about the profile picture size? at the time of implementing login with Facebook using PHP. We’ll show you the simple way to get large size profile picture in Facebook PHP SDK. Also, you can get the custom size image of Facebook profile.
Set the profile picture dimension by using the following line of code.
$userProfile = $facebook->api('/me?fields=picture.width(400).height(400)');
check this post:http://www.codexworld.com/how-to-guides/get-large-size-profile-picture-in-facebook-php-sdk/
Typescript from v1.4 has the type
keyword which declares a type alias (analogous to a typedef
in C/C++). You can declare your callback type thus:
type CallbackFunction = () => void;
which declares a function that takes no arguments and returns nothing. A function that takes zero or more arguments of any type and returns nothing would be:
type CallbackFunctionVariadic = (...args: any[]) => void;
Then you can say, for example,
let callback: CallbackFunctionVariadic = function(...args: any[]) {
// do some stuff
};
If you want a function that takes an arbitrary number of arguments and returns anything (including void):
type CallbackFunctionVariadicAnyReturn = (...args: any[]) => any;
You can specify some mandatory arguments and then a set of additional arguments (say a string, a number and then a set of extra args) thus:
type CallbackFunctionSomeVariadic =
(arg1: string, arg2: number, ...args: any[]) => void;
This can be useful for things like EventEmitter handlers.
Functions can be typed as strongly as you like in this fashion, although you can get carried away and run into combinatoric problems if you try to nail everything down with a type alias.
The various Office 2003 XML libraries avaliable work pretty well for smaller excel files. However, I find the sheer size of a large workbook saved in the XML format to be a problem. For example, a workbook I work with that would be 40MB in the new (and admittedly more tightly packed) XLSX format becomes a 360MB XML file.
As far as my research has taken me, there are two commercial packages that allow output to the older binary file formats. They are:
Neither are cheap (500USD and 800USD respectively, I think). but both work independant of Excel itself.
What I would be curious about is the Excel output module for the likes of OpenOffice.org. I wonder if they can be ported from Java to .Net.
OK, this post is a little old, but... if you want to do SQL-like query in native JSON (or JS objects) on JS objects, take a look at https://github.com/deitch/searchjs
It is both a jsql language written entirely in JSON, and a reference implementation. You can say, "I want to find all object in an array that have name==="John" && age===25 as:
{name:"John",age:25,_join:"AND"}
The reference implementation searchjs works in the browser as well as as a node npm package
npm install searchjs
It can also do things like complex joins and negation (NOT). It natively ignores case.
It doesn't yet do summation or count, but it is probably easier to do those outside.
For beginners, the accepted answer is correct, but a little terse if you're not that familiar with either VSC or Regex.
So, in case this is your first contact with either:
To find and modify text,
In the "Find" step, you can use regex with "capturing groups," e.g. I want to find (group1) and (group2)
, using parentheses. This would find the same text as I want to find group1 and group2
, but with the difference that you can then reference group1
and group2
in the next step:
In the "Replace" step, you can refer to the capturing groups via $1
, $2
etc, so you could change the sentence to I found $1 and $2 having a picnic
, which would output I found group1 and group2 having a picnic.
Notes:
Instead of just a string, anything inside or outside the ()
can be a regular expression.
$0
refers to the whole match
Here is an alternative that worked for me:
$('div#somediv').css({'width': '70%'});
If you are using underscorejs I always use
if (!_.isUndefined(data) && !_.isNull(data)) {
//your stuff
}
nasm -f bin -o 2_hello 2_hello.asm
I've coded a simple function which allows to get the absolute location of the current javascript file, by using a try/catch method.
// Get script file location
// doesn't work for older browsers
var getScriptLocation = function() {
var fileName = "fileName";
var stack = "stack";
var stackTrace = "stacktrace";
var loc = null;
var matcher = function(stack, matchedLoc) { return loc = matchedLoc; };
try {
// Invalid code
0();
} catch (ex) {
if(fileName in ex) { // Firefox
loc = ex[fileName];
} else if(stackTrace in ex) { // Opera
ex[stackTrace].replace(/called from line \d+, column \d+ in (.*):/gm, matcher);
} else if(stack in ex) { // WebKit, Blink and IE10
ex[stack].replace(/at.*?\(?(\S+):\d+:\d+\)?$/g, matcher);
}
return loc;
}
};
You can see it here.
This solution is about 3.6× faster than the top rated answer when tested on a file with 13.8 million lines. It simply reads the bytes into a buffer and counts the \n
characters. You could play with the buffer size, but on my machine, anything above 8KB didn't make the code faster.
private int countLines(File file) throws IOException {
int lines = 0;
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[BUFFER_SIZE]; // BUFFER_SIZE = 8 * 1024
int read;
while ((read = fis.read(buffer)) != -1) {
for (int i = 0; i < read; i++) {
if (buffer[i] == '\n') lines++;
}
}
fis.close();
return lines;
}
Simply declare in styles.xml
<style name="AppTheme.Fullscreen" parent="AppTheme">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
Then use in menifest.xml
<activity
android:name=".activities.Splash"
android:theme="@style/AppTheme.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Chill Pill :)
myDate.ToString("yyyy-MM-dd HH:mm:ss")
the capital HH is for 24 hours format as you specified
Use foreach($fields as &$field){
- so you will work with the original array.
Here is more about passing by reference.
You can also use WriteConsole method to print on console.
AllocConsole();
LPSTR lpBuff = "Hello Win32 API";
DWORD dwSize = 0;
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), lpBuff, lstrlen(lpBuff), &dwSize, NULL);
try this for hide autofill style
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:active,
input:-webkit-autofill:focus {
background-color: #FFFFFF !important;
color: #555 !important;
-webkit-box-shadow: 0 0 0 1000px white inset !important;
-webkit-text-fill-color: #555555 !important;
}
Here is the proper documentation for the jQueryUI widget. There isn't a built-in parameter for limiting max results, but you can accomplish it easily:
$("#auto").autocomplete({
source: function(request, response) {
var results = $.ui.autocomplete.filter(myarray, request.term);
response(results.slice(0, 10));
}
});
You can supply a function to the source
parameter and then call slice
on the filtered array.
Here's a working example: http://jsfiddle.net/andrewwhitaker/vqwBP/
Just run the following command from your terminal, it will show you your Loaded Configuration File easiest way I have ever found.
php --ini
There is another way to pass arguments to CreateInstance through named parameters.
Based on that, you can pass a array towards CreateInstance
. This will allow you to have 0 or multiple arguments.
public T CreateInstance<T>(params object[] paramArray)
{
return (T)Activator.CreateInstance(typeof(T), args:paramArray);
}
If you don't want 'a' in the index
In :
col = ['a','b','c']
data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)
data
Out:
a b c
0 1 2 3
1 10 11 12
2 20 21 22
In :
data2 = data.set_index('a')
Out:
b c
a
1 2 3
10 11 12
20 21 22
In :
data2.index.name = None
Out:
b c
1 2 3
10 11 12
20 21 22
Read Byte by Byte and check that each byte against '\n'
if it is not, then store it into buffer
if it is '\n'
add '\0'
to buffer and then use atoi()
You can read a single byte like this
char c;
read(fd,&c,1);
See read()
For Mac Users who using Eclipse Use Cmd + I(Indent) and Cmd + F(Format). But I had worst experience with Cmd + F which breaks the code in to several lines as follows
String A = MyClass.getA(x, y);
if (A != null) {
A = Long.parseLong(0);
}
Where my original code is as follows
String A = MyClass.get(x, y);
if (A != null) {
A = Long.parseLong(0);
}
There are two ways : First : Use a SMS API Gateway which you need to pay for it , maybe you find some trial even free ones but it's scarce . Second : To use AT command with a modem GSM connected to your laptop . that's all
Try this: http://jsfiddle.net/xA5B7/
var MyDate = new Date();
var MyDateString;
MyDate.setDate(MyDate.getDate() + 20);
MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/'
+ ('0' + (MyDate.getMonth()+1)).slice(-2) + '/'
+ MyDate.getFullYear();
EDIT:
To explain, .slice(-2)
gives us the last two characters of the string.
So no matter what, we can add "0"
to the day or month, and just ask for the last two since those are always the two we want.
So if the MyDate.getMonth()
returns 9
, it will be:
("0" + "9") // Giving us "09"
so adding .slice(-2)
on that gives us the last two characters which is:
("0" + "9").slice(-2)
"09"
But if MyDate.getMonth()
returns 10
, it will be:
("0" + "10") // Giving us "010"
so adding .slice(-2)
gives us the last two characters, or:
("0" + "10").slice(-2)
"10"
If all your dates are posterior to the 1st of January of 1970, you could use something like:
$today = date("Y-m-d");
$expire = $row->expireDate; //from database
$today_time = strtotime($today);
$expire_time = strtotime($expire);
if ($expire_time < $today_time) { /* do Something */ }
If you are using PHP 5 >= 5.2.0, you could use the DateTime class:
$today_dt = new DateTime($today);
$expire_dt = new DateTime($expire);
if ($expire_dt < $today_dt) { /* Do something */ }
Or something along these lines.
You can use // MARK:
There has also been discussion that liberal use of class extensions might be a better practice anyway. Since extensions can implement protocols, you can e.g. put all of your table view delegate methods in an extension and group your code at a more semantic level than #pragma mark
is capable of.
Extracted from @Resord's comments above. This one worked for me and more closely inclined with the question.
$(this).parent().closest('.a');
Thanks
If you don't want to modify ansible.cfg
or the playbook.yml
then you can just set an environment variable:
export ANSIBLE_HOST_KEY_CHECKING=False
Yes. There is a method on UIButton -setTitle:forState:
use that.
You can use Runtime.getRuntime().addShutdownHook(...)
, but you cannot be guaranteed that it will be called in any case.
Make sure to target x86 on your project in Visual Studio. This should fix your trouble.
Here is a fast solution of your confusion.
SELECT * FROM table ORDER BY `id` DESC LIMIT N, 1
Here You may get Last row by Filling N=0, Second last by N=1, Fourth Last By Filling N=3 and so on.
This is very common question over the interview and this is Very simple ans of it.
Further If you want Amount, ID or some Numeric Sorting Order than u may go for CAST function in MySQL.
SELECT DISTINCT (`amount`) FROM cart ORDER BY CAST( `amount` AS SIGNED ) DESC LIMIT 4 , 1
Here By filling N = 4 You will be able to get Fifth Last Record of Highest Amount from CART table. You can fit your field and table name and come up with solution.
For the latest Node.js
sudo apt-get install curl
curl -sL https://deb.nodesource.com/setup_13.x | sudo -E bash -
sudo apt-get install nodejs
node -v
npm -v
If precision matters and you require consistent results, here are a few propositions that will return the decimal part of any number as a string, including the leading "0.". If you need it as a float, just add var f = parseFloat( result )
in the end.
If the decimal part equals zero, "0.0" will be returned. Null, NaN and undefined numbers are not tested.
var nstring = (n + ""),
narray = nstring.split("."),
result = "0." + ( narray.length > 1 ? narray[1] : "0" );
var nstring = (n + ""),
nindex = nstring.indexOf("."),
result = "0." + (nindex > -1 ? nstring.substring(nindex + 1) : "0");
var nstring = (n + ""),
nindex = nstring.indexOf("."),
result = ( nindex > -1 ? (n - Math.floor(n)).toFixed(nstring.length - nindex - 1) : "0.0");
var nstring = (n + ""),
narray = nstring.split("."),
result = (narray.length > 1 ? (n - Math.floor(n)).toFixed(narray[1].length) : "0.0");
Here is a jsPerf link: https://jsperf.com/decpart-of-number/
We can see that proposition #2 is the fastest.
In Android Studio, go to your build.gradle (check both project and modules build.gradle files) and search for duplicate dependencies.
Delete those your project does not need.
public static bool CheckFiles(string pathA, string pathB)
{
string[] extantionFormat = new string[] { ".war", ".pkg" };
return CheckFiles(pathA, pathB, extantionFormat);
}
public static bool CheckFiles(string pathA, string pathB, string[] extantionFormat)
{
System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo(pathA);
System.IO.DirectoryInfo dir2 = new System.IO.DirectoryInfo(pathB);
// Take a snapshot of the file system. list1/2 will contain only WAR or PKG
// files
// fileInfosA will contain all of files under path directories
FileInfo[] fileInfosA = dir1.GetFiles("*.*",
System.IO.SearchOption.AllDirectories);
// list will contain all of files that have ..extantion[]
// Run on all extantion in extantion array and compare them by lower case to
// the file item extantion ...
List<System.IO.FileInfo> list1 = (from extItem in extantionFormat
from fileItem in fileInfosA
where extItem.ToLower().Equals
(fileItem.Extension.ToLower())
select fileItem).ToList();
// Take a snapshot of the file system. list1/2 will contain only WAR or
// PKG files
// fileInfosA will contain all of files under path directories
FileInfo[] fileInfosB = dir2.GetFiles("*.*",
System.IO.SearchOption.AllDirectories);
// list will contain all of files that have ..extantion[]
// Run on all extantion in extantion array and compare them by lower case to
// the file item extantion ...
List<System.IO.FileInfo> list2 = (from extItem in extantionFormat
from fileItem in fileInfosB
where extItem.ToLower().Equals
(fileItem.Extension.ToLower())
select fileItem).ToList();
FileCompare myFileCompare = new FileCompare();
// This query determines whether the two folders contain
// identical file lists, based on the custom file comparer
// that is defined in the FileCompare class.
return list1.SequenceEqual(list2, myFileCompare);
}
> grepl("^[^_]+_1",s)
[1] FALSE
> grepl("^[^_]+_2",s)
[1] TRUE
basically, look for everything at the beginning except _
, and then the _2
.
+1 to @Ananda_Mahto for suggesting grepl
instead of grep
.
Off the top of my head:
float fl = 0.678;
int rounded_f = (int)(fl+0.5f);
Just change the version of opencv to 3.4.2.16 .Since it is patented it is not available in newer version.
It should also be noted that you can't override the constructor in the subclass with the constructor of the superclass's name. The rule of OOPS tells that a constructor should have name as its class name. If we try to override the superclass constructor it will be seen as an unknown method without a return type.
I believe that javac behaviour has changed - with 1.5 it prohibited the annotation, with 1.6 it doesn't. The annotation provides an extra compile-time check, so if you're using 1.6 I'd go for it.
//Convert a float to integer_x000D_
_x000D_
Math.floor(5.95)_x000D_
//5_x000D_
_x000D_
Math.ceil(5.95)_x000D_
//6_x000D_
_x000D_
Math.round(5.4)_x000D_
//5_x000D_
_x000D_
Math.round(5.5)_x000D_
//6_x000D_
_x000D_
Math.trunc(5.5)_x000D_
//5_x000D_
_x000D_
//Quick Ways_x000D_
console.log(5.95| 0)_x000D_
console.log(~~5.95) _x000D_
console.log(5.95 >> 0)_x000D_
//5
_x000D_
One more variation. So you get readability and good performace:
NSMutableIndexSet *discardedItems = [NSMutableIndexSet indexSet];
SomeObjectClass *item;
NSUInteger index = 0;
for (item in originalArrayOfItems) {
if ([item shouldBeDiscarded])
[discardedItems addIndex:index];
index++;
}
[originalArrayOfItems removeObjectsAtIndexes:discardedItems];
You can use the existing $filter service. I updated the fiddle above http://jsfiddle.net/gbW8Z/12/
$scope.showdetails = function(fish_id) {
var found = $filter('filter')($scope.fish, {id: fish_id}, true);
if (found.length) {
$scope.selected = JSON.stringify(found[0]);
} else {
$scope.selected = 'Not found';
}
}
Angular documentation is here http://docs.angularjs.org/api/ng.filter:filter
The international versions:
Public Shared Function GetDouble(ByVal doublestring As String) As Double
Dim retval As Double
Dim sep As String = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
Double.TryParse(Replace(Replace(doublestring, ".", sep), ",", sep), retval)
Return retval
End Function
' NULLABLE VERSION:
Public Shared Function GetDoubleNullable(ByVal doublestring As String) As Double?
Dim retval As Double
Dim sep As String = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
If Double.TryParse(Replace(Replace(doublestring, ".", sep), ",", sep), retval) Then
Return retval
Else
Return Nothing
End If
End Function
Results:
' HUNGARIAN REGIONAL SETTINGS (NumberDecimalSeparator: ,)
' Clean Double.TryParse
' -------------------------------------------------
Double.TryParse("1.12", d1) ' Type: DOUBLE Value: d1 = 0.0
Double.TryParse("1,12", d2) ' Type: DOUBLE Value: d2 = 1.12
Double.TryParse("abcd", d3) ' Type: DOUBLE Value: d3 = 0.0
' GetDouble() method
' -------------------------------------------------
d1 = GetDouble("1.12") ' Type: DOUBLE Value: d1 = 1.12
d2 = GetDouble("1,12") ' Type: DOUBLE Value: d2 = 1.12
d3 = GetDouble("abcd") ' Type: DOUBLE Value: d3 = 0.0
' Nullable version - GetDoubleNullable() method
' -------------------------------------------------
d1n = GetDoubleNullable("1.12") ' Type: DOUBLE? Value: d1n = 1.12
d2n = GetDoubleNullable("1,12") ' Type: DOUBLE? Value: d2n = 1.12
d3n = GetDoubleNullable("abcd") ' Type: DOUBLE? Value: d3n = Nothing
I'm sitting at a computer with none of the relevant bits of software, but from memory that code looks wrong. You're executing the command but discarding the RecordSet
that objMyCommand.Execute
returns.
I'd do:
Set objMyRecordset = objMyCommand.Execute
...and then lose the "open recordset" part.
Make sure "Use: Regular expressions" is selected in the Find and Replace dialog:
Note that for Visual Studio 2010, this doesn't work in the Visual Studio Productivity Power Tools' "Quick Find" extension (as of the July 2011 update); instead, you'll need to use the full Find and Replace dialog (use Ctrl+Shift+H, or Edit --> Find and Replace --> Replace in Files), and change the scope to "Current Document".
Rather than throwing code at you, there are 2 concepts that are key to understanding how JS handles callbacks and asynchronicity. (is that even a word?)
There are three things you need to be aware of; The queue; the event loop and the stack
In broad, simplistic terms, the event loop is like the project manager, it is constantly listening for any functions that want to run and communicates between the queue and the stack.
while (queue.waitForMessage()) {
queue.processNextMessage();
}
Once it receives a message to run something it adds it to the queue. The queue is the list of things that are waiting to execute (like your AJAX request). imagine it like this:
1. call foo.com/api/bar using foobarFunc
2. Go perform an infinite loop
... and so on
When one of these messages is going to execute it pops the message from the queue and creates a stack, the stack is everything JS needs to execute to perform the instruction in the message. So in our example it's being told to call foobarFunc
function foobarFunc (var) {
console.log(anotherFunction(var));
}
So anything that foobarFunc needs to execute (in our case anotherFunction
) will get pushed onto the stack. executed, and then forgotten about - the event loop will then move onto the next thing in the queue (or listen for messages)
The key thing here is the order of execution. That is
When you make a call using AJAX to an external party or run any asynchronous code (a setTimeout for example), Javascript is dependant upon a response before it can proceed.
The big question is when will it get the response? The answer is we don't know - so the event loop is waiting for that message to say "hey run me". If JS just waited around for that message synchronously your app would freeze and it will suck. So JS carries on executing the next item in the queue whilst waiting for the message to get added back to the queue.
That's why with asynchronous functionality we use things called callbacks. - A function or handler that, when passed into another function, will be executed at a later date. A promise uses callbacks (functions passed to .then()
for eg.) as a way to reason about this asynchronous behaviour in a more linear way. The promise is a way of saying "I promise to return something at some point" and the callback is how we handle that value that is eventually returned. jQuery uses specific callbacks called deffered.done
deffered.fail
and deffered.always
(amongst others). You can see them all here
So what you need to do is pass a function that is promised to execute at some point with data that is passed to it.
Because a callback is not executed immediately but at a later time it's important to pass the reference to the function not it executed. so
function foo(bla) {
console.log(bla)
}
so most of the time (but not always) you'll pass foo
not foo()
Hopefully that will make some sense. When you encounter things like this that seem confusing - i highly recommend reading the documentation fully to at least get an understanding of it. It will make you a much better developer.
Your program should work exactly the same with either import java.util.*; or import java.util.Date;. There has to be something else you did in between.
Change MySQL character:
default-character-set=utf8
character_set_server=utf8
We should not write default-character-set=utf8
in mysqld, because that could result in an error like:
start: Job failed to start
At last:
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
C is statically typed language. You can't declare a function which operate on type A or type B, and you can't declare variable which hold type A or type B. Every variable has an explicitly declared and unchangeable type, and you supposed to use this knowledge.
And when you want to know if void * points to memory representation of float or integer - you have to store this information somewhere else. The language is specifically designed not to care if char * points to something stored as int or char.
var todayDate = moment().format('DD-MM-YYYY');//to get today date 06/03/2018 if you want to add extra day to your current date
then var dueDate = moment().add(15,'days').format('DD-MM-YYYY')// to add 15 days to current date..
point 2 and 3 are using in your jquery code...
If you're using a relatively new version of Python, you can also use a context manager, such as this one:
from __future__ import with_statement
from grizzled.os import working_directory
with working_directory(path_to_directory):
# code in here occurs within the directory
# code here is in the original directory
UPDATE
If you prefer to roll your own:
import os
from contextlib import contextmanager
@contextmanager
def working_directory(directory):
owd = os.getcwd()
try:
os.chdir(directory)
yield directory
finally:
os.chdir(owd)
the mobile solution suggested by Sumit works perfectly for AS3 Air:
html.location = "http://m.facebook.com/logout.php?confirm=1&next=http://yoursitename.com"
It's used to add padding in UIScrollView
Without contentInset
, a table view is like this:
Then set contentInset
:
tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
The effect is as below:
Seems to be better, right?
And I write a blog to study the contentInset
, criticism is welcome.
It is really simple, there are just some syntax you have to keep in mind.
Arrays.sort(contests, (a, b) -> Integer.compare(a[0],b[0]));//increasing order ---1
Arrays.sort(contests, (b, a) -> Integer.compare(b[0],a[0]));//increasing order ---2
Arrays.sort(contests, (a, b) -> Integer.compare(b[0],a[0]));//decreasing order ---3
Arrays.sort(contests, (b, a) -> Integer.compare(a[0],b[0]));//decreasing order ---4
If you notice carefully, then it's the change in the order of 'a' and 'b' that affects the result. For line 1, the set is of (a,b) and Integer.compare(a[0],b[0]), so it is increasing order. Now if we change the order of a and b in any one of them, suppose the set of (a,b) and Integer.compare(b[0],a[0]) as in line 3, we get decreasing order.
Use:
private void TimeFormats()
{
DateTime localTime = DateTime.Now;
DateTime utcTime = DateTime.UtcNow;
DateTimeOffset localTimeAndOffset = new DateTimeOffset(localTime, TimeZoneInfo.Local.GetUtcOffset(localTime));
//UTC
string strUtcTime_o = utcTime.ToString("o");
string strUtcTime_s = utcTime.ToString("s");
string strUtcTime_custom = utcTime.ToString("yyyy-MM-ddTHH:mm:ssK");
//Local
string strLocalTimeAndOffset_o = localTimeAndOffset.ToString("o");
string strLocalTimeAndOffset_s = localTimeAndOffset.ToString("s");
string strLocalTimeAndOffset_custom = utcTime.ToString("yyyy-MM-ddTHH:mm:ssK");
//Output
Response.Write("<br/>UTC<br/>");
Response.Write("strUtcTime_o: " + strUtcTime_o + "<br/>");
Response.Write("strUtcTime_s: " + strUtcTime_s + "<br/>");
Response.Write("strUtcTime_custom: " + strUtcTime_custom + "<br/>");
Response.Write("<br/>Local Time<br/>");
Response.Write("strLocalTimeAndOffset_o: " + strLocalTimeAndOffset_o + "<br/>");
Response.Write("strLocalTimeAndOffset_s: " + strLocalTimeAndOffset_s + "<br/>");
Response.Write("strLocalTimeAndOffset_custom: " + strLocalTimeAndOffset_custom + "<br/>");
}
UTC
strUtcTime_o: 2012-09-17T22:02:51.4021600Z
strUtcTime_s: 2012-09-17T22:02:51
strUtcTime_custom: 2012-09-17T22:02:51Z
Local Time
strLocalTimeAndOffset_o: 2012-09-17T15:02:51.4021600-07:00
strLocalTimeAndOffset_s: 2012-09-17T15:02:51
strLocalTimeAndOffset_custom: 2012-09-17T22:02:51Z
They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.
File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish
But if you do not have samples loaded, then download it using the below steps
Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install
Our computer science professor urged us to never use inline in a c++ program. When asked why, he kindly explained to us that modern compilers should detect when to use inline automatically.
So yes, the inline can be an optimization technique to be used wherever possible, but apparently this is something that is already done for you whenever it's possible to inline a function anyways.
I made another variant with dropdown menu (perhaps for advanced search etc).. Here is how it looks like:
<div class="input-group my-4 col-6 mx-auto">
<input class="form-control py-2 border-right-0 border" type="search" placeholder="Type something..." id="example-search-input">
<span class="input-group-append">
<button type="button" class="btn btn-outline-primary dropdown-toggle dropdown-toggle-split border border-left-0 border-right-0 rounded-0" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="sr-only">Toggle Dropdown</span>
</button>
<button class="btn btn-outline-primary rounded-right" type="button">
<i class="fas fa-search"></i>
</button>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
<div role="separator" class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Separated link</a>
</div>
</span>
</div>
Note: It appears green in the screenshot because my site main theme is green.
Relative paths can be best understood if you know how Java runs the program.
There is a concept of working directory when running programs in Java. Assuming you have a class, say, FileHelper
that does the IO under
/User/home/Desktop/projectRoot/src/topLevelPackage/
.
Depending on the case where you invoke java
to run the program, you will have different working directory. If you run your program from within and IDE, it will most probably be projectRoot
.
In this case $ projectRoot/src : java topLevelPackage.FileHelper
it will be src
.
In this case $ projectRoot : java -cp src topLevelPackage.FileHelper
it will be projectRoot
.
In this case $ /User/home/Desktop : java -cp ./projectRoot/src topLevelPackage.FileHelper
it will be Desktop
.
(Assuming $ is your command prompt with standard Unix-like FileSystem. Similar correspondence/parallels with Windows system)
So, your relative path root (.)
resolves to your working directory. Thus to be better sure of where to write files, it's said to consider below approach.
package topLevelPackage
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileHelper {
// Not full implementation, just barebone stub for path
public void createLocalFile() {
// Explicitly get hold of working directory
String workingDir = System.getProperty("user.dir");
Path filePath = Paths.get(workingDir+File.separator+"sampleFile.txt");
// In case we need specific path, traverse that path, rather using . or ..
Path pathToProjectRoot = Paths.get(System.getProperty("user.home"), "Desktop", "projectRoot");
System.out.println(filePath);
System.out.println(pathToProjectRoot);
}
}
Hope this helps.
Aus_lacy's post gave me the idea of trying related methods, of which join does work:
In [196]:
hl.name = 'hl'
Out[196]:
'hl'
In [199]:
df.join(hl).head(4)
Out[199]:
high low loc_h loc_l hl
2014-01-01 17:00:00 1.376235 1.375945 1.376235 1.375945 1.376090
2014-01-01 17:01:00 1.376005 1.375775 NaN NaN NaN
2014-01-01 17:02:00 1.375795 1.375445 NaN 1.375445 1.375445
2014-01-01 17:03:00 1.375625 1.375515 NaN NaN NaN
Some insight into why concat works on the example but not this data would be nice though!
For me on Macbook Book Pro 2019 MacOS version 10.15.6, shortcut to open command palette in VSCode was Shift
+ Command
+ P
.
On opening it one has to just write install code
and press enter
.
After that just open the terminal and type code
your vscode will start opening.
var elm = document.createElement("div");
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element
Steve's solution does not work. When calling this.Close(), current form is disposed together with form2. Therefore you need to hide it and set form2.Closed event to call this.Close().
private void OnButton1Click(object sender, EventArgs e)
{
this.Hide();
var form2 = new Form2();
form2.Closed += (s, args) => this.Close();
form2.Show();
}
You can use this:
$this->db->last_query();
"Returns the last query that was run (the query string, not the result)."
Reff: https://www.codeigniter.com/userguide3/database/helpers.html
Under the conditions stipulated in the question:
git init
,git add
operations,git commit
,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.
Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?
Currently it only works for the .dropdown-menu
:
.dropdown-menu .divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
If you want it for other use, in your own css, following the bootstrap.css create another one:
.divider {
height: 1px;
width:100%;
display:block; /* for use on default inline elements like span */
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
There is a dedicated npm
package for it. css-scrollbar-side
Here is a jQuery plugin that does exactly that: http://fixedheadertable.com/
Usage:
$('selector').fixedHeaderTable({ fixedColumn: 1 });
Set the fixedColumn
option if you want any number of columns to be also fixed for horizontal scrolling.
EDIT: This example http://www.datatables.net/examples/basic_init/scroll_y.html is much better in my opinion, although with DataTables you'll need to get a better understanding of how it works in general.
EDIT2: For Bootstrap to work with DataTables you need to follow the instructions here: http://datatables.net/blog/Twitter_Bootstrap_2 (I have tested this and it works)- For Bootstrap 3 there's a discussion here: http://datatables.net/forums/discussion/comment/53462 - (I haven't tested this)
After seeing CLIFFORD's answer to see the error, what helped me to solve this issue was renaming 'android:namex' to 'android:name' in the intent-filter action tag. In case if the same solution helps someone else .
<activity android:name=".MainActivity">
<intent-filter>
<action android:namex="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Map.of
literalsAs of Java 9, there is yet another way to instantiate a Map
. You can create an unmodifiable map from zero, one, or several pairs of objects in a single-line of code. This is quite convenient in many situations.
For an empty Map
that cannot be modified, call Map.of()
. Why would you want an empty set that cannot be changed? One common case is to avoid returning a NULL where you have no valid content.
For a single key-value pair, call Map.of( myKey , myValue )
. For example, Map.of( "favorite_color" , "purple" )
.
For multiple key-value pairs, use a series of key-value pairs. ``Map.of( "favorite_foreground_color" , "purple" , "favorite_background_color" , "cream" )`.
If those pairs are difficult to read, you may want to use Map.of
and pass Map.Entry
objects.
Note that we get back an object of the Map
interface. We do not know the underlying concrete class used to make our object. Indeed, the Java team is free to used different concrete classes for different data, or to vary the class in future releases of Java.
The rules discussed in other Answers still apply here, with regard to type-safety. You declare your intended types, and your passed objects must comply. If you want values of various types, use Object
.
Map< String , Color > preferences = Map.of( "favorite_color" , Color.BLUE ) ;
Simple, you just open klik file -> import -> General -> existing project into workspace -> browse file in your directory.
(I'am used Eclipse Mars)
Based on @ArchCodeMonkey answer.
If you have declare(strict_types=1)
you must cast second argument to string
Here's a c# implementation for windows based on Christopher Oezbek's answer
It was made more complex by the containsFolder boolean, but hopefully covers everything
/// <summary>
/// This will replace invalid chars with underscores, there are also some reserved words that it adds underscore to
/// </summary>
/// <remarks>
/// https://stackoverflow.com/questions/1976007/what-characters-are-forbidden-in-windows-and-linux-directory-names
/// </remarks>
/// <param name="containsFolder">Pass in true if filename represents a folder\file (passing true will allow slash)</param>
public static string EscapeFilename_Windows(string filename, bool containsFolder = false)
{
StringBuilder builder = new StringBuilder(filename.Length + 12);
int index = 0;
// Allow colon if it's part of the drive letter
if (containsFolder)
{
Match match = Regex.Match(filename, @"^\s*[A-Z]:\\", RegexOptions.IgnoreCase);
if (match.Success)
{
builder.Append(match.Value);
index = match.Length;
}
}
// Character substitutions
for (int cntr = index; cntr < filename.Length; cntr++)
{
char c = filename[cntr];
switch (c)
{
case '\u0000':
case '\u0001':
case '\u0002':
case '\u0003':
case '\u0004':
case '\u0005':
case '\u0006':
case '\u0007':
case '\u0008':
case '\u0009':
case '\u000A':
case '\u000B':
case '\u000C':
case '\u000D':
case '\u000E':
case '\u000F':
case '\u0010':
case '\u0011':
case '\u0012':
case '\u0013':
case '\u0014':
case '\u0015':
case '\u0016':
case '\u0017':
case '\u0018':
case '\u0019':
case '\u001A':
case '\u001B':
case '\u001C':
case '\u001D':
case '\u001E':
case '\u001F':
case '<':
case '>':
case ':':
case '"':
case '/':
case '|':
case '?':
case '*':
builder.Append('_');
break;
case '\\':
builder.Append(containsFolder ? c : '_');
break;
default:
builder.Append(c);
break;
}
}
string built = builder.ToString();
if (built == "")
{
return "_";
}
if (built.EndsWith(" ") || built.EndsWith("."))
{
built = built.Substring(0, built.Length - 1) + "_";
}
// These are reserved names, in either the folder or file name, but they are fine if following a dot
// CON, PRN, AUX, NUL, COM0 .. COM9, LPT0 .. LPT9
builder = new StringBuilder(built.Length + 12);
index = 0;
foreach (Match match in Regex.Matches(built, @"(^|\\)\s*(?<bad>CON|PRN|AUX|NUL|COM\d|LPT\d)\s*(\.|\\|$)", RegexOptions.IgnoreCase))
{
Group group = match.Groups["bad"];
if (group.Index > index)
{
builder.Append(built.Substring(index, match.Index - index + 1));
}
builder.Append(group.Value);
builder.Append("_"); // putting an underscore after this keyword is enough to make it acceptable
index = group.Index + group.Length;
}
if (index == 0)
{
return built;
}
if (index < built.Length - 1)
{
builder.Append(built.Substring(index));
}
return builder.ToString();
}
You can pass values from one activity to another activity using the Bundle. In your current activity, create a bundle and set the bundle for the particular value and pass that bundle to the intent.
Intent intent = new Intent(this,NewActivity.class);
Bundle bundle = new Bundle();
bundle.putString(key,value);
intent.putExtras(bundle);
startActivity(intent);
Now in your NewActivity, you can get this bundle and retrive your value.
Bundle bundle = getArguments();
String value = bundle.getString(key);
You can also pass data through the intent. In your current activity, set intent like this,
Intent intent = new Intent(this,NewActivity.class);
intent.putExtra(key,value);
startActivity(intent);
Now in your NewActivity, you can get that value from intent like this,
String value = getIntent().getExtras().getString(key);
You are using a pathname separator which is platform dependent. Windows uses "\" and Unix uses "/".
I am using an ashx file in an MVC application and none of the above answers worked for me. IIS 10.
Here's what did work. Instead of changing "ExtensionlessUrl-Integrated-4.0" in IIS or web.config I changed "SimpleHandlerFactory-Integrated-4.0" for "*.ashx" files:
<add name="SimpleHandlerFactory-Integrated-4.0" path="*.ashx"
verb="GET,HEAD,POST,DEBUG,PUT,DELETE"
type="System.Web.UI.SimpleHandlerFactory"
resourceType="Unspecified" requireAccess="Script"
preCondition="integratedMode,runtimeVersionv4.0" />
You need to add this code in your AppDelegate file, not in your Root View Controller
Or add the property Status bar is initially hidden in your plist file
Folks, in iOS 7+
please add this to your info.plist file, It will make the difference :)
UIStatusBarHidden UIViewControllerBasedStatusBarAppearance
For iOS 11.4+ and Xcode 9.4 +
Use this code either in one or all your view controllers
override var prefersStatusBarHidden: Bool { return true }
Only call time pass-by-reference is removed. So change:
call_user_func($func, &$this, &$client ...
To this:
call_user_func($func, $this, $client ...
&$this
should never be needed after PHP4 anyway period.
If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {
)
Have a look at this Everything You Need to Know About HTML5 Video and Audio post at the Opera Dev site under the "I want to roll my own controls" section.
This is the pertinent section:
<video src="video.ogv">
video not supported
</video>
then you can use:
<script>
var video = document.getElementsByTagName('video')[0];
video.onended = function(e) {
/*Do things here!*/
};
</script>
onended
is a HTML5 standard event on all media elements, see the HTML5 media element (video/audio) events documentation.
var result = priceLog.GroupBy(s => s.LogDateTime.ToString("MMM yyyy")).Select(grp => new PriceLog() { LogDateTime = Convert.ToDateTime(grp.Key), Price = (int)grp.Average(p => p.Price) }).ToList();
I have converted it to int because my Price field was int and Average method return double .I hope this will help
If you are looking to just repopulate the fields with the values that were posted in them, then just echo the post value back into the field, like so:
<input type="text" name="myField1" value="<?php echo isset($_POST['myField1']) ? $_POST['myField1'] : '' ?>" />
Don't know men. I found the best way for me after testing different ways like 10 minutes. ( Change the numbers in code to get big or small random number.)
int x;
srand ( time(NULL) );
x = rand() % 1000 * rand() % 10000 ;
cout<<x;
<button my-directive="push">Push to Go</button>
app.directive("myDirective", function() {
return {
restrict : "A",
link: function(scope, elm, attrs) {
elm.bind('click', function(event) {
alert("You pressed button: " + event.target.getAttribute('my-directive'));
});
}
};
});
here is what I did
I'm using directive as html attribute and I passed parameter as following in my HTML file. my-directive="push"
And from the directive I retrieved it from the Mouse-click event object. event.target.getAttribute('my-directive')
.
$("#yourbuttonid").click(function(){ document.location = "<%= Url.Action("Youraction") %>";})
use a HEREDOC, which eliminates any need to swap quote types and/or escape them:
echo <<<EOL
<script>$('#edit_errors').html('<h3><em><font color="red">Please Correct Errors Before Proceeding</font></em></h3>')</script>
EOL;
strconv.Itoa(int(time.Now().Unix()))
Use the menu selection Navigate -> Test, or Ctrl+Shift+T (Shift+?+T on Mac). This will go to the existing test class, or offer to generate it for you through a little wizard.
You can use String formatting for the double type. Here is an example:
double val = 58.6547;
String.Format("{0:0.##}", val);
//Output: "58.65"
double val = 58.6;
String.Format("{0:0.##}", val);
//Output: "58.6"
double val = 58.0;
String.Format("{0:0.##}", val);
//Output: "58"
Let me know if this doesn't help.
Here this should help you
The below jsfiddle link will help you understand how to rotate a image.I used the same one to rotate the dial of a clock.
var rotation = function (){
$("#image").rotate({
angle:0,
animateTo:360,
callback: rotation,
easing: function (x,t,b,c,d){
return c*(t/d)+b;
}
});
}
rotation();
Where: • t: current time,
• b: begInnIng value,
• c: change In value,
• d: duration,
• x: unused
No easing (linear easing): function(x, t, b, c, d) { return b+(t/d)*c ; }
You don't need an array to do it.
var ItemNode = this.state.data.map(function(itemData) {
return (
<ComponentName title={itemData.title} key={itemData.id} number={itemData.id}/>
);
});
Putting this http://www.mredkj.com/javascript/numberFormat.html and $('.number').formatNumber();
concept together, you may use the following line of code;
e.g. <td class="number">1172907.50</td>
will be formatted like <td class="number">1,172,907.50</td>
$('.number').text(function () {
var str = $(this).html() + '';
x = str.split('.');
x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
$(this).html(x1 + x2);
});
Brendon Crawford had the best answer here (in comment), so I'll move it to an answer until he does (and maybe expand a little).
var offset = $('#whatever').offset();
offset.right = $(window).width() - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = $(window).height() - (offset.top + $('#whatever').outerHeight(true));
For Facebook page:
try {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/" + pageId));
} catch (Exception e) {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + pageId));
}
For Facebook profile:
try {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("fb://profile/" + profileId));
} catch (Exception e) {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/" + profileId));
}
...because none of the answers points out the difference
Both tested with Facebook v.27.0.0.24.15 and Android 5.0.1 on Nexus 4
This question is old and Carlos Rojas's answer is good, but I think I should post few things which should be kept in mind while trying to open the ports.
The first thing to remember is that Networking section is renamed to VPC Networking. So if you're trying to find out where Firewall Rules option is available, go look at VPC Networking.
The second thing is, if you're trying to open ports on a Linux VM, make sure under no circumstances should you try to open port using ufw
command. I tried using that and lost ssh access to the VM. So don't repeat my mistake.
The third thing is, if you're trying to open ports on a Windows VM, you'll need to create Firewall rules inside the VM also in Windows Firewall along with VPC Networking -> Firewall Rules. The port needs to be opened in both firewall rules, unlike Linux VM. So if you're not getting access to the port from outside the VM, check if you've opened the port in both GCP console and Windows Firewall.
The last (obvious) thing is, do not open ports unnecessarily. Close the ports, as soon as you no longer need it.
I hope this answer is useful.
Another possible solution with JS
function onSelect(e) {
if (e.files.length > 5) {
alert("Only 5 files accepted.");
e.preventDefault();
}
}
If you are doing this in a browser, you can capture keyboard events.
Can all be listened to on HTML nodes in most browsers.
Webkit also supports...
See for more details .. http://unixpapa.com/js/key.html
The underscore usually means a C module (i.e. DLL), and Python can't find it. Did you build python yourself? If so, you need to include SSL support.
Simple solution by Underscore.js
For example: Get all links text who's parents have class someClass
_.pluck($('.someClass').find('a'), 'text');
This gets part way there. There is no ActualFontSize property but there is an ActualHeight and that would relate to the FontSize. Right now this only sizes for the original render. I could not figure out how to register the Converter as resize event. Actually maybe need to register the FontSize as a resize event. Please don't mark me down for an incomplete answer. I could not put code sample in a comment.
<Window.Resources>
<local:WidthConverter x:Key="widthConverter"/>
</Window.Resources>
<Grid>
<Grid>
<StackPanel VerticalAlignment="Center" Orientation="Vertical" >
<Viewbox Margin="100,0,100,0">
<TextBlock x:Name="headerText" Text="Lorem ipsum dolor" Foreground="Black"/>
</Viewbox>
<TextBlock Margin="150,0,150,0" FontSize="{Binding ElementName=headerText, Path=ActualHeight, Converter={StaticResource widthConverter}}" x:Name="subHeaderText" Text="Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, " TextWrapping="Wrap" Foreground="Gray" />
</StackPanel>
</Grid>
</Grid>
Converter
[ValueConversion(typeof(double), typeof(double))]
public class WidthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double width = (double)value*.7;
return width; // columnsCount;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Bootstrap versions before 4 and 5 do not define ml
, mr
, pl
, and pr
.
Bootstrap versions 4 and 5 define the classes of ml
, mr
, pl
, and pr
.
For example:
mr--1
ml--1
pr--1
pl--1
Building on rq's answer, I found this line does what I want:
git grep "search for something" $(git log -g --pretty=format:%h -S"search for something")
Which will report the commit ID, filename, and display the matching line, like this:
91ba969:testFile:this is a test
... Does anyone agree that this would be a nice option to be included in the standard git grep command?
When I set up a new service project a few weeks ago I found this post. While there are many great suggestions, I still didn't find the solution I wanted: The possibility to call the service classes' OnStart
and OnStop
methods without any modification to the service classes.
The solution I came up with uses the Environment.Interactive
the select running mode, as suggested by other answers to this post.
static void Main()
{
ServiceBase[] servicesToRun;
servicesToRun = new ServiceBase[]
{
new MyService()
};
if (Environment.UserInteractive)
{
RunInteractive(servicesToRun);
}
else
{
ServiceBase.Run(servicesToRun);
}
}
The RunInteractive
helper uses reflection to call the protected OnStart
and OnStop
methods:
static void RunInteractive(ServiceBase[] servicesToRun)
{
Console.WriteLine("Services running in interactive mode.");
Console.WriteLine();
MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart",
BindingFlags.Instance | BindingFlags.NonPublic);
foreach (ServiceBase service in servicesToRun)
{
Console.Write("Starting {0}...", service.ServiceName);
onStartMethod.Invoke(service, new object[] { new string[] { } });
Console.Write("Started");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(
"Press any key to stop the services and end the process...");
Console.ReadKey();
Console.WriteLine();
MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop",
BindingFlags.Instance | BindingFlags.NonPublic);
foreach (ServiceBase service in servicesToRun)
{
Console.Write("Stopping {0}...", service.ServiceName);
onStopMethod.Invoke(service, null);
Console.WriteLine("Stopped");
}
Console.WriteLine("All services stopped.");
// Keep the console alive for a second to allow the user to see the message.
Thread.Sleep(1000);
}
This is all the code required, but I also wrote walkthrough with explanations.
I guess your code relates to Windows Forms.
You call BeginInvoke
if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases.
Roughly speaking this is accomplished be passing the delegate to some procedure which is being periodically executed. (message loop processing and the stuff like that)
If BeginInvoke
is called for Delegate
type the delegate is just invoked asynchronously.
(Invoke
for the sync version.)
If you want more universal code which works perfectly for WPF and WinForms you can consider Task Parallel Library and running the Task
with the according context. (TaskScheduler.FromCurrentSynchronizationContext()
)
And to add a little to already said by others:
Lambdas can be treated either as anonymous methods or expressions.
And that is why you cannot just use var
with lambdas: compiler needs a hint.
UPDATE:
this requires .Net v4.0 and higher
// This line must be called in UI thread to get correct scheduler
var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();
// this can be called anywhere
var task = new System.Threading.Tasks.Task( () => someformobj.listBox1.SelectedIndex = 0);
// also can be called anywhere. Task will be scheduled for execution.
// And *IF I'm not mistaken* can be (or even will be executed synchronously)
// if this call is made from GUI thread. (to be checked)
task.Start(scheduler);
If you started the task from other thread and need to wait for its completition task.Wait()
will block calling thread till the end of the task.
Read more about tasks here.
I would definitely split them. It would be easy to sort the numbers by area code and contry code. But even if you're not going to split, just insert the numbers into the DB in one certain format. e.g. 1-555-555-1212 Your client side will be thankfull for not making it reformat your numbers.
If you want to overwrite any css in bootstrap use !important
Let's say here is the page header class in bootstrap which have 40px margin on top, my client don't like it and he want it to be 15 on top and 10 on bottom only
.page-header {
border-bottom: 1px solid #EEEEEE;
margin: 40px 0 20px;
padding-bottom: 9px;
}
So I added on class in my site.css file with the same name like this
.page-header
{
padding-bottom: 9px;
margin: 15px 0 10px 0px !important;
}
Note the !important with my margin, which will overwrite the margin of bootstarp page-header class margin.
When I run in a similar issue, in Vs 2012, it turned out that the "Custom Tool Namespace" property of the resx file was wrong (in my case, actually, it was unset, so the generated code yeld this exception at runtime). My final set of properties for the resx file was something like this:
on Mac, how I usually solve it
Hope this helps OP or someone else reading
Create a class Extends Application
and create a static method.
Then you can call this method in all activities before setContentView()
.
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
}
public static void setLocaleFa (Context context){
Locale locale = new Locale("fa");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getApplicationContext().getResources().updateConfiguration(config, null);
}
public static void setLocaleEn (Context context){
Locale locale = new Locale("en_US");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getApplicationContext().getResources().updateConfiguration(config, null);
}
}
Usage in activities:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApp.setLocaleFa(MainActivity.this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
}
open windows powershell, run as administrater and SetExecution policy as Unrestricted then it will work.
(SELECT CASE WHEN (SELECT Salary FROM tbl_Salary WHERE Code=102 AND Month=1 AND Year=2020 )=0 THEN 'Pending'
WHEN (SELECT Salary FROM tbl_Salary WHERE Code=102 AND Month=1 AND Year=2020 AND )<>0 THEN (SELECT CASE WHEN ISNULL(ChequeNo,0) IS NOT NULL THEN 'Deposit' ELSE 'Pending' END AS Deposite FROM tbl_EEsi WHERE AND (Month= 1) AND (Year = 2020) AND )END AS Stat)
Instead of using config files you can use a configuration database with a scoped systemConfig table and add all your settings there.
CREATE TABLE [dbo].[SystemConfig]
(
[Id] [int] IDENTITY(1, 1)
NOT NULL ,
[AppName] [varchar](128) NULL ,
[ScopeName] [varchar](128) NOT NULL ,
[Key] [varchar](256) NOT NULL ,
[Value] [varchar](MAX) NOT NULL ,
CONSTRAINT [PK_SystemConfig_ID] PRIMARY KEY NONCLUSTERED ( [Id] ASC )
WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]
)
ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[SystemConfig] ADD CONSTRAINT [DF_SystemConfig_ScopeName] DEFAULT ('SystemConfig') FOR [ScopeName]
GO
With such configuration table you can create rows like such:
Then from your your application dal(s) wrapping EF you can easily retrieve the scoped configuration.
If you are not using dal(s) and working in the wire directly with EF, you can make an Entity from the SystemConfig table and use the value depending on the application you are on.
Perhaps a use might be:
#debug = []
def debuglog(text, obj=None):
" Simple little logger. "
try:
debug # does global exist?
except NameError:
pass # if not, don't even bother displaying
except:
print('Unknown cause. Debug debuglog().')
else:
# debug does exist.
# Now test if you want to log this debug message
# from caller "obj"
try:
if obj in debug:
print(text) # stdout
except TypeError:
print('The global "debug" flag should be an iterable.')
except:
print('Unknown cause. Debug debuglog().')
def myfunc():
debuglog('Made it to myfunc()', myfunc)
debug = [myfunc,]
myfunc()
Maybe this will lead you too a use.
A few people actually missed a very important point - 'throw' and 'throw ex' may do the same thing but they don't give you a crucial piece of imformation which is the line where the exception happened.
Consider the following code:
static void Main(string[] args)
{
try
{
TestMe();
}
catch (Exception ex)
{
string ss = ex.ToString();
}
}
static void TestMe()
{
try
{
//here's some code that will generate an exception - line #17
}
catch (Exception ex)
{
//throw new ApplicationException(ex.ToString());
throw ex; // line# 22
}
}
When you do either a 'throw' or 'throw ex' you get the stack trace but the line# is going to be #22 so you can't figure out which line exactly was throwing the exception (unless you have only 1 or few lines of code in the try block). To get the expected line #17 in your exception you'll have to throw a new exception with the original exception stack trace.
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);
}
Use Constructors.
<?php
class TestClass
{
public $testVar = "default value";
public function __construct($varValue)
{
$this->testVar = $varValue;
}
}
$object = new TestClass('another value');
print $object->testVar;
?>
You may also be able to use the Duration
class. E.g.
Date currentDate = new Date();
Date oneDayFromCurrentDate = new Date(currentDate.getTime() - Duration.ofDays(1).toMillis());
from django.utils.datastructures import SortedDict
def sortedDictByKey(self,data):
"""Sorted dictionary order by key"""
sortedDict = SortedDict()
if data:
if isinstance(data, dict):
sortedKey = sorted(data.keys())
for k in sortedKey:
sortedDict[k] = data[k]
return sortedDict
try this:
ComboBox cbx = new ComboBox();
cbx.DisplayMember = "Text";
cbx.ValueMember = "Value";
EDIT (a little explanation, sory, I also didn't notice your combobox wasn't bound, I blame the lack of caffeine):
The difference between SelectedValue and SelectedItem are explained pretty well here: ComboBox SelectedItem vs SelectedValue
So, if your combobox is not bound to datasource, DisplayMember and ValueMember doesn't do anything, and SelectedValue will always be null, SelectedValueChanged won't be called. So either bind your combobox:
comboBox1.DisplayMember = "Text";
comboBox1.ValueMember = "Value";
List<ComboboxItem> list = new List<ComboboxItem>();
ComboboxItem item = new ComboboxItem();
item.Text = "choose a server...";
item.Value = "-1";
list.Add(item);
item = new ComboboxItem();
item.Text = "S1";
item.Value = "1";
list.Add(item);
item = new ComboboxItem();
item.Text = "S2";
item.Value = "2";
list.Add(item);
cbx.DataSource = list; // bind combobox to a datasource
or use SelectedItem property:
if (cbx.SelectedItem != null)
Console.WriteLine("ITEM: "+comboBox1.SelectedItem.ToString());
To create within a function (for repeat usage) and dynamical limited length, use:
function string_length_cutoff($string, $limit, $subtext = '...')
{
return (strlen($string) > $limit) ? substr($string, 0, ($limit-strlen(subtext))).$subtext : $string;
}
// example usage:
echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26);
// or (for custom substitution text
echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26, '..');
I have overcome this problem by changing the device screen size.
I have found that if you are specifying 1024 mb ram then you have to specify the device screen size in hdpi only and if it is 512 mb ram then it should be mdpi or others.
So, We can clearly say that ram size should be specify according to the screen size . If you are specifying the 1024 ram size while keeping the device screen size in mdpi then it results in the above mentioned error i.e "Failed to allocate memory: 8 This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information."
or
make your options in AVD manager as follows:
[2013-01-11 14:44:01 - SDK Manager] hw.sensors.orientation=yes
[2013-01-11 14:44:01 - SDK Manager] hw.camera.front=none
[2013-01-11 14:44:01 - SDK Manager] hw.gps=yes
[2013-01-11 14:44:01 - SDK Manager] skin.dynamic=no
[2013-01-11 14:44:01 - SDK Manager] hw.keyboard=no
[2013-01-11 14:44:01 - SDK Manager] vm.heapSize=32
[2013-01-11 14:44:01 - SDK Manager] hw.ramSize=343
'-----Implementation of VB6 App object in VBScript-----
Class clsApplication
Property Get Path()
Dim sTmp
If IsObject(Server) Then
'Classic ASP
Path = Server.MapPath("../")
ElseIf IsObject(WScript) Then
'Windows Scripting Host
Path = Left(WScript.ScriptFullName, InStr(WScript.ScriptFullName, WScript.ScriptName) - 2)
ElseIf IsObject(window) Then
'Internet Explorer HTML Application (HTA)
sTmp = Replace( Replace(Unescape(window.location), "file:///", "") ,"/", "\")
Path = Left(sTmp, InstrRev( sTmp , "\") - 1)
End If
End Property
End Class
Dim App : Set App = New clsApplication 'use as App.Path
In some languages this can be solved with tail call optimization, where the recursion call is transformed under the hood into a loop so no maximum stack size reached error exists.
But in javascript the current engines don't support this, it's foreseen for new version of the language Ecmascript 6.
Node.js has some flags to enable ES6 features but tail call is not yet available.
So you can refactor your code to implement a technique called trampolining, or refactor in order to transform recursion into a loop.
There are two types of LinearSegmentedColormaps. In some, the _segmentdata is given explicitly, e.g., for jet:
>>> cm.jet._segmentdata
{'blue': ((0.0, 0.5, 0.5), (0.11, 1, 1), (0.34, 1, 1), (0.65, 0, 0), (1, 0, 0)), 'red': ((0.0, 0, 0), (0.35, 0, 0), (0.66, 1, 1), (0.89, 1, 1), (1, 0.5, 0.5)), 'green': ((0.0, 0, 0), (0.125, 0, 0), (0.375, 1, 1), (0.64, 1, 1), (0.91, 0, 0), (1, 0, 0))}
For rainbow, _segmentdata is given as follows:
>>> cm.rainbow._segmentdata
{'blue': <function <lambda> at 0x7fac32ac2b70>, 'red': <function <lambda> at 0x7fac32ac7840>, 'green': <function <lambda> at 0x7fac32ac2d08>}
We can find the functions in the source of matplotlib, where they are given as
_rainbow_data = {
'red': gfunc[33], # 33: lambda x: np.abs(2 * x - 0.5),
'green': gfunc[13], # 13: lambda x: np.sin(x * np.pi),
'blue': gfunc[10], # 10: lambda x: np.cos(x * np.pi / 2)
}
Everything you want is already done in matplotlib, just call cm.revcmap, which reverses both types of segmentdata, so
cm.revcmap(cm.rainbow._segmentdata)
should do the job - you can simply create a new LinearSegmentData from that. In revcmap, the reversal of function based SegmentData is done with
def _reverser(f):
def freversed(x):
return f(1 - x)
return freversed
while the other lists are reversed as usual
valnew = [(1.0 - x, y1, y0) for x, y0, y1 in reversed(val)]
So actually the whole thing you want, is
def reverse_colourmap(cmap, name = 'my_cmap_r'):
return mpl.colors.LinearSegmentedColormap(name, cm.revcmap(cmap._segmentdata))
var link = $("#me").closest(":has(h3 span b)").find('h3 span b');
Example: http://jsfiddle.net/e27r8/
This uses the closest()
[docs] method to get the first ancestor that has a nested h3 span b
, then does a .find()
.
Of course you could have multiple matches.
Otherwise, you're looking at doing a more direct traversal.
var link = $("#me").closest("h3 + div").prev().find('span b');
edit: This one works with your updated HTML.
Example: http://jsfiddle.net/e27r8/2/
EDIT: Updated to deal with updated question.
var link = $("#me").closest("h3 + *").prev().find('span b');
This makes the targeted element for .closest()
generic, so that even if there is no parent, it will still work.
Example: http://jsfiddle.net/e27r8/4/
You can add a guard condition to the method to ensure books
is not null and then check for null when iterating the array:
public static double calculateInventoryTotal(Book[] books)
{
if(books == null){
throw new IllegalArgumentException("Books cannot be null");
}
double total = 0;
for (int i = 0; i < books.length; i++)
{
if(books[i] != null){
total += books[i].getPrice();
}
}
return total;
}
public class RemoveExtraSpacesEfficient {
public static void main(String[] args) {
String s = "my name is mr space ";
char[] charArray = s.toCharArray();
char prev = s.charAt(0);
for (int i = 0; i < charArray.length; i++) {
char cur = charArray[i];
if (cur == ' ' && prev == ' ') {
} else {
System.out.print(cur);
}
prev = cur;
}
}
}
The above solution is the algorithm with the complexity of O(n) without using any java function.
To some extent, this is going to vary by the "flavour" of RegEx you're using. The following is based on .NET RegEx, which uses \b
for word boundaries. In the last example, it also uses negative lookaround (?<!)
and (?!)
as well as non-capturing parentheses (?:)
Basically, though, if the terms always contain at least one uppercase letter followed by at least one number, you can use
\b[A-Z]+[0-9]+\b
For all-uppercase and numbers (total must be 2 or more):
\b[A-Z0-9]{2,}\b
For all-uppercase and numbers, but starting with at least one letter:
\b[A-Z][A-Z0-9]+\b
The granddaddy, to return items that have any combination of uppercase letters and numbers, but which are not single letters at the beginning of a line and which are not part of a line that is all uppercase:
(?:(?<!^)[A-Z]\b|(?<!^[A-Z0-9 ]*)\b[A-Z0-9]+\b(?![A-Z0-9 ]$))
breakdown:
The regex starts with (?:
. The ?:
signifies that -- although what follows is in parentheses, I'm not interested in capturing the result. This is called "non-capturing parentheses." Here, I'm using the paretheses because I'm using alternation (see below).
Inside the non-capturing parens, I have two separate clauses separated by the pipe symbol |
. This is alternation -- like an "or". The regex can match the first expression or the second. The two cases here are "is this the first word of the line" or "everything else," because we have the special requirement of excluding one-letter words at the beginning of the line.
Now, let's look at each expression in the alternation.
The first expression is: (?<!^)[A-Z]\b
. The main clause here is [A-Z]\b
, which is any one capital letter followed by a word boundary, which could be punctuation, whitespace, linebreak, etc. The part before that is (?<!^)
, which is a "negative lookbehind." This is a zero-width assertion, which means it doesn't "consume" characters as part of a match -- not really important to understand that here. The syntax for negative lookbehind in .NET is (?<!x)
, where x is the expression that must not exist before our main clause. Here that expression is simply ^
, or start-of-line, so this side of the alternation translates as "any word consisting of a single, uppercase letter that is not at the beginning of the line."
Okay, so we're matching one-letter, uppercase words that are not at the beginning of the line. We still need to match words consisting of all numbers and uppercase letters.
That is handled by a relatively small portion of the second expression in the alternation: \b[A-Z0-9]+\b
. The \b
s represent word boundaries, and the [A-Z0-9]+
matches one or more numbers and capital letters together.
The rest of the expression consists of other lookarounds. (?<!^[A-Z0-9 ]*)
is another negative lookbehind, where the expression is ^[A-Z0-9 ]*
. This means what precedes must not be all capital letters and numbers.
The second lookaround is (?![A-Z0-9 ]$)
, which is a negative lookahead. This means what follows must not be all capital letters and numbers.
So, altogether, we are capturing words of all capital letters and numbers, and excluding one-letter, uppercase characters from the start of the line and everything from lines that are all uppercase.
There is at least one weakness here in that the lookarounds in the second alternation expression act independently, so a sentence like "A P1 should connect to the J9" will match J9, but not P1, because everything before P1 is capitalized.
It is possible to get around this issue, but it would almost triple the length of the regex. Trying to do so much in a single regex is seldom, if ever, justfied. You'll be better off breaking up the work either into multiple regexes or a combination of regex and standard string processing commands in your programming language of choice.
It's been a little while since I coded with selenium, but your code looks ok to me. One thing to note is that if the element is not found, but the timeout is passed, I think the code will continue to execute. So you can do something like this:
boolean exists = driver.findElements(By.xpath("//*[@id='someID']")).size() != 0
What does the above boolean return? And are you sure selenium actually navigates to the expected page? (That may sound like a silly question but are you actually watching the pages change... selenium can be run remotely you know...)
CMake produces Visual Studio Projects and Solutions seamlessly. You can even produce projects/solutions for different Visual Studio versions without making any changes to the CMake files.
Adding and removing source files is just a matter of modifying the CMakeLists.txt
which has the list of source files and regenerating the projects/solutions. There is even a globbing function to find all the sources in a directory (though it should be used with caution).
The following link explains CMake and Visual Studio specific behavior very well.
Use this...
$('#cat_icon').click(function () {
$('#categories').toggle("slow");
//$('#cat_icon').hide();
});
$('.panel_title').click(function () {
$('#categories').toggle("slow");
//$('#cat_icon').show();
});
See this Example
Greetings.
If you will later know the length of the array you can create the initial array like this:
String[] array;
And later when you know the length you can finish initializing it like this
array = new String[42];
There is a more effective way of generating an intersect, by using UNION ALL and GROUP BY. Performances are twice better according to my tests on large datasets.
Example:
SELECT t1.value from (
(SELECT DISTINCT value FROM table_a)
UNION ALL
(SELECT DISTINCT value FROM table_b)
) AS t1 GROUP BY value HAVING count(*) >= 2;
It is more effective, because with the INNER JOIN solution, MySQL will look up for the results of the first query, then for each row, look up for the result in the second query. With the UNION ALL-GROUP BY solution, it will query results of the first query, results of the second query, then group the results all together at once.
For me / had to be in a new line.
For example
create type emp_t;/
didn't work
but
create type emp_t;
/
worked.
Use update
, stop
and receive
events, check it over here
Edit: For newer versions of Git, --set-upstream master
has been deprecated, you should use --set-upstream-to
instead:
git branch --set-upstream-to=origin/master master
As it prompted, you can just run:
git branch --set-upstream master origin/master
After that, you can simply run git pull
to update your code.
Refer to http://api.jquery.com/on/
It says
In all browsers, the load, scroll, and error events (e.g., on an
<img>
element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event.
If you want to do something when a new input box is added then you can simply write the code after appending it.
$('#add').click(function(){
$('body').append(x);
// Your code can be here
});
And if you want the same code execute when the first input box within the document is loaded then you can write a function and call it in both places i.e. $('#add').click
and document's ready event
There isn't one.
I use underscores all the time, due to hyphens messing up the syntax highlighting of my text editor (Gedit), but that's personal preference.
I've seen all these conventions used all over the place. Use the one that you think is best - the one that looks nicest/easiest to read for you, as well as easiest to type because you'll be using it a lot. For example, if you've got your underscore key on the underside of the keyboard (unlikely, but entirely possible), then stick to hyphens. Just go with what is best for yourself. Additionally, all 3 of these conventions are easily readable. If you're working in a team, remember to keep with the team-specified convention (if any).
Update 2012
I've changed how I program over time. I now use camel case (thisIsASelector
) instead of hyphens now; I find the latter rather ugly. Use whatever you prefer, which may easily change over time.
Update 2013
It looks like I like to mix things up yearly... After switching to Sublime Text and using Bootstrap for a while, I've gone back to dashes. To me now they look a lot cleaner than un_der_scores or camelCase. My original point still stands though: there isn't a standard.
Update 2015
An interesting corner case with conventions here is Rust. I really like the language, but the compiler will warn you if you define stuff using anything other than underscore_case
. You can turn the warning off, but it's interesting the compiler strongly suggests a convention by default. I imagine in larger projects it leads to cleaner code which is no bad thing.
Update 2016 (you asked for it)
I've adopted the BEM standard for my projects going forward. The class names end up being quite verbose, but I think it gives good structure and reusability to the classes and CSS that goes with them. I suppose BEM is actually a standard (so my no
becomes a yes
perhaps) but it's still up to you what you decide to use in a project. Most importantly: be consistent with what you choose.
Update 2019 (you asked for it)
After writing no CSS for quite a while, I started working at a place that uses OOCSS in one of their products. I personally find it pretty unpleasant to litter classes everywhere, but not having to jump between HTML and CSS all the time feels quite productive.
I'm still settled on BEM, though. It's verbose, but the namespacing makes working with it in React components very natural. It's also great for selecting specific elements when browser testing.
OOCSS and BEM are just some of the CSS standards out there. Pick one that works for you - they're all full of compromises because CSS just isn't that good.
Update 2020
A boring update this year. I'm still using BEM. My position hasn't really changed from the 2019 update for the reasons listed above. Use what works for you that scales with your team size and hides as much or as little of CSS' poor featureset as you like.
You also need to change the build.gradle file, and add the used Android SDK version into it:
implementation 'com.android.support:appcompat-v7:28.0.0'
This worked like a charm in my case.
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
I used this with Amazon EC2 with 1 master and 2 slaves and Spark 1.2.1.
# Step 1. Change config file on the master node
nano /root/ephemeral-hdfs/conf/log4j.properties
# Before
hadoop.root.logger=INFO,console
# After
hadoop.root.logger=WARN,console
# Step 2. Replicate this change to slaves
~/spark-ec2/copy-dir /root/ephemeral-hdfs/conf/
You can't expect ObjectInputStream
to automagically convert text into objects. The hexadecimal 54657374
is "Test"
as text. You must be sending it directly as bytes.
You can loop throw the rows and columns, checking for nulls, keeping track of whether there's a null with a bool, then check it after looping through the table and handle it.
//your DataTable, replace with table get code
DataTable table = new DataTable();
bool tableHasNull = false;
foreach (DataRow row in table.Rows)
{
foreach (DataColumn col in table.Columns)
{
//test for null here
if (row[col] == DBNull.Value)
{
tableHasNull = true;
}
}
}
if (tableHasNull)
{
//handle null in table
}
You can also come out of the foreach loop with a break statement e.g.
//test for null here
if (row[col] == DBNull.Value)
{
tableHasNull = true;
break;
}
To save looping through the rest of the table.
It may or may not be the case that there is only one developer on this branch, that is now (after the rebase) not inline with the origin/feature.
As such I would suggest to use the following sequence:
git rebase master
git checkout -b feature_branch_2
git push origin feature_branch_2
Yeah, new branch, this should solve this without a --force, which I think generally is a major git drawback.
You can only use await
in an async
method, and Main
cannot be async
.
You'll have to use your own async
-compatible context, call Wait
on the returned Task
in the Main
method, or just ignore the returned Task
and just block on the call to Read
. Note that Wait
will wrap any exceptions in an AggregateException
.
If you want a good intro, see my async
/await
intro post.
Now a days, the easiest way I found to have a more updated version of Python is to install it via conda into a conda environment.
Install conda(you may need a virtualenv for this)
pip install conda
I'm adding this answer here because no manual download is needed. conda
will do that for you.
Now create an environment for the Python version you want. In this example I will use 3.5.2
, because it it the latest version at this time of writing (Aug 2016).
conda create -n py35 python=3.5.2
Will create a environment for conda to install packages
To activate this environment(I'm assuming linux otherwise check the conda docs):
source activate py35
Now install what you need either via pip or conda in the environemnt(conda has better binary package support).
conda install <package_name>
Just stick with the virtual machine: If you're running Internet Explorer 8 you'll be able to activate the developer window using F12. There you're able to edit CSS as well as HTML on the fly without saving/reloading the page.
Your date object is probably ok, since you sent your date encoded in ISO format with GMT timezone and you are in EST when you print your date.
Note that Date objects perform timezone translation at the moment they are printed. You can check if your date
object is correct with:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.setTime(date);
System.out.println (cal);
Either
Method 2 by step
i.fa {_x000D_
display: inline-block;_x000D_
border-radius: 60px;_x000D_
box-shadow: 0px 0px 2px #888;_x000D_
padding: 0.5em 0.6em;_x000D_
_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />_x000D_
<i class="fa fa-wrench"></i>
_x000D_
in batch file abc.bat
cd c:\user\ben_dchost\documents\
executible.exe -flag1 -flag2 -flag3
I am assuming that your executible.exe
is present in c:\user\ben_dchost\documents\
I am also assuming that the parameters it takes are -flag1
-flag2
-flag3
Edited:
For the command you say you want to execute, do:
cd C:\Users\Ben\Desktop\BGInfo\
bginfo.exe dc_bginfo.bgi
pause
Hope this helps
The PDO solution, just for a better implementation then mysql_*
:
$array = $pdo->query("SELECT id, title, '$year-month-10' as start,url
FROM table")->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($array);
Nice feature is also that it will leave integers as integers as opposed to strings.
Whenever I set debug="off" in my web.config and run my mvc4 application i would end up with ...
<script src="/bundles/jquery?v=<some long string>"></script>
in my html code and a JavaScript error
Expected ';'
There were 2 ways to get rid of the javascript error
BundleTable.EnableOptimizations = false
in BundleConfig.cs OR
If you want run formula on worksheet by function that execute SQL statement then use Add-in A-Tools
Example, function BS_SQL("SELECT ...")
:
Personally, I prefer the simple modulo operation solution in the accepted answer. Unfortunately, SonarQube doesn't like equality tests with floating points without setting a round precision. So we have tried to find a more compliant solution. Here it is:
if (new BigDecimal(decimalValue).remainder(new BigDecimal(1)).equals(BigDecimal.ZERO)) {
// no decimal places
} else {
// decimal places
}
Remainder(BigDecimal)
returns a BigDecimal
whose value is (this % divisor)
. If this one's equal to zero, we know there is no floating point.
Instead of directly messing with innerHTML
it might be better to create a fragment and then insert that:
function create(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
var fragment = create('<div>Hello!</div><p>...</p>');
// You can use native DOM methods to insert the fragment:
document.body.insertBefore(fragment, document.body.childNodes[0]);
Benefits:
Even though innerHTML
is used within the function, it's all happening outside of the DOM so it's much faster than you'd think...
Try and retrieve the text property of the link button in the code behind:
protected void ENameLinkBtn_Click (object sender, EventArgs e)
{
string val = ((LinkButton)sender).Text
}
Grep is useful if you want to quickly search for lines that match in a file. It can also return some other simple information like matching line numbers, match count, and file name lists.
Awk is an entire programming language built around reading CSV-style files, processing the records, and optionally printing out a result data set. It can do many things but it is not the easiest tool to use for simple tasks.
Sed is useful when you want to make changes to a file based on regular expressions. It allows you to easily match parts of lines, make modifications, and print out results. It's less expressive than awk but that lends it to somewhat easier use for simple tasks. It has many more complicated operators you can use (I think it's even turing complete), but in general you won't use those features.
break;
.
while(choice!=99)
{
cin>>choice;
if (choice==99)
break;
cin>>gNum;
}
Yes, easy. Just run a data-definition query to update the tables, adding an AUTO_INCREMENT column.
If you have an existing database, be careful to preserve any foreign-key relationships that might already be there on the "artificially created" primary keys.