In your layout (xml) files almost every element has a property i.e. "id" which, can be assigned in order to refer to it from the java/kotlin code or from the xml itself.
Now sometimes or in some versions of Android Studio errors in xml files is either not reported or some random error is thrown while compiling, of which, this thread is an example i.e. when assigning an id to an element or when refering to another element in the layout we use the ID but ids are not just written like any other word rather they are prefixed by these characters: @+id/
, otherwise the above error is thrown.
Hence the solution below should be considered:-
I resolved it by adding @+id/
before all my IDs.
i.e. @+id/your_item_id
Try adding the conda-forge channel to your list of channels with this command:
conda config --append channels conda-forge
. It tells conda to also look on the conda-forge channel when you search for packages. You can then simply install the two packages with conda install slycot control
.
Channels are basically servers for people to host packages on and the community-driven conda-forge is usually a good place to start when packages are not available via the standard channels. I checked and both slycot and control seem to be available there.
The reason is your current ruby environment, you got a different version of bundler with the version in Gemfile.lock
.
Gemfile.lock
, this won't break anything if there is some incampatibly thing happened.Gemfile.lock
, and run bundle install
.If you use VSCode, consider using the Angular Console
It provides an interface for the Angular CLI. You will see an option to specify the path.
The Angular CLI is immensely powerful and extensible. In fact, there are so many capabilities that it is helpful for developers to have all of the different configuration options for every command available to them.
With Angular Console, you’ll get recommendations and be able to pull up even the most easily forgotten or rarely used features!
Angular Console is, first and foremost, a more productive way to work with what the Angular CLI provides.
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
For anyone using Windows 10 and nothing else working for him/her:
In my case, I had to clone the repo with https instead of ssh and a window popped-up asking for my credentials. After that everything works fine.
I'd like to plug in some (shallow) reasons I have experienced as follows:
Hope that helps.
In ASP.NET Core, there are configuration providers for reading configurations from almost anywhere such as files e.g. JSON, INI or XML, environment variables, Azure key vault, command-line arguments, etc. and many more sources. I have written a step by step guide to show you how can you configure your application settings in various files such as JSON, INI or XML and how can you read those settings from your application code. I will also demonstrate how can you read application settings as custom .NET types (classes) and how can you use the built-in ASP.NET Core dependency injection to read your configuration settings in multiple classes, services or even projects available in your solution.
Since the deprecation of RequestOptions, sending data as body in a DELETE request is not supported.
If you look at the definition of DELETE, it looks like this:
delete<T>(url: string, options?: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe?: 'body';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<T>;
You can send payload along with the DELETE request as part of the params in the options object as follows:
this.http.delete('http://testAPI:3000/stuff', { params: {
data: yourData
}).subscribe((data)=>.
{console.log(data)});
However, note that params only accept data as string or string[] so you will not be able to send your own interface data unless you stringify it.
You can use store
object that is returned from createStore
function (which should be already used in your code in app initialization). Than you can use this object to get current state with store.getState()
method or store.subscribe(listener)
to subscribe to store updates.
You can even save this object to window
property to access it from any part of application if you really want it (window.store = store
)
More info can be found in the Redux documentation .
Working for me, just add className="nav-link"
and activeStyle{{textDecoration:'underline'}}
<NavLink className="nav-link" to="/" exact activeStyle=
{{textDecoration:'underline'}}>My Record</NavLink>
Choosing the right file format is important to building performant data applications. The concepts outlined in this post carry over to Pandas, Dask, Spark, and Presto / AWS Athena.
Column pruning
Column pruning is a big performance improvement that's possible for column-based file formats (Parquet, ORC) and not possible for row-based file formats (CSV, Avro).
Suppose you have a dataset with 100 columns and want to read two of them into a DataFrame. Here's how you can perform this with Pandas if the data is stored in a Parquet file.
import pandas as pd
pd.read_parquet('some_file.parquet', columns = ['id', 'firstname'])
Parquet is a columnar file format, so Pandas can grab the columns relevant for the query and can skip the other columns. This is a massive performance improvement.
If the data is stored in a CSV file, you can read it like this:
import pandas as pd
pd.read_csv('some_file.csv', usecols = ['id', 'firstname'])
usecols
can't skip over entire columns because of the row nature of the CSV file format.
Spark doesn't require users to explicitly list the columns that'll be used in a query. Spark builds up an execution plan and will automatically leverage column pruning whenever possible. Of course, column pruning is only possible when the underlying file format is column oriented.
Popularity
Spark and Pandas have built-in readers writers for CSV, JSON, ORC, Parquet, and text files. They don't have built-in readers for Avro.
Avro is popular within the Hadoop ecosystem. Parquet has gained significant traction outside of the Hadoop ecosystem. For example, the Delta Lake project is being built on Parquet files.
Arrow is an important project that makes it easy to work with Parquet files with a variety of different languages (C, C++, Go, Java, JavaScript, MATLAB, Python, R, Ruby, Rust), but doesn't support Avro. Parquet files are easier to work with because they are supported by so many different projects.
Schema
Parquet stores the file schema in the file metadata. CSV files don't store file metadata, so readers need to either be supplied with the schema or the schema needs to be inferred. Supplying a schema is tedious and inferring a schema is error prone / expensive.
Avro also stores the data schema in the file itself. Having schema in the files is a huge advantage and is one of the reasons why a modern data project should not rely on JSON or CSV.
Column metadata
Parquet stores metadata statistics for each column and lets users add their own column metadata as well.
The min / max column value metadata allows for Parquet predicate pushdown filtering that's supported by the Dask & Spark cluster computing frameworks.
Here's how to fetch the column statistics with PyArrow.
import pyarrow.parquet as pq
parquet_file = pq.ParquetFile('some_file.parquet')
print(parquet_file.metadata.row_group(0).column(1).statistics)
<pyarrow._parquet.Statistics object at 0x11ac17eb0>
has_min_max: True
min: 1
max: 9
null_count: 0
distinct_count: 0
num_values: 3
physical_type: INT64
logical_type: None
converted_type (legacy): NONE
Complex column types
Parquet allows for complex column types like arrays, dictionaries, and nested schemas. There isn't a reliable method to store complex types in simple file formats like CSVs.
Compression
Columnar file formats store related types in rows, so they're easier to compress. This CSV file is relatively hard to compress.
first_name,age
ken,30
felicia,36
mia,2
This data is easier to compress when the related types are stored in the same row:
ken,felicia,mia
30,36,2
Parquet files are most commonly compressed with the Snappy compression algorithm. Snappy compressed files are splittable and quick to inflate. Big data systems want to reduce file size on disk, but also want to make it quick to inflate the flies and run analytical queries.
Mutable nature of file
Parquet files are immutable, as described here. CSV files are mutable.
Adding a row to a CSV file is easy. You can't easily add a row to a Parquet file.
Data lakes
In a big data environment, you'll be working with hundreds or thousands of Parquet files. Disk partitioning of the files, avoiding big files, and compacting small files is important. The optimal disk layout of data depends on your query patterns.
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
Your second solution is probably the most correct. You should use the HTTP spec and mimetypes the way they were intended and upload the file via multipart/form-data
. As far as handling the relationships, I'd use this process (keeping in mind I know zero about your assumptions or system design):
POST
to /users
to create the user entity.POST
the image to /images
, making sure to return a Location
header to where the image can be retrieved per the HTTP spec.PATCH
to /users/carPhoto
and assign it the ID of the photo given in the Location
header of step 2.In Android Studio 3.0, I had the same issue. This fixed it:
Using history.listen
For example like below:
In your component,
componentWillMount() {
this.props.history.listen(() => {
// Detecting, user has changed URL
console.info(this.props.history.location.pathname);
});
}
Use rel="preload"
to make it download independently, then use onload="this.rel='stylesheet'"
to apply it to the stylesheet (as="style"
is necessary to apply it to stylesheet else the onload
won't work)
<link rel="preload" as="style" type="text/css" href="mystyles.css" onload="this.rel='stylesheet'">
Google cautions against using local copies of the analtics scripts. However if you are doing it, you will probably want to use local copies of the plugins & the debug script.
A second concern with agressive caching is that you will be getting hits from cached pages - which may have changed or have been removed from the site.
Seems related to https://groups.google.com/forum/#!msg/google-caja-discuss/ite6K5c8mqs/Ayqw72XJ9G8J.
The so-called "Rosetta Flash" vulnerability is that allowing arbitrary yet identifier-like text at the beginning of a JSONP response is sufficient for it to be interpreted as a Flash file executing in that origin. See for more information: http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
JSONP responses from the proxy servlet now: * are prefixed with "/**/", which still allows them to execute as JSONP but removes requester control over the first bytes of the response. * have the response header Content-Disposition: attachment.
I know this is an old post but I had a lot of issues trying to solve this and I finally did so I wanted to share.
My issue was that I was adding an event listener within the ontouchstart and removing it in the ontouchend functions - something like this
function onTouchStart() {
window.addEventListener("touchmove", handleTouchMove, {
passive: false
});
}
function onTouchEnd() {
window.removeEventListener("touchmove", handleTouchMove, {
passive: true
});
}
function handleTouchMove(e) {
e.preventDefault();
}
For some reason adding it removing it like this was causing this issue of the event randomly not being cancelable. So to solve this I kept the listener active and toggled a boolean on whether or not it should prevent the event - something like this:
let stopScrolling = false;
window.addEventListener("touchmove", handleTouchMove, {
passive: false
});
function handleTouchMove(e) {
if (!stopScrolling) {
return;
}
e.preventDefault();
}
function onTouchStart() {
stopScrolling = true;
}
function onTouchEnd() {
stopScrolling = false;
}
I was actually using React so my solution involved setting state, but I've simplified it for a more generic solution. Hopefully this helps someone!
Changing the above options form Help menu didn't work for me. You have edit idea.properties file and change to some large no.
MAC: /Applications/<Android studio>.app/Contents/bin[Open App contents]
Idea.max.intellisense.filesize=999999
WINDOWS: IDE_HOME\bin\idea.properties
I allowed myself to create a javascript version of it. Might it be helpful. The javascript should be direct transcription of the Pseudocode given above. Available as npm package and github repo:
// javascript port of: https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/48895639#48895639
function sum(a) {
return a.reduce((acc, val) => acc + val)
}
function mean(a) {
return sum(a) / a.length
}
function stddev(arr) {
const arr_mean = mean(arr)
const r = function(acc, val) {
return acc + ((val - arr_mean) * (val - arr_mean))
}
return Math.sqrt(arr.reduce(r, 0.0) / arr.length)
}
function smoothed_z_score(y, params) {
var p = params || {}
// init cooefficients
const lag = p.lag || 5
const threshold = p.threshold || 3.5
const influence = p.influece || 0.5
if (y === undefined || y.length < lag + 2) {
throw ` ## y data array to short(${y.length}) for given lag of ${lag}`
}
//console.log(`lag, threshold, influence: ${lag}, ${threshold}, ${influence}`)
// init variables
var signals = Array(y.length).fill(0)
var filteredY = y.slice(0)
const lead_in = y.slice(0, lag)
//console.log("1: " + lead_in.toString())
var avgFilter = []
avgFilter[lag - 1] = mean(lead_in)
var stdFilter = []
stdFilter[lag - 1] = stddev(lead_in)
//console.log("2: " + stdFilter.toString())
for (var i = lag; i < y.length; i++) {
//console.log(`${y[i]}, ${avgFilter[i-1]}, ${threshold}, ${stdFilter[i-1]}`)
if (Math.abs(y[i] - avgFilter[i - 1]) > (threshold * stdFilter[i - 1])) {
if (y[i] > avgFilter[i - 1]) {
signals[i] = +1 // positive signal
} else {
signals[i] = -1 // negative signal
}
// make influence lower
filteredY[i] = influence * y[i] + (1 - influence) * filteredY[i - 1]
} else {
signals[i] = 0 // no signal
filteredY[i] = y[i]
}
// adjust the filters
const y_lag = filteredY.slice(i - lag, i)
avgFilter[i] = mean(y_lag)
stdFilter[i] = stddev(y_lag)
}
return signals
}
module.exports = smoothed_z_score
try this scp -r -P2222 [email protected]:/home2/kwazy/www/utrecht-connected.nl /Desktop
Another easier option if you're going to be pulling files left and right is to just use an SFTP client like WinSCP. Then you're not typing out 100 characters every time you want to pull something, just drag and drop.
Edit: Just noticed /Desktop probably isn't where you're looking to download the file to. Should be something like C:\Users\you\Desktop
To view the differences going from the remote file to the local file:
git diff remotename/branchname:remote/path/file1.txt local/path/file1.txt
To view the differences in the other direction:
git diff HEAD:local/path/file1.txt remotename/branchname:remote/path/file1.txt
Basically you can diff any two files anywhere using this notation:
git diff ref1:path/to/file1 ref2:path/to/file2
As usual, ref1
and ref2
could be branch names, remotename/branchname, commit SHAs, etc.
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.
Weird, just had simmilar issue, went here http://www.microsoft.com/en-us/download/confirmation.aspx?id=30679 downloaded and installed vcredist_x86 (i'm using 32bit apache) and it works like a charm.
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');
}
});
});
I built a laravel package for making statistics : https://github.com/Ifnot/statistics
It is based on eloquent, carbon and indicators so it is really easy to use. It may be usefull for extracting date grouped indicators.
$statistics = Statistics::of(MyModel::query());
$statistics->date('validated_at');
$statistics->interval(Interval::$DAILY, Carbon::createFromFormat('Y-m-d', '2016-01-01'), Carbon::now())
$statistics->indicator('total', function($row) {
return $row->counter;
});
$data = $statistics->make();
echo $data['2016-01-01']->total;
```
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()
In Laravel 5, there is a .env
file,
It looks like
APP_ENV=local
APP_DEBUG=true
APP_KEY=YOUR_API_KEY
DB_HOST=YOUR_HOST
DB_DATABASE=YOUR_DATABASE
DB_USERNAME=YOUR_USERNAME
DB_PASSWORD=YOUR_PASSWORD
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
Edit that .env There is .env.sample is there , try to create from that if no such .env file found.
Try this:
SELECT *
INTO #Temp
FROM
(select * from tblorders where busidate ='2016-11-24' and locationID=12
) as X
Please use alias with x so it will not failed the script and result.
Not exactly. You can't get two Stream
s out of one; this doesn't make sense -- how would you iterate over one without needing to generate the other at the same time? A stream can only be operated over once.
However, if you want to dump them into a list or something, you could do
stream.forEach((x) -> ((x == 0) ? heads : tails).add(x));
I actually ended up with something like this to allow for the navbar collapse.
@media (min-width: 768px) { //set this to wherever the navbar collapse executes
.navbar-nav > li > a{
line-height: 7em; //set this height to the height of the logo.
}
}
When I uninstalled Java 8 it worked fine.
I also faced a similar issue. The reason was that I had the changes done in the .aspx page but not the designer page and hence I got the mentioned error. When the reference was created in the designer page I was able to build the solution.
Change column type to LONGTEXT
Hi For jQuery You can only use like this
Use async and type="text/javascript" only
I have had to unpack a .ab
-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.
Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab
-file is password-protected.
Usage:java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]
Example:
Let's say, you've got a file test.ab
, which is not password-protected, you're using Windows and want the resulting .tar
-Archive to be called test.tar
. Then your command should be:
java.exe -jar abe.jar unpack test.ab test.tar ""
additionally you may want mongo to run on another port, then paste this command on terminal,
mongod --dbpath /data/db/ --port 27018
where 27018 is the port we want mongo to run on
/usr/local/bin/
for mac ( which would be if you installed with brew), otherwise you'd need to navigate to the path where mongo is installed/data/db/
existsNo, it is not a bad practice to break out of a loop when if certain desired condition is reached(like a match is found). Many times, you may want to stop iterations because you have already achieved what you want, and there is no point iterating further. But, be careful to make sure you are not accidentally missing something or breaking out when not required.
This can also add to performance improvement if you break the loop, instead of iterating over thousands of records even if the purpose of the loop is complete(i.e. may be to match required record is already done).
Example :
for (int j = 0; j < type.size(); j++) {
if (condition) {
// do stuff after which you want
break; // stop further iteration
}
}
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 ...
As of September 2016 this addon is the best to disable CORS: https://github.com/fredericlb/Force-CORS/releases
In the options panel you can configure which header to inject and specific website to have it enabled automatically.
Using regedit, remove the entries corresponding to java 7. It will work.
found this on Zurb's github
In case you want to do some more custom styling. Here's all the default CSS for webkit rendering of the date components.
input[type="date"] {
-webkit-align-items: center;
display: -webkit-inline-flex;
font-family: monospace;
overflow: hidden;
padding: 0;
-webkit-padding-start: 1px;
}
input::-webkit-datetime-edit {
-webkit-flex: 1;
-webkit-user-modify: read-only !important;
display: inline-block;
min-width: 0;
overflow: hidden;
}
input::-webkit-datetime-edit-fields-wrapper {
-webkit-user-modify: read-only !important;
display: inline-block;
padding: 1px 0;
white-space: pre;
}
it's very easy code .. but hard to fined..
detailsApp.controller("SchoolCtrl", function ($scope, $location) {
$scope.addSchool = function () {
location.href='/ManageSchool/TeacherProfile?ID=' + $scope.TeacherID;
}
});
Basically the scope of workspace(s) is divided in two points.
First point (and primary) is the eclipse it self and is related with the settings and metadata configurations (plugin ctr). Each time you create a project, eclipse collects all the configurations and stores them on that workspace and if somehow in the same workspace a conflicting project is present you might loose some functionality or even stability of eclipse it self.
And second (secondary) the point of development strategy one can adopt. Once the primary scope is met (and mastered) and there's need for further adjustments regarding project relations (as libraries, perspectives ctr) then initiate separate workspace(s) could be appropriate based on development habits or possible language/frameworks "behaviors". DLTK for examples is a beast that should be contained in a separate cage. Lots of complains at forums for it stopped working (properly or not at all) and suggested solution was to clean the settings of the equivalent plugin from the current workspace.
Personally, I found myself lean more to language distinction when it comes to separate workspaces which is relevant to known issues that comes with the current state of the plugins are used. Preferably I keep them in the minimum numbers as this is leads to less frustration when the projects are become... plenty and version control is not the only version you keep your projects. Finally, loading speed and performance is an issue that might come up if lots of (unnecessary) plugins are loaded due to presents of irrelevant projects. Bottom line; there is no one solution to every one, no master blue print that solves the issue. It's something that grows with experience, Less is more though!
In EF Core, I use the following statements to rename tables and columns:
As for renaming tables:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameTable(name: "OldTableName", schema: "dbo", newName: "NewTableName", newSchema: "dbo");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameTable(name: "NewTableName", schema: "dbo", newName: "OldTableName", newSchema: "dbo");
}
As for renaming columns:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(name: "OldColumnName", table: "TableName", newName: "NewColumnName", schema: "dbo");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(name: "NewColumnName", table: "TableName", newName: "OldColumnName", schema: "dbo");
}
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.
try this out let me know what happens.
Form:
<form action="form.php" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
Form.php:
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'Primary key: ' .$row['PRIMARYKEY'];
echo '<br /> Code: ' .$row['Code'];
echo '<br /> Description: '.$row['Description'];
echo '<br /> Category: '.$row['Category'];
echo '<br /> Cut Size: '.$row['CutSize'];
}
Edit: Cleaned it up a little more.
Final Cut (my test file):
<?php
$db_hostname = 'localhost';
$db_username = 'demo';
$db_password = 'demo';
$db_database = 'demo';
// Database Connection String
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_database, $con);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
<?php
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'Primary key: ' .$row['PRIMARYKEY'];
echo '<br /> Code: ' .$row['Code'];
echo '<br /> Description: '.$row['Description'];
echo '<br /> Category: '.$row['Category'];
echo '<br /> Cut Size: '.$row['CutSize'];
}
}
?>
</body>
</html>
assertTrue()/assertFalse() : to use only to assert boolean result returned
assertTrue(Iterables.elementsEqual(argumentComponents, returnedComponents));
You want to use Assert.assertTrue()
or Assert.assertFalse()
as the method under test returns a boolean
value.
As the method returns a specific thing such as a List
that should contain some expected elements, asserting with assertTrue()
in this way : Assert.assertTrue(myActualList.containsAll(myExpectedList)
is an anti pattern.
It makes the assertion easy to write but as the test fails, it also makes it hard to debug because the test runner will only say to you something like :
expected
true
but actual isfalse
Assert.assertEquals(Object, Object)
in JUnit4 or Assertions.assertIterableEquals(Iterable, Iterable)
in JUnit 5 : to use only as both equals()
and toString()
are overrided for the classes (and deeply) of the compared objects
It matters because the equality test in the assertion relies on equals()
and the test failure message relies on toString()
of the compared objects.
As String
overrides both equals()
and toString()
, it is perfectly valid to assert the List<String>
with assertEquals(Object,Object)
.
And about this matter : you have to override equals()
in a class because it makes sense in terms of object equality, not only to make assertions easier in a test with JUnit.
To make assertions easier you have other ways (that you can see in the next points of the answer).
Is Guava a way to perform/build unit test assertions ?
Is Google Guava Iterables.elementsEqual() the best way, provided I have the library in my build path, to compare those two lists?
No it is not. Guava is not an library to write unit test assertions.
You don't need it to write most (all I think) of unit tests.
What's the canonical way to compare lists for unit tests?
As a good practice I favor assertion/matcher libraries.
I cannot encourage JUnit to perform specific assertions because this provides really too few and limited features : it performs only an assertion with a deep equals.
Sometimes you want to allow any order in the elements, sometimes you want to allow that any elements of the expected match with the actual, and so for...
So using a unit test assertion/matcher library such as Hamcrest or AssertJ is the correct way.
The actual answer provides a Hamcrest solution. Here is a AssertJ solution.
org.assertj.core.api.ListAssert.containsExactly()
is what you need : it verifies that the actual group contains exactly the given values and nothing else, in order as stated :
Verifies that the actual group contains exactly the given values and nothing else, in order.
Your test could look like :
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
@Test
void ofComponent_AssertJ() throws Exception {
MyObject myObject = MyObject.ofComponents("One", "Two", "Three");
Assertions.assertThat(myObject.getComponents())
.containsExactly("One", "Two", "Three");
}
A AssertJ good point is that declaring a List
as expected is needless : it makes the assertion straighter and the code more readable :
Assertions.assertThat(myObject.getComponents())
.containsExactly("One", "Two", "Three");
And if the test fails :
// Fail : Three was not expected
Assertions.assertThat(myObject.getComponents())
.containsExactly("One", "Two");
you get a very clear message such as :
java.lang.AssertionError:
Expecting:
<["One", "Two", "Three"]>
to contain exactly (and in same order):
<["One", "Two"]>
but some elements were not expected:
<["Three"]>
Assertion/matcher libraries are a must because these will really further
Suppose that MyObject
doesn't store String
s but Foo
s instances such as :
public class MyFooObject {
private List<Foo> values;
@SafeVarargs
public static MyFooObject ofComponents(Foo... values) {
// ...
}
public List<Foo> getComponents(){
return new ArrayList<>(values);
}
}
That is a very common need.
With AssertJ the assertion is still simple to write. Better you can assert that the list content are equal even if the class of the elements doesn't override equals()/hashCode()
while JUnit ways require that :
import org.assertj.core.api.Assertions;
import static org.assertj.core.groups.Tuple.tuple;
import org.junit.jupiter.api.Test;
@Test
void ofComponent() throws Exception {
MyFooObject myObject = MyFooObject.ofComponents(new Foo(1, "One"), new Foo(2, "Two"), new Foo(3, "Three"));
Assertions.assertThat(myObject.getComponents())
.extracting(Foo::getId, Foo::getName)
.containsExactly(tuple(1, "One"),
tuple(2, "Two"),
tuple(3, "Three"));
}
Hello world :)
The best but strange way for me was to do next things.
1) Download postgres93.app or other version. Add this app into /Applications/ folder.
2) Add a row (command) into the file .bash_profile
(which is in my home directory):
export PATH=/Applications/Postgres93.app/Contents/MacOS/bin/:$PATHIt's a PATH to
psql
from Postgres93.app
. The row (command) runs every time console is started.
3) Launch Postgres93.app
from /Applications/
folder. It starts a local server (port is "5432" and host is "localhost").
4) After all of this manipulations I was glad to run $ createuser -SRDP user_name
and other commands and to see that it worked! Postgres93.app
can be made to run every time your system starts.
5) Also if you wanna see your databases graphically you should install PG Commander.app
. It's good way to see your postgres DB as pretty data-tables
Of, course, it's helpful only for local server. I will be glad if this instructions help others who has faced with this problem.
Here is the answer for those of you who need a Boostrap 3 solution.
In bootstrap 3 use 'shown.bs.tab' instead of 'shown' in the next line
// tab
$('#rowTab a:first').tab('show');
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
//show selected tab / active
console.log ( $(e.target).attr('id') );
});
You really shouldn't need to use the numbers 1-1000 in a list. But if for some reason you really do need these numbers, then you could do:
[i for i in range(1, 1001)]
List Comprehension in a nutshell:
The above list comprehension translates to:
nums = []
for i in range(1, 1001):
nums.append(i)
This is just the list comprehension syntax, though from 2.x. I know that this will work in python 3, but am not sure if there is an upgraded syntax as well
Range starts inclusive of the first parameter; but ends Up To, Not Including the second Parameter (when supplied 2 parameters; if the first parameter is left off, it'll start at '0')
range(start, end+1)
[start, start+1, .., end]
You maybe wanted to do the following:
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?
The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.
The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.
The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations. GET - represent() POST - acceptRepresention() PUT - storeRepresention() DELETE - removeRepresention()
SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better. SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not. The SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.
The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.
source http://java-success.blogspot.in/2012/02/java-web-services-interview-questions.html
Based on the documentation you should be able to use auto
in combination with the preferred placement e.g. auto left
http://getbootstrap.com/javascript/#popovers: "When "auto" is specified, it will dynamically reorient the popover. For example, if placement is "auto left", the tooltip will display to the left when possible, otherwise it will display right."
I was trying to do the same thing and then realised that this functionality already existed.
You cannot access var
with the generic.
Try something like
Console.WriteLine("Generic : {0}", test);
And override ToString
method [1]
[1] http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx
The repository no longer supports self-signed certificates. You need to upgrade npm
.
// Disable the certificate temporarily in order to do the upgrade
npm config set ca ""
// Upgrade npm. -g (global) means you need root permissions; be root
// or prepend `sudo`
sudo npm install npm -g
// Undo the previous config change
npm config delete ca
// For Ubuntu/Debian-sid/Mint, node package is renamed to nodejs which
// npm cannot find. Fix this:
sudo ln -s /usr/bin/nodejs /usr/bin/node
You need to open a new terminal session in order to use the updated npm
.
Source: This was originally an edit on jnylen's answer. Although the guidelines say "We welcome all constructive edits, but please make them substantial," the edit was rejected due to "This edit changes too much in the original post; the original meaning or intent of the post would be lost." I guess the community prefers a separate answer.
You have to use a dictionnary/array. For example :
to_19= ['zero','one','two','three','four','five','six','seven','eight','nine'..'nineteen']
tens = ['twenty'...'ninety']
And you could generate the string of a number by doing, for example :
if len(str(number)) == 2 and number > 20:
word_number = tens[str(number)[0]]+' '+units[str(number)[0]]
You have to check if the last figure is not a zero and so on.. classic value checking.
It reminds a project euler challenge (problem 17).. you should try to find some solutions about it
Hope it helps
It may be old C++ and optimizations. On my computer I obtained almost the same speed:
One loop: 1.577 ms
Two loops: 1.507 ms
I run Visual Studio 2015 on an E5-1620 3.5 GHz processor with 16 GB RAM.
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.
There is just a caveat that I discovered today.
If you have a function that is calling a plot a lot of times you better use plt.close(fig)
instead of fig.clf()
somehow the first does not accumulate in memory. In short if memory is a concern use plt.close(fig) (Although it seems that there are better ways, go to the end of this comment for relevant links).
So the the following script will produce an empty list:
for i in range(5):
fig = plot_figure()
plt.close(fig)
# This returns a list with all figure numbers available
print(plt.get_fignums())
Whereas this one will produce a list with five figures on it.
for i in range(5):
fig = plot_figure()
fig.clf()
# This returns a list with all figure numbers available
print(plt.get_fignums())
From the documentation above is not clear to me what is the difference between closing a figure and closing a window. Maybe that will clarify.
If you want to try a complete script there you have:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1000)
y = np.sin(x)
for i in range(5):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y)
plt.close(fig)
print(plt.get_fignums())
for i in range(5):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y)
fig.clf()
print(plt.get_fignums())
If memory is a concern somebody already posted a work-around in SO see: Create a figure that is reference counted
You have to use bracket notation:
var obj = {};
obj[a[i]] = 0;
x.push(obj);
The result will be:
x = [{left: 0}, {top: 0}];
Maybe instead of an array of objects, you just want one object with two properties:
var x = {};
and
x[a[i]] = 0;
This will result in x = {left: 0, top: 0}
.
I usually prefer the key sampling method to troubleshoot such scenarios.
redis-cli -p 6379 -n db_number --bigkeys
Eg:-
redis-cli -p 6370 -n 0 --bigkeys
It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here:
http://www.microsoft.com/sqlserver/en/us/editions/express.aspx
and the one for 64 bit WITH the management tools (management studio) is here:
http://www.microsoft.com/sqlserver/en/us/editions/express.aspx
From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively.
Just wanted to update this thread for future developers.
JQuery >1.12 Now supports being able to change every little piece of the request through JQuery.post ($.post({...}). see second function signature in https://api.jquery.com/jquery.post/
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');
Try to do...
DELIMITER $$
CREATE TRIGGER aumentarsalario
BEFORE INSERT
ON empregados
FOR EACH ROW
BEGIN
if (NEW.SALARIO < 900) THEN
set NEW.SALARIO = NEW.SALARIO + (NEW.SALARIO * 0.1);
END IF;
END $$
DELIMITER ;
Both the .ordinal()
and values()[i]
are unstable since they are dependent to the order of enums. Thus if you change the order of enums or add/delete some your program would break.
Here is a simple yet effective method to map between enum and int.
public enum Action {
ROTATE_RIGHT(0), ROTATE_LEFT(1), RIGHT(2), LEFT(3), UP(4), DOWN(5);
public final int id;
Action(int id) {
this.id = id;
}
public static Action get(int id){
for (Action a: Action.values()) {
if (a.id == id)
return a;
}
throw new IllegalArgumentException("Invalid id");
}
}
Applying it for strings shouldn't be difficult.
In the following example you have an PHP array, then firstly create a JavaScript array by a PHP array:
<script type="javascript">
day = new Array(<?php echo implode(',', $day); ?>);
week = new Array(<?php echo implode(',',$week); ?>);
month = new Array(<?php echo implode(',',$month); ?>);
<!-- Then pass it to the JavaScript function: -->
drawChart(<?php echo count($day); ?>, day, week, month);
</script>
Use ToString()
with this format:
12345.678901.ToString("0.0000"); // outputs 12345.6789
12345.0.ToString("0.0000"); // outputs 12345.0000
Put as much zero as necessary at the end of the format.
Even though, I have been using 400 to represent logical errors also, I have to say that returning 400 is wrong in this case because of the way the spec reads. Here is why i think so, the logical error could be that a relationship with another entity was failing or not satisfied and making changes to the other entity could cause the same exact to pass later. Like trying to (completely hypothetical) add an employee as a member of a department when that employee does not exist (logical error). Adding employee as member request could fail because employee does not exist. But the same exact request could pass after the employee has been added to the system.
Just my 2 cents ... We need lawyers & judges to interpret the language in the RFC these days :)
Thank You, Vish
Just read this great .Net DI container comparison blog by Philip Mat.
He does some thorough performance comparison tests on;
He recommends Autofac as it is small, fast, and easy to use ... I agree. It appears that Unity and Ninject are the slowest in his tests.
Loading the file from: {project}/src/main/webapp/WEB-INF/spring-dispatcher-servlet.xml
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring-dispatcher-servlet.xml" })
@WebAppConfiguration
public class TestClass {
@Test
public void test() {
// test definition here..
}
}
Chaining with the query builder interface in Mongoose 4.
// Build up a query using chaining syntax. Since no callback is passed this will create an instance of Query.
var query = Person.
find({ occupation: /host/ }).
where('name.last').equals('Ghost'). // find each Person with a last name matching 'Ghost'
where('age').gt(17).lt(66).
where('likes').in(['vaporizing', 'talking']).
limit(10).
sort('-occupation'). // sort by occupation in decreasing order
select('name occupation'); // selecting the `name` and `occupation` fields
// Excute the query at a later time.
query.exec(function (err, person) {
if (err) return handleError(err);
console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host
})
See the docs for more about queries.
You could try using the <col>
tag manage table styling for all rows but you will need to set the table-layout:fixed
style on the <table>
or the tables css class and set the overflow
style for the cells
http://www.w3schools.com/TAGS/tag_col.asp
<table class="fixed">
<col width="20px" />
<col width="30px" />
<col width="40px" />
<tr>
<td>text</td>
<td>text</td>
<td>text</td>
</tr>
</table>
and this be your CSS
table.fixed { table-layout:fixed; }
table.fixed td { overflow: hidden; }
I have build such kind of application using approximatively the same approach except :
UIImage
but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued.Whenever the user start zooming, I acquire the CGPDFPage
and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context
is like :
CGAffineTransform currentCTM = CGContextGetCTM(context);
if (currentCTM.a == 1.0 && baseImage) {
//Calculate ideal scale
CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width;
CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height;
CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight);
CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor);
CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height);
CGContextDrawImage(context, imageRect, [baseImage CGImage]);
} else {
@synchronized(issue) {
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1);
pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true);
CGContextConcatCTM(context, pdfToPageTransform);
CGContextDrawPDFPage(context, pdfPage);
}
}
issue is the object containg the CGPDFDocumentRef
. I synchronize the part where I access the pdfDoc
property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef
object do some internal caching that I did not find how to get rid of.
In case someone google for this, the solutions above didn't work for me so i ended using "pure" javascript
document.getElementById("The id of the element").value = "The value"
And that would set the value and make the current value selected in the combo box. Tested in firefox.
it was easier than keep googling a solution for jQuery
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.
The "BIGINT(20)" specification isn't a digit limit. It just means that when the data is displayed, if it uses less than 20 digits it will be left-padded with zeros. 2^64 is the hard limit for the BIGINT type, and has 20 digits itself, hence BIGINT(20) just means everything less than 10^20 will be left-padded with spaces on display.
The stopPropagation
options are bad because they can interfere with other event handlers including other menus that might have attached close handlers to the HTML element.
Here is a simple solution based on user2989143's answer:
$('html').click(function(event) {
if ($(event.target).closest('#menu-container, #menu-activator').length === 0) {
$('#menu-container').hide();
}
});
This powershell example looks for all instances of the string "\foo\" in a folder and its subfolders, replaces "\foo\" with "\bar\" AND DOES NOT REWRITE files that don't contain the string "\foo\" This way you don't destroy the file last update datetime stamps where the string was not found:
Get-ChildItem -Path C:\YOUR_ROOT_PATH\*.* -recurse
| ForEach {If (Get-Content $_.FullName | Select-String -Pattern '\\foo\\')
{(Get-Content $_ | ForEach {$_ -replace '\\foo\\', '\bar\'}) | Set-Content $_ }
}
I was having a very similar problem. I was getting inconsistent height() values when I refreshed my page. (It wasn't my variable causing the problem, it was the actual height value.)
I noticed that in the head of my page I called my scripts first, then my css file. I switched so that the css file is linked first, then the script files and that seems to have fixed the problem so far.
Hope that helps.
Use serialization to make deep copies. This is not the quickest solution but it does not depend on the type.
check
System.getProperty("sun.jnu.encoding")
it seems to be the same encoding as the one used in your system's command line.
The easiest way is to populate your bean would be from a Reader object, this can be done in a single call:
BufferedReader reader = request.getReader();
Gson gson = new Gson();
MyBean myBean = gson.fromJson(reader, MyBean.class);
The pointer str
is never allocated. It should be malloc
'd before use.
Use something like this to update your tomcat users.
<role rolename="manager-gui"/>
<user username="admin" password="admin" roles="manager-gui"/>
Tomcat users file is located inside conf
folder of tomcat installation.
To find the path of catalina_base you can use the command:
ps aux | grep catalina
You can find one of the values -Dcatalina.base=/usr/local/Cellar/tomcat/9.0.37/libexec
Don't forget to remove the comment lines from the tomcat-users.xml just before the start of the roles. <!-- -->
Hi I ran into the same problem when I was developing an application and wanted to install it on a remote PC, I fixed it by doing the following:
1) Goto your registry, locate: HKLM\System\CurrentControlSet\Services\EventLog\Application(???YOUR_SERVICE_OR_APP_NAME???)
Note that "(???YOUR_SERVICE_OR_APP_NAME???)" is your application service name as you defined it when you created your .NET deployment, for example, if you named your new application "My new App" then the key would be: HKLM\System\CurrentControlSet\Services\EventLog\Application\My New app
Note2: Depending on which eventLog you are writing into, you may find on your DEV box, \Application\ (as noted above), or also (\System) or (\Security) depending on what event your application is writing into, mostly, (\Application) should be fine all the times.
2) Being on the key above, From the menu; Select "FILE" -> "Export", and then save the file. (Note: This would create your necessary registry settings when the application would need to access this key to write into the Event Viewer), the new file will be a .REG file, for the argument sake, call it "My New App.REG"
3) When deploying on PRODuction, consult the Server's System's administrator (SA), hand over the "My New App.REG" file along with the application, and ask the SA to install this REG file, once done (as admin) this would create the key for your applicaion.
4) Run your application, it should not need to access anything else other than this key.
Problem should be resolved by now.
Cause:
When developing an application that writes anything into the EventLog, it would require a KEY for it under the Eventlog registry if this key isn't found, it would try to create it, which then fails for having no permissions to do so. The above process, is similar to deploying an application (manually) whereas we are creating this ourselves, and no need to have a headache since you are not tweaking the registry by adding permissions to EVERYONE which is a securty risk on production servers.
I hope this helps resolving it.
Try this
$('#your_select_element_id').val('your_value').attr().add('selected');
Most SSL certificates are bound to the hostname of the machine and not the ip address.
You might get a better answer if you ask this question on serverfault.com
This is the perfect answer for difference between Cloud Computing and Grid Computing ? Check this:
"this" extends the next class in the parameter list
So in the method signature below "this" extends "String". Line is passed to the function as a normal argument to the method. public static string[] SplitCsvLine(this String line)
In the above example "this" class is extending the built in "String" class.
I prefer to read and write clean code - as outlined in "Clean Code" by Robert C. Martin. When following his credo you should not require the developer (as user of your API) to know the (internal) structure of your array.
The API user may ask: Is that an array with one dimension only? Are the objects spread around on all levels of a multi dimensional array? How many nested loops (foreach, etc.) do i need to access all objects? What type of objects are "stored" in that array?
As you outlined you want to use that array (which contains objects) as a one dimensional array.
As outlined by Nishi you can use:
/**
* @return SomeObj[]
*/
for that.
But again: be aware - this is not a standard docblock notation. This notation was introduced by some IDE producers.
Okay, okay, as a developer you know that "[]" is tied to an array in PHP. But what do a "something[]" mean in normal PHP context? "[]" means: create new element within "something". The new element could be everything. But what you want to express is: array of objects with the same type and it´s exact type. As you can see, the IDE producer introduces a new context. A new context you had to learn. A new context other PHP developers had to learn (to understand your docblocks). Bad style (!).
Because your array do have one dimension you maybe want to call that "array of objects" a "list". Be aware that "list" has a very special meaning in other programming languages. It would be mutch better to call it "collection" for example.
Remember: you use a programming language that enables you all options of OOP. Use a class instead of an array and make your class traversable like an array. E.g.:
class orderCollection implements ArrayIterator
Or if you want to store the internal objects on different levels within an multi dimensional array/object structure:
class orderCollection implements RecursiveArrayIterator
This solution replaces your array by an object of type "orderCollection", but do not enable code completion within your IDE so far. Okay. Next step:
Implement the methods that are introduced by the interface with docblocks - particular:
/**
* [...]
* @return Order
*/
orderCollection::current()
/**
* [...]
* @return integer E.g. database identifier of the order
*/
orderCollection::key()
/**
* [...]
* @return Order
*/
orderCollection::offsetGet()
Do not forget to use type hinting for:
orderCollection::append(Order $order)
orderCollection::offsetSet(Order $order)
This solution stops introducing a lot of:
/** @var $key ... */
/** @var $value ... */
all over your code files (e.g. within loops), as Zahymaka confirmed with her/his answer. Your API user is not forced to introduce that docblocks, to have code completion. To have @return on only one place reduces the redundancy (@var) as mutch as possible. Sprinkle "docBlocks with @var" would make your code worst readable.
Finaly you are done. Looks hard to achive? Looks like taking a sledgehammer to crack a nut? Not realy, since you are familiar with that interfaces and with clean code. Remember: your source code is written once / read many.
If code completion of your IDE do not work with this approach, switch to a better one (e.g. IntelliJ IDEA, PhpStorm, Netbeans) or file a feature request on the issue tracker of your IDE producer.
Thanks to Christian Weiss (from Germany) for being my trainer and for teaching me such a great stuff. PS: Meet me and him on XING.
I do believe proper way to set the colour of UINavigationBar
is:
NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor],UITextAttributeTextColor, nil];
self.titleTextAttributes = attributes;
Code above is written is subclass on UINavigationBar
, obviously works without subclassing as well.
I believe you can only add variables to the Watch window while the debugger is stopped on a breakpoint. If you set a breakpoint on a step, you should be able to enter variables into the Watch window when the breakpoint is hit. You can select the first empty row in the Watch window and enter the variable name (you may or may not get some Intellisense there, I can't remember how well that works.)
Just going through http://projecteuler.net/problem=2 this was my take on it
# Even Fibonacci numbers
# Problem 2
def get_fibonacci(size):
numbers = [1,2]
while size > len(numbers):
next_fibonacci = numbers[-1]+numbers[-2]
numbers.append(next_fibonacci)
print numbers
get_fibonacci(20)
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.
Stack allocation will almost always be as fast or faster than heap allocation, although it is certainly possible for a heap allocator to simply use a stack based allocation technique.
However, there are larger issues when dealing with the overall performance of stack vs. heap based allocation (or in slightly better terms, local vs. external allocation). Usually, heap (external) allocation is slow because it is dealing with many different kinds of allocations and allocation patterns. Reducing the scope of the allocator you are using (making it local to the algorithm/code) will tend to increase performance without any major changes. Adding better structure to your allocation patterns, for example, forcing a LIFO ordering on allocation and deallocation pairs can also improve your allocator's performance by using the allocator in a simpler and more structured way. Or, you can use or write an allocator tuned for your particular allocation pattern; most programs allocate a few discrete sizes frequently, so a heap that is based on a lookaside buffer of a few fixed (preferably known) sizes will perform extremely well. Windows uses its low-fragmentation-heap for this very reason.
On the other hand, stack-based allocation on a 32-bit memory range is also fraught with peril if you have too many threads. Stacks need a contiguous memory range, so the more threads you have, the more virtual address space you will need for them to run without a stack overflow. This won't be a problem (for now) with 64-bit, but it can certainly wreak havoc in long running programs with lots of threads. Running out of virtual address space due to fragmentation is always a pain to deal with.
You also might want to take a look at libtap, a C testing framework which outputs the Test Anything Protocol (TAP) and thus integrates well with a variety of tools coming out for this technology. It's mostly used in the dynamic language world, but it's easy to use and becoming very popular.
An example:
#include <tap.h>
int main () {
plan(5);
ok(3 == 3);
is("fnord", "eek", "two different strings not that way?");
ok(3 <= 8732, "%d <= %d", 3, 8732);
like("fnord", "f(yes|no)r*[a-f]$");
cmp_ok(3, ">=", 10);
done_testing();
}
With xc8 you have to be careful about declaring a variable
as the same type in each file as you could , erroneously,
declare something an int
in one file and a char
say in another.
This could lead to corruption of variables.
This problem was elegantly solved in a microchip forum some 15 years ago /* See "http:www.htsoft.com" / / "forum/all/showflat.php/Cat/0/Number/18766/an/0/page/0#18766"
But this link seems to no longer work...
So I;ll quickly try to explain it; make a file called global.h.
In it declare the following
#ifdef MAIN_C
#define GLOBAL
/* #warning COMPILING MAIN.C */
#else
#define GLOBAL extern
#endif
GLOBAL unsigned char testing_mode; // example var used in several C files
Now in the file main.c
#define MAIN_C 1
#include "global.h"
#undef MAIN_C
This means in main.c the variable will be declared as an unsigned char
.
Now in other files simply including global.h will have it declared as an extern for that file.
extern unsigned char testing_mode;
But it will be correctly declared as an unsigned char
.
The old forum post probably explained this a bit more clearly.
But this is a real potential gotcha
when using a compiler
that allows you to declare a variable in one file and then declare it extern as a different type in another. The problems associated with
that are if you say declared testing_mode as an int in another file
it would think it was a 16 bit var and overwrite some other part of ram, potentially corrupting another variable. Difficult to debug!
In your link function, do this:
// link function
function (scope, element, attrs) {
var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}
Also, in your link function, don't name your scope
variable using a $
. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.
Here s what I suggest without using any other dependency , just node and express, use app.locals, here s an example :
app.get("/", function(req, res) {
var context = req.app.locals.specialContext;
req.app.locals.specialContext = null;
res.render("home.jade", context);
// or if you are using ejs
res.render("home", {context: context});
});
function middleware(req, res, next) {
req.app.locals.specialContext = * your context goes here *
res.redirect("/");
}
You can add #define uAppDelegate (AppDelegate *)[[UIApplication sharedApplication] delegate]
in your project's Prefix.pch
file and then call any method of your AppDelegate
in any UIViewController
with the below code.
[uAppDelegate showLoginView];
sdbm:this algorithm was created for sdbm (a public-domain reimplementation of ndbm) database library
static unsigned long sdbm(unsigned char *str)
{
unsigned long hash = 0;
int c;
while (c = *str++)
hash = c + (hash << 6) + (hash << 16) - hash;
return hash;
}
I am not about your PHP configuration but until PHP 5.2.6 , PHP does have some problem with SOAP client :
Not in the RFC, no, but there are practical limits.
The HTTP protocol does not place any a priori limit on the length of a URI. Servers MUST be able to handle the URI of any resource they serve, and SHOULD be able to handle URIs of unbounded length if they provide GET-based forms that could generate such URIs. A server SHOULD return 414 (Request-URI Too Long) status if a URI is longer than the server can handle (see section 10.4.15).
Note: Servers should be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations may not properly support these lengths.
You are confuising two CSS styles, the display style and the visibility style.
If the element is hidden by setting the visibility css style, then you should be able to get the height regardless of whether or not the element is visible or not as the element still takes space on the page.
If the element is hidden by changing the display css style to "none", then the element doesn't take space on the page, and you will have to give it a display style which will cause the element to render in some space, at which point, you can get the height.
I know its a long time since Jon's original answer, but I had a similar requirement to the OP.
By way of extending Jon's solution I came up with the following, which will take one or more path segments takes as many path segments that you can throw at it.
Usage
Path.combine("/Users/beardtwizzle/");
Path.combine("/", "Users", "beardtwizzle");
Path.combine(new String[] { "/", "Users", "beardtwizzle", "arrayUsage" });
Code here for others with a similar problem
public class Path {
public static String combine(String... paths)
{
File file = new File(paths[0]);
for (int i = 1; i < paths.length ; i++) {
file = new File(file, paths[i]);
}
return file.getPath();
}
}
for i,j in dictionary .items():
if i=='C1':
c=[]
for k in j:
j=k+10
c.append(j)
dictionary .update({i:c})
div{
border-left:solid red 3px;
border-right:solid violet 4px;
border-top:solid blue 4px;
border-bottom:solid green 4px;
background:grey;
width:100px; height:50px
}
I create a common init for the designated and required. For convenience inits I delegate to init(frame:)
with frame of zero.
Having zero frame is not a problem because typically the view is inside a ViewController's view; your custom view will get a good, safe chance to layout its subviews when its superview calls layoutSubviews()
or updateConstraints()
. These two functions are called by the system recursively throughout the view hierarchy. You can use either updateContstraints()
or layoutSubviews()
. updateContstraints()
is called first, then layoutSubviews()
. In updateConstraints()
make sure to call super last. In layoutSubviews()
, call super first.
Here's what I do:
@IBDesignable
class MyView: UIView {
convenience init(args: Whatever) {
self.init(frame: CGRect.zero)
//assign custom vars
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
commonInit()
}
private func commonInit() {
//custom initialization
}
override func updateConstraints() {
//set subview constraints here
super.updateConstraints()
}
override func layoutSubviews() {
super.layoutSubviews()
//manually set subview frames here
}
}
The best way to set/get the value of a textarea is the .val()
, .value
method.
.text()
internally uses the .textContent
(or .innerText
for IE) method to get the contents of a <textarea>
. The following test cases illustrate how text()
and .val()
relate to each other:
var t = '<textarea>';
console.log($(t).text('test').val()); // Prints test
console.log($(t).val('too').text('test').val()); // Prints too
console.log($(t).val('too').text()); // Prints nothing
console.log($(t).text('test').val('too').val()); // Prints too
console.log($(t).text('test').val('too').text()); // Prints test
The value
property, used by .val()
always shows the current visible value, whereas text()
's return value can be wrong.
You can index Dictionary, you didn't need 'get'.
Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);
An efficient way to test/get values is TryGetValue
(thanx to Earwicker):
if (otherExample.TryGetValue("key", out value))
{
otherExample["key"] = value + 1;
}
With this method you can fast and exception-less get values (if present).
Resources:
SHA1 is a one way hash. So you can not really revert it.
That's why applications use it to store the hash of the password and not the password itself.
Like every hash function SHA-1 maps a large input set (the keys) to a smaller target set (the hash values). Thus collisions can occur. This means that two values of the input set map to the same hash value.
Obviously the collision probability increases when the target set is getting smaller. But vice versa this also means that the collision probability decreases when the target set is getting larger and SHA-1's target set is 160 bit.
Jeff Preshing, wrote a very good blog about Hash Collision Probabilities that can help you to decide which hash algorithm to use. Thanks Jeff.
In his blog he shows a table that tells us the probability of collisions for a given input set.
As you can see the probability of a 32-bit hash is 1 in 2 if you have 77163 input values.
A simple java program will show us what his table shows:
public class Main {
public static void main(String[] args) {
char[] inputValue = new char[10];
Map<Integer, String> hashValues = new HashMap<Integer, String>();
int collisionCount = 0;
for (int i = 0; i < 77163; i++) {
String asString = nextValue(inputValue);
int hashCode = asString.hashCode();
String collisionString = hashValues.put(hashCode, asString);
if (collisionString != null) {
collisionCount++;
System.out.println("Collision: " + asString + " <-> " + collisionString);
}
}
System.out.println("Collision count: " + collisionCount);
}
private static String nextValue(char[] inputValue) {
nextValue(inputValue, 0);
int endIndex = 0;
for (int i = 0; i < inputValue.length; i++) {
if (inputValue[i] == 0) {
endIndex = i;
break;
}
}
return new String(inputValue, 0, endIndex);
}
private static void nextValue(char[] inputValue, int index) {
boolean increaseNextIndex = inputValue[index] == 'z';
if (inputValue[index] == 0 || increaseNextIndex) {
inputValue[index] = 'A';
} else {
inputValue[index] += 1;
}
if (increaseNextIndex) {
nextValue(inputValue, index + 1);
}
}
}
My output end with:
Collision: RvV <-> SWV
Collision: SvV <-> TWV
Collision: TvV <-> UWV
Collision: UvV <-> VWV
Collision: VvV <-> WWV
Collision: WvV <-> XWV
Collision count: 35135
It produced 35135 collsions and that's the nearly the half of 77163. And if I ran the program with 30084 input values the collision count is 13606. This is not exactly 1 in 10, but it is only a probability and the example program is not perfect, because it only uses the ascii chars between A
and z
.
Let's take the last reported collision and check
System.out.println("VvV".hashCode());
System.out.println("WWV".hashCode());
My output is
86390
86390
Conclusion:
If you have a SHA-1 value and you want to get the input value back you can try a brute force attack. This means that you have to generate all possible input values, hash them and compare them with the SHA-1 you have. But that will consume a lot of time and computing power. Some people created so called rainbow tables for some input sets. But these do only exist for some small input sets.
And remember that many input values map to a single target hash value. So even if you would know all mappings (which is impossible, because the input set is unbounded) you still can't say which input value it was.
Strange behavior with MS Excel
:
If i export to "text based, comma-separated format (csv
)" this is the mime-type I get after uploading on my webserver:
[name] => data.csv
[type] => application/vnd.ms-excel
So Microsoft seems to be doing own things again, regardless of existing standards: https://en.wikipedia.org/wiki/Comma-separated_values
This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.
The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(42, 68)
);
As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.
Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:
The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null
. In other words, leaving the anchor null ensures the tip points where it is supposed to point.
However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.
By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.
var pinShadow = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
null,
null,
/* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
new google.maps.Point(40, 110),
new google.maps.Size(120, 110));
to give this:
Hi in my case solutions here won't work My code:
index.js
import App from './App';
let store = createStore(App);
render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" name='Strona glówna' component={App}>
<IndexRoute name='' component={Welcome}/>
<Route name='Dashboard' path="dashboard" component={ReatEstateList}/>
Error apeares in App.js after import
Uncaught TypeError: Cannot call a class as a function
var data = Encoding.ASCII.GetBytes(json);
byte[] postBytes = Encoding.UTF8.GetBytes(json);
Use ASCII instead of UFT8
Sometimes you can have a bunch of keys in your ~/.ssh
directory, and don't know which matches the fingerprint shown by GitHub/Gitlab/etc.
Here's how to show the key filenames and MD5 fingerprints of all the keys in your ~/.ssh
directory:
cd ~/.ssh
find . -type f -exec printf "\n{}\n" \; -exec ssh-keygen -E md5 -lf {} \;
(For what the parameters mean, refer to this answer about the find
command.
Note that the private/public files that belong to one key have the same fingerprint, so you'll see duplicates.
What did the trick for me was to do cd src
from my project directoy, and then use the php artisan
command, since my artisan
file was in the src
folder. Here is my project structure:
project
|__ config
|__ src
|__ app
|__ ..
|__ artisan // hello there!
|__ ...
|__ ...
int index = dt.Rows.IndexOf(row);
But you're probably better off using a for loop instead of foreach.
Hash can create a new hash from an existing hash:
irb(main):009:0> h1 = {1 => 2}
=> {1=>2}
irb(main):010:0> h2 = Hash[h1]
=> {1=>2}
irb(main):011:0> h1.object_id
=> 2150233660
irb(main):012:0> h2.object_id
=> 2150205060
Create an Android app using Eclipse.
Create a layout that has a <WebView>
control.
Move your HTML code to /assets
folder.
Load webview with your file:///android_asset/ file.
And you have an android app!
The question is old but there is now this kind of desired function. I added a wrapper with not, left shift and dec.
You can use a wrapper function based on signbit from C99 in order to get the exact desired behavior (see code further below).
Returns whether the sign of x is negative.
This can be also applied to infinites, NaNs and zeroes (if zero is unsigned, it is considered positive
#include <math.h>
int signValue(float a) {
return ((!signbit(a)) << 1) - 1;
}
NB: I use operand not ("!") because the return value of signbit is not specified to be 1 (even though the examples let us think it would always be this way) but true for a negative number:
Return value
A non-zero value (true) if the sign of x is negative; and zero (false) otherwise.
Then I multiply by two with left shift (" << 1") which will give us 2 for a positive number and 0 for a negative one and finally decrement by 1 to obtain 1 and -1 for respectively positive and negative numbers as requested by OP.
I was in a position where I had 6 identical arrays and I needed to pick the right one depending on another variable and then assign values to it. In the case shown here $comp_cat was 'a' so I needed to pick my 'a' array ( I also of course had 'b' to 'f' arrays)
Note that the values for the position of the variable in the array go after the closing brace.
${'comp_cat_'.$comp_cat.'_arr'}[1][0] = "FRED BLOGGS";
${'comp_cat_'.$comp_cat.'_arr'}[1][1] = $file_tidy;
echo 'First array value is '.$comp_cat_a_arr[1][0].' and the second value is .$comp_cat_a_arr[1][1];
for Python and Swagger example:
import requests
base_url = 'https://petstore.swagger.io/v2'
def store_order(uid):
api_url = f"{base_url}/store/order"
api_data = {
'id':uid,
"petId": 0,
"quantity": 0,
"shipDate": "2020-04-08T07:56:05.832Z",
"status": "placed",
"complete": "true"
}
# is a kind of magic..
r = requests.post(api_url, json=api_data)
return r
print(store_order(0).content)
Most important string with MIME type: r = requests.post(api_url, json=api_data)
I prefer doing a "PAD" to the data. MySql calls it LPAD, but you can work your way around to doing the same thing in SQL Server.
ORDER BY REPLACE(STR(ColName, 3), SPACE(1), '0')
This formula will provide leading zeroes based on the Column's length of 3. This functionality is very useful in other situations outside of ORDER BY, so that is why I wanted to provide this option.
Results: 1 becomes 001, and 10 becomes 010, while 100 remains the same.
This is the W3C solution. Works in Firefox and Chrome.
ul { list-style-type: ""; }
/* Sets the marker to a emoji character */
http://dev.w3.org/csswg/css-lists/#marker-content
ul { list-style-type: " "; }
_x000D_
<ul><li>item</li></ul>
_x000D_
If the node.js or browser supported Object.entries()
, it can be used as an alternative to using Object.keys()
(https://stackoverflow.com/a/18804596/225291).
const h = {_x000D_
a: 1,_x000D_
b: 2_x000D_
};_x000D_
_x000D_
Object.entries(h).forEach(([key, value]) => console.log(value));_x000D_
// logs 1, 2
_x000D_
in this example, forEach
uses Destructuring assignment of an array.
ExecuteNonQuery():
ExecuteReader():
ExecuteScalar():
Reference URL:
http://nareshkamuni.blogspot.in/2012/05/what-is-difference-between.html
Unlike if
, guard
creates the variable that can be accessed from outside its block. It is useful to unwrap a lot of Optional
s.
This works for me, I only need first numbers in string:
TO_NUMBER(regexp_substr(h.HIST_OBSE, '\.*[[:digit:]]+\.*[[:digit:]]*'))
the field had the following string: "(43 Paginas) REGLAS DE PARTICIPACION"
.
result field: 43
If you have a collection of ints:
List<int> customerIds= new List<int>() { 1,2,3,3,4,5,6,7,8,9 };
You can use string.Join
to get a string:
var result = String.Join(",", customerIds);
Enjoy!
while true ; do
...
if [ something ]; then
break
fi
done
Main classes should be under src/main/java
and
test classes should be under src/test/java
If all in the correct places and still main classes are not accessible then
Right click project => Maven => Update Project
Hope so this will resolve the issue
When working in an enterprise project, there are many requirements available in middle-ware such as (saga) not available in simple asynchronous flow, below are some:
The list is long just review the advanced section in saga documentation
ActionBar actionBar;
actionBar = getActionBar();
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#93E9FA"));
actionBar.setBackgroundDrawable(colorDrawable);
You can use the below syntax -
from FolderName.FileName import Classname
First, to convert a Categorical column to its numerical codes, you can do this easier with: dataframe['c'].cat.codes
.
Further, it is possible to select automatically all columns with a certain dtype in a dataframe using select_dtypes
. This way, you can apply above operation on multiple and automatically selected columns.
First making an example dataframe:
In [75]: df = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab'), 'col3':list('ababb')})
In [76]: df['col2'] = df['col2'].astype('category')
In [77]: df['col3'] = df['col3'].astype('category')
In [78]: df.dtypes
Out[78]:
col1 int64
col2 category
col3 category
dtype: object
Then by using select_dtypes
to select the columns, and then applying .cat.codes
on each of these columns, you can get the following result:
In [80]: cat_columns = df.select_dtypes(['category']).columns
In [81]: cat_columns
Out[81]: Index([u'col2', u'col3'], dtype='object')
In [83]: df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes)
In [84]: df
Out[84]:
col1 col2 col3
0 1 0 0
1 2 1 1
2 3 2 0
3 4 0 1
4 5 1 1
I needed to know how to loop over enum values (was testing lots of permutations of several enums) and I found this to work well:
export enum Environment {
Prod = "http://asdf.com",
Stage = "http://asdf1234.com",
Test = "http://asdfasdf.example.com"
}
Object.keys(Environment).forEach((environmentKeyValue) => {
const env = Environment[environmentKeyValue as keyof typeof Environment]
// env is now equivalent to Environment.Prod, Environment.Stage, or Environment.Test
}
Source: https://blog.mikeski.net/development/javascript/typescript-enums-to-from-string/
I just ran into this problem. For me the issue was with:
readfile("$archive_file_name");
It was resulting in a out of memory error.
Allowed memory size of 134217728 bytes exhausted (tried to allocate 292982784 bytes)
I was able to correct the problem by replacing readfile() with the following:
$handle = fopen($zipPath, "rb");
while (!feof($handle)){
echo fread($handle, 8192);
}
fclose($handle);
Not sure if this is your same issue or not seeing that your file is only 1.2 MB. Maybe this will help someone else with a similar problem.
Test if SSH over the HTTPS port is possible, run this SSH command:
$ ssh -T -p 443 [email protected]
Hi username! You've successfully authenticated, but GitHub does not
provide shell access.
If that worked, great! If not, you may need to follow our troubleshooting guide.
If you are able to SSH into [email protected]
over port 443, you can override your SSH settings to force any connection to GitHub to run though that server and port.
To set this in your ssh config, edit the file at ~/.ssh/config
, and add this section:
Host github.com
Hostname ssh.github.com
Port 443
You can test that this works by connecting once more to GitHub:
$ ssh -T [email protected]
Hi username! You've successfully authenticated, but GitHub does not
provide shell access.
From Authenticating to GitHub / Using SSH over the HTTPS port
you are almost there; you just need to give the reference to master; since you want to get the file from the master branch:
git checkout master -- filename
Note that the differences will be cached; so if you want to see the differences you obtained; use
git diff --cached
I like to do it with a static method in the second activity:
private static final String EXTRA_GAME_ID = "your.package.gameId";
public static void start(Context context, String gameId) {
Intent intent = new Intent(context, SecondActivity.class);
intent.putExtra(EXTRA_GAME_ID, gameId);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
...
Intent intent = this.getIntent();
String gameId = intent.getStringExtra(EXTRA_GAME_ID);
}
Then from your first activity (and for anywhere else), you just do:
SecondActivity.start(this, "the.game.id");
You can try the display:inline-block and :after.Like this:
<ul>
<li><a href="">I would like this text centered vertically</a></li>
</ul>
li a {
width: 300px;
height: 100px;
margin: auto 0;
display: inline-block;
vertical-align: middle;
background: red;
}
li a:after {
content:"";
display: inline-block;
width: 1px solid transparent;
height: 100%;
vertical-align: middle;
}
Please view the demo.
You don't need any plugins to do this.
Just select all lines (Ctrl A) and then from the menu select Edit → Line → Reindent.
This will work if your file is saved with an extension that contains HTML like .html
or .php
.
If you do this often, you may find this key mapping useful:
{ "keys": ["ctrl+shift+r"], "command": "reindent" , "args": { "single_line": false } }
If your file is not saved (e.g. you just pasted in a snippet to a new window), you can manually set the language for indentation by selecting the menu View → Syntax → language of choice
before selecting the reindent option.
A re-hash of Aacini's code because most likely you are going to set the start time as a variable and want to save that data for output:
@echo off
rem ****************** MAIN CODE SECTION
set STARTTIME=%TIME%
rem Your code goes here (remove the ping line)
ping -n 4 -w 1 127.0.0.1 >NUL
set ENDTIME=%TIME%
rem ****************** END MAIN CODE SECTION
rem Change formatting for the start and end times
for /F "tokens=1-4 delims=:.," %%a in ("%STARTTIME%") do (
set /A "start=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
for /F "tokens=1-4 delims=:.," %%a in ("%ENDTIME%") do (
IF %ENDTIME% GTR %STARTTIME% set /A "end=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
IF %ENDTIME% LSS %STARTTIME% set /A "end=((((%%a+24)*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
rem Calculate the elapsed time by subtracting values
set /A elapsed=end-start
rem Format the results for output
set /A hh=elapsed/(60*60*100), rest=elapsed%%(60*60*100), mm=rest/(60*100), rest%%=60*100, ss=rest/100, cc=rest%%100
if %hh% lss 10 set hh=0%hh%
if %mm% lss 10 set mm=0%mm%
if %ss% lss 10 set ss=0%ss%
if %cc% lss 10 set cc=0%cc%
set DURATION=%hh%:%mm%:%ss%,%cc%
echo Start : %STARTTIME%
echo Finish : %ENDTIME%
echo ---------------
echo Duration : %DURATION%
Output:
Start : 11:02:45.92
Finish : 11:02:48.98
---------------
Duration : 00:00:03,06
First, checkout to your Branch3:
git checkout Branch3
Then merge the Branch1:
git merge Branch1
And if you want the updated commits of Branch1 on Branch2, you are probaly looking for git rebase
git checkout Branch2
git rebase Branch1
This will update your Branch2 with the latest updates of Branch1.
Your error message is pretty explicit about what is going wrong:
laravel/framework v5.2.9 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
Do you have mbstring
installed on your server and is it enabled?
You can install mbstring
as part of the libapache2-mod-php5 package:
sudo apt-get install libapache2-mod-php5
Or standalone with:
sudo apt-get install php-mbstring
Installing it will also enable it, however you can also enable it by editing your php.ini
file and remove the ;
that is commenting it out if it is already installed.
If this is on your local machine, then follow the appropriate steps to install this on your environment.
Eclipse artifact searching depends on repository's index file. It seems you did not download the index file.
Go to Window -> Prefrences -> Maven and check "Download repository index updates on start". Restart Eclipse and then look at the progress view. An index file should be downloading.
After downloading completely, artifact searching will be ready to use.
UPDATE You also need to rebuild your Maven repository index in 'maven repository view'.
In this view , open 'Global Repositories', right-click 'central', check 'Full Index Enable', and then, click 'Rebuild Index' in the same menu.
A 66M index file will be downloaded.
In my windows machine, I solved this by adding the below code snippet in rules
object of .eslintrc.js
file present in my current project's directory.
"prettier/prettier": [
"error",
{
"endOfLine": "auto"
},
],
This worked on my Mac as well
Just in case you want to handle the behaviour of the back button (at the bottom of the phone) and the home button (the one to the left of the action bar), this custom activity I'm using in my project may help you.
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
/**
* Activity where the home action bar button behaves like back by default
*/
public class BackActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupHomeButton();
}
private void setupHomeButton() {
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onMenuHomePressed();
return true;
}
return super.onOptionsItemSelected(item);
}
protected void onMenuHomePressed() {
onBackPressed();
}
}
Example of use in your activity:
public class SomeActivity extends BackActivity {
// ....
@Override
public void onBackPressed()
{
// Example of logic
if ( yourConditionToOverride ) {
// ... do your logic ...
} else {
super.onBackPressed();
}
}
}
If you know the format of date in $_POST[intake_date] you can use explode to get year , month and time and then concatenate to form a valid mySql date. for example if you are getting something like 12/15/1988 in date you can do like this
$date = explode($_POST['intake_date'], '/');
mysql_date = $date[2].'-'$date[1].'-'$date[0];
though if you have valid date date('y-m-d', strtotime($date)); should also work
You can use gethostname followed by gethostbyname to get your local interface internal IP.
This returned IP may be different from your external IP though. To get your external IP you would have to communicate with an external server that will tell you what your external IP is. Because the external IP is not yours but it is your routers.
//Example: b1 == 192, b2 == 168, b3 == 0, b4 == 100
struct IPv4
{
unsigned char b1, b2, b3, b4;
};
bool getMyIP(IPv4 & myIP)
{
char szBuffer[1024];
#ifdef WIN32
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD(2, 0);
if(::WSAStartup(wVersionRequested, &wsaData) != 0)
return false;
#endif
if(gethostname(szBuffer, sizeof(szBuffer)) == SOCKET_ERROR)
{
#ifdef WIN32
WSACleanup();
#endif
return false;
}
struct hostent *host = gethostbyname(szBuffer);
if(host == NULL)
{
#ifdef WIN32
WSACleanup();
#endif
return false;
}
//Obtain the computer's IP
myIP.b1 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b1;
myIP.b2 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b2;
myIP.b3 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b3;
myIP.b4 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b4;
#ifdef WIN32
WSACleanup();
#endif
return true;
}
You can also always just use 127.0.0.1 which represents the local machine always.
Subnet mask in Windows:
You can get the subnet mask (and gateway and other info) by querying subkeys of this registry entry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
Look for the registry value SubnetMask.
Other methods to get interface information in Windows:
You could also retrieve the information you're looking for by using: WSAIoctl with this option: SIO_GET_INTERFACE_LIST
This should be enough to get you started.
class Program
{
static void Main(String[] args)
{
const int bufferSize = 1024;
var sb = new StringBuilder();
var buffer = new Char[bufferSize];
var length = 0L;
var totalRead = 0L;
var count = bufferSize;
using (var sr = new StreamReader(@"C:\Temp\file.txt"))
{
length = sr.BaseStream.Length;
while (count > 0)
{
count = sr.Read(buffer, 0, bufferSize);
sb.Append(buffer, 0, count);
totalRead += count;
}
}
Console.ReadKey();
}
}
-(void)setNavigationItems{
UIBarButtonItem *leftBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"**Your title here**" style:UIBarButtonItemStyleBordered target:self action:@selector(backButtonClicked)];
self.navigationController.navigationBar.topItem.backBarButtonItem=leftBarButtonItem;
}
-(void)backButtonClicked{
[self.navigationController popViewControllerAnimated:YES];
}
If you are using sublime then this code may work if you add it in build as code for building system. You can use this link for more information.
{
"shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\"",
"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
"working_dir": "${file_path}",
"selector": "source.c, source.c++",
"variants":
[
{
"name": "Run",
"shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""
}
]
}
I haven't played with these settings myself so this is just speculation but if we think about this issue as normal cores and threads in a distributed system then in your cluster you can use up to 12 cores (4 * 3 machines) and 24 threads (8 * 3 machines). In your first two examples you are giving your job a fair number of cores (potential computation space) but the number of threads (jobs) to run on those cores is so limited that you aren't able to use much of the processing power allocated and thus the job is slower even though there is more computation resources allocated.
you mention that your concern was in the shuffle step - while it is nice to limit the overhead in the shuffle step it is generally much more important to utilize the parallelization of the cluster. Think about the extreme case - a single threaded program with zero shuffle.
When you define any variable then you do not have to put in any extra spaces.
E.g.
name = "Stack Overflow"
// it is not valid, you will get an error saying- "Command not found"
So remove spaces:
name="Stack Overflow"
and it will work fine.
const char*
is a pointer to a constant character
char* const
is a constant pointer to a character
const char* const
is a constant pointer to a constant character
The simplest and best solution is just to use XMLRoot attribute in your class, in which you wish to deserialize.
Like:
[XmlRoot(ElementName = "YourPreferableNameHere")]
public class MyClass{
...
}
Also, use the following Assembly :
using System.Xml.Serialization;
From strdup man:
The strdup()
function shall return a pointer to a new string, which is a duplicate of the string pointed to by s1
. The returned pointer can be passed to free()
. A null pointer is returned if the new string cannot be created.
It is called an array initializer and can be explained in the Java specification 10.6.
This can be used to initialize any array, but it can only be used for initialization (not assignment to an existing array). One of the unique things about it is that the dimensions of the array can be determined from the initializer. Other methods of creating an array require you to manually insert the number. In many cases, this helps minimize trivial errors which occur when a programmer modifies the initializer and fails to update the dimensions.
Basically, the initializer allocates a correctly sized array, then goes from left to right evaluating each element in the list. The specification also states that if the element type is an array (such as it is for your case... we have an array of double[]), that each element may, itself be an initializer list, which is why you see one outer set of braces, and each line has inner braces.
As stated by alfo888_ibg:
@Override
public void onClick(View arg0) {
Toast.makeText(activity,"Text!",Toast.LENGTH_SHORT).show();
}
Just do:
Toast.makeText(getActivity(),"Text!",Toast.LENGTH_SHORT).show();
this worked for me.
There is the .update() method :)
update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.
update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).
Changed in version 2.4: Allowed the argument to be an iterable of key/value pairs and allowed keyword arguments.
Use this to get time from 00:00:00 to 23:59:59
If your time is having date from it by using 'LT or LTS'
var now = moment('23:59:59','HHmmss').format("HH:mm:ss")
Check if the user has scrolled past the header ad, then display the footer ad.
if($(your header ad).position().top < 0) { $(your footer ad).show() }
Am I correct at what you are looking for?
Use like this (source):
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie = c_name+"="+c_value+"; path=/";
}
Have a look at List.AddRange to merge Lists
To access properties and methods of a parent class use the base
keyword. So in your child class LoadData()
method you would do this:
public class Child : Parent
{
public void LoadData()
{
base.MyMethod(); // call method of parent class
base.CurrentRow = 1; // set property of parent class
// other stuff...
}
}
Note that you would also have to change the access modifier of your parent MyMethod()
to at least protected
for the child class to access it.
Env - AS 3.3.2 Linux 4 (ubuntu)
in AS used menu Tools > Create desktop entry
Desktop file content - ( note the path does NOT include Platform-tools )
[Desktop Entry]
Encoding=UTF-8
Version=1.0
Type=Application
Name=Android Studio
Icon=jetbrains-studio.png
Path=/home/rob/android-studio
Exec=sh -c ' /home/rob/android-studio/bin/studio.sh'
StartupNotify=false
StartupWMClass=jetbrains-studio
OnlyShowIn=Unity;
X-UnityGenerated=true
Note that the location of SDK.platform-tools 'adb' below will not be found by desktop.PATH above:
$ which adb
/usr/local/src/android-sdk-linux/platform-tools/adb
On my setup, my symptom was that any terminal would list the device OK but the toolbar button in AS would never show a connected device... "no devices" is all i would ever see when my phone was connected via USB cable.
SOLUTION for me was adding the correct PATH near the top of the file:
${AS_HOME}/bin/studio.sh ...
PATH=$PATH:/usr/local/src/android-sdk-linux/platform-tools:/usr/local/src/android-sdk-linux/tools
In case of using Mysql query browser, SET FOREIGN_KEY_CHECKS=0;
does not have any impact in version 1.1.20. However, it works fine on Mysql query browser 1.2.17
@PaulR posted this as a comment, but people should view it as an answer (and this answer works best for my needs):
sed -i 's/abc/xyz/g' xa*
This will work for a moderate amount of files, probably on the order of tens, but probably not on the order of millions.
From reading the source code, if a java.sql.Date
does actually have time information, calling getTime()
will return a value that includes the time information.
If that is not working, then the information is not in the java.sql.Date
object. I expect that the JDBC drivers or the database is (in effect) zeroing the time component ... or the information wasn't there in the first place.
I think you should be using java.sql.Timestamp
and the corresponding resultset methods, and the corresponding SQL type.
They all are unique, yes
If you're sure that your values are unique you can iterate over the entries of your old map .
Map<String, Character> myNewHashMap = new HashMap<>();
for(Map.Entry<Character, String> entry : myHashMap.entrySet()){
myNewHashMap.put(entry.getValue(), entry.getKey());
}
Alternatively, you can use a Bi-Directional map like Guava provides and use the inverse()
method :
BiMap<Character, String> myBiMap = HashBiMap.create();
myBiMap.put('a', "test one");
myBiMap.put('b', "test two");
BiMap<String, Character> myBiMapInversed = myBiMap.inverse();
As java-8 is out, you can also do it this way :
Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);
Map<Integer, String> mapInversed =
map.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey))
Finally, I added my contribution to the proton pack library, which contains utility methods for the Stream API. With that you could do it like this:
Map<Character, String> mapInversed = MapStream.of(map).inverseMapping().collect();
You can implement a class that holds the fields you have in your JSON
class MyData
{
public string t;
public bool a;
public object[] data;
public string[][] type;
}
and then use the generic version of DeserializeObject:
MyData tmp = JsonConvert.DeserializeObject<MyData>(json);
foreach (string typeStr in tmp.type[0])
{
// Do something with typeStr
}
Documentation: Serializing and Deserializing JSON
This is my error code:
OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "The Microsoft Access database engine could not find the object 'ByStore$'. Make sure the object exists and that you spell its name and the path name correctly. If 'ByStore$' is not a local object, check your network connection or contact the server administrator.".
Msg 7350, Level 16, State 2, Procedure PeopleCounter_daily, Line 26
Cannot get the column information from OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".
My problem was the excel file was missing at the path. Just put the file with the correct sheet will do.
Not the answer for the above problem but on the similar lines.
Program to print the elements of the array sequentially but use two different threads to print the adjacent elements
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author ntv
*/
public class PrintLAternateNumber {
public static void main(String[] args) {
int [] num = {1,2,3,4,5,6};
Printer p = new Printer();
Thread t1 = new Thread(new Thread1(num, p), "Thread1");
Thread t2 = new Thread(new Thread2(num, p), "Thread2");
t1.start();
t2.start();
}
}
class Thread1 implements Runnable {
int [] num;
Printer p ;
public Thread1(int[] num, Printer p) {
this.num = num;
this.p = p;
}
public void run() {
try {
print();
} catch (InterruptedException ex) {
Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void print() throws InterruptedException {
int i = 1;
while(i < num.length) {
synchronized(num) {
while (p.evenPrinted) {
num.wait();
}
}
synchronized(num) {
p.printEven(Thread.currentThread().getName(), num[i]);
i= i + 2;
num.notifyAll();
}
}
}
}
class Thread2 implements Runnable {
int [] num;
Printer p ;
public Thread2(int[] num, Printer p) {
this.num = num;
this.p = p;
}
public void run() {
try {
print();
} catch (InterruptedException ex) {
Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void print() throws InterruptedException {
int i = 0;
while(i < num.length) {
synchronized(num) {
while (!p.evenPrinted) {
num.wait();
}
}
synchronized(num) {
p.printOdd(Thread.currentThread().getName(), num[i]);
i = i + 2;
num.notifyAll();
}
}
}
}
class Printer {
boolean evenPrinted = true;
void printEven(String threadName , int i) {
System.out.println(threadName + "," + i);
evenPrinted = true;
}
void printOdd(String threadName , int i) {
System.out.println(threadName + "," + i);
evenPrinted = false;
}
}
Got this off an Android forum where I asked the same question. Hope this helps somebody else.
On a terminal emulator on the phone:
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
Then on the cmd prompt, do the adb push
I wanted to do this in React using plain Js and the fetch polyfill. OP didn't say he specifically wanted to create a form and invoke the submit method on it, so I have done it by posting the form values as json:
examplePostData = {
method: 'POST',
headers: {
'Content-type' : 'application/json',
'Accept' : 'text/html'
},
body: JSON.stringify({
someList: [1,2,3,4],
someProperty: 'something',
someObject: {some: 'object'}
})
}
asyncPostPopup = () => {
//open a new window and set some text until the fetch completes
let win=window.open('about:blank')
writeToWindow(win,'Loading...')
//async load the data into the window
fetch('../postUrl', this.examplePostData)
.then((response) => response.text())
.then((text) => writeToWindow(win,text))
.catch((error) => console.log(error))
}
writeToWindow = (win,text) => {
win.document.open()
win.document.write(text)
win.document.close()
}
In relation to the top answer I have a possible solution to the security risk.
<?php
if(isset($_GET['path'])){
if(in_array($_GET['path'], glob("*/*.*"))){
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
}
}
?>
Using the glob() function (I tested the download file in a path one folder up from the file to be downloaded) I was able to make a quick array of files that are "allowed" to be downloaded and checked the passed path against it. Not only does this insure that the file being grabbed isn't something sensitive but also checks on the files existence at the same time.
~Note: Javascript / HTML~
HTML:
<iframe id="download" style="display:none"></iframe>
and
<input type="submit" value="Download" onclick="ChangeSource('document_path');return false;">
JavaScript:
<script type="text/javascript">
<!--
function ChangeSource(path){
document.getElementByID('download').src = 'path_to_php?path=' + document_path;
}
-->
</script>
Note: I am assuming the array is sorted.
Code:
int[] input = new int[]{1, 1, 3, 7, 7, 8, 9, 9, 9, 10};
int current = input[0];
boolean found = false;
for (int i = 0; i < input.length; i++) {
if (current == input[i] && !found) {
found = true;
} else if (current != input[i]) {
System.out.print(" " + current);
current = input[i];
found = false;
}
}
System.out.print(" " + current);
output:
1 3 7 8 9 10
You have to add the reference to the project.
In Assemblies, there is a System.Web.Extensions Add that.
Once that is done put:
using System.Web;
using System.Web.Script;
using System.Web.Script.Serialization;
That worked for me.
Working in Rails 5
ActiveModel::Type::Boolean.new.cast('t') # => true
ActiveModel::Type::Boolean.new.cast('true') # => true
ActiveModel::Type::Boolean.new.cast(true) # => true
ActiveModel::Type::Boolean.new.cast('1') # => true
ActiveModel::Type::Boolean.new.cast('f') # => false
ActiveModel::Type::Boolean.new.cast('0') # => false
ActiveModel::Type::Boolean.new.cast('false') # => false
ActiveModel::Type::Boolean.new.cast(false) # => false
ActiveModel::Type::Boolean.new.cast(nil) # => nil
netstat -aof | findstr :8080
(Change 8080 for any port)
I used yet another trick to format date with 6-digit precision (microseconds):
System.out.println(
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.").format(microseconds/1000)
+String.format("%06d", microseconds%1000000));
This technique can be extended further, to nanoseconds and up.
I did following steps to downgrade Gradle back to the original version:
Probably last step is enough as in my case the path to the new Gradle distribution was hardcoded there under 'Gradle home' option.
I like how the pycron package solves this problem.
import pycron
import time
while True:
if pycron.is_now('0 2 * * 0'): # True Every Sunday at 02:00
print('running backup')
time.sleep(60) # The process should take at least 60 sec
# to avoid running twice in one minute
else:
time.sleep(15) # Check again in 15 seconds
On Windows 10, you can enable Ctrl + C and Ctrl + V to work in the command prompt:
In PHP this did it for me (assuming the filename is UTF8 encoded):
header('Content-Disposition: attachment;'
. 'filename="' . addslashes(utf8_decode($filename)) . '";'
. 'filename*=utf-8\'\'' . rawurlencode($filename));
Tested against IE8-11, Firefox and Chrome.
If the browser can interpret filename*=utf-8 it will use the UTF8 version of the filename, else it will use the decoded filename. If your filename contains characters that can't be represented in ISO-8859-1 you might want to consider using iconv
instead.
body{_x000D_
background: #333 url(/images/classy_fabric.png);_x000D_
width: 430px;_x000D_
margin: 0 auto;_x000D_
padding: 30px;_x000D_
}_x000D_
.preview{_x000D_
background: #ccc;_x000D_
width: 415px;_x000D_
height: 430px;_x000D_
border: solid 10px #fff;_x000D_
}_x000D_
_x000D_
input[type='radio'] {_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
width: 25px;_x000D_
height: 25px;_x000D_
margin: 5px 0 5px 5px;_x000D_
background-size: 225px 70px;_x000D_
position: relative;_x000D_
float: left;_x000D_
display: inline;_x000D_
top: 0;_x000D_
border-radius: 3px;_x000D_
z-index: 99999;_x000D_
cursor: pointer;_x000D_
box-shadow: 1px 1px 1px #000;_x000D_
}_x000D_
_x000D_
input[type='radio']:hover{_x000D_
-webkit-filter: opacity(.4);_x000D_
filter: opacity(.4); _x000D_
}_x000D_
_x000D_
.red{_x000D_
background: red;_x000D_
}_x000D_
_x000D_
.red:checked{_x000D_
background: linear-gradient(brown, red)_x000D_
}_x000D_
_x000D_
.green{_x000D_
background: green;_x000D_
}_x000D_
_x000D_
.green:checked{_x000D_
background: linear-gradient(green, lime);_x000D_
}_x000D_
_x000D_
.yellow{_x000D_
background: yellow;_x000D_
}_x000D_
_x000D_
.yellow:checked{_x000D_
background: linear-gradient(orange, yellow);_x000D_
}_x000D_
_x000D_
.purple{_x000D_
background: purple;_x000D_
}_x000D_
_x000D_
.pink{_x000D_
background: pink;_x000D_
}_x000D_
_x000D_
.purple:checked{_x000D_
background: linear-gradient(purple, violet);_x000D_
}_x000D_
_x000D_
.red:checked ~ img{_x000D_
-webkit-filter: opacity(.5) drop-shadow(0 0 0 red);_x000D_
filter: opacity(.5) drop-shadow(0 0 0 red);_x000D_
}_x000D_
_x000D_
.green:checked ~ img{_x000D_
-webkit-filter: opacity(.5) drop-shadow(0 0 0 green);_x000D_
filter: opacity(.5) drop-shadow(0 0 0 green);_x000D_
}_x000D_
_x000D_
.yellow:checked ~ img{_x000D_
-webkit-filter: opacity(.5) drop-shadow(0 0 0 yellow);_x000D_
filter: opacity(.5) drop-shadow(0 0 0 yellow);_x000D_
}_x000D_
_x000D_
.purple:checked ~ img{_x000D_
-webkit-filter: opacity(.5) drop-shadow(0 0 0 purple);_x000D_
filter: opacity(.5) drop-shadow(0 0 0 purple);_x000D_
}_x000D_
_x000D_
.pink:checked ~ img{_x000D_
-webkit-filter: opacity(.5) drop-shadow(0 0 0 pink);_x000D_
filter: opacity(.5) drop-shadow(0 0 0 pink);_x000D_
}_x000D_
_x000D_
_x000D_
img{_x000D_
width: 394px;_x000D_
height: 375px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.label{_x000D_
width: 150px;_x000D_
height: 75px;_x000D_
position: absolute;_x000D_
top: 170px;_x000D_
margin-left: 130px;_x000D_
}_x000D_
_x000D_
::selection{_x000D_
background: #000;_x000D_
}
_x000D_
<div class="preview">_x000D_
<input class='red' name='color' type='radio' />_x000D_
<input class='green' name='color' type='radio' />_x000D_
<input class='pink' name='color' type='radio' />_x000D_
<input checked class='yellow' name='color' type='radio' />_x000D_
<input class='purple' name='color' type='radio' /> _x000D_
<img src="https://i.stack.imgur.com/bd7VJ.png"/>_x000D_
</div>
_x000D_
You can easily make SSH connections using SSHLibrary. Read this post :
https://workpython.blogspot.com/2020/04/creating-ssh-connections-with-python.html
You would normally use next(incsv)
which advances the iterator one row, so you skip the header. The other (say you wanted to skip 30 rows) would be:
from itertools import islice
for row in islice(incsv, 30, None):
# process
new DecimalFormat("#0.##").format(bd)
log
simply takes the logarithm (base e
, by default) of each element of the vector.
scale
, with default settings, will calculate the mean and standard deviation of the entire vector, then "scale" each element by those values by subtracting the mean and dividing by the sd. (If you use scale(x, scale=FALSE)
, it will only subtract the mean but not divide by the std deviation.)
Note that this will give you the same values
set.seed(1)
x <- runif(7)
# Manually scaling
(x - mean(x)) / sd(x)
scale(x)
Find the local IP address of computer A and find the port that your website is running on. Then from computer B open a web browser and go to IP:port. Example: 192.168.1.5:80 if computer A's IP is 192.168.1.5 and your website is running on port 80
You should use this:
<Link to={this.props.myroute} onClick={hello}>Here</Link>
Or (if method hello
lays at this class):
<Link to={this.props.myroute} onClick={this.hello}>Here</Link>
Update: For ES6 and latest if you want to bind some param with click method, you can use this:
const someValue = 'some';
....
<Link to={this.props.myroute} onClick={() => hello(someValue)}>Here</Link>
Swift 5 for cocoa
// Getting the Contents of a Directory in a Single Batch Operation
let bundleRoot = Bundle.main.bundlePath
let url = URL(string: bundleRoot)
let properties: [URLResourceKey] = [ URLResourceKey.localizedNameKey, URLResourceKey.creationDateKey, URLResourceKey.localizedTypeDescriptionKey]
if let src = url{
do {
let paths = try FileManager.default.contentsOfDirectory(at: src, includingPropertiesForKeys: properties, options: [])
for p in paths {
if p.hasSuffix(".data"){
print("File Path is: \(p)")
}
}
} catch { }
}
This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:
bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$
In Node.js we can do it in simple way
var base64 = 'SGVsbG8gV29ybGQ='
var base64_decode = new Buffer(base64, 'base64').toString('ascii');
console.log(base64_decode); // "Hello World"
Try
find . -name \*.mp3 -print0 | xargs -0 mplayer
instead of
ls | grep mp3
The equivalent C code looks like this:
#include <stdio.h>
#include <string.h>
// This code outputs: h is in "This is my test string"
int main(int argc, char* argv[])
{
const char *invalid_characters = "hz";
char *mystring = "This is my test string";
char *c = mystring;
while (*c)
{
if (strchr(invalid_characters, *c))
{
printf("%c is in \"%s\"\n", *c, mystring);
}
c++;
}
return 0;
}
Note that invalid_characters is a C string, ie. a null-terminated char
array.
The way I would do it is to leave the __ init__.py files empty, and do:
import lib.mod1.mod11
lib.mod1.mod11.mod12()
or
from lib.mod1.mod11 import mod12
mod12()
You may find that the mod1 dir is unnecessary, just have mod12.py in lib.
Here is another way you can get to the root of your website without hard coding the url:
var response = Request.CreateResponse(HttpStatusCode.Moved);
string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
response.Headers.Location = new Uri(fullyQualifiedUrl);
Note: Will only work if both your MVC website and WebApi are on the same URL
NOTE: Please check device location latitude & logitude if you are using simulator means. By defaults its none only.
Step 1: Import CoreLocation
framework in .h File
#import <CoreLocation/CoreLocation.h>
Step 2: Add delegate CLLocationManagerDelegate
@interface yourViewController : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
CLLocation *currentLocation;
}
Step 3: Add this code in class file
- (void)viewDidLoad
{
[super viewDidLoad];
[self CurrentLocationIdentifier]; // call this method
}
Step 4: Method to detect current location
//------------ Current Location Address-----
-(void)CurrentLocationIdentifier
{
//---- For getting current gps location
locationManager = [CLLocationManager new];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
//------
}
Step 5: Get location using this method
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
currentLocation = [locations objectAtIndex:0];
[locationManager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
{
if (!(error))
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"\nCurrent Location Detected\n");
NSLog(@"placemark %@",placemark);
NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
NSString *Address = [[NSString alloc]initWithString:locatedAt];
NSString *Area = [[NSString alloc]initWithString:placemark.locality];
NSString *Country = [[NSString alloc]initWithString:placemark.country];
NSString *CountryArea = [NSString stringWithFormat:@"%@, %@", Area,Country];
NSLog(@"%@",CountryArea);
}
else
{
NSLog(@"Geocode failed with error %@", error);
NSLog(@"\nCurrent Location Not Detected\n");
//return;
CountryArea = NULL;
}
/*---- For more results
placemark.region);
placemark.country);
placemark.locality);
placemark.name);
placemark.ocean);
placemark.postalCode);
placemark.subLocality);
placemark.location);
------*/
}];
}
serialize() is not a good idea if you want to send a form with post method. For example if you want to pass a file via ajax its not gonna work.
Suppose that we have a form with this id : "myform".
the better solution is to make a FormData and send it:
var myform = document.getElementById("myform");
var fd = new FormData(myform );
$.ajax({
url: "example.php",
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (dataofconfirm) {
// do something with the result
}
});
You can run build
for a specific service by running docker-compose up --build <service name>
where the service name must match how did you call it in your docker-compose file.
Example
Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application
in docker-compose file.
You can then simply run docker-compose up --build application
Extra parameters
In case you want to add extra parameters to your command such as -d
for running in the background, the parameter must be before the service name:
docker-compose up --build -d application
This sentence gets it:
In general, the way to get the best of both worlds is to rebase local changes you’ve made, but haven’t shared yet, before you push them in order to clean up your story, but never rebase anything you’ve pushed somewhere.
I used pandas and it worked well... While I was using it, I had to open a file and add some random columns to it and then save back to same file only.
This code adds multiple column entries, you may edit as much you need.
import pandas as pd
csv_input = pd.read_csv('testcase.csv') #reading my csv file
csv_input['Phone1'] = csv_input['Name'] #this would also copy the cell value
csv_input['Phone2'] = csv_input['Name']
csv_input['Phone3'] = csv_input['Name']
csv_input['Phone4'] = csv_input['Name']
csv_input['Phone5'] = csv_input['Name']
csv_input['Country'] = csv_input['Name']
csv_input['Website'] = csv_input['Name']
csv_input.to_csv('testcase.csv', index=False) #this writes back to your file
If you want that cell value doesn't gets copy, so first of all create a empty Column in your csv file manually, like you named it as Hours then, Now for this you can add this line in above code,
csv_input['New Value'] = csv_input['Hours']
or simply we can, without adding the manual column, we can
csv_input['New Value'] = '' #simple and easy
I Hope it helps.
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
Mindless passenger has a project that allows you to call a stored proc from entity frame work like this....
using (testentities te = new testentities())
{
//-------------------------------------------------------------
// Simple stored proc
//-------------------------------------------------------------
var parms1 = new testone() { inparm = "abcd" };
var results1 = te.CallStoredProc<testone>(te.testoneproc, parms1);
var r1 = results1.ToList<TestOneResultSet>();
}
... and I am working on a stored procedure framework (here) which you can call like in one of my test methods shown below...
[TestClass]
public class TenantDataBasedTests : BaseIntegrationTest
{
[TestMethod]
public void GetTenantForName_ReturnsOneRecord()
{
// ARRANGE
const int expectedCount = 1;
const string expectedName = "Me";
// Build the paraemeters object
var parameters = new GetTenantForTenantNameParameters
{
TenantName = expectedName
};
// get an instance of the stored procedure passing the parameters
var procedure = new GetTenantForTenantNameProcedure(parameters);
// Initialise the procedure name and schema from procedure attributes
procedure.InitializeFromAttributes();
// Add some tenants to context so we have something for the procedure to return!
AddTenentsToContext(Context);
// ACT
// Get the results by calling the stored procedure from the context extention method
var results = Context.ExecuteStoredProcedure(procedure);
// ASSERT
Assert.AreEqual(expectedCount, results.Count);
}
}
internal class GetTenantForTenantNameParameters
{
[Name("TenantName")]
[Size(100)]
[ParameterDbType(SqlDbType.VarChar)]
public string TenantName { get; set; }
}
[Schema("app")]
[Name("Tenant_GetForTenantName")]
internal class GetTenantForTenantNameProcedure
: StoredProcedureBase<TenantResultRow, GetTenantForTenantNameParameters>
{
public GetTenantForTenantNameProcedure(
GetTenantForTenantNameParameters parameters)
: base(parameters)
{
}
}
If either of those two approaches are any good?
Interesting I just ran a test using LinqPad with SQL Server which should be just running Linq to SQL underneath and it generates the following SQL statement.
Records .Where(r => r.Name.Contains("lkjwer--_~[]"))
-- Region Parameters
DECLARE @p0 VarChar(1000) = '%lkjwer--~_~~~[]%'
-- EndRegion
SELECT [t0].[ID], [t0].[Name]
FROM [RECORDS] AS [t0]
WHERE [t0].[Name] LIKE @p0 ESCAPE '~'
So I haven't tested it yet but it looks like potentially the ESCAPE '~'
keyword may allow for automatic escaping of a string for use within a like expression.
The first one will be implemented:
Collection.Where(x => x.Age == 10)
.Where(x => x.Name == "Fido") // applied to the result of the previous
.Where(x => x.Fat == true) // applied to the result of the previous
As opposed to the much simpler (and far fasterpresumably faster):
// all in one fell swoop
Collection.Where(x => x.Age == 10 && x.Name == "Fido" && x.Fat == true)
Following on from the earlier answers above but based on a VS 2019 install ;
I needed to run "tf git permission" commands, and copied the following files from:
C:\Program Files (x86)\Microsoft Visual Studio\2019\TeamExplorer\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer
Microsoft.TeamFoundation.Client.dll
Microsoft.TeamFoundation.Common.dll
Microsoft.TeamFoundation.Core.WebApi.dll
Microsoft.TeamFoundation.Diff.dll
Microsoft.TeamFoundation.Git.Client.dll
Microsoft.TeamFoundation.Git.Contracts.dll
Microsoft.TeamFoundation.Git.Controls.dll
Microsoft.TeamFoundation.Git.CoreServices.dll
Microsoft.TeamFoundation.Git.dll
Microsoft.TeamFoundation.Git.Graph.dll
Microsoft.TeamFoundation.Git.HostingProvider.AzureDevOps.dll
Microsoft.TeamFoundation.Git.HostingProvider.GitHub.dll
Microsoft.TeamFoundation.Git.HostingProvider.GitHub.imagemanifest
Microsoft.TeamFoundation.Git.Provider.dll
Microsoft.TeamFoundation.SourceControl.WebApi.dll
Microsoft.TeamFoundation.VersionControl.Client.dll
Microsoft.TeamFoundation.VersionControl.Common.dll
Microsoft.TeamFoundation.VersionControl.Common.Integration.dll
Microsoft.TeamFoundation.VersionControl.Controls.dll
Microsoft.VisualStudio.Services.Client.Interactive.dll
Microsoft.VisualStudio.Services.Common.dll
Microsoft.VisualStudio.Services.WebApi.dll
TF.exe
TF.exe.config
You should look at charAt function and take length of the string.
var b = 'I am a JavaScript hacker.';
console.log(b.charAt(b.length-1));
Two possible approaches.
If you have a foreign key, declare it as on-delete-cascade and delete the parent rows older than 30 days. All the child rows will be deleted automatically.
Based on your description, it looks like you know the parent rows that you want to delete and need to delete the corresponding child rows. Have you tried SQL like this?
delete from child_table
where parent_id in (
select parent_id from parent_table
where updd_tms != (sysdate-30)
-- now delete the parent table records
delete from parent_table
where updd_tms != (sysdate-30);
---- Based on your requirement, it looks like you might have to use PL/SQL. I'll see if someone can post a pure SQL solution to this (in which case that would definitely be the way to go).
declare
v_sqlcode number;
PRAGMA EXCEPTION_INIT(foreign_key_violated, -02291);
begin
for v_rec in (select parent_id, child id from child_table
where updd_tms != (sysdate-30) ) loop
-- delete the children
delete from child_table where child_id = v_rec.child_id;
-- delete the parent. If we get foreign key violation,
-- stop this step and continue the loop
begin
delete from parent_table
where parent_id = v_rec.parent_id;
exception
when foreign_key_violated
then null;
end;
end loop;
end;
/
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
@synthesize will generate getter and setter methods for your property. @dynamic just tells the compiler that the getter and setter methods are implemented not by the class itself but somewhere else (like the superclass or will be provided at runtime).
Uses for @dynamic are e.g. with subclasses of NSManagedObject
(CoreData) or when you want to create an outlet for a property defined by a superclass that was not defined as an outlet.
@dynamic also can be used to delegate the responsibility of implementing the accessors. If you implement the accessors yourself within the class then you normally do not use @dynamic.
Super class:
@property (nonatomic, retain) NSButton *someButton;
...
@synthesize someButton;
Subclass:
@property (nonatomic, retain) IBOutlet NSButton *someButton;
...
@dynamic someButton;
There is a new function in SQL called string_split
if you are using list of string.
Ref Link STRING_SPLIT (Transact-SQL)
DECLARE @tags NVARCHAR(400) = 'clothing,road,,touring,bike'
SELECT value
FROM STRING_SPLIT(@tags, ',')
WHERE RTRIM(value) <> '';
you can pass this query with in
as follows:
SELECT *
FROM [dbo].[yourTable]
WHERE (strval IN (SELECT value FROM STRING_SPLIT(@tags, ',') WHERE RTRIM(value) <> ''))
For CGSize
CGSize(width: self.view.frame.width * 3, height: self.view.frame.size.height)
It might be a lot easier than all that. If you want your page to load then check on the availability or content of some foreign page to trigger other web page activity, you could do it using only javascript and php like this.
yourpage.php
<?php
if (isset($_GET['urlget'])){
if ($_GET['urlget']!=''){
$foreignpage= file_get_contents('http://www.foreignpage.html');
// you could also use curl for more fancy internet queries or if http wrappers aren't active in your php.ini
// parse $foreignpage for data that indicates your page should proceed
echo $foreignpage; // or a portion of it as you parsed
exit(); // this is very important otherwise you'll get the contents of your own page returned back to you on each call
}
}
?>
<html>
mypage html content
...
<script>
var stopmelater= setInterval("getforeignurl('?urlget=doesntmatter')", 2000);
function getforeignurl(url){
var handle= browserspec();
handle.open('GET', url, false);
handle.send();
var returnedPageContents= handle.responseText;
// parse page contents for what your looking and trigger javascript events accordingly.
// use handle.open('GET', url, true) to allow javascript to continue executing. must provide a callback function to accept the page contents with handle.onreadystatechange()
}
function browserspec(){
if (window.XMLHttpRequest){
return new XMLHttpRequest();
}else{
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
</script>
That should do it.
The triggered javascript should include clearInterval(stopmelater)
Let me know if that works for you
Jerry
Worth to mention to make sure your dependencies should be in the dependencies
part of your package.json
(as opposed to devDependencies
).
My issue was basically the same as OP:
repo1
) via "module-name": "git+ssh://git@myserver:user/my-repo-name.git"
in other repo(Let's call it repo2
), repo2
's node_modules
, one package dependency from repo1
wasn't there.repo1
was listing that dependency in devDependencies
instead of dependencies
repo1
's package.json
from devDependencies
to dependencies
repo2
, I removed my node_modules
and package-lock.json
, did npm install
, an voilà!... dependency was there!We were getting the same error.For us, it solved by upgrading pip version (also discussed in FAQ of OpenCV GitHub). Earlier we had pip-7.1.0, post upgrading it to "pip-9.0.2", it successfully installed.
pip install --upgrade pip
pip install opencv-python
I was given a similar task to disable the auto-filling up of login name and passwords by browser, after lot of trial and errors i found the below solution to be optimal. Just add the below controls before your original controls.
<input type="text" style="display:none">
<input type="text" name="OriginalLoginTextBox">
<input type="password" style="display:none">
<input type="text" name="OriginalPasswordTextBox">
This is working fine for IE11 and Chrome 44.0.2403.107
Charles is an excellent Web Debugging Proxy for Windows, Mac OS and Linux. The full version is 50$ but it's well worth it.
You need to access image IDs using R.mipmap.yourImageName
Alpine docker image doesn't have bash installed by default. You will need to add following commands to get bash
:
RUN apk update && apk add bash
If youre using Alpine 3.3+
then you can just do
RUN apk add --no-cache bash
to keep docker image size small. (Thanks to comment from @sprkysnrky)
Setting the timeout in the web.xml is the correct way to set the timeout.
You didn't typed the closingtag from the div with id="infohold.
as long as you did not commit you can type
git merge --abort
just as the command line suggested.
Date.js is a handy library for manipulating and formatting dates. It can help in this situation.
These are the changes to make:
CSS:
#container {
width: 100%;
height: 100%;
top: 0;
position: absolute;
visibility: hidden;
display: none;
background-color: rgba(22,22,22,0.5); /* complimenting your modal colors */
}
#container:target {
visibility: visible;
display: block;
}
.reveal-modal {
position: relative;
margin: 0 auto;
top: 25%;
}
/* Remove the left: 50% */
HTML:
<a href="#container">Reveal</a>
<div id="container">
<div id="exampleModal" class="reveal-modal">
........
<a href="#">Close Modal</a>
</div>
</div>
Be nice if there was a Javascript API version. That way can integrate w/ other AJAX apps or browser extensions/gadgets/widgets.
Right now, current APIs restrict to web app technologies that support Java, .NET, or Python, more for server side, unless may use Google Web Toolkit to translate Java code to Javascript.
Here is what I did recently in PHP on one of my bigger systems:
User inputs newsletter text and selects the recipients (which generates a query to retrieve the email addresses for later).
Add the newsletter text and recipients query to a row in mysql table called *email_queue*
I created another script, which runs every minute as a cron job. It uses the SwiftMailer class. This script simply:
during business hours, sends all email with priority == 0
after hours, send other emails by priority
Depending on the hosts settings, I can now have it throttle using standard swiftmailers plugins like antiflood and throttle...
$mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(50, 30));
and
$mailer->registerPlugin(new Swift_Plugins_ThrottlerPlugin( 100, Swift_Plugins_ThrottlerPlugin::MESSAGES_PER_MINUTE ));
etc, etc..
I have expanded it way beyond this pseudocode, with attachments, and many other configurable settings, but it works very well as long as your server is setup correctly to send email. (Probably wont work on shared hosting, but in theory it should...) Swiftmailer even has a setting
$message->setReturnPath
Which I now use to track bounces...
Happy Trails! (Happy Emails?)
Another thing that people may find useful when using the develop
method is the --user
option to install without sudo. Ex:
python setup.py develop --user
instead of
sudo python setup.py develop
It prints the byte
in Hexadecimal format.
No format string: 13
'X2' format string: 0D
http://msdn.microsoft.com/en-us/library/aa311428(v=vs.71).aspx
Yes, PHP supports arrays as session variables. See this page for an example.
As for your second question: once you set the session variable, it will remain the same until you either change it or unset
it. So if the 3rd page doesn't change the session variable, it will stay the same until the 2nd page changes it again.
Here's how I download CSV files on the client side in my Java GWT application. Special thanks to Xavier John for his solution. It's been verified to work in FF 24.6.0, IE 11.0.20, and Chrome 45.0.2454.99 (64-bit). I hope this saves someone a bit of time:
public class ExportFile
{
private static final String CRLF = "\r\n";
public static void exportAsCsv(String filename, List<List<String>> data)
{
StringBuilder sb = new StringBuilder();
for(List<String> row : data)
{
for(int i=0; i<row.size(); i++)
{
if(i>0) sb.append(",");
sb.append(row.get(i));
}
sb.append(CRLF);
}
generateCsv(filename, sb.toString());
}
private static native void generateCsv(String filename, String text)
/*-{
var blob = new Blob([text], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) // IE 10+
{
navigator.msSaveBlob(blob, filename);
}
else
{
var link = document.createElement("a");
if (link.download !== undefined) // feature detection
{
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}-*/;
}
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(444, 25);
this.toolStrip1.TabIndex = 0;
this.toolStrip1.Text = "toolStrip1";
object O = global::WindowsFormsApplication1.Properties.Resources.ResourceManager.GetObject("best_robust_ghost");
ToolStripButton btn = new ToolStripButton("m1");
btn.DisplayStyle = ToolStripItemDisplayStyle.Image;
btn.Image = (Image)O;
this.toolStrip1.Items.Add(btn);
By regex i think this is java, the method replaceAll()
returns a new String with the substrings replaced, so try this:
String teste = "abcd=0; efgh=1";
String teste2 = teste.replaceAll("abcd", "dddd");
System.out.println(teste2);
Output:
dddd=0; efgh=1
To send to both remote with one command, you can create a alias for it:
git config alias.pushall '!git push origin devel && git push github devel'
With this, when you use the command git pushall
, it will update both repositories.
Becasue is a TextBox already initialized would be better to control if there is something in there outside the empty string (which is no null or empty string I am afraid). What I did is just check is there is something different than "", if so do the thing:
if (TextBox.Text != "") //Something different than ""?
{
//Do your stuff
}
else
{
//Do NOT do your stuff
}
JSESSIONID cookie is created/sent when session is created. Session is created when your code calls request.getSession()
or request.getSession(true)
for the first time. If you just want to get the session, but not create it if it doesn't exist, use request.getSession(false)
-- this will return you a session or null
. In this case, new session is not created, and JSESSIONID cookie is not sent. (This also means that session isn't necessarily created on first request... you and your code are in control when the session is created)
Sessions are per-context:
SRV.7.3 Session Scope
HttpSession objects must be scoped at the application (or servlet context) level. The underlying mechanism, such as the cookie used to establish the session, can be the same for different contexts, but the object referenced, including the attributes in that object, must never be shared between contexts by the container.
Update: Every call to JSP page implicitly creates a new session if there is no session yet. This can be turned off with the session='false'
page directive, in which case session variable is not available on JSP page at all.
A couple of years late to the party, but I had a requirement to do this for both past and future dates, so I combined Jeff's and Vincent's into this. It's a ternarytastic extravaganza! :)
public static class DateTimeHelper
{
private const int SECOND = 1;
private const int MINUTE = 60 * SECOND;
private const int HOUR = 60 * MINUTE;
private const int DAY = 24 * HOUR;
private const int MONTH = 30 * DAY;
/// <summary>
/// Returns a friendly version of the provided DateTime, relative to now. E.g.: "2 days ago", or "in 6 months".
/// </summary>
/// <param name="dateTime">The DateTime to compare to Now</param>
/// <returns>A friendly string</returns>
public static string GetFriendlyRelativeTime(DateTime dateTime)
{
if (DateTime.UtcNow.Ticks == dateTime.Ticks)
{
return "Right now!";
}
bool isFuture = (DateTime.UtcNow.Ticks < dateTime.Ticks);
var ts = DateTime.UtcNow.Ticks < dateTime.Ticks ? new TimeSpan(dateTime.Ticks - DateTime.UtcNow.Ticks) : new TimeSpan(DateTime.UtcNow.Ticks - dateTime.Ticks);
double delta = ts.TotalSeconds;
if (delta < 1 * MINUTE)
{
return isFuture ? "in " + (ts.Seconds == 1 ? "one second" : ts.Seconds + " seconds") : ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
}
if (delta < 2 * MINUTE)
{
return isFuture ? "in a minute" : "a minute ago";
}
if (delta < 45 * MINUTE)
{
return isFuture ? "in " + ts.Minutes + " minutes" : ts.Minutes + " minutes ago";
}
if (delta < 90 * MINUTE)
{
return isFuture ? "in an hour" : "an hour ago";
}
if (delta < 24 * HOUR)
{
return isFuture ? "in " + ts.Hours + " hours" : ts.Hours + " hours ago";
}
if (delta < 48 * HOUR)
{
return isFuture ? "tomorrow" : "yesterday";
}
if (delta < 30 * DAY)
{
return isFuture ? "in " + ts.Days + " days" : ts.Days + " days ago";
}
if (delta < 12 * MONTH)
{
int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
return isFuture ? "in " + (months <= 1 ? "one month" : months + " months") : months <= 1 ? "one month ago" : months + " months ago";
}
else
{
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return isFuture ? "in " + (years <= 1 ? "one year" : years + " years") : years <= 1 ? "one year ago" : years + " years ago";
}
}
}
$('#test').click(function() {_x000D_
var startDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
var endDate = moment("01.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
var result = 'Diff: ' + endDate.diff(startDate, 'days');_x000D_
_x000D_
$('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #ffb;_x000D_
padding: 10px;_x000D_
border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
To summarize and complement the existing answers:
python.exe
is a console (terminal) application for launching CLI-type scripts.
python.exe
opens a new console window.sys.stdin
, sys.stdout
and sys.stderr
are connected to the console window.Execution is synchronous when launched from a cmd.exe
or PowerShell console window: See eryksun's 1st comment below.
pythonw.exe
is a GUI app for launching GUI/no-UI-at-all scripts.
sys.stdin
, sys.stdout
and sys.stderr
are NOT available.
print()
can cause that to happen (in 3.x, print()
simply has no effect).pythonw.exe yourScript.pyw 1>stdout.txt 2>stderr.txt
cmd /c pythonw.exe yourScript.pyw 1>stdout.txt 2>stderr.txt
) to capture stdout and stderr output in files.print()
is the only reason your script fails silently with pythonw.exe
, and you're not interested in stdout output, use @handle's command from the comments:pythonw.exe yourScript.pyw 1>NUL 2>&1
*.pyw
scripts directly (as opposed to by passing the script file path to pythonw.exe
). See eryksun's 2nd comment and its follow-ups below.You can control which of the executables runs your script by default - such as when opened from Explorer - by choosing the right filename extension:
*.py
files are by default associated (invoked) with python.exe
*.pyw
files are by default associated (invoked) with pythonw.exe
Be careful when you are using one liner using sslKey or sslCert, as in Josh Peak's answer:
git clone -c http.sslCAPath="/path/to/selfCA" \
-c http.sslCAInfo="/path/to/selfCA/self-signed-certificate.crt" \
-c http.sslVerify=1 \
-c http.sslCert="/path/to/privatekey/myprivatecert.pem" \
-c http.sslCertPasswordProtected=0 \
https://mygit.server.com/projects/myproject.git myproject
Only Git 2.14.x/2.15 (Q3 2015) would be able to interpret a path like ~username/mykey
correctly (while it still can interpret an absolute path like /path/to/privatekey
).
See commit 8d15496 (20 Jul 2017) by Junio C Hamano (gitster
).
Helped-by: Charles Bailey (hashpling
).
(Merged by Junio C Hamano -- gitster
-- in commit 17b1e1d, 11 Aug 2017)
http.c
:http.sslcert
andhttp.sslkey
are both pathnamesBack when the modern http_options() codepath was created to parse various http.* options at 29508e1 ("Isolate shared HTTP request functionality", 2005-11-18, Git 0.99.9k), and then later was corrected for interation between the multiple configuration files in 7059cd9 ("
http_init()
: Fix config file parsing", 2009-03-09, Git 1.6.3-rc0), we parsed configuration variables likehttp.sslkey
,http.sslcert
as plain vanilla strings, becausegit_config_pathname()
that understands "~[username]/
" prefix did not exist.Later, we converted some of them (namely,
http.sslCAPath
andhttp.sslCAInfo
) to use the function, and added variables likehttp.cookeyFile
http.pinnedpubkey
to use the function from the beginning. Because of that, these variables all understand "~[username]/
" prefix.Make the remaining two variables,
http.sslcert
andhttp.sslkey
, also aware of the convention, as they are both clearly pathnames to files.
You're right in your assumption about Spring vs. Quartz instantiating the class. However, Spring provides some classes that let you do some primitive dependency injection in Quartz. Check out SchedulerFactoryBean.setJobFactory() along with the SpringBeanJobFactory. Essentially, by using the SpringBeanJobFactory, you enable dependency injection on all Job properties, but only for values that are in the Quartz scheduler context or the job data map. I don't know what all DI styles it supports (constructor, annotation, setter...) but I do know it supports setter injection.
In Bootstrap 5, which doesn't use jQuery, you can do this:
const btn = document.createElement('button');
btn.innerHTML = 'Click me';
btn.dataset['toggle'] = 'tooltip';
btn.dataset['placement'] = 'top';
btn.title = 'Your Tooltip Here';
new bootstrap.Tooltip(btn);
document.getElementById('parent').appendChild(btn);
_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-CuOF+2SnTUfTwSZjCXf01h7uYhfOBuxIhGKPbfEJ3+FqH/s6cIFN9bGr1HmAg4fQ" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-popRpmFF9JQgExhfw5tZT4I9/CI5e2QcuUZPOVXb1m7qUmeR2b50u+YFEYe1wgzy" crossorigin="anonymous"></script>
<div id="parent"></div>
_x000D_
To write a newline use \n
not /n
the latter is just a slash and a n
Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.
But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)
var arr = [1, 2, 3]_x000D_
_x000D_
// ES5 syntax_x000D_
arr = arr.filter(function(item){ return item != 3 })_x000D_
_x000D_
// ES2015 syntax_x000D_
arr = arr.filter(item => item != 3)_x000D_
_x000D_
console.log( arr )
_x000D_
What a BUG ! Here is another workaround...
public void forceRefresh() {
final TableColumn< Prospect, ? > firstColumn = view.getColumns().get( 0 );
firstColumn.setVisible( false );
new Timer().schedule( new TimerTask() { @Override public void run() {
Platform.runLater( new Runnable() { @Override public void run() {
firstColumn.setVisible( true ); }});
}}, 100 );
}
I've done a SSCCE to show the bug. I encourage everyone to fix it by another more elegant way because my workaround is very ugly!
If it's a .mdf database and the connection string was saved when it was created, you should be able to access it via:
Dim cn As SqlConnection = New SqlConnection(My.Settings.DatabaseNameConnectionString)
Hope that helps someone.
Not sure if there was file corruption or what, but after confirming proper pom configuration I was able to resolve this issue by deleting the jar from my local m2 repository, forcing Maven to download it again when I ran the tests.
You can use <i [className]="'fa fa-' + data?.icon"> </i>
So the length is between 10 16-bit chars, and 40 hex digits.
In any case decide the format you are going to store, and make the field a fixed size based on that format. That way you won't have any wasted space.
I know the question is asking about your "csv" package implementation, but for your information, there are options that are much simpler — numpy, for instance.
import numpy as np
np.savetxt('data.csv', (col1_array, col2_array, col3_array), delimiter=',')
(This answer posted 6 years later, for posterity's sake.)
In a different case similar to what you're asking about, say you have two columns like this:
names = ['Player Name', 'Foo', 'Bar']
scores = ['Score', 250, 500]
You could save it like this:
np.savetxt('scores.csv', [p for p in zip(names, scores)], delimiter=',', fmt='%s')
scores.csv
would look like this:
Player Name,Score
Foo,250
Bar,500
Adding java.util.list
will resolve your problem because List interface which you are trying to use is part of java.util.list
package.
Above, Abhishek mentions the command line differences specified in two URLS:
PhoneGap: http://docs.phonegap.com/en/edge/guide_cli_index.md.html
Cordova: http://cordova.apache.org/docs/en/3.0.0/guide_cli_index.md.html#The%20Command-line%20Interface
One thing to point out is that, as of this post, the phonegap one looks to be almost the same as the cordova one, and is probably not an accurate image of the command line option differences. As such, I installed both on my system so I could look at the differences.
These are just a few of them. Hopefully they are brought more in sync sometime. If anyone has better information, please tell me.
I guess my point is that the phonegap CLI documention mentioned quite often is not really for the phonegap CLI, but for the cordova CLI, at this time. Please tell me if I am missing something. Thanks.
Additionally, you can just sleep:
sleep(10)
Since the UITests run in another process, this works. I don’t know how advisable it is, but it works.
FragmentActivity
replaces requestCode
by a modified one. After that, when onActivityResult()
will be invoked, FragmentActivity
parses the higher 16 bits and restores the index of the original Fragment. Look at this scheme:
If you have a few fragments at the root level there are no problems. But if you have nested fragments, for example Fragment
with a few tabs inside ViewPager
, you guaranteed will face with a problem (or already faced it).
Because only one index is stored inside requestCode
. That is index of Fragment
inside its FragmentManager
. When we are using nested fragments, there are child FragmentManager
s, which have their own list of Fragments. So, it's necessary to save the whole chain of indices, starting from root FragmentManager
.
How do we resolve this issue? There is common workaround solution in this post.
<script>
$(function(){
$('.movie').click(function(){
var this_href=$(this).attr('href');
$.ajax({
url:this_href,
type:'post',
cache:false,
success:function(data)
{
$('#summary').html(data);
}
});
return false;
});
});
</script>
Apparently, org.json.simple.JSONArray
implements a raw Iterator. This means that each element is considered to be an Object
. You can try to cast:
for(Object o: arr){
if ( o instanceof JSONObject ) {
parse((JSONObject)o);
}
}
This is how things were done back in Java 1.4 and earlier.
remove the http
or https
from wget https:github.com/facebook/facebook-php-sdk/archive/master.zip
. this worked fine for me.
According to the explanation in my “main” answer the document in question should be marked up according to an outline.
In the following two tables I show:
original html (shortened)
<body>
<section>
<header>
<div id=logo></div>
<div id=language></div>
</header>
<nav>
...
</nav>
<div id=main>
<div id=main-left>
<article>
<header>
<h1>The real thing</h1>
</header>
</article>
</div>
<div id=main-right>
<section id=main-right-hot>
<h2>Hot items</h2>
</section>
<section id=main-right-new>
<h2>New items</h2>
</section>
</div>
</div>
<div id=news-items>
<header>
<h2>The latest news</h2>
</header>
<div id=item_1>
<article>
<header>
<h3>...</h3>
</header>
<a>read more</a>
</article>
</div>
<div id=item_2>
<article>
<header>
<h3>...</h3>
</header>
<a>read more</a>
</article>
</div>
<div id=item_3>
<article>
<header>
<h3>...</h3>
</header>
<a>read more</a>
</article>
</div>
</div>
<footer>
<ul><li>...</ul>
</footer>
</section>
original html relevant for outline
<body>
<section>
// logo and language
<nav>
...
</nav>
<article>
<h1>The real thing</h1>
</article>
<section>
<h2>Hot items</h2>
</section>
<section>
<h2>New items</h2>
</section>
<h2>The latest news</h2>
<article>
<h3>...</h3>
</article>
<article>
<h3>...</h3>
</article>
<article>
<h3>...</h3>
</article>
// footer links
</section>
resulting outline
1. (untitled document)
1.1. (untitled section)
1.1.1. (untitled navigation)
1.1.2. The real thing (h1)
1.1.3. Hot items (h2)
1.1.4. New items (h2)
1.1.5. The latest news (h2)
1.1.6. news item_1 (h3)
1.1.7. news item_2 (h3)
1.1.8. news item_3 (h3)
The outline of the original is
definitively not what was intended.
The following table shows my proposal for an improved version. I use the following markup:
<removed>
<NEW_OR_CHANGED_ELEMENT>
<element MOVED_ATTRIBUTE=1>
possible intended outline
1. (main)
1.1. The real thing
1.2. (hot&new)
1.2.1. Hot items
1.2.2. New items
2. The latest news
2.1. news item_1
2.2. news item_2
2.3. news item_3
modified html
<body>
<section>
<header>
<ASIDE>
<div id=logo></div>
<div id=language></div>
</ASIDE>
</header>
<nav>
...
</nav>
<ARTICLE id=main>
<div id=main-left>
<article ID=main-left>
<header>
<h1>The real thing</h1>
</header>
</article>
</div>
<ARTICLE id=main-right>
<ARTICLE id=main-right-hot>
<h2>Hot items</h2>
</ARTICLE>
<ARTICLE id=main-right-new>
<h2>New items</h2>
</ARTICLE>
</ARTICLE>
</ARTICE>
<ARTICLE id=news-items>
<header>
<h2>The latest news</h2>
</header>
<div id=item_1>
<article ID=item_1>
<header>
<h3>...</h3>
</header>
<a>read more</a>
</article>
</div>
<div id=item_2>
<article ID=item_2>
<header>
<h3>...</h3>
</header>
<a>read more</a>
</article>
</div>
<div id=item_3>
<article ID=item_3>
<header>
<h3>...</h3>
</header>
<a>read more</a>
</article>
</div>
</ARTICLE>
<footer>
<NAV>
<ul><li>...</ul>
</NAV>
</footer>
``
</section>
resulting outline
1. (untitled document)
1.1. (untitled logo and lang)
1.2. (untitled navigation)
1.3. (untitled main)
1.3.1 The real thing
1.3.2. (untitled hot&new)
1.3.2.1. Hot items
1.3.2.2. New items
1.4. The latest news
1.4.1. news item_1
1.4.2. news item_2
1.4.3. news item_3
1.5. (untitled footer nav)
The modified HTML reflects the
intended outline way better than
the original.
use labelpad parameter:
pl.xlabel("...", labelpad=20)
or set it after:
ax.xaxis.labelpad = 20
Just use !important
it will help to override
background:none !important;
Although it is said to be a bad practice, !important
can be useful for utility classes, you just need to use it responsibly, check this: When Using important is the right choice
To satisfy the requirement that "it needs to be as fast as possible" I ran a benchmark against some possible solutions. Each solution had to satisfy this set of test cases.
$cases = [
'aaa-zzz' => 'zzz',
'zzz' => 'zzz',
'-zzz' => 'zzz',
'aaa-' => '',
'' => '',
'aaa-bbb-ccc-ddd-eee-fff-zzz' => 'zzz',
];
Here are the solutions:
function test_substr($str, $delimiter = '-') {
$idx = strrpos($str, $delimiter);
return $idx === false ? $str : substr($str, $idx + 1);
}
function test_end_index($str, $delimiter = '-') {
$arr = explode($delimiter, $str);
return $arr[count($arr) - 1];
}
function test_end_explode($str, $delimiter = '-') {
$arr = explode($delimiter, $str);
return end($arr);
}
function test_end_preg_split($str, $pattern = '/-/') {
$arr = preg_split($pattern, $str);
return end($arr);
}
Here are the results after each solution was run against the test cases 1,000,000 times:
test_substr : 1.706 sec
test_end_index : 2.131 sec +0.425 sec +25%
test_end_explode : 2.199 sec +0.493 sec +29%
test_end_preg_split : 2.775 sec +1.069 sec +63%
So turns out the fastest of these was using substr
with strpos
. Note that in this solution we must check strpos
for false
so we can return the full string (catering for the zzz
case).
use an enum type to indicate your ViewModel's State
public enum ViewModeType
{
Default,
Busy
//etc.
}
then in your ViewModels Base class use a property
public ViewModeType ViewMode
{
get { return this.viewMode; }
set
{
if (this.viewMode != value)
{
this.viewMode = value;
//You should notify property changed here
}
}
}
and in view trigger the ViewMode and if it is busy show busyindicator:
<Trigger Property="ViewMode" Value="Busy">
<!-- Show BusyIndicator -->
</Trigger>
You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.
Here is a solution that cleans up a lot of code and makes the animation start from the center:
.gps_ring {
border: 3px solid #999;
-webkit-border-radius: 30px;
height: 18px;
width: 18px;
position: absolute;
left:20px;
top:214px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.0
}
@-webkit-keyframes pulsate {
0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
50% {opacity: 1.0;}
100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}
You can see it in action here: http://jsfiddle.net/Fy8vD/
int value = 1;
string description = Enumerations.GetEnumDescription((MyEnum)value);
The default underlying data type for an enum
in C# is an int
, you can just cast it.
As of Android O this is now possible to define directly from the XML and my bug is now closed!
TL;DR:
First you must add your fonts to the project
Second you add a font family, like so:
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
<font
android:fontStyle="normal"
android:fontWeight="400"
android:font="@font/lobster_regular" />
<font
android:fontStyle="italic"
android:fontWeight="400"
android:font="@font/lobster_italic" />
</font-family>
Finally, you can use the font in a layout or style:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/lobster"/>
<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
<item name="android:fontFamily">@font/lobster</item>
</style>
Enjoy!
A 500 from ASP.NET probably means an unhandled exception was thrown at some point when serving the request.
I suggest you attach a debugger to the web server process (assuming you have access).
One strange thing: You make a POST request to the server, but you do not pass any data (everything is in the query string). Perhaps it should be a GET request instead?
You should also double check that the URL is correct.
This solution uses jQuery. If you want to use same placeholder text for all text inputs, you can use
$('input:text').attr('placeholder','Some New Text');
And if you want different placeholders, you can use the element's id to change placeholder
$('#element1_id').attr('placeholder','Some New Text 1');
$('#element2_id').attr('placeholder','Some New Text 2');
You're pretty stuck with substring()
, given your requirements. The standard way would be charAt()
, but you said you won't accept a char data type.
Sometimes, pprint()
in pprint
module works wonder, especially for dict
variables.
The server first tries to authenticate you by public key. That doesn't work (I guess you haven't set one up), so it then falls back to 'keyboard-interactive'. It should then ask you for a password, which presumably you're not getting right. Did you see a password prompt?
5 years later-version:
Today, there are JS libraries for you, if you don't want to get into the nitty gritty of the different methods described on this page.
On of these is https://github.com/hubspot/offline. It checks for the connectivity of a pre-defined URI, by default your favicon. It automatically detects when the user's connectivity has been reestablished and provides neat events like up
and down
, which you can bind to in order to update your UI.
both your conditions are the same:
if(s < f) { calc = f - s; n = s; }else if(f > s){ calc = s - f; n = f; }
so
if(s < f)
and
}else if(f > s){
are the same
change to
}else if(f < s){
W3Schools have a nice article on this subject.
Scripts in <head>
Scripts to be executed when they are called, or when an event is triggered, are placed in functions.
Put your functions in the head section, this way they are all in one place, and they do not interfere with page content.
Scripts in <body>
If you don't want your script to be placed inside a function, or if your script should write page content, it should be placed in the body section.
You're using S_ISREG()
and S_ISDIR()
correctly, you're just using them on the wrong thing.
In your while((dit = readdir(dip)) != NULL)
loop in main
, you're calling stat
on currentPath
over and over again without changing currentPath
:
if(stat(currentPath, &statbuf) == -1) {
perror("stat");
return errno;
}
Shouldn't you be appending a slash and dit->d_name
to currentPath
to get the full path to the file that you want to stat
? Methinks that similar changes to your other stat
calls are also needed.
Putting the onclick within the href would offend those who believe strongly in separation of content from behavior/action. The argument is that your html content should remain focused solely on content, not on presentation or behavior.
The typical path these days is to use a javascript library (eg. jquery) and create an event handler using that library. It would look something like:
$('a').click( function(e) {e.preventDefault(); /*your_code_here;*/ return false; } );
I've had the same issue when some ASP.NET installation was corrupted. In that case they suggest running aspnet_regiis -i -enable
While the post of Oka is working great, it might be a bit outdated. I figured out that lodash can tackle it with one single function. If you have lodash installed, it might save you a few lines.
Just try:
import { startsWith } from lodash;
. . .
if (startsWith(yourVariable, 'REP')) {
return yourVariable;
return yourVariable;
}
}
You can add a new Primary Key column to an existing table, which can have sequence numbers, using command:
ALTER TABLE mydb.mytable ADD pk_columnName INT IDENTITY
I would be using laravel whereDoesntHave to achieve this.
Customer::whereDoesntHave('orders')->get();
It can also happen if your password policy or something else have changed your password in case your appPools are using the the user with changed password.
So, you should update the user password from the advanced settings of your appPool throught "Identity" property.
The reference is here
"user.dir" is the current working directory, not the home directory It is all described here.
http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
Also, by using \\
instead of File.separator, you will lose portability with *nix system which uses /
for file separator.
Are there any other "modifiers" (other than
= 0
and= delete
)?
Since it appears no one else answered this question, I should mention that there is also =default
.
The previously mentioned wmic
command is the way to go, as it is installed by default in recent versions of Windows.
Here is my small improvement to generalize it, by retrieving the current name from the environment:
wmic computersystem where name="%COMPUTERNAME%"
call rename name="NEW-NAME"
NOTE: The command must be given in one line, but I've broken it into two to make scrolling unnecessary. As @rbeede mentions you'll have to reboot to complete the update.
No, and your compiler already gave you a comprehensive explanation.
But you could do this:
constexpr char constString[] = "constString";
At runtime, this can be used to construct a std::string
when needed.
The object where Oracle stores the name of the identifiers (e.g. the table names of the user are stored in the table named as USER_TABLES and the column names of the user are stored in the table named as USER_TAB_COLUMNS), have the NAME columns (e.g. TABLE_NAME in USER_TABLES) of size Varchar2(30)...and it's uniform through all system tables of objects or identifiers --
DBA_ALL_TABLES ALL_ALL_TABLES USER_ALL_TABLES
DBA_PARTIAL_DROP_TABS ALL_PARTIAL_DROP_TABS USER_PARTIAL_DROP_TABS
DBA_PART_TABLES ALL_PART_TABLES USER_PART_TABLES
DBA_TABLES ALL_TABLES USER_TABLES
DBA_TABLESPACES USER_TABLESPACES TAB
DBA_TAB_COLUMNS ALL_TAB_COLUMNS USER_TAB_COLUMNS
DBA_TAB_COLS ALL_TAB_COLS USER_TAB_COLS
DBA_TAB_COMMENTS ALL_TAB_COMMENTS USER_TAB_COMMENTS
DBA_TAB_HISTOGRAMS ALL_TAB_HISTOGRAMS USER_TAB_HISTOGRAMS
DBA_TAB_MODIFICATIONS ALL_TAB_MODIFICATIONS USER_TAB_MODIFICATIONS
DBA_TAB_PARTITIONS ALL_TAB_PARTITIONS USER_TAB_PARTITIONS
Check the thread status by calling Thread.isAlive
.
You need to add a name
attribute.
Since this is a multiple select, at the HTTP level, the client just sends multiple name/value pairs with the same name, you can observe this yourself if you use a form with method="GET": someurl?something=1&something=2&something=3
.
In the case of PHP, Ruby, and some other library/frameworks out there, you would need to add square braces ([]
) at the end of the name. The frameworks will parse that string and wil present it in some easy to use format, like an array.
Apart from manually parsing the request there's no language/framework/library-agnostic way of accessing multiple values, because they all have different APIs
For PHP you can use:
<select name="something[]" id="inscompSelected" multiple="multiple" class="lstSelected">
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
select_statement
Example :
CREATE TEMPORARY TABLE IF NOT EXISTS mytable
(id int(11) NOT NULL, PRIMARY KEY (id)) ENGINE=MyISAM;
INSERT IGNORE INTO mytable SELECT id FROM table WHERE xyz;
same for Terminator
Ctrl + Shift + V
Look at your terminal key-bindings if any if that doesn't work
Here is a little refactoring of your function (it does not use "else" or "elif"):
def function(a):
if a not in (1, 2):
a = 3
print(str(a) + "a")
@ghostdog74: Python 3 requires parentheses for "print".