input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
PCA in Python: scikit-learn vs numpy approach <p>I have 4 classes of images (72 .png files for each class) and I am carrying out PCA on them, in order to find the two components that show most variance on the data. Here's the code:</p>
<pre><code>data_list = []
for file in fileList: # fileList contains the name of the 72x4 .png files
img_data = np.asarray(Image.open('C:\\Users\\Gian\\Desktop\\UNI\\' \
'Sapienza\\Machine Learning\\Homeworks\\' \
'First\\Data\\samples\\' + file)) # open image
x = img_data.ravel() # transform image into 49152-length vector
data_list.append(x)
X = np.array(data_list) # create data matrix (72*4=288 rows by 49152 columns)
</code></pre>
<p>Now, at this point I just use <code>scikit-learn</code>, applying the <code>fit_transform</code> function on the data matrix:</p>
<pre><code># Transform data on to new subspace and plot
X_t = PCA(2).fit_transform(X)
plt.scatter(X_t[0:72,0], X_t[0:72,1], c='y')
plt.scatter(X_t[72:144,0], X_t[72:144,1], c='m')
plt.scatter(X_t[144:216,0], X_t[144:216,1], c='r')
plt.scatter(X_t[216:288,0], X_t[216:288,1], c='g')
plt.show()
</code></pre>
<p>I get this graph:<a href="https://i.stack.imgur.com/Jdfbt.png" rel="nofollow"><img src="https://i.stack.imgur.com/Jdfbt.png" alt="enter image description here"></a>
which seems good. Classes are pretty distinct, although I think the graph is maybe mirrored with respect to the y-axis (not sure about this). So I decide to double check the results. I use <code>numpy</code> to compute the covariance matrix of X, the eigenvalues and eigenvectors:</p>
<pre><code>covX = np.cov(X)
eig_val, eig_vec = np.linalg.eig(covX)
# make a list of (eig_val, eig_vec) tuples
eig_pairs = [(np.abs(eig_val_cov[i]), eig_vec_cov[:,i]) for i in range(len(eig_val_cov))]
# Sort the tuples from highest eigenvalue to lowest
eig_pairs.sort(key=lambda x: x[0], reverse=True)
</code></pre>
<p>I choose the two eigenvectors with highest eigenvalues (two principal components), and create a matrix with them:</p>
<pre><code>matrix_w = np.hstack((eig_pairs[0][1].reshape(288,1), eig_pairs[1][1].reshape(288,1))) # eigenvectors along columns
</code></pre>
<p>Now, here's the problem. I have to transform the data matrix onto the new subspace. So I just compute:</p>
<pre><code>standX = (X - mean(X))/std(X) # standardized data matrix (zero mean and unit variance)
X_t = matrix_w.T.dot(standX) # transformed data matrix
</code></pre>
<p>This is what I am not understanding: when I used <code>fit_transform</code> I got a transformed matrix <code>X_t</code> which is 288 (=number of images) rows by 2 columns. Now my <code>X_t</code> is 2 rows by 49152 columns! Why are they different? It feels like I should be getting a 288x2 <code>X_t</code>, as indeed it was when I used <code>fit_transform</code>, but I don't get how.
Also, how can <code>standX</code> (288 rows by 49152 columns) be multiplied by the eigenvector matrix <code>matrix_w.T</code> (which is 2 rows by 288 columns)? There's something wrong in my code, but I don't understand what exactly.</p>
| <p>I think you may have got your matrix multiplication the wrong way around. Does it work if you do something like <code>X_t = standX.dot(matrix_w)</code> ?</p>
|
How to add a "select file" button that saves an image in a mongodb collection for a meteor project <p>I've made a form for a project I'm working on and in it there's the tipical text inputs: "First Name", "Last Name", "Address" etc, etc... but there's a problem I'm facing and it's due to my lack of knowledge in Meteor and maybe HTML and Javascript too... I tried searching in other places but I didn't seem to find exactly what I'm looking for.</p>
<p>Anyways what I'm looking for is a way to make that when a user clicks on a button it pops up a window that lets the user select an image from his or her computer and then it will be saved in a mongodb collection. It also has to show inside this form in a small image.</p>
<p>I tried looking, and so far I've found that the HTML has the "input" tag with the "file" attribute that makes the pop-up window I want, my problem is what do I do from there? How do I link the event the user inputs and save the image into a mongodb collection?</p>
<p>I know this might sound really silly, I've seen many webpages and what not that have this kind of things... I'm really new at learning to code, and I really want to learn. So thank you for any help I can get.</p>
| <p>There are 2 packkages on atmosphere you could use</p>
<p><a href="https://atmospherejs.com/vsivsi/file-collection" rel="nofollow">https://atmospherejs.com/vsivsi/file-collection</a></p>
<p><a href="https://atmospherejs.com/jalik/ufs" rel="nofollow">https://atmospherejs.com/jalik/ufs</a></p>
<p>I have used the first of these successfully on several projects now, and recommend it. File uploading is fiddly in any environment, but they come with examples and documentation, so it's quite possible to be successful.</p>
|
Property '' does not exist on type 'Object'. Observable subscribe <p>I have just started with Angular2 and I've got an issue I cannot really understand.</p>
<p>I have some mock data created as such:</p>
<pre><code>export const WORKFLOW_DATA: Object =
{
"testDataArray" : [
{ key: "1", name: "Don Meow", source: "cat1.png" },
{ key: "2", parent: "1", name: "Roquefort", source: "cat2.png" },
{ key: "3", parent: "1", name: "Toulouse", source: "cat3.png" },
{ key: "4", parent: "3", name: "Peppo", source: "cat4.png" },
{ key: "5", parent: "3", name: "Alonzo", source: "cat5.png" },
{ key: "6", parent: "2", name: "Berlioz", source: "cat6.png" }
]
};
</code></pre>
<p>Which is then imported in a service and "observed"</p>
<pre><code>import { Injectable } from '@angular/core';
import { WORKFLOW_DATA } from './../mock-data/workflow'
import {Observable} from "rxjs";
@Injectable()
export class ApiService {
constructor() { }
getWorkflowForEditor(): Observable<Object>
{
return Observable.of( WORKFLOW_DATA );
}
}
</code></pre>
<p>I then have a component which, in the constructor:</p>
<pre><code>constructor( private apiService: ApiService)
{
this.apiService.getWorkflowForEditor().subscribe( WORKFLOW_DATA => {
console.log( WORKFLOW_DATA);
console.log( WORKFLOW_DATA.testDataArray );
} );
}
</code></pre>
<p>The first console.log logs an Object of type Object which contains the testDataArray property.</p>
<p>The second console.log, results in an error at compile time:</p>
<pre><code>Property 'testDataArray' does not exist on type 'Object'.
</code></pre>
<p>While still logging an array of objects [Object, Object, ..] as intended.</p>
<p>I really do not understand why, I am sure I am doing something wrong, I would love an explanation.</p>
<p>Thank you for any help!</p>
| <p>Typescript expects <code>WORKFLOW_DATA</code> to be <code>Object</code> here:</p>
<pre><code>.subscribe( WORKFLOW_DATA => {} )
</code></pre>
<p>because you told it so:</p>
<pre><code> getWorkflowForEditor(): Observable<Object>
</code></pre>
<p>But <code>Object</code> doesn't have <code>testDataArray</code> property... You should either tell TypeScript that data can have any properties:</p>
<pre><code> getWorkflowForEditor(): Observable<any>
</code></pre>
<p>or use</p>
<pre><code>console.log( WORKFLOW_DATA["testDataArray"] );
</code></pre>
|
How to initialize over a 100 QLabel in an efficient way <p>I want to have the ability to update over 100 labels, so I was going to put them in an array like this:</p>
<pre><code>voltage_label_array[0] = this->ui->Voltage_0;
voltage_label_array[1] = this->ui->Voltage_1;
voltage_label_array[...] = this->ui->Voltage_2;
voltage_label_array[...n] = this->ui->Voltage_n;
</code></pre>
<p>and then have this method</p>
<pre><code>void MainWindow::updateValue(int i, int voltage){
voltage_label_array[i]->setText(QString::number(voltage));
}
</code></pre>
<p>but having 100 lines to set this up seems like a bad idea. Is there a way I can initialize a <code>QLabel</code> array inside a for loop or something? </p>
| <p>If you need to do this, something is horribly wrong with your design. But it is possible.</p>
<p>Assuming your labels are named <code>Voltage_0</code> to <code>Voltage_99</code>:</p>
<pre><code>for(int i = 0; i < 100; ++i) {
auto ptr = this->findChild<QLabel*>(QString("Voltage_%1").arg(i));
voltage_label_array[i] = ptr;
}
</code></pre>
<p>This "solution" uses Qt's runtime reflection and carries the expected performance penalties.</p>
<p>But if you need to display several similar values, look up <a href="http://doc.qt.io/qt-5/qlistwidget.html" rel="nofollow"><code>QListWidget</code></a> and similar classes.</p>
|
C++ - SFML When using textEntered I can't get the backspace key to delete last character of the string <p>I am trying to create a text box a user an input data into, it is going fine , however, whenever I try to set up the backspace key to delete the last character of the string, it doesn't seem to work even though countless tutorials have showed me this way . </p>
<pre><code>if (event.type == sf::Event::TextEntered) {
sentence += (char)event.text.unicode;
//if (sentence.getSize() < 16) {
//
if (event.text.unicode == 8) {
sentence.erase(sentence.getSize() - 1, sentence.getSize());
}
text.setString(sentence);
break;
//}
}
</code></pre>
<p>Also, was wondering what would be the best way to stop the string from advancing 16 characters. </p>
| <p>Nevermind, its not that hard, you're going to feel weird after what i'm going to say ^^</p>
<pre><code>if (event.type == sf::Event::TextEntered) {
if (event.text.unicode == 8)
if (sentence.getSize())//If the string doesn't have any char, don't do anything
sentence.erase(sentence.getSize() - 1, sentence.getSize());
else //Don't add any character when you delete one
if(sentence.getSize() < 16)//Yeah, thats the best way to do it
sentence += (char)event.text.unicode;
text.setString(sentence);
break;
}
</code></pre>
<p>If you were pressing backspace, your program was adding it to the string and then deleting it... so... it wasn't doing anything ^^</p>
|
Chrome Browser becomes laggy after an onClick event <p>I am developing a parallax solution for my website which gets the mouse position every time the user moves the cursor. The problem that I ran into was that when I click anywhere on the document, the browser becomes laggy and jittery. I am able to log the position of the cursor without any lag however the display of movement on the document itself is choppy.</p>
<p>This is how I am getting the mouse position</p>
<pre><code>this.onMove=function(posX, posY){
bigX = $('#Stage').width();
bigY = $('#Stage').height();
console.log(posX+" - "+posY); //this is working properly in real-time
posX = bigX/2 - (posX);
posY = bigY/2 - (posY);
for(i = 1; i<4; i++){ //the part that seems to be lagging
$('.layer'+(i-1)+'').css({"-webkit-transform":"translate("+posX/50*i+"px,"+posY/50*i+"px)"});
}
}
$(document).mousemove(function(e){
this.onMove(e.pageX, e.pageY);
});
</code></pre>
<p>I also tried implementing the translations without a for loop but the result is the same. Is this a problem with the browser being bogged down or is there some sort of onclick event that may be stuck in a loop?</p>
| <p>I made a test CopePen to understand the problem...<br>
Since no code was provided.</p>
<p>While playing with it (I really had fun!), I found these things that should be considered.</p>
<ol>
<li>Reduce the unnecessary calculations.</li>
<li>Limit decimals passed to <code>translate()</code>.</li>
<li>Disable mouse events in the "Stage" zone.</li>
</ol>
<p>The two first are more about a performance concern...</p>
<p>But your main question was about mouse click "interference"... If I undestood well.<br>
I noticed it in this very simple codePen!<br>
One can't say there's a lot elements moving...<br></p>
<p>Still, it happens when you hold a mouse down and move, like a drag attempt.<br>
Not always on the firsts... But it happens.</p>
<p>I fixed with <code>preventDefault()</code> and <code>return false</code> on these mouse events, inside the <code>#Stage</code> div.:<br></p>
<ul>
<li><code>mousedown</code></li>
<li><code>mouseup</code></li>
<li><code>click</code></li>
</ul>
<p>So in <a href="http://codepen.io/Bes7weB/pen/rrqOob" rel="nofollow"><strong>this codePen</strong></a>, there are buttons that you can play with to see the effect of all this.<br>
I hope you will like the effort made on this. ;)</p>
<p><strong>Here is my suggested <code>onMove</code> function:</strong><br>
<em>(I removed the unnessary from what's in CodePen)</em></p>
<pre><code>function onMove(posX, posY){
bigX = $('#Stage').width();
bigY = $('#Stage').height();
console.log(posX+" - "+posY); //this is working properly in real-time
// Make most of your calculation ONCE
posX = (bigX/2 - (posX))/50;
posY = (bigY/2 - (posY))/50;
// Translating layers now
for(i = 1; i<4; i++){
// Make the multiplication ONCE
var thisLayerPosX = posX*i;
var thisLayerPosY = posY*i;
// Limit decimals
thisLayerPosX = thisLayerPosX.toFixed(3);
thisLayerPosY = thisLayerPosY.toFixed(3);
var k = i-1;
$('.layer'+k).css({"-webkit-transform":"translate("+thisLayerPosX+"px,"+thisLayerPosY+"px)"});
}
}
</code></pre>
<p>I think that 3 decimals are ok.<br>
It keeps the layers movement smooth.<br>
1 or 0 makes it "pixel jumpy".</p>
|
How to create external source maps so can use the Chrome debugger in Vscode / Typescript for the browser using Gulp <p>I wish to use Gulp to build my very simple Typescript project <em>running in the browser</em>. Using <code>gulp-typescript</code> it appears to add modules.export into the generated js files, so I then found some <code>browserify</code> examples.</p>
<p>I now have the following gulp.js file</p>
<pre><code>var gulp = require('gulp');
var del = require('del');
var ts = require("gulp-typescript");
var tsProject = ts.createProject("tsconfig.json");
var sourcemaps = require('gulp-sourcemaps');
var browserify = require("browserify");
var source = require('vinyl-source-stream');
var tsify = require("tsify");
gulp.task('clean', function () {
return del(['build/**/*']);
});
gulp.task("copy-html", function () {
return gulp.src("*.html")
.pipe(gulp.dest("build"));
});
gulp.task("copy-css", function () {
return gulp.src("src/*.css")
.pipe(gulp.dest("build"));
});
gulp.task("default", ["clean", "copy-html", "copy-css"], function () {
return browserify({
basedir: '.',
debug: true,
entries: ['src/main.ts'],
cache: {},
packageCache: {}
})
.plugin(tsify)
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest("build"));
});
</code></pre>
<p>This creates bundle.js, and this seems to have the soucemaps embedded in it. Debugging on Chrome seems to work fine, but I am trying to use the vscode Chrome debugger plugin from <a href="https://github.com/Microsoft/vscode-chrome-debug" rel="nofollow">here</a>, but breakpoints are disabled.</p>
<p>My launch.json is as follows.</p>
<pre><code>{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Chrome against localhost, with sourcemaps",
"type": "chrome",
"request": "launch",
"file": "${workspaceRoot}/build/index.html",
"sourceMaps": true
},
{
"name": "Attach to Chrome, with sourcemaps",
"type": "chrome",
"request": "attach",
"port": 9222,
"sourceMaps": true,
"webRoot": "${workspaceRoot}"
}
]
}
</code></pre>
<p>So I thought perhaps I need the external source maps, so have tried using the <code>gulp-sourcemaps</code> from <a href="https://www.npmjs.com/package/gulp-sourcemaps" rel="nofollow">here</a>, but just can't get the example to work with the above script (no matter where I insert the <code>.pipe(sourcemaps.init())</code> and <code>.pipe(sourcemaps.write())</code> I get gulp build errors.</p>
<p>I have tried various suggestions, but none work (perhaps many of them are now out of date, e.g. using <code>outDir</code> in launch.json I get the error <code>Property ourDir is not allowed.</code></p>
<p>So, am just after whatever I need to do to use this debugger with, Typescript, in Chrome, which to me I thought would be common, but cannot find an example to get this working. I am guessing it is the (embedded) sourcemaps, but not sure.</p>
<p>Any help here would be greatly appreciated!</p>
| <p>Does your "Launch Chrome" actually start up chrome and find your localhost? I don't see a url option there. I started with that same example code you linked to and it didn't work for me as is, I added some options I found elsewhere and it works. Here's my "launch"</p>
<pre><code> {
"name": "Chrome : Launch with sourcemaps",
"type": "chrome",
"request": "launch",
// "preLaunchTask": "sync",
"url": "http://localhost:3000",
"webRoot": "${workspaceRoot}",
"sourceMaps": true,
"runtimeArgs": [
"--remote-debugging-port=9222"
]
}
</code></pre>
<p>Note the localhost port, which is what my browserSync is using (and browserSync is started <strong>first</strong>, in my case with a preLaunchTask or manually with a gulp task call). I am not using browserify or typescript so I don't know much about them so I apologize if this code doesn't make sense with them. But I would try adding the url option with your port number and the runtimeArgs option and see if they help. </p>
|
max OSX EI Cap why there are two php.ini files? <p>For the mac os shipped php5.5, i find there are two php.ini files, one is in /etc/php.ini, the other is in /usr/local/etc/php/5.5</p>
<p>I tried phpinfo(), it points to the one in /etc/php.ini
However, when i use php --ini, it shows the one in the /usr/local/etc/php/5.5</p>
<p>I am getting confused, which is the one that being used for php init? what's the use of the other?</p>
| <p>When you call php from the CLI you can specify the path to your desired ini file with the -c flag. Any php run by your server uses the ini specified in your server configuration. If you're just looking to make sure they're both looking at the same ini file probably easiest to just tell your CLI calls to php to use the same file as your server already uses.</p>
|
how to know which css and js files have been applied to an element <p>Suppose I inspect the navbar in a web page in google chrome. How do I know which CSS and js files are being applied to that navbar?</p>
| <p>In the Chrome dev tools you can see what CSS is applied to an element under the "Computed" tab. Scroll down to the attribute such as "font-size" and expand the attribute to see the where the style is set. <a href="https://developers.google.com/web/tools/chrome-devtools/inspect-styles/" rel="nofollow">https://developers.google.com/web/tools/chrome-devtools/inspect-styles/</a></p>
<p>For Javascript view the "Event Listeners" tab to see the Javascript events acting on that element and expand to see where the listener is defined and what it does. </p>
|
Optim() taking too long when trying to maximize GARCH(1,1) <p>I have been trying to build my own GARCH(1,1) model. However the solvers I have used so far have either failed to return the optimized parameters or taking way too long to optimize (maybe not converging?). So far I have tried optim() (with Nelder-Mead & BFGS), nlm() with no success. I have included my code with the "solnp" optimizer which is actually used in the "rugarch" package as well.Thought that might solve the issue, however it didn't. Would really appreciate if someone can point out where I am making mistakes. Thanks!</p>
<pre><code>library(tseries)
library(zoo)
AAPL <-get.hist.quote(instrument = "AAPL",
start = "2015-09-15",
end = "2016-09-14",
quote = "AdjClose",
retclass = "zoo",
quiet = TRUE)
garch_likelihood <- function(asset,fixed=c(FALSE,FALSE,FALSE)) {
pars <- fixed
function(p) {
pars[!fixed] <- p
omega <- pars[1]
alpha <- pars[2]
beta <- pars[3]
#constructor function
# object must be a time series class
if (class(asset) !="zoo")
stop("asset must be a time series object!!")
# Calculating log returns
r <- log(asset)-log(lag(asset,-1))
#calculating squared returns & variance
r2 <- r^2
variance.r <- var(r,na.rm = TRUE)
# Setting up the initial model
mod.pregarch <- cbind(r2,variance.r)
mod.pregarch[2:nrow(mod.pregarch),2] <- 0
# Using a loop to calculate the conditional variances
for (i in 2:nrow(mod.pregarch)) {
# pregarch model: var(t+1) = omega+alpha*r(t)^2+beta*var(t)
mod.pregarch[i,2] <- omega +alpha*mod.pregarch[i-1,1]+beta*mod.pregarch[i-1,2]}
pregarch <-mod.pregarch[,2]
sum(pregarch)
pregarch <- cbind(pregarch,rep(0,length(pregarch)))
#calculating log likelihoods
for (i in 1:nrow(pregarch)){
pregarch[i,2] <- dnorm(r[i,1],mean = 0,sd = sqrt(pregarch[i,1]),log = TRUE)
}
## Loglike.alternative <- -.5*log(2*pi)-.5*log(pregarch[i,1])-.5*(r2[i]/pregarch[[i,1]])
sum_log.like <- sum(pregarch[,2])
sum_log.like
}
}
pars <- c(0.000005,0.10,0.85) #initial values
garch11.ML <- garch_likelihood(AAPL)
library(Rsolnp)
optim_garch <- solnp(pars =pars,fun = garch11.ML) #Rsolnp solver package
</code></pre>
| <p>I would suggest re visiting your model, when I ask the function to print the parameters e.g.</p>
<pre><code>garch_likelihood <- function(asset,fixed=c(FALSE,FALSE,FALSE)) {
pars <- fixed
function(p) {
print(p)
...}
</code></pre>
<p>Parameters look like in the right range as follows.</p>
<pre><code>[1] 0.0000781018 0.0672768675 0.6338644923
[1] 5.796055e-05 6.020388e-02 7.161618e-01
</code></pre>
<p>I used optim also with the following call,</p>
<pre><code>optim_garch <- optim(par =pars ,fn = garch11.ML, control =list(fnscale = -1))
</code></pre>
<p>I also get the following warnings()</p>
<pre><code>warnings()
1: In sqrt(pregarch[i, 1]) : NaNs produced
</code></pre>
<p>I am unfamiliar with this model, but if you have an idea on the bounds of your parameters you can penalise for when parameters getting close to to avoid getting NaN results. I know this doesn't answer your question but in order to get help optimising your code, it should be able to reach a solution first.</p>
|
How can I get type safety for returned functions in TypeScript? <p>This TypeScript compiles fine:</p>
<pre><code>abstract class Animal {
/*
Any extension of Animal MUST have a function which returns
another function that has exactly the signature (string): void
*/
abstract getPlayBehavior(): (toy: string) => void;
}
class Cat extends Animal {
/*
Clearly does not have a function which returns a function
that has the correct signature. This function returns a function with
the signature (void) : void
*/
getPlayBehavior() {
return () => {
console.log(`Play with toy_var_would_go_here!`);
};
}
}
class Program {
static main() {
let cat: Animal = new Cat();
cat.getPlayBehavior()("Toy");
}
}
Program.main();
</code></pre>
<p>I am expecting an error because the Cat class definitely does not implement the abstract Animal class <em>properly</em>. I expect that the Cat class must have a function which returns another function of the exact signature specified in the abstract Animal class.</p>
<p>Running the code, I get:</p>
<pre><code>> node index.js
> Play with toy_var_would_go_here!
</code></pre>
<p>Is there anything I can do to make sure the compiler enforces this kind of policy?</p>
| <blockquote>
<p>I am expecting an error because the Cat class definitely does not implement the abstract Animal class properly</p>
</blockquote>
<p>Because of type compatability. A function (say <code>foo</code>) that doesn't take any parameter is assignable to a function (say <code>bar</code>) that does take a parameter. </p>
<p>Reason: There is no usage of <code>bar</code> where all the information needed for <code>foo</code> to function will be absent. </p>
<h1>More</h1>
<p>This is also covered here : <a href="https://basarat.gitbooks.io/typescript/content/docs/types/type-compatibility.html#number-of-arguments" rel="nofollow">https://basarat.gitbooks.io/typescript/content/docs/types/type-compatibility.html#number-of-arguments</a></p>
|
std::map::operator[] <p>I was doing a simple map program but ended up with this question. The c++ doc says this:</p>
<p><em>Access element
If k matches the key of an element in the container, the function returns a reference to its mapped value.
If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).</em></p>
<p>The part I don't really get is where it says "the element is constructerd using its default constructor". </p>
<p>I gave it a try and made this</p>
<pre><code>std::map<string, int> m;
m["toast"];
</code></pre>
<p>I just wanted to see what value would the mapped element of "toast" be. And it ended up being zero, but, why? does the primitive types have a default constructor? or what is happening?</p>
| <p>The statement of "using its default constructor" is confusing. More precisely, for <a href="http://en.cppreference.com/w/cpp/container/map/operator_at" rel="nofollow">std::map::operator[]</a>, if the key does not exist, the inserted value will be <a href="http://en.cppreference.com/w/cpp/language/value_initialization" rel="nofollow">value-initialized</a>.</p>
<blockquote>
<p>When the default allocator is used, this results in the key being copy constructed from key and the mapped value being <a href="http://en.cppreference.com/w/cpp/language/value_initialization" rel="nofollow">value-initialized</a>.</p>
</blockquote>
<p>For <code>int</code>, it means <a href="http://en.cppreference.com/w/cpp/language/zero_initialization" rel="nofollow">zero-initialization</a>.</p>
<blockquote>
<p>4) otherwise, the object is zero-initialized.</p>
</blockquote>
|
SQL Server 2016 JSON in existing column <p>I have been banging my head against the wall, for something that is probably fairly obvious, but no amount of googling has provided me with the answer, or hint that I need. Hopefully the geniuses here can help me :)</p>
<p>I have a table that looks a bit like this:</p>
<p><a href="https://i.stack.imgur.com/CK20x.png" rel="nofollow"><img src="https://i.stack.imgur.com/CK20x.png" alt="enter image description here"></a>
The JSON is already in my SQL Server table, and is basically the product contents of a basket. The current row, is the transaction of the entire purchase, and the JSON is another subset of each product and their various attributes.</p>
<p>Here are 2 rows of the JSON string as an example:</p>
<pre><code>[{"id":"429ac4e546-11e6-471e","product_id":"dc85bff3ecb24","register_id":"0adaaf5c4a65e37c7","sequence":"0","handle":"Skirts","sku":"20052","name":"Skirts","quantity":1,"price":5,"cost":0,"price_set":1,"discount":-5,"loyalty_value":0.2,"tax":0,"tax_id":"dc85058a-a69e-11e58394d","tax_name":"No Tax","tax_rate":0,"tax_total":0,"price_total":5,"display_retail_price_tax_inclusive":"1","status":"CONFIRMED","attributes":[{"name":"line_note","value":""}]}]
</code></pre>
<p>and</p>
<pre><code>[{"id":"09237884-9713-9b6751fe0b85ffd","product_id":"dc85058a-a66b4c06702e13","register_id":"06bf5b9-31e2b4ac9d0a","sequence":"0","handle":"BricaBrac","sku":"20076","name":"Bric a Brac","quantity":1,"price":7,"cost":0,"price_set":1,"discount":-7,"loyalty_value":0.28,"tax":0,"tax_id":"dc85058a-2-54f20388394d","tax_name":"No Tax","tax_rate":0,"tax_total":0,"price_total":7,"display_retail_price_tax_inclusive":"1","status":"CONFIRMED","attributes":[{"name":"line_note","value":""}]},{"id":"09237884-9713-9b601235370","product_id":"dc85058a-a6fe112-6b4bfafb107e","register_id":"06bf537bf6b9-31e2b4ac9d0a","sequence":"1","handle":"LadiesTops","sku":"20040","name":"Ladies Tops","quantity":1,"price":10,"cost":0,"price_set":1,"discount":-10,"loyalty_value":0.4,"tax":0,"tax_id":"dc85058a-a690388394d","tax_name":"No Tax","tax_rate":0,"tax_total":0,"price_total":10,"display_retail_price_tax_inclusive":"1","status":"CONFIRMED","attributes":[{"name":"line_note","value":""}]},{"id":"09237884-9713-9b52007fa6c7d","product_id":"dc85058a-a6fa-b4c06d7ed5a","register_id":"06bf537b-cf6b9-31e2b4ac9d0a","sequence":"2","handle":"DVD","sku":"20077","name":"DVD","quantity":1,"price":3,"cost":0,"price_set":1,"discount":-3,"loyalty_value":0.12,"tax":0,"tax_id":"dc85058a-e5-e112-54f20388394d","tax_name":"No Tax","tax_rate":0,"tax_total":0,"price_total":3,"display_retail_price_tax_inclusive":"1","status":"CONFIRMED","attributes":[{"name":"line_note","value":""}]}]
</code></pre>
<p>So what I am trying to achieve is to create a new table from the data in that column. (I can then join the product table to this first table via unique string in the id fields).</p>
<p>Is it possible to do this with the new native JSON that is in sql2016.</p>
<p>My alternative is to do it with a plugin via SSIS but it would be cleaner if I can do it with a stored procedure inside SQL Server itself.</p>
<p>Thanks in advance!</p>
| <p>Here is one way using <a href="https://msdn.microsoft.com/en-in/library/dn921885.aspx" rel="nofollow"><strong><code>OPENJSON</code></strong></a> to extract the <code>ID</code> from your <code>JSON</code></p>
<pre><code>SELECT id
FROM Yourtable
CROSS apply Openjson([register_sale_products])
WITH (id varchar(500) 'lax $.id')
</code></pre>
<p>There are two path modes in <code>OPENJSON</code></p>
<ol>
<li>strick</li>
<li>lax</li>
</ol>
<p><code>Strict</code> : will throw error when the <code>property</code> is <strong>not found</strong> in the <code>path</code></p>
<p><strong><code>lax</code></strong> : This will return <code>NULL</code> when the <code>property</code> is <strong>not found</strong> in the <strong><code>path</code></strong>. If you did not mention any <em>mode</em> then <code>Lax</code> will be used by default </p>
<p>You can use the above modes based on your requirement </p>
<p><strong>DEMO :</strong></p>
<p><strong><em>Schema Setup</em></strong></p>
<pre><code>CREATE TABLE json_test
(
json_col VARCHAR(8000)
)
</code></pre>
<p><strong><em>Sample Data</em></strong></p>
<pre><code>INSERT INTO json_test
VALUES ('[{"id":"429ac4e546-11e6-471e","product_id":"dc85bff3ecb24","register_id":"0adaaf5c4a65e37c7","sequence":"0","handle":"Skirts","sku":"20052","name":"Skirts","quantity":1,"price":5,"cost":0,"price_set":1,"discount":-5,"loyalty_value":0.2,"tax":0,"tax_id":"dc85058a-a69e-11e58394d","tax_name":"No Tax","tax_rate":0,"tax_total":0,"price_total":5,"display_retail_price_tax_inclusive":"1","status":"CONFIRMED","attributes":[{"name":"line_note","value":""}]}]'),
('[{"id":"09237884-9713-9b6751fe0b85ffd","product_id":"dc85058a-a66b4c06702e13","register_id":"06bf5b9-31e2b4ac9d0a","sequence":"0","handle":"BricaBrac","sku":"20076","name":"Bric a Brac","quantity":1,"price":7,"cost":0,"price_set":1,"discount":-7,"loyalty_value":0.28,"tax":0,"tax_id":"dc85058a-2-54f20388394d","tax_name":"No Tax","tax_rate":0,"tax_total":0,"price_total":7,"display_retail_price_tax_inclusive":"1","status":"CONFIRMED","attributes":[{"name":"line_note","value":""}]},{"id":"09237884-9713-9b601235370","product_id":"dc85058a-a6fe112-6b4bfafb107e","register_id":"06bf537bf6b9-31e2b4ac9d0a","sequence":"1","handle":"LadiesTops","sku":"20040","name":"Ladies Tops","quantity":1,"price":10,"cost":0,"price_set":1,"discount":-10,"loyalty_value":0.4,"tax":0,"tax_id":"dc85058a-a690388394d","tax_name":"No Tax","tax_rate":0,"tax_total":0,"price_total":10,"display_retail_price_tax_inclusive":"1","status":"CONFIRMED","attributes":[{"name":"line_note","value":""}]},{"id":"09237884-9713-9b52007fa6c7d","product_id":"dc85058a-a6fa-b4c06d7ed5a","register_id":"06bf537b-cf6b9-31e2b4ac9d0a","sequence":"2","handle":"DVD","sku":"20077","name":"DVD","quantity":1,"price":3,"cost":0,"price_set":1,"discount":-3,"loyalty_value":0.12,"tax":0,"tax_id":"dc85058a-e5-e112-54f20388394d","tax_name":"No Tax","tax_rate":0,"tax_total":0,"price_total":3,"display_retail_price_tax_inclusive":"1","status":"CONFIRMED","attributes":[{"name":"line_note","value":""}]}]')
</code></pre>
<p><strong>Query</strong></p>
<pre><code>SELECT id
FROM json_test
CROSS apply Openjson(json_col)
WITH (id varchar(500) 'lax $.id')
</code></pre>
<p><strong><em>Result :</em></strong></p>
<pre><code>âââââââââââââââââââââââââââââââââ
â id â
â ââââââââââââââââââââââââââââââââ£
â 429ac4e546-11e6-471e â
â 09237884-9713-9b6751fe0b85ffd â
â 09237884-9713-9b601235370 â
â 09237884-9713-9b52007fa6c7d â
â 429ac4e546-11e6-471e â
â 09237884-9713-9b6751fe0b85ffd â
â 09237884-9713-9b601235370 â
â 09237884-9713-9b52007fa6c7d â
âââââââââââââââââââââââââââââââââ
</code></pre>
|
Handling SIGTSTP signals in C <p>I came across this example code in my studies:</p>
<pre><code>#include <signal.h>
#include <stdio.h>
#include <string.h>
char* nums[5] = {"One", "Two", "Three", "Four", "Five"};
char number[6];
void handler(int n) {
printf(" %s\n", number);
}
int main() {
signal(SIGTSTP, handler); // ^Z
for(int n = 0; ; n++) {
strcpy(number, nums[n % 5]);
}
}
</code></pre>
<p>Apparently, there is something wrong with this code when it's compiled and ran. Attempting to generate the SIGTSTP with Ctrl+Z, instead of printing out one of the words in "nums" and then exiting, instead prints out the number as expected, but then continues running. It takes <em>another</em> SIGTSTP signal from the keyboard to actually make the program exit.</p>
<p>Why is this?</p>
| <p>To answer the two actual questions you had, the program continues running because your signal handler returns, and nothing you have written in your signal handler causes your program to terminate, so your program continues as normal. If you want your program to terminate, you'd need to call <code>_exit()</code> or <code>_Exit()</code> from it.</p>
<p>The reason a second <code>SIGTSTP</code> causes your program to terminate is because <code>signal()</code> is an outdated and unreliable interface that is also not standard across Unix-like platforms. The original behavior is that after registering your signal handler with <code>signal()</code>, when that signal is actually delivered, first the disposition of that signal is reset to <code>SIG_DFL</code>, and <em>then</em> your signal handler is run. So after the first delivery of that signal, your signal handler is not registered anymore, unless you call <code>signal()</code> again. So, when the signal is delivered to your program a second time, your signal handler is not called, and the default action is taken, which in this case is to stop the process. This behavior is different on BSD-derived systems, where the signal handler remains registered. So really, the only reliable thing you can do with <code>signal()</code> is to set the disposition to <code>SIG_IGN</code> or <code>SIG_DFL</code>. For anything else, you should use the modern reliable signals interface with <code>sigaction()</code>.</p>
<p>There are some other problems with your program. First, <code>printf()</code>, along with most standard library functions, are not safe to call from a signal handler. POSIX defines <a href="https://www.securecoding.cert.org/confluence/display/c/SIG30-C.+Call+only+asynchronous-safe+functions+within+signal+handlers" rel="nofollow">a complete list of asynchronous-signal-safe functions</a> that can be safely called from a signal handler. Instead, you should in this case set a flag, of type <code>volatile sig_atomic_t</code>, and set that in your handler. </p>
<p>Second, the way you use <code>strcpy()</code> here in particular is dangerous. Suppose <code>number</code> currently contains <code>"Two"</code>. Then, on the next iteration of your loop, it copies in <code>'T'</code>, <code>'h'</code>, <code>'r'</code>, and <code>'e'</code>, the last character overwriting the existing terminating null character. <em>Then</em> the signal is delivered and this string gets passed to <code>printf()</code>. Even without the problems of calling <code>printf()</code> from a signal handler, you're sending it an array of <code>char</code> which is not terminated by a null character, and you'll incur undefined behavior and probably segfault.</p>
<p>Here's a better version of your example, using the <code>sigaction()</code> interface, and not calling unsafe functions from the signal handler:</p>
<pre><code>#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
char * nums[] = {"One", "Two", "Three", "Four", "Five"};
volatile sig_atomic_t stop;
void handler(int n)
{
stop = 1;
}
int main(void)
{
struct sigaction sa;
sa.sa_handler = handler;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
if ( sigaction(SIGTSTP, &sa, NULL) == -1 ) {
perror("Couldn't set SIGTSTP handler");
exit(EXIT_FAILURE);
}
int n = 0;
while ( !stop ) {
puts(nums[n]);
n = (n + 1) % 5;
}
puts("Signal handler called, exiting.");
return 0;
}
</code></pre>
<p>with output:</p>
<pre><code>paul@horus:~/src/sandbox$ ./sig
One
Two
Three
Four
Five
One
^ZTwo
Three
Four
Five
One
Signal handler called, exiting.
paul@horus:~/src/sandbox$
</code></pre>
<p>You can see there's a delay between inputting <code>Ctrl-Z</code> and the actual delivery of the signal, which is perfectly normal and to be expected based on how the kernel actually delivers signals. </p>
|
Protractor - Ignore Synchronisation flag <p>I have started doing a POC on Protractor as our e2e automation testing tool.
Our application is designed in angular which makes it a perfect fit.</p>
<p>However, I need to login via google which is a non-angular website and therefore at the start of my test I state</p>
<blockquote>
<p>browser.ignoreSynchronization = true;</p>
</blockquote>
<p>Then I go to </p>
<blockquote>
<p>'<a href="https://accounts.google.com/ServiceLogin" rel="nofollow">https://accounts.google.com/ServiceLogin</a>'</p>
</blockquote>
<p>Enter my google credentials and click on signin</p>
<p>At this point I try to go to my application's URL, which is an angular application so I was hoping to turn</p>
<blockquote>
<p>browser.ignoreSynchronization = false;</p>
</blockquote>
<p>All the the above steps are part of a beforeEach so that I can login before each test</p>
<p>But when I turn ignoreSynchronization to false, all my tests start failing.
On the other hand, if I don't turn it to false, I am compelled to use a lot of browser.sleeps as Protractor is still treating it as a non-angular app and does not wait for angular to load fully</p>
<p>I have also tried to put the ignoreSynchronization = false in each individual test as opposed to beforeEach but even then all my tests start failing.</p>
<p>Below is my beforeEach code</p>
<pre><code> browser.ignoreSynchronization = true;
browser.driver.manage().window().setSize(1280, 1024);
browser.get(googlelogin);
email.sendKeys('username');
next.click();
browser.wait(EC.visibilityOf(pwd), 5000);
pwd.sendKeys('pwd');
signin.click();
browser.ignoreSynchronization = false;
browser.driver.get(tdurl);
</code></pre>
| <p>Few things to fix:</p>
<ul>
<li>wait for the "click" to go through</li>
<li>use <code>browser.get()</code> on the Angular Page</li>
</ul>
<p>Here are the modifications:</p>
<pre><code>signin.click().then(function () {
browser.ignoreSynchronization = false;
browser.get(tdurl);
browser.waitForAngular(); // might not be necessary
});
</code></pre>
<p>You may also add a <a href="http://www.protractortest.org/#/api?view=webdriver.WebDriver.prototype.wait" rel="nofollow">wait</a> with an Expected Condition to wait for the login step to be completed - say, wait for a specific URL, or page title, or an element on the page.</p>
|
What does <function at ...> mean <p>Here's the code:</p>
<pre><code>def my_func(f, arg):
return f(arg)
print((lambda x: 2*x*x, (5)))
>>>(<function <lambda> at 0x10207b9d8>, 5)
</code></pre>
<p>How to solve the error, and can some please explain in a clear language what exactly that error means.</p>
| <p>There is no error; you simply supplied two arguments to <code>print</code>, the <code>lambda x: 2*x*x</code> and <code>5</code>. You're not calling your anonymous function rather, just passing it to <code>print</code>.</p>
<p><code>print</code> will then call the objects <code>__str__</code> method which returns what you see:</p>
<pre><code>>>> str(lambda x: 2*x*x) # similarly for '5'
'<function <lambda> at 0x7fd4ec5f0048>'
</code></pre>
<p>Instead, fix your parenthesis to actually <em>call</em> the lambda with the <code>5</code> passed as the value for <code>x</code>:</p>
<pre><code>print((lambda x: 2*x*x)(5))
</code></pre>
<p>which prints out <code>50</code>.</p>
<hr>
<blockquote>
<p>What's the general meaning of <code><function at 0x ...></code>?</p>
</blockquote>
<p>That's simply the way Python has chosen to represent function objects when printed. Their <code>str</code> takes the name of the function and the <code>hex</code> of the <code>id</code> of the function and prints it out. E.g:</p>
<pre><code>def foo(): pass
print(foo) # <function foo at 0x7fd4ec5dfe18>
</code></pre>
<p>Is created by returning the string:</p>
<pre><code>"<function {0} at {1}>".format(foo.__name__, hex(id(foo)))
</code></pre>
|
Converting If statement to a loop <p>I am working on a practice problem where we are to input a list into a function argument, that will represent a tic tac toe board, and return the outcome of the board. That is, X wins, O wins, Draw, or None (null string).</p>
<p>I have it solved, but I was wondering if there is a way I could manipulate my algorithm into a loop, as it was recommended to use a loop to compare each element of the main diagonal with all the
elements of its intersecting row and column, and then check the two diagonals. I'm new to python, so my solution might be a bit longer then it needs to be. How could a loop be implemented to check the outcome of the tic tac toe board? </p>
<pre><code>def gameState (List):
xcounter=0
ocounter=0
if List[0][0]==List[0][1] and List[0][0]==List[0][2]:
return List[0][0]
elif List[0][0]==List[1][0] and List[0][0]==List[2][0]:
return List[0][0]
elif List[0][0]==List[1][1] and List[0][0]==List[2][2]:
return List[0][0]
elif List[1][1]==List[1][2] and List[1][1]==List[1][0] :
return List[1][1]
elif List[1][1]==List[0][1] and List[1][1]==List[2][1]:
return List[1][1]
elif List[1][1]==List[0][0] and List[1][1]==List[2][2]:
return List[1][1]
elif List[2][2]==List[2][0] and List[2][2]==List[2][1]:
return List[2][2]
elif List[2][2]==List[1][2] and List[2][2]==List[0][2]:
return List[2][2]
elif List[2][2]==List[1][1] and List[2][2]==List[0][0]:
return List[2][2]
for listt in List:
for elm in listt:
if elm=="X" or elm=="x":
xcounter+=1
elif elm=="O" or elm=="o":
ocounter+=1
if xcounter==5 or ocounter==5:
return "D"
else:
return ''
</code></pre>
| <p>First up, there are only <em>eight</em> ways to win at TicTacToe. You have nine compare-and-return statements so one is superfluous. In fact, on further examination, you check <code>00, 11, 22</code> <em>three</em> times (cases 3, 6 and 9) and totally <em>miss</em> the <code>02, 11, 20</code> case.</p>
<p>In terms of checking with a loop, you can split out the row/column checks from the diagonals as follows:</p>
<pre><code># Check all three rows and columns.
for idx in range(3):
if List[0][idx] != ' ':
if List[0][idx] == List[1][idx] and List[0][idx] == List[2][idx]:
return List[0][idx]
if List[idx][0] != ' ':
if List[idx][0] == List[idx][1] and List[idx][0] == List[idx][2]:
return List[idx][0]
# Check two diagonals.
if List[1][1] != ' ':
if List[1][1] == List[0][0] and List[1][1] == List[2][2]:
return List[1][1]
if List[1][1] == List[0][2] and List[1][1] == List[2][0]:
return List[1][1]
# No winner yet.
return ' '
</code></pre>
<p>Note that this ensures a row of empty cells isn't immediately picked up as a win by nobody. You need to check only for wins by a "real" player. By that, I mean you don't want to detect three empty cells in the first row and return an indication based on that if the second row has an <em>actual</em> winner.</p>
<hr>
<p>Of course, there are numerous ways to refactor such code to make it more easily read and understood. One way is to separate out the logic for checking a <em>single</em> line and then call that for each line:</p>
<pre><code># Detect a winning line. First cell must be filled in
# and other cells must be equal to first.
def isWinLine(brd, x1, y1, x2, y2, x3, y3):
if brd[x1][y1] == ' ': return False
return brd[x1][y1] == brd[x2][y2] and brd[x1][y1] == brd[x3][y3]
# Get winner of game by checking each possible line for a winner,
# return contents of one of the cells if so. Otherwise return
# empty value.
def getWinner(brd):
# Rows and columns first.
for idx in range(3):
if isWinLine(brd, idx, 0, idx, 1, idx, 2): return brd[idx][0]
if isWinLine(brd, 0, idx, 1, idx, 2, idx): return brd[0][idx]
# Then diagonals.
if isWinLine(brd, 0, 0, 1, 1, 2, 2): return brd[1][1]
if isWinLine(brd, 2, 0, 1, 1, 0, 2): return brd[1][1]
# No winner yet.
return ' '
</code></pre>
<p>Then you can just use:</p>
<pre><code>winner = getWinner(List)
</code></pre>
<p>in your code and you'll either get back the winner or an empty indication if there isn't one.</p>
|
Use a list to conditionally fill a new column based on values in multiple columns <p>I am trying to populate a new column within a pandas dataframe by using values from several columns. The original columns are either <code>0</code> or '1' with exactly a single <code>1</code> per series. The new column would correspond to df['A','B','C','D'] by populating <code>new_col = [1, 3, 7, 10]</code> as shown below. (A <code>1</code> at <code>A</code> means <code>new_col = 1</code>; if <code>B=1</code>,<code>new_col = 3</code>, etc.)</p>
<pre><code>df
A B C D
1 1 0 0 0
2 0 0 1 0
3 0 0 0 1
4 0 1 0 0
</code></pre>
<p>The new <code>df</code> should look like this.</p>
<pre><code>df
A B C D new_col
1 1 0 0 0 1
2 0 0 1 0 7
3 0 0 0 1 10
4 0 1 0 0 3
</code></pre>
<p>I've tried to use <code>map</code>, <code>loc</code>, and <code>where</code> but can't seem to formulate an efficient way to get it done. Problem seems very close <a href="http://stackoverflow.com/questions/36551128/how-to-fill-a-column-conditionally-to-values-in-an-other-column-being-in-a-list">to this</a>. A couple other posts I've looked at <a href="http://stackoverflow.com/questions/10715519/conditionally-fill-column-values-based-on-another-columns-value-in-pandas">1</a> <a href="http://stackoverflow.com/questions/19226488/python-pandas-change-one-value-based-on-another-value">2</a> <a href="http://stackoverflow.com/questions/17071871/select-rows-from-a-dataframe-based-on-values-in-a-column-in-pandas">3</a>. None of these show how to use multiple columns conditionally to fill a new column based on a list.</p>
| <p>I can think of a few ways, mostly involving <code>argmax</code> or <code>idxmax</code>, to get either an ndarray or a Series which we can use to fill the column.</p>
<p>We could drop down to <code>numpy</code>, find the maximum locations (where the 1s are) and use those to index into an array version of new_col:</p>
<pre><code>In [148]: np.take(new_col,np.argmax(df.values,1))
Out[148]: array([ 1, 7, 10, 3])
</code></pre>
<p>We could make a Series with new_col as the values and the columns as the index, and index into that with idxmax:</p>
<pre><code>In [116]: pd.Series(new_col, index=df.columns).loc[df.idxmax(1)].values
Out[116]: array([ 1, 7, 10, 3])
</code></pre>
<p>We could use get_indexer to turn the column idxmax results into integer offsets we can use with new_col:</p>
<pre><code>In [117]: np.array(new_col)[df.columns.get_indexer(df.idxmax(axis=1))]
Out[117]: array([ 1, 7, 10, 3])
</code></pre>
<p>Or (and this seems very wasteful) we could make a new frame with the new columns and use idxmax directly:</p>
<pre><code>In [118]: pd.DataFrame(df.values, columns=new_col).idxmax(1)
Out[118]:
0 1
1 7
2 10
3 3
dtype: int64
</code></pre>
|
For loop - Magic number program <p>What changes should I make so that the user of this code can guess at the amount of magic numbers they choose, with three different chances to guess at each magic number? I am also confused on what to change so that the magic number can change once the user guesses the magic number correctly. </p>
<pre><code>#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstdio>
using namespace std;
int main()
{
int magic; // This is a random number between 1 and 20
int guess; // This is the guess number being attempted (up to 3 guesses)
int magicguesses; // This is the amount of magic numbers being guessed attempted
int i;
int number; // This is the number the user guessed
bool numberismagic = false; // This is the flag variable
unsigned int seed;
seed = time(NULL);
srand(seed);
magic = rand() % 20 + 1;
cout << "How many magic numbers would you like to guess at today?\n";
cin >> magicguesses;
for (i = 1; i < magicguesses + 1; i++)
{
cout << "This is trial number:" << i << endl;
for (guess = 1; (guess < 4) && (!numberismagic); guess++)
{
cout << "This is guess number:" << guess << endl;
cout << "Guess a number between 1 and 20:" << endl;
cin >> number;
while ((number < 1) || (number > 20))
{
cout << "Your guess is invalid; guess a number between 1 and 20 \n";
cin >> number;
cout << endl;
}
if (number == magic)
{
cout << "You have guessed the magic number correctly! \n";
numberismagic = true;
}
else
{
cout << "Sorry - you guessed incorrectly! \n";
if (number > magic)
cout << "Your guess is too high \n" << endl;
else
cout << "Your guess is too low \n" << endl;
}
}
if (number != magic)
cout << "The magic number is:" << magic << endl;
}
return 0;
}
</code></pre>
| <p>I'm not sure what your first question is, but for this question "I am also confused on what to change so that the magic number can change once the user guesses the magic number correctly", you should edit the variable <code>magic</code> inside the first <code>for loop</code> so the magic number changes after the user guesses correctly or they run out of tries.</p>
<pre><code>for (i=1;i<magicguesses+1;i++)
{
//magic equals new random number
//the rest of your code
}
</code></pre>
|
Java safe return type container <p>I am a c++ developer by day, and I am used to the convention of const return types. I am aware that there is no facility similar to this in java.</p>
<p>I have a specific situation and was wondering the best immutable collection for my task. In C++ I would just use std::vector.</p>
<p>I have a WavFile class that currently has a float[] data, I would like to replace this with something that could be immutable.</p>
<p>Some important stipulations about the container is that its size is known at creation, and it does not need to dynamically grow or shrink at all. Secondly, it should be O(1) to index into the container. </p>
<p>And most importantly, like the topic alludes to, I want to be able to have a getter that returns an immutable version of this container.</p>
<p>What would be the container type I am looking for? Is this something that is possible in java?</p>
| <p>If you can live with the boxing cost, a <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableList-java.util.List-" rel="nofollow"><code>Collections.unmodifiableList()</code></a> or <a href="http://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/ImmutableList.html" rel="nofollow">Guava <code>ImmutableList</code></a> will work.</p>
<p>If not, try <a href="http://trove.starlight-systems.com/" rel="nofollow">Trove</a>, which provides <a href="http://trove4j.sourceforge.net/javadocs/gnu/trove/list/array/TFloatArrayList.html" rel="nofollow"><code>TFloatArrayList</code></a> and <a href="http://trove4j.sourceforge.net/javadocs/gnu/trove/TCollections.html#unmodifiableCollection(gnu.trove.TFloatCollection)" rel="nofollow">an easy way to make them unmodifiable</a>.</p>
|
How to register JS object via Electron? <p>I'm new on Node.js and Electron.</p>
<p>I already developed a Web View Application via CefSharp.WinForm.</p>
<p>When I used CefSharp, I added <code>window.AppViewport</code> object like this.</p>
<pre><code>chromeBrowser.RegisterAsyncJsObject("AppViewport", new AppViewport(this));
</code></pre>
<p>And in web page, I used the <code>AppViewport</code> like this.</p>
<pre><code>if(window.AppViewport !== undefined){
window.AppViewport.setDepth(widthDepthLevel);
}
</code></pre>
<p>However, I couldn't find <code>registerAsyncJsObject</code> or <code>registerJjObject</code> in electron. </p>
<p>How can I add the javascript object handler in electron like C# appllication?
Is there anything equivalent with that method?</p>
| <p>You need to define a <code>global</code> object on your <code>Main</code> process,</p>
<pre><code>global.yourSharedObj = {some_prop: true};
</code></pre>
<p>and with Electron's Remote API, you can access that object in <code>Renderer</code> with something like this:</p>
<pre><code>var remote = require('electron').remote;
console.log(remote.getGlobal('yourSharedObj').some_prop);
</code></pre>
<p>Remote API Docs:<br>
<a href="https://github.com/electron/electron/blob/master/docs/api/remote.md" rel="nofollow">https://github.com/electron/electron/blob/master/docs/api/remote.md</a></p>
|
how's the input word2vec get fine-tuned when training CNN <p>When I read the paper "Convolutional Neural Networks for Sentence Classification"-Yoon Kim-New York University, I noticed that the paper implemented the "CNN-non-static" model--A model with pre-trained vectors from word2vec,and all wordsâ including the unknown ones that are randomly initialized, <strong>and the pre-trained vectors are fine-tuned for each task</strong>.
So I just do not understand how the pre-trained vectors are fine-tuned for each task. Cause as far as I know, the input vectors, which are converted from strings by word2vec.bin(pre-trained), just like image matrix, which can not change during training CNN. So, if they can, HOW? Please help me out, Thanks a lot in advance!</p>
| <p>The word embeddings are weights of the neural network, and can therefore be updated during backpropagation.</p>
<p>E.g. <a href="http://sebastianruder.com/word-embeddings-1/" rel="nofollow">http://sebastianruder.com/word-embeddings-1/</a> :</p>
<blockquote>
<p>Naturally, every feed-forward neural network that takes words from a vocabulary as input and embeds them as vectors into a lower dimensional space, which it then fine-tunes through back-propagation, necessarily yields word embeddings as the weights of the first layer, which is usually referred to as Embedding Layer.</p>
</blockquote>
|
If multiple classes have a static variable in common, are they shared (within the same scope?) <p>I have the following example code:</p>
<pre><code>class A {
public:
static int a;
};
int A::a = 0;
class B {
public:
static A a1;
};
A B::a1;
class C {
public:
static A a1;
};
A C::a1;
int main(int argc, const char * argv[]) {
C::a1.a++;
B::a1.a++;
std::cout << B::a1.a << " " << C::a1.a << std::endl;
return 0;
}
</code></pre>
<p>Class B and C have class A as a static member variable.</p>
<p>I expected the program to print "1 1", however it prints "2 2".</p>
<p>If multiple classes have a static variable in common, are they shared (within the same scope?)</p>
| <p>The <a href="http://en.cppreference.com/w/cpp/language/static">static members</a> belong to class, it has nothing to do with objects. </p>
<blockquote>
<p>Static members of a class are not associated with the objects of the class: they are independent objects with static storage duration or regular functions defined in namespace scope, only once in the program.</p>
</blockquote>
<p>For your code, there's only one <code>A::a</code>, which is independent of <code>B::a1</code> and <code>C::a1</code> (which are objects of class <code>A</code>). So both <code>B::a1.a</code> and <code>C::a1.a</code> refer to <code>A::a</code>.</p>
|
The `or` operator on dict.keys() <p>As I've been unable to find any documentation on this, so I'll ask here. </p>
<p>As shown in the code below, I found that the <code>or</code> operator (<code>|</code>), worked as such:</p>
<pre><code>a = {"a": 1,"b": 2, 2: 3}
b = {"d": 10, "e": 11, 11: 12}
keys = a.keys() | b.keys()
aonce = a.keys() | a.values()
bonce = b.keys() | b.values()
for i in keys:
print(i, end=" ")
print()
for i in aonce:
print(i, end=" ")
print()
for i in bonce:
print(i, end=" ")
print()
</code></pre>
<p>Which produces the result, in some order:</p>
<pre><code>2 d 11 a b e
3 1 2 a b
10 e 11 12 d
</code></pre>
<p>Initially I assumed these iterable was compatible with <code>|</code>, similar to the way sets are, however. Testing with other iterable, such as a <code>list.__iter__()</code>, threw an error. Even; </p>
<pre><code>values = a.values() | b.values()
for i in values:
print(i, end=" ")
print()
</code></pre>
<p>Which I'd assume worked, due to the use of <code>dict.values()</code> in the previous examples, threw an error.</p>
<p>So, my question is; What on earth have I come across, and more importantly, how reliable is it? What subclass does my arguments need to be, for me to be able to use this?</p>
| <p>The <a href="https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects">Python 3 Documentation</a> notes that the <code>dict.keys</code> method is set-like and implements <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Set"><code>collections.abc.Set</code></a>.</p>
<p>Note that <code>dict.values</code> is <strong>not set-like</strong> even though it might appear to be so in your examples:</p>
<pre><code>aonce = a.keys() | a.values()
bonce = b.keys() | b.values()
</code></pre>
<p>However these are leveraging off the fact that the keys view implements <code>__or__</code> (and <code>__ror__</code>) over arbitrary iterables.</p>
<p>For example, the following will not work:</p>
<pre><code>>>> a.values() | b.values()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for |: 'dict_values' and 'dict_values'
</code></pre>
|
What is the file extension when creating Binary files <p>I am just trying to learn to write to Binary files. When we create text files we normally give the extension .txt. The same way, what should be the file extension for Binary files created using C#.</p>
<p>Which are the contexts that demands us to write to a binary file. What is the benefit in writing/creating a binary file rather than a text file when processing data?</p>
| <p>Absolutely anything you want, or even nothing at all.</p>
<p>Just make sure you're consistent, and it helps not to use an extension already in wide use such as .doc or .pdf</p>
<p>Microsoft once advised using long extensions of the form <code>.company-program-format</code> [1] since you can have extensions longer than 3 characters now, but this never took off to gain wide acceptance in the industry.</p>
<p>1: Footnote: I cannot find a source for this claim but I remember reading it on MSDN around the time Windows Vista came out. You see it in Windows OS files like <code>dvr-ms</code>. These former guidelines are alluded to in this page, but the it's link is now broken and points to a totally different page: <a href="https://msdn.microsoft.com/en-gb/library/windows/desktop/cc144156(v=vs.85).aspx#short_and_long" rel="nofollow">https://msdn.microsoft.com/en-gb/library/windows/desktop/cc144156(v=vs.85).aspx#short_and_long</a></p>
|
On android, how to abort geocoder.getFromLocation <p>A am using the code bellow to get the adress of my lat/lon</p>
<pre><code>Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
</code></pre>
<p>The method getFromLocation is bloking. I am already execution in another Thread, but i would like to cancel the operation. </p>
<p>So how do i cancel the getFromLocation ?</p>
| <p>Check out the Android documentation for <a href="https://developer.android.com/training/location/display-address.html" rel="nofollow">Displaying a Location Address</a>. </p>
<p>Here you create an IntentService, which runs on a worker thread and finishes itself after the <code>onHandleIntent()</code> has completed. They are using a <a href="https://developer.android.com/reference/android/os/ResultReceiver.html#ResultReceiver(android.os.Handler)" rel="nofollow">ResultReceiver</a>, that receives the results from geocoder.getFromLocation(lat, lng, 1). The <code>handler</code> passed into the <code>ResultReceiver</code> constructor, would be back on the main/ui thread. </p>
<p>In this example, you wouldn't need to cancel the operation at all. It is running in a service, on a worker thread and therefore not blocking your main/ui thread. Also, the service shuts itself down after it completes geocoder.getFromLocation(lat, lng, 1). If you no longer wanted to receive the Location results back on the main/ui thread, you could easily handle that as well from within the <code>ResultReceiver</code>.</p>
|
nginx reverse proxy fails for post/get requests <p>I'm trying to set up a reverse proxy using nginx for a nodejs application. My node application currently runs on port 8005 of the example.com server. Running the application and going to example.com:8005 the application works perfect. But When I tried to set up nginx my application seems to work at first by going to example.com/test/ but when I try and post or get requests the request wants to use the example.com:8005 url and I end up with a cross origin error, CORS. I would like to have the request url reflect the nginx url but I'm having no luck getting there. Below is my nginx default.conf file. </p>
<pre><code>server {
listen 80;
server_name example;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
location /test/ {
proxy_pass http://localhost:8005/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
</code></pre>
| <p>There got to be some way to tell nginx about whichever app you are using.</p>
<p>So for that, either you can prefix all the apis with say test<code>(location /test/api_uri</code>), and then catch all the urls with prefix /test and proxy_pass them to node, or if there is some specific pattern in your urk, you can catch that pattern with regex, like suppose, all the app1 apis contain app1 somewhere in it, then catch those urls using <code>location ~ /.*app1.* {} location ~ /.*app2.*</code>, make sure that you maintain the <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#location" rel="nofollow">order</a> of location.</p>
<p>Demo Code :</p>
<pre><code>server {
...
location /test {
proxy_pass http://localhost:8005/; #app1
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location /test2 {
proxy_pass http://localhost:8006/; #app2
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
...
}
</code></pre>
<p>Other Demo for regex,</p>
<pre><code>server {
...
location ~ /.*app1.* {
proxy_pass http://localhost:8005/; #app1
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location ~ /.*app2.* {
proxy_pass http://localhost:8006/; #app2
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
...
}
</code></pre>
|
How to disable content selection in mobile browser <p>I'm trying to include a command to disable content in mobile browser. Initially i tried to insert this code in the body of the blog:</p>
<pre><code> <body expr:class='&quot;loading&quot; + data:blog.mobileClass'>
</code></pre>
<p>And this code in the css style</p>
<pre><code> <style>.mobile body{ -webkit-touch-callout:none; -webkit-user-select:none; -khtml-user-select:none; -moz-user-select:none; -ms-user-select:none; user-select:none; -webkit-tap-highlight-color:rgba(0,0,0,0); } </style>
</code></pre>
<p>But i couldn't make this work. I try to insert inside the and outside too but nothing changes. </p>
<p>If i forgot something that need to be included or something, let me know it.
Thanks for the help and sorry for the question .</p>
| <p>Is <code>expr:class='&quot;loading&quot; + data:blog.mobileClass'</code> what applies the <code>mobile</code> class you're trying to target? If so, your selector is a little off. </p>
<p><code>.mobile body</code> is looking for a <code>.mobile</code> with a <code>body</code> inside it. What you want is <code>body.mobile</code> or just <code>.mobile</code>, depending on how specific you need it to be.</p>
|
What does "Load Playlist started" mean in Visual Studio? <p>When I load my solution into Visual Studio, I get the following in the Output window:</p>
<pre><code>------ Load Playlist started ------
========== Load Playlist finished (0:00:00.0030077) ==========
</code></pre>
<p><a href="https://i.stack.imgur.com/CNCRV.png" rel="nofollow"><img src="https://i.stack.imgur.com/CNCRV.png" alt="enter image description here"></a></p>
<p>What does it mean?</p>
| <p>Starting with Visual Studio 2012 Update 2 you can create a Playlist in the Test Explorer that consists of a subset of your existing unit tests. (Before VS2012 Update 2 you could only use Traits to sort of group them together.)</p>
<p>A Playlist is essentially needed when you only want to run specific unit tests that make sense in a given logical context which doesn't match your project or class structure. Playlists are then saved in .playlist files.</p>
<p>If you start VS it will try to load any Playlists which outputs the message you posted. In my case VS only shows this message if I have the Test Explorer window open but I don't know if there are other criteria that can trigger the lookup of the Playlists. So if Test Explorer isn't open then I don't get your <code>Load Playlist started</code> message.</p>
<p>After loading the Playlists VS usually tries to discover the actual unit tests and you get something like this message in the Output window:</p>
<pre><code>------ Discover test started ------
========== Discover test finished: 534 found (0:00:01,6890966) ==========
</code></pre>
<p>If you haven't used Playlists before you can read more about them <a href="http://dailydotnettips.com/2015/06/19/create-and-run-subset-of-unit-test-using-playlist-in-visual-studio/" rel="nofollow">here</a>.</p>
|
How to create this type of view in ionic? <p>I tried below code</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.halfOval {
background-color: #a0C580;
width: 400px;
height: 100px;
margin: 50px auto 0px;
border-radius: 0 0 80% 80%/ 0px 0px 100% 100%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="halfOval"></div></code></pre>
</div>
</div>
</p>
<p>and I am getting this type of view
<a href="https://i.stack.imgur.com/JXUM9.png" rel="nofollow"><img src="https://i.stack.imgur.com/JXUM9.png" alt="enter image description here"></a></p>
<p>How can i achieve below type of image view in ionic?</p>
<p><a href="https://i.stack.imgur.com/SB38Q.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/SB38Q.jpg" alt="enter image description here"></a></p>
<p><strong>Finally i came up with solution and i posted below</strong></p>
| <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="
background-color: #19cb8d;
width: 100%;
height: 130px;
margin: 0px auto 0px;
border-radius: 200px/ 50px;
border-top-right-radius: 0px;
border-top-left-radius: 0px;"></div>
<!--rgba(236 , 239 , 241, 0)-->
<center>
<div style="width: 100px;height:100px;margin-top: -50px;border-radius: 100px;background-color: whitesmoke;box-shadow: 0 4px 8px 0 rgba(0 , 0 0, 0.2), 0 6px 20px 0 rgba(0 , 0 , 0, 0.19);border: 4px solid white;">
<img src="http://www.freeiconspng.com/uploads/profile-icon-png-profiles-13.png" class="img-responsive" alt="Cinque Terre" width="42px" style="margin-top: 10px">
<p style="color: grey;margin-top:-5px !important;font-size: 16px;font-family: "-apple-system", "Helvetica Neue", Roboto, "Segoe UI", sans-serif">Profile Pic</p>
</div>
</center></code></pre>
</div>
</div>
</p>
|
python array data structure <p>is there a data structure in python that is equivalent to array in cpp?
one that some elements are initialized and some are not?
for example, in python list: [1,2,3], elements have to be sequentially filled
in cpp array can be a[0] == 0, a<a href="https://i.stack.imgur.com/G7MBe.png" rel="nofollow">1</a> -- arbitrary, uninitialized, a[2] == 2</p>
<p>is there an cpp-array equivalent structure in python?
ps, python array doesn't seem to be equivalent, all elements have to be filled sequentially too</p>
<p><img src="https://i.stack.imgur.com/G7MBe.png" alt="enter image description here"></p>
| <p>Perhaps this answer here on StackOverflow may be what you are looking for?</p>
<p><a href="https://stackoverflow.com/questions/10617045/how-to-create-a-fix-size-list-in-python">How to create a fix size list in python?</a></p>
|
pandas Dataframe columns doing algorithm <p>I have a dataframe like this:</p>
<pre><code>df = pd.DataFrame({
'A': ['a', 'a', 'a', 'a', 'a'],
'lon1': [128.0, 135.0, 125.0, 123.0, 136.0],
'lon2': [128.0, 135.0, 139.0, 142.0, 121.0],
'lat1': [38.0, 32.0, 38.0, 38.0, 38.0],
'lat2': [31.0, 32.0, 35.0, 38.0, 29.0],
'angle': [0, 0, 0, 0, 0]
})
</code></pre>
<p>I want to count the angle of each row by this function and save back to the angle column</p>
<pre><code>def angle(lon1,lat1,lon2,lat2):
dx = lon2 - lon1
dy = lat2 - lat1
direction = 0;
if ((dx == 0) & (dy == 0)): # same position
return direction
if (dx > 0.0) :
direction = 90-np.arctan2(dy,dx)*180/np.pi
elif (dy > 0.0 ) :
direction = 180+(270-(np.arctan2(dy,dx)*180/np.pi))
else :
direction = 360-(270+(np.arctan2(dy,dx)*180/np.pi))
if (direction < 0) :
direction += 360
return (direction.astype(int) % 360)
</code></pre>
<p>I tried </p>
<pre><code>df.ix[df['A'].notnull(), 'angle'] =angle(
df[df['A'].notnull()]['lon1'],
df[df['A'].notnull()]['lat1'],
df[df['A'].notnull()]['lon2'],
df[df['A'].notnull()]['lat2'])
</code></pre>
<p>and I got an error</p>
<blockquote>
<p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p>
</blockquote>
<p>I tried <code>for index,row in df.iterrows():</code> the result of for loop is ok but it took terribly long long time(original data is about 10 million rows ) </p>
<p>could anyone kindly give some efficient methods?</p>
| <p>It seems like you are trying to apply function <code>angle(...)</code> to every row of your dataframe.</p>
<p>First it is necessary to cast all your string-typed numbers into float so as to calculate.</p>
<pre><code>df1.loc[:, "lon1"] = df1.loc[:, "lon1"].astype("float")
df1.loc[:, "lon2"] = df1.loc[:, "lon2"].astype("float")
df1.loc[:, "lat1"] = df1.loc[:, "lat2"].astype("float")
df1.loc[:, "lat2"] = df1.loc[:, "lat2"].astype("float")
</code></pre>
<p>There you go.</p>
<pre><code>df1.loc[:, "angle"] = df1.apply(lambda x: angle(x["lon1"], x["lat1"], x["lon2"], x["lat2"]), axis = 1)
</code></pre>
<p>As for performance concern, here are some tips for you.</p>
<ol>
<li>Profiling. </li>
<li>Use <code>numba</code> for JIT compilation and automatic vectorization of your function.</li>
</ol>
|
SQL- The multi-part identifier could not be bound <p><a href="https://i.stack.imgur.com/pG5LJ.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/pG5LJ.jpg" alt="enter image description here"></a></p>
<p>While executing the following query, I am getting the Multi Part Identifier could not be bound error. Kindly help.</p>
<p>Query:</p>
<pre><code>SELECT
C.CustomerID, C.LastName, A.ArtistID, A.LastName
FROM
CUSTOMER as C, ARTIST as A
WHERE
CUSTOMER_ARTIST_INT.CustomerID = CUSTOMER.CustomerID
AND CUSTOMER_ARTIST_INT.ArtistID = ARTIST.ArtistID;
</code></pre>
| <p>Try this</p>
<pre><code>SELECT C.CustomerID, C.LastName, A.ArtistID, A.LastName
FROM CUSTOMER as C, ARTIST as A WHERE CUSTOMER_ARTIST_INT.CustomerID=C.CustomerID AND CUSTOMER_ARTIST_INT.A=ARTIST.ArtistID
</code></pre>
|
How can I access a file that I have created externally? AKA where is the file? <p>I'm in the process of trying to create a backup/restore (export/import) process for an SQLite Database App.</p>
<p>Although I appear to have created and populated the file (OK I now know that I have). I cannot see the file in DDMS nor in Windows Explorer. I'd really like to be able to do the latter (see the bottom for a more specific question).</p>
<p>I've successfully written the file and read the file using the following code:</p>
<pre><code>package mjt.sqlitetutorial;
import android.database.Cursor; //+++++ Added
import android.os.Build;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log; //+++++ Added
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
public int API_VERSION = Build.VERSION.SDK_INT;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (API_VERSION >= 23) {
ExternalStoragePermissions.verifyStoragePermissions(this);
}
final String EXTSTGTAG = "EXTERNSTG";
File file = getExternalFilesDir("File");
Log.i(EXTSTGTAG,file.toString());
//String extstgdirabs = Environment.getExternalStorageDirectory().getAbsolutePath();
String extstgdirpth = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
Log.i(EXTSTGTAG,"<=\nEXTERN STG PUB DIR=>" + extstgdirpth);
String filepath = extstgdirpth + File.separator + "myfile.txt";
Log.i(EXTSTGTAG,"Full File Path and name is\n\t" + filepath);
File f = new File(filepath);
if(!f.exists() ) {
Log.i(EXTSTGTAG,"File did not exist (path=" + filepath + ")");
try {
f.createNewFile();
}
catch (IOException e) {
Log.e(EXTSTGTAG,"Failure Creating New File MSG=" + e.getMessage());
}
}
if(f.exists()) {
Log.i(EXTSTGTAG,"File Already Exists (" + filepath + ")");
try {
Log.i(EXTSTGTAG,"Creating FileOutputStream instance.");
FileOutputStream fos = new FileOutputStream(f);
Log.i(EXTSTGTAG,"Creating OutputStreamWriter instance from FileOutputStream.");
OutputStreamWriter osw = new OutputStreamWriter(fos);
Log.i(EXTSTGTAG,"Adding Data to OutputStreamWriter.");
osw.append("My Test Data.");
Log.i(EXTSTGTAG,"Closing OutputStreamWriter.");
osw.close();
Log.i(EXTSTGTAG,"Flushing FileOutputStream.");
fos.flush();
Log.i(EXTSTGTAG,"Closing FileOutputStream");
fos.close();
Log.i(EXTSTGTAG,"All Done OK.");
} catch (IOException e) {
Log.e(EXTSTGTAG, "Failure Trying to write to file." + e.getMessage());
e.printStackTrace();
}
} else {
Log.i(EXTSTGTAG,"File doesn't appear to exist when it should????");
}
f.setReadable(true);
f.setWritable(true);
if(f.exists()) {
try {
byte[] bytes;
FileInputStream fis = new FileInputStream(f);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
br.close();
Log.i(EXTSTGTAG,"Read the following data:\n" + sb.toString());
}
catch (IOException e) {
Log.e(EXTSTGTAG,"Failure trying to read file." + e.getMessage());
e.printStackTrace();
}
}
}
}
</code></pre>
<p>Output to the log (using EXTERN as the filter) shows (note the first run when installing the App run fails but requests and sets permissions. I don't believe this is an issue/cause) :-</p>
<pre><code>10-18 12:54:40.159 32393-32393/? I/EXTERNSTG: /storage/emulated/0/Android/data/mjt.sqlitetutorial/files/File
10-18 12:54:40.159 32393-32393/? I/EXTERNSTG: <=
EXTERN STG PUB DIR=>/storage/emulated/0/Download
10-18 12:54:40.159 32393-32393/? I/EXTERNSTG: Full File Path and name is
/storage/emulated/0/Download/myfile.txt
10-18 12:54:40.159 32393-32393/? I/EXTERNSTG: File Already Exists (/storage/emulated/0/Download/myfile.txt)
10-18 12:54:40.159 32393-32393/? I/EXTERNSTG: Creating FileOutputStream instance.
10-18 12:54:40.159 32393-32393/? I/EXTERNSTG: Creating OutputStreamWriter instance from FileOutputStream.
10-18 12:54:40.159 32393-32393/? I/EXTERNSTG: Adding Data to OutputStreamWriter.
10-18 12:54:40.159 32393-32393/? I/EXTERNSTG: Closing OutputStreamWriter.
10-18 12:54:40.159 32393-32393/? I/EXTERNSTG: Flushing FileOutputStream.
10-18 12:54:40.159 32393-32393/? I/EXTERNSTG: Closing FileOutputStream
10-18 12:54:40.169 32393-32393/? I/EXTERNSTG: All Done OK.
10-18 12:54:40.169 32393-32393/? I/EXTERNSTG: Read the following data:
My Test Data.
</code></pre>
<p><strong>The last line indicating that it has read the file (I assume).</strong> There are no other log messages during the provided messages (many before and after though).</p>
<p>the device that I'm testing this on is a non-rooted HTC One M8s with an SDcard. However, I believe that <strong>/storage/emulated/0/Download</strong>, the directory where the file is being written to is on the internal memory.</p>
<p>With DDMS I don't appear to be able to see this (the actual SD card has a Download<strong>s</strong> directory as opposed to a Download directory). </p>
<p>In Windows explorer I can see both <strong>Internal Storage</strong> and <strong>SD card</strong> as devices under the <strong>HTC_0PKV1</strong> device.</p>
<p>In Windows Explorer the <strong>Download</strong> directory has (via properties) 0 Directories and Files. Neither read only nor hidden are ticked.</p>
<p>I've tried both with and without the <code>setReadable</code> and <code>setWritable()</code>.</p>
<p>I've just tried using the file manager on the phone and can now see the file. So more specifically, the question is; <strong>Is there any way excluding rooting the phone and moving the file via file manager on the phone, to access the file via Windows Explorer?</strong></p>
<p>I should also state that the App will run on tablets, so the method should be generic rather than specific to a device.</p>
| <p>The file becomes visible in Windows explorer after disconnecting and re-connecting the USB cable. I'm not sure if this how MTP is meant to work or it could perhaps be due to ADB as per this snippet:-</p>
<blockquote>
<p>However, if youâve ever attempted to unlock your device such as to
install a new ROM or root it, then you may have at one time or another
installed the Android Debug Bridge (ADB) driver on your computer. This
driver works great for being able to use the computer to send commands
to your device, but it may mess up your easy-peasy file manipulation.</p>
</blockquote>
<p>found at <a href="http://www.howtogeek.com/195607/how-to-get-your-android-device-to-show-up-in-file-explorer-if-it-isnt/" rel="nofollow">How to Get Your Android Device to Show up in File Explorer (If It Isnât)</a></p>
|
Python format() without {} <p>I am working on python 3.6 64 bit.</p>
<p>Here is my code:</p>
<pre><code>days = "Mon Tue Wed Thu Fri Sat Sun"
print("Here are the days",format(days))
</code></pre>
<p>The output I got is </p>
<p>Here are the days Mon Tue Wed Thu Fri Sat Sun</p>
<p>I didn't add "{}" in my string. Also I used a comma "," instead of a dot "."</p>
<p>My understanding was that format() will replace {} in string with its arguments.</p>
<p>Question : How did format() worked without {} and . operator</p>
| <p>I think you're thinking what's happening is similar to:</p>
<pre><code>print("Here are the days {}".format(days))
</code></pre>
<p>However, what's actually happening is that you're passing in multiple arguments to print(). If you look at the <a href="https://docs.python.org/3/library/functions.html#print" rel="nofollow">docs</a> for print(), it takes a couple of parameters:</p>
<pre><code>print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
</code></pre>
<p>The asterisk in front of objects indicates it can take multiple arguments. Right now you're passing in "Here are the days" as the first argument, and format(days) as the second, which results in:</p>
<pre><code>Here are the days Mon Tue Wed Thu Fri Sat Sun
</code></pre>
|
How To use Database as a variable with blade template in laravel? <p>i'm new in laravel, i have some problem to make database as variable to be shown on blade template,
example i want to get any data from database :</p>
<pre><code>{{$get = DB::table('perangkat')->get()}}
</code></pre>
<p>then:</p>
<pre><code>@foreach ($get as $got)
{{$got->jabatan}}
@endforeach
</code></pre>
<p>if the result of the <code>$got->jabatan</code> is <code>kepala</code>, But i want the result is Change To <code>"Kepala Desa"</code>, How can i do ??
Please Help Mee ...</p>
| <p>Write database related stuff in model or controller in a method and pass that value to view. It will be very neat and clear</p>
<pre><code>public function getData(){
$get = DB::table('perangkat')->get();
return view('myblade', ['data' => $get]);
}
</code></pre>
<p>In your view</p>
<pre><code>@foreach ($data as $got)
{{$got->jabatan}} Desa
@endforeach
</code></pre>
<p>Also can you update where you get <strong>Desa</strong> .so i can update answer according to that.</p>
<p><strong>Updated</strong>
you keep different roles in array and do some think like this</p>
<pre><code> <?php
$role=['a'=>'operator','b'=>'admin'] ; ?>
@foreach ($data as $got)
<?php $result = isset($role[$got->jabatan]) ? $role[$got->jabatan] : null; ?>
{{$result}}
@endforeach
</code></pre>
|
How rotate a Landscape Image to Portrait in Android OpenCV 3 <p>This code rotate a image from Landscape to Portrait, but I can't do it in Android. What is the equivalent code?</p>
<pre><code>import cv2
import numpy
img = cv2.imread('original.png')
h, w = img.shape[:2]
img2 = numpy.zeros((w, h, 3), numpy.uint8)
cv2.transpose(img, img2)
cv2.flip(img2, 1, img2)
cv2.imwrite('rotate.png', img2)
</code></pre>
| <p>I assume you have your image as OpenCV Mat in Android (you can load an image by using the <code>Imgcodecs.imread()</code> method).</p>
<p>Then you can just do it like this:</p>
<pre><code>Mat src = Imgcodecs.imread("path/to/file"); // initialize this with your image from file
Core.flip(src.t(), src, 1); // this will rotate the image 90° clockwise
Core.flip(src.t(), src, 0); // this will rotate the image 90° counter-clockwise
</code></pre>
<p>After that, use <code>Imgcodecs.imwrite()</code> to save the image. Make sure you add the permissions to your Manifest: </p>
<pre><code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</code></pre>
|
Python code to return total count of no. of positions in which items are differing at same index <p>A=[1,2,3,4,5,6,7,8,9]
B=[1,2,3,7,4,6,5,8,9]</p>
<p>I have to compare these two lists and return the count of no. of location in which items are differing using one line python code.</p>
<p>For example:
the output should be 4 for given arrays because at index (3,4,5,6) the items are differing.So, program should return 4.</p>
<p>My way of doing this is comparing each and every location using for loop:</p>
<pre><code>count=0
for i in range(0,len(A)):
if(A[i]==B[i]):
continue
else:
count+=1
print(count)
</code></pre>
<p>Please help me in writing one line python code for this.</p>
| <pre><code>count = sum(a != b for a, b in zip(A, B))
print(count)
</code></pre>
<p>or just <code>print sum(a != b for a, b in zip(A, B))</code></p>
<p>you can check about <a href="https://bradmontgomery.net/blog/pythons-zip-map-and-lambda/" rel="nofollow">zip/lambda/map here</a>, those tools are very powerfull and important in python..</p>
<p><a href="http://stackoverflow.com/questions/14050824/add-sum-of-values-of-two-lists-into-new-list">Here</a> you can also check others kind of ways to use those tools.</p>
<p>Have fun!!</p>
|
Special characters and json_encode <p>I'm trying to pull some information from a mysql database and then json encode it. I'm running into problems with special characters. I'll pull the info from the database containing the special characters, but then when I use the PHP json_encode function, it fails to encode and returns FALSE.</p>
<p>I I've tried the two methods below.</p>
<p>In my query I have this:</p>
<pre><code>CONVERT(item_stub.name USING utf8)
</code></pre>
<p>That didn't seem to do anything. So then I added the following to convert the data to UTF8 after the query:</p>
<pre><code> while($r = $db->fetch($result)){
$r[] = array_map('utf8_encode', $r);
</code></pre>
<p>This seemed to handle non-utf8 single quotes, but I'm still having the problem with the trademark symbol.</p>
<p>I've also tried using the PHP htmlentities and htmlspecialchars functions, but these also fail like json_encode</p>
| <blockquote>
<p>Try adding the <code>ENT_QUOTES</code> flag to <code>htmlspecialchars()</code>. It will take care of both single and double quotes for you like so:</p>
</blockquote>
<pre><code> <?php
while($r = $db->fetch($result)){
$r[] = array_map(
'utf8_encode',
htmlentities(htmlspecialchars($r, ENT_QUOTES, 'UTF-8', true)));
// CODE CONTINUES... (IF ANY)...
}
</code></pre>
<p><a href="https://eval.in/662239" rel="nofollow">QUICK-TEST THIS:</a></p>
<pre><code> $r = "â¢â¢â¢â¢@â ©ââ«â«~ªÃÂ¥ÃâÆÃ¥ÃÃÃ¥ââ¬Æââ¬Ã¥Ã¥â¬ââ¬âÆ";
$s = htmlentities(htmlspecialchars($r, ENT_QUOTES, 'UTF-8', true));
var_dump($s);
//YIELDS:
'&trade;&trade;&trade;&trade;@&dagger;&copy;&radic;&int;&int;~&ordf;&szlig;&yen;&szlig;&part;&fnof;&aring;&szlig;&szlig;&aring;&sum;&euro;&fnof;&sum;&euro;&aring;&aring;&euro;&sum;&euro;&sum;&fnof;' (length=196)
</code></pre>
|
How to work with iframes in Chrome DevTools? <p>I'd like to point the developer tools at a specific <code>iframe</code> within a document. In Firefox, there is a <a href="https://developer.mozilla.org/en-US/docs/Tools/Working_with_iframes" rel="nofollow">button</a> in the toolbar. In Chrome, I found this:</p>
<p><a href="https://i.stack.imgur.com/JuvRj.png" rel="nofollow"><img src="https://i.stack.imgur.com/JuvRj.png" alt="chrome-iframe-console"></a></p>
<p>But I don't know how to use this feature in panels other than the Console. In <a href="https://developer.mozilla.org/en-US/docs/Tools/Working_with_iframes" rel="nofollow">Firefox</a>, "If you select an entry in the list, all the tools in the toolbox - the Inspector, the Console, the Debugger and so on - will now target only that iframe, and will essentially behave as if the rest of the page does not exist."</p>
<p>How to inspect elements in an iframe as if the rest of the page does not exist? I need to see how the iframe fits in the parent page, but don't want to see the elements of the parent page in the Elements panel (because of the depth of the elements).</p>
| <p>One possible workaround is to enable the still-in-development <a href="http://www.chromium.org/developers/design-documents/oop-iframes" rel="nofollow">Out-of-process iframes (OOPIF)</a> using <code>chrome://flags/#enable-site-per-process</code> flag:</p>
<ul>
<li>A new devtools floating window will open when an iframe is inspected via rightclick menu.<br>
To inspect a youtube-like iframe with a custom context menu just rightclick again on that menu.</li>
<li>IFRAME contents won't be shown in the parent Inspector since it's in a different process.</li>
</ul>
<p>You may want to do it on a separate installation of Chrome like Canary or a portable because the feature breaks iframes on some sites (these flags affect the entire data folder with all profiles inside).</p>
|
sbcl Common Lisp incf warning <p>I was following a tutorial on lisp and they did the following code </p>
<pre><code>(set 'x 11)
(incf x 10)
</code></pre>
<p>and interpreter gave the following error:</p>
<pre><code>; in: INCF X
; (SETQ X #:NEW671)
;
; caught WARNING:
; undefined variable: X
;
; compilation unit finished
; Undefined variable:
; X
; caught 1 WARNING condition
21
</code></pre>
<p>what is the proper way to increment x ?</p>
| <p>This is indeed how you are meant to increment <code>x</code>, or at least one way of doing so. However it is not how you are meant to bind <code>x</code>. In CL you need to establish a binding for a name before you use it, and you don't do that by just assigning to it. So, for instance, this code (in a fresh CL image) is not legal CL:</p>
<pre><code>(defun bad ()
(setf y 2))
</code></pre>
<p>Typically this will cause a compile-time warning and a run-time error, although it may do something else: its behaviour is not defined.</p>
<p>What you have done, in particular, is actually worse than this: you have rammed a value into the <code>symbol-value</code> of <code>x</code> (with <code>set</code>, which does this), and then assumed that something like <code>(incf x)</code> will work, which it is extremely unlikely to do. For instance consider something like this:</p>
<pre><code>(defun worse ()
(let ((x 2))
(set 'x 4)
(incf x)
(values x (symbol-value 'x))))
</code></pre>
<p>This is (unlike <code>bad</code>) legal code, but it probably does not do what you want it to do.</p>
<p>Many CL implementations <em>do</em> allow assignment to previously unbound variables at the top-level, because in a conversational environment it is convenient. But the exact meaning of such assignments is outwith the language standard.</p>
<p>CMUCL and its derivatives, including SBCL, have historically been rather more serious about this than other implementations were at the time. I think the reason for this is that the interpreter was a bunch more serious than most others and/or they secretly compiled everything anyway and the compiler picked things up.</p>
<p>A further problem is that CL has slightly awkward semantics for top-level variables: if you go to the effort to establish a toplevel binding in the normal way, with <code>defvar</code> & friends, then you also cause the variable to be <em>special</em> -- dynamically scoped -- and this is a pervasive effect: it makes <em>all</em> bindings of that name special. That is often a quite undesirable consequence. CL, as a language, has no notion of a top-level <em>lexical</em> variable.</p>
<p>What many implementations did, therefore, was to have some kind of informal notion of a top-level binding of something which did not imply a special declaration: if you just said <code>(setf x 3)</code> at the toplevel then this would not contage the entire environment. But then there were all sorts of awkward questions: after doing that, what is the result of <code>(symbol-value 'x)</code> for instance?</p>
<p>Fortunately CL is a powerful language, and it is quite possible to <em>define</em> top-level lexical variables within the language. Here is a very hacky implementation called <code>deflexical</code>. Note that there are better implementations out there (including at least one by me, which I can't find right now): this is not meant to be a bullet-proof solution.</p>
<pre><code>(defmacro deflexical (var &optional value)
;; Define a cheap-and-nasty global lexical variable. In this
;; implementation, global lexicals are not boundp and the global
;; lexical value is not stored in the symbol-value of the symbol.
;;
;; This implementation is *not* properly thought-through and is
;; without question problematic
`(progn
(define-symbol-macro ,var (get ',var 'lexical-value))
(let ((flag (cons nil nil)))
;; assign a value only if there is not one already, like DEFVAR
(when (eq (get ',var 'lexical-value flag) flag)
(setf (get ',var 'lexical-value) ,value))
;; Return the symbol
',var)))
</code></pre>
|
How do I find the location of Python module sources while I can not import it? <p>The answer in <a href="http://stackoverflow.com/questions/269795/how-do-i-find-the-location-of-python-module-sources">How do I find the location of Python module sources?</a> says just import it and print its <code>__file__</code>. But my question is that I cannot import a library <code>cv2</code> while it returns <code>ImportError: libcudart.so.7.5: cannot open shared object file: No such file or directory</code>, so I cannot get its <code>__file__</code> too. I want to find where does Python import this library so that I can check what is wrong with the library.</p>
| <p>Try:</p>
<pre><code>import imp
imp.find_module('cv2')
</code></pre>
|
Division in Ruby, error <p>it's my first day learning Ruby. I'm trying to write a Ruby program that asks the user for the cost of a meal and then what percentage they would like to tip and then does the calculation and prints out the result. I wrote the following:</p>
<pre><code>puts "How much did your meal cost?"
cost = gets
puts "How much do you want to tip? (%)"
tip = gets
tip_total = cost * (tip/100.0)
puts "You should tip $" + tip_total
</code></pre>
<p>When I try to run it in Terminal, I get the following error message:</p>
<pre><code>ip_calculator.rb:7:in `<main>': undefined method `/' for "20\n":String (NoMethodError)
</code></pre>
<p>I have no idea what this message means, can someone help me out understanding the error message and/or with what is wrong with my code? Thank you.</p>
| <pre><code>ip_calculator.rb:7:in `<main>': undefined method `/' for "20\n":String (NoMethodError)
</code></pre>
<blockquote>
<p>I have no idea what this message means</p>
</blockquote>
<p>Let's break it down:</p>
<ul>
<li><code>ip_calculator.rb</code> the file the error occured in</li>
<li><code>7</code> the line number (that's probably <code>tip_total = cost * (tip/100.0)</code>)</li>
<li><code><main></code> the class (<code>main</code> is Ruby's top-level class)</li>
<li><code>"undefined method `/' for "20\n":String"</code> error message</li>
<li><code>NoMethodError</code> exception class (<a href="http://ruby-doc.org/core/NoMethodError.html" rel="nofollow">http://ruby-doc.org/core/NoMethodError.html</a>)</li>
</ul>
<blockquote>
<p>can someone help me out understanding the error message</p>
</blockquote>
<p>The error message <code>"undefined method `/' for "20\n":String"</code> means, that you are attempting to call the method <code>/</code> on the object <code>"20\n"</code> which is a <code>String</code> and that this object doesn't implement such method:</p>
<pre><code>"20\n" / 100
#=> NoMethodError: undefined method `/' for "20\n":String
</code></pre>
<blockquote>
<p>what is wrong with my code?</p>
</blockquote>
<p><a href="http://ruby-doc.org/core-2.3.1/Kernel.html#method-i-gets" rel="nofollow"><code>Kernel#gets</code></a> returns a string. <code>gets</code> doesn't attempt to interpret your input, it just passes the received characters. If you type <kbd>2</kbd><kbd>0</kbd><kbd>return</kbd> in your terminal, then <code>gets</code> returns a string containing the corresponding characters <code>"2"</code>, <code>"0"</code>, and <code>"\n"</code>.</p>
<p>To convert the values, I'd use the built-in conversion methods <a href="http://ruby-doc.org/core-2.3.1/Kernel.html#method-i-Integer" rel="nofollow"><code>Kernel#Integer</code></a> or <a href="http://ruby-doc.org/core-2.3.1/Kernel.html#method-i-Float" rel="nofollow"><code>Kernel#Float</code></a>:</p>
<pre><code>cost = Float(gets)
</code></pre>
<p>Unlike <code>to_i</code> and <code>to_f</code>, these methods will raise an error if you enter a non-numeric value.</p>
|
Perl Syntax help <p>I am new in perl and Can anyone explain me below command to understand what is purpose of using $t[1]-- and timelocal(1,1,1,reverse @t).</p>
<p>Below command used to convert timestamp into epoch format. but please explain me use of this command $t[1]-- and timelocal(1,1,1,reverse @t).</p>
<pre><code>perl -MTime::Local=timelocal -e '@t = split(/[-\/]/, $ARGV[0]); $t[1]--; print timelocal(1,1,1,reverse @t);' $date
</code></pre>
| <p>An example is in order:</p>
<pre><code>perl -MTime::Local=timelocal -e '
@t = split(/[-\/]/, $ARGV[0]);
$t[1]--;
print timelocal(1,1,1,reverse @t);
' "2016-10-18"
</code></pre>
<p>Will print out an epoch date (seconds since Jan 1, 1970)</p>
<pre><code>1476766861
</code></pre>
<p>Having a look at the documentation: <a href="http://perldoc.perl.org/Time/Local.html" rel="nofollow">perldoc Time::Local</a> we see that:</p>
<blockquote>
<p>It is worth drawing particular attention to the expected ranges for the values provided. The value for the day of the month is the actual day (ie 1..31),
while the month is the number of months since January (0..11). This is
consistent with the values returned from localtime() and gmtime().</p>
</blockquote>
<p>The first statement splits the string <code>2016-10-18</code> by dashes and slashes into the array <code>@t = (2016, 10, 18)</code>. Perl arrays are 0-based by default, so <code>$t[1]</code> means the second item, i.e. the month, here set to <code>10</code>. Since <code>localtime</code> takes months in the range <code>(0-11)</code> we need to subtract <code>1</code>, setting <code>$t[1]</code> to <code>9</code>. The last statement just converts the date parts back into epoch time, reversing <code>@t</code> to match the order of arguments to timelocal:</p>
<pre><code> # timelocal( $sec, $min, $hour, $mday, $mon, $year )
$time = timelocal( 1, 1, 1, 18, 9, 2016 ); # time in seconds = 1476766861
</code></pre>
|
Make chrome put table header at the top of each page for long printed table <p>I have a really long table that when printed, spans several pages.</p>
<p>Currently, when printing the table, the header row only appears at the very top of the table and not at the top of each page.</p>
<p>How can I make the browser (specifically chrome) print a "sticky" table header at the top of every printed page?</p>
<p>My html:</p>
<pre><code><table>
<!--header-->
<tr>
<td>Col 1</td>
<td>Col 2</td>
<td>Col 3</td>
<td>Col 4</td>
</tr>
<!--body-->
<tr>
<td>Row 1</td>
<td>Row 1</td>
<td>Row 1</td>
<td>Row 1</td>
</tr>
<tr>
<td>Row 2</td>
<td>Row 2</td>
<td>Row 2</td>
<td>Row 2</td>
</tr>
. . . . . .
<tr>
<td>Row nth</td>
<td>Row nth</td>
<td>Row nth</td>
<td>Row nth</td>
</tr>
</table>
</code></pre>
| <p>Use <code><thead></code> tag. This is used to group header content in an HTML table.
When printing a large table that spans multiple pages, these elements can enable the table header and footer to be printed at the top and bottom of each page.</p>
<p>Try this,</p>
<pre><code><table>
<!--header-->
<thead>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
<th>Col 4</th>
</tr>
</thead>
<tbody>
<tr>
. .
</tr>
</tbody>
. . .
</table>
</code></pre>
|
tester program for my subclass java <p>Output: Write algorithms and programs to create a BetterRectangle sub-class - refer to E9.10 on page 459 in the text. Provide a BetterRectangle sub-class that extends the Rectangle class of the standard Java library by adding methods to compute the area and perimeter of the rectangle, as well as a valid constructor for the sub-class. Provide a tester program that will execute and validate the new methods of the extended class. All output should be handled by the tester class, not the super or sub-class.</p>
<p>Input: As required to execute the tester class. All input should be handled by the tester class, not the super or sub-class.</p>
<p>Requirements: Use only material covered in the first nine chapters. Style requirements as discussed in class expected. Class design guidelines as discussed in class and described in chapter 8 expected. Import libraries as required.</p>
<p>You must write at least two programs: one would be the sub-class extension of the java.awt.Rectangle class; and one tester class that will perform the actions required to execute and validate all the added or overridden methods of the extended sub-class. Do not add any instance variables to the sub-class. In the sub-class constructor, use the setLocation() and setSize() methods of the Rectangle class. Include an override for the toString() and equals() methods, if appropriate.</p>
<pre><code>import java.awt.Rectangle;
public class BetterRectangle extends Rectangle
{
public BetterRectangle(int i, int j, int Width, int height
{
super.setLocation(i, j);
super.setSize(width, height);
}
public double calculatePerimeter() {
return super.getHeight() * 2 + super.getWidth() * 2;
}
public double calculateArea() {
return super.getHeight() * super.getWidth(); }}
this is what i have so far but im confused about tester classes, im supposed to write 2 programs? i have the sub class extention of the java awt.rectangle but im unsure how to do a tester class that performs the actions required to execute and validate all the added or overridden methods of the extended sub-class.
</code></pre>
<p>please help</p>
| <p>A Tester Class is really just there to let you test your code. The most straightforward way is to define another class, where in the main method, you run a few cases to make sure your newly-added methods are correct. For example:</p>
<pre><code>public class BetterRectangleTester {
public static void main(String[] args){
BetterRectangle r1 = new BetterRectangle(0, 0, 1, 2);
if (r1.calculatePerimeter != 6){
System.out.println("calculatePerimeter is wrong!");
}
else{
System.out.println("calculatePerimeter is working fine.");
}
}
}
</code></pre>
<p>The above is a pretty shoddy Tester Class, and ideally you should be using a unit-testing framework such as JUnit. Generally, it's important to test for "edge cases", as well as all the functions (I didn't do one for calculateArea, for example).</p>
|
How to get the total internal storage of device <p>I am trying to get the total internal storage of the device like user storage with device storage. i am able to get the internal device storage using this code.</p>
<pre><code>final File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long bytesAvailable = (long)stat.getBlockSize() * (long)stat.getBlockCount();
long megAvailable = bytesAvailable / 1048576;
</code></pre>
<p>but the problem is that in my device i have 16GB internal memory and the result i am getting is 11GB. its not showing the System memory(where OS stored).</p>
| <pre><code> public static String getAvailableInternalMemorySize() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return bytesToHuman(availableBlocks * blockSize);
}
</code></pre>
<p>bytesToHuman can be read from <a href="http://stackoverflow.com/a/22967188/2772552">this</a></p>
<pre><code> public static String floatForm (double d)
{
return new DecimalFormat("#.##").format(d);
}
public static String bytesToHuman(long size)
{
long Kb = 1 * 1024;
long Mb = Kb * 1024;
long Gb = Mb * 1024;
long Tb = Gb * 1024;
long Pb = Tb * 1024;
long Eb = Pb * 1024;
if (size < Kb) return floatForm( size ) + " byte";
if (size >= Kb && size < Mb) return floatForm((double)size / Kb) + " KB";
if (size >= Mb && size < Gb) return floatForm((double)size / Mb) + " MB";
if (size >= Gb && size < Tb) return floatForm((double)size / Gb) + " GB";
if (size >= Tb && size < Pb) return floatForm((double)size / Tb) + " TB";
if (size >= Pb && size < Eb) return floatForm((double)size / Pb) + " PB";
if (size >= Eb) return floatForm((double)size / Eb) + " EB";
return "???";
}
</code></pre>
|
Replace values in factor based on frequency of levels <p>Here is a data frame:</p>
<pre><code>vegetables <- c("carrots", "carrots", "carrots", "carrots", "carrots")
animals <- c("cats", "dogs", "dogs", "fish", "cats")
df <- data.frame(vegetables, animals)
</code></pre>
<p>Looks like:</p>
<pre><code>> df
vegetables animals
1 carrots cats
2 carrots dogs
3 carrots dogs
4 carrots fish
5 carrots cats
</code></pre>
<p>If I wanted to remove rows where the levels frequency was below e.g. 2 (so fish in the example df) then remove that row:</p>
<pre><code>for ( i in names(df) ) {
df <- subset(df, with(df, df[,i] %in% names(which(table(df[,i]) >= 2))))
}
> df
vegetables animals
1 carrots cats
2 carrots dogs
3 carrots dogs
5 carrots cats
</code></pre>
<p>But what if I don't want to remove the observation but instead replace fish with "bla".</p>
<p>How would I do that?</p>
<p>Desired output:</p>
<pre><code>> df
vegetables animals
1 carrots cats
2 carrots dogs
3 carrots dogs
4 carrots bla
5 carrots cats
</code></pre>
| <p>Not sure if the levels of variable are important, if not, you could do the following with <code>stringsAsFactors=FALSE</code>
as option in <code>data.frame</code></p>
<pre><code>vegetables <- c("carrots", "carrots", "carrots", "carrots", "carrots")
animals <- c("cats", "dogs", "dogs", "fish", "cats")
DF <- data.frame(vegetables, animals,stringsAsFactors=FALSE)
threshold = 2
DF$animals[ DF$animals == names(which(table(DF$animals) < threshold)) ] = "foo"
DF
# vegetables animals
#1 carrots cats
#2 carrots dogs
#3 carrots dogs
#4 carrots foo
#5 carrots cats
</code></pre>
|
Backbone view - Cross component communication <pre><code>var BaseView = Backbone.View.extends({
});
var ComponentView = BaseView.extends({
});
var ChildView1 = ComponentView.extends({
});
var ChileView2 = ComponentView.extends({
});
</code></pre>
<p>I want to a have cross component communication between <code>ChildView1</code> and <code>ChileView2.</code></p>
<p>I would like to have <code>a _.extend({}, Backbone.Events)</code> obj in the <code>parent(ComponentView)</code>.</p>
<p>I saw in some of the examples something like below</p>
<pre><code>var ComponentView = BaseView.extends(_.extend({}, Backbone.Events, {
});
</code></pre>
<p>PS: i am initializing all the components from another BackboneView using an attribute present on the components </p>
| <p>In Backbone, I prefer using some sort of publish/subscribe event pattern to communicate between views. In it's most simplest form, your code will look something like the following:</p>
<pre><code>/* Create an Event Aggregator for our Pub/Sub */
var eventAggregator = _.extend({}, Backbone.Events);
/* Pass that Event Aggregator to our Child Views */
var childView1 = new ChildView1({ "eventAggregator": eventAggregator });
/* From here we can just bind/trigger off of eventAggregator whenever we need */
eventAggregator.bind("tellChild", function(e) { alert(e.message); });
eventAggregator.trigger("tellChild", { "message": "hello" });
</code></pre>
<p>Notice how we are creating a new object that extends off of the built in <code>Backbone.Events</code> and passing it into the <code>ChildView1</code>. Inside of the ChildView or anywhere else that has a reference to eventAggregator you can bind/trigger new events. However, this is the tip of the iceberg as you will need to handle no longer needing to know about this event handler, unbinding the event handler and ensuring you're not leaking memory.</p>
<p>There isn't enough space here to go deep into this, so I would recommend reading more about event aggregation in Backbone. All of my logic that I have ever used is derived from the work that Derick Bailey wrote in <a href="https://lostechies.com/derickbailey/2012/04/03/revisiting-the-backbone-event-aggregator-lessons-learned/" rel="nofollow">blog posts</a> and his book "<a href="https://leanpub.com/building-backbone-plugins" rel="nofollow">Building Backbone Plugins</a>" (both excellence sources of information). These came ultimately from his work in creating <a href="http://marionettejs.com" rel="nofollow">Marionette</a>, which is a nice compliment to Backbone. If you don't want to have to worry about these issues or just want a simpler API, I recommend using <a href="http://marionettejs.com" rel="nofollow">Marionette</a> or something equivalent to improve your Backbone Views.</p>
|
HttpClient handshake stuck forever <pre><code>public HttpResponseBean get(String url, Map<String, String> headers) throws Exception {
logger.debug("Sending get request...");
HttpClient httpClient = null;
try {
int timeout = 30 * 1000; // 30 seconds
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout).build();
httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig).build();
HttpGet httpGetRequest = new HttpGet(url);
if (headers != null) {
for (Entry<String, String> entry: headers.entrySet()) {
httpGetRequest.addHeader(new BasicHeader(entry.getKey(), entry.getValue()));
}
}
HttpResponse response = httpClient.execute(httpGetRequest);
HttpResponseBean hrb = new HttpResponseBean(response);
logger.debug("Get response: Response: " + hrb.toString());
return hrb;
} finally {
closeConnection(httpClient);
}
}
</code></pre>
<p>This works well most of the time...but once in a while it gets stuck on handshake and will take forever until the server(tomcat) is restarted.
As per this link looks like a bug -> <a href="http://stackoverflow.com/questions/21611528/apache-httpclient-4-3-not-timing-out">apache httpclient 4.3 not timing out</a> </p>
<p>Is there a way out of this? I am using httpclient 4.4.1</p>
| <blockquote>
<p>Is there a way out of this? I am using httpclient 4.4.1</p>
</blockquote>
<p>Here's the <a href="https://issues.apache.org/jira/browse/HTTPCLIENT-1478" rel="nofollow">associated bug on the Apache site</a>. It looks like people have had problems with the 4.4.1 version:</p>
<blockquote>
<p>I had this issue with version 4.4.1. At first I ignored this thread because it was flagged as resolved in 4.3.</p>
</blockquote>
<p>But this seemed to have been resolved in the <strong>4.5.1 version</strong>. I'd encourage you to upgrade if possible.</p>
<blockquote>
<p>I encountered this issue on version 4.3.4. I upgraded to 4.5.1 and the issue was fixed there.</p>
</blockquote>
<p>Here's additional information:</p>
<blockquote>
<p>In version 4.3.4, http:// worked fine and timed out after 1 second. With https, the request hangs beyond 1 seconds and hangs until the [...] server closes the TCP connection.</p>
<p>In version 4.5.1, the [correct] http behaviour was identical, and on https I got the following exception: [...] <code>org.apache.http.conn.ConnectTimeoutException: Connect to localhost:6171 [localhost/127.0.0.1] failed: Read timed out</code></p>
</blockquote>
<p>Hope this helps.</p>
|
Stop Laravel from loading new URL and let angular handle it <p>So, I have a single page angular app that is opened when I navigate to a URL. If I use the links, moving around within the app is fine - new URLs load just fine. However, if I enter a new URL in the browser URL window and hit enter, the back end framework - Laravel in my case - tries to resolve the URL.</p>
<p>How do I either </p>
<ol>
<li><p>Intercept the URL change so that I can simple direct it to the appropriate state in the app</p></li>
<li><p>Tell Laravel to ignore the new URL and let the angular app handle it</p></li>
</ol>
<p>Thanks</p>
| <p>If I understand your question correctly, you don't want Laravel handles it because the routes is defined in javascript, not in server side. If that's the case, you can simply solve it by using wildcard.</p>
<p>Let's say in your laravel's routes you have this line to load your app, views, javascripts etc:</p>
<pre><code>Route::get('/', 'PagesController@index');
</code></pre>
<p>You can use the wildcard modifier to ignore whatever url that has appended, and always serve your index view instead:</p>
<pre><code>Route::get('/{any?}', 'PagesController@index')->where('any', '.*');
</code></pre>
<p>I'm not sure why it's not in the latest documentation, but you can find the docs <a href="https://laravel.com/docs/5.2/routing#parameters-regular-expression-constraints" rel="nofollow">at Laravel 5.2 doc regarding regular expression constraints</a></p>
|
Links not working with angular ui-router <p>So I've set up ui-router and I had it working a few minutes ago, sort of, it would display the template with content loaded from another html file, but none of the links would work. Now nothing is working: the template shows up but the content is not pulled in and none of the links work.</p>
<p><strong>Ctrl.js</strong></p>
<pre><code>var site = angular.module('site', ['ui.router']);
site.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('page', {
url: '/page',
templateUrl: 'page.html',
})
.state('about', {
url: '/about',
templateUrl: 'about.html',
});
$urlRouterProvider.otherwise('/page');
})
</code></pre>
<p><strong>Index.html</strong></p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://angular-ui.github.io/ui-router/release/angular-ui-router.js"></script>
<script src="scripts/ctrl.js"></script>
<link rel="stylesheet" href="style/main.css">
</head>
<body ng-app="site">
<nav class="navbar navbar-default navbar-fixed-top" id="navigate">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navSmall">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="navSmall">
<ul class="nav navbar-nav navbar-right">
<li><a href="#/about.html">about</a></li>
</ul>
</div>
</div>
</nav>
<div class="jumbotron text-center container-fluid">
<div ui-view></div>
</div>
<footer class="footer">
<div id="note" class="container">
<div class="row">
<div class="col-sm-8">
-----Footer Content-----
</div>
<div class="col-sm-4">
</div>
</div>
</div>
</footer>
</body>
</html>
</code></pre>
<p><strong>About.html (should be loaded but it's not)</strong></p>
<pre><code> <div ui-view="about">
<div class="container-fluid bg-about">
<div class="container-content">
<div class="row">
</div>
</div>
</div>
</div>
</code></pre>
<p>Wow you all are fast! Thanks for the suggestions. So update: changing it to <code>ahref="#/about"</code> helped in that I can now go to the link but still no content displays. There is a console error: </p>
<pre><code> Error: Access to restricted URI denied
fg/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:103:167
n@https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:98:460
m/g<@https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:95:489
e/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:130:409
uf/this.$get</m.prototype.$eval@https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:145:103
uf/this.$get</m.prototype.$digest@https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:142:165
uf/this.$get</m.prototype.$apply@https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:145:399
Ac/c/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:21:115
h/<.invoke@https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:41:374
Ac/c@https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:21:36
Ac@https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:21:332
fe@https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:20:156
@https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:315:135
g/</j@https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js:2:29566
g/</k<@https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js:2:29882
angular.min.js:117:399
</code></pre>
| <p>You are mistake the state URL</p>
<p>your code <code><li><a href="#/about.html">about</a></li></code></p>
<p>You can access the state by URL from browser, but referencing other section of the app is a <strong>bad practice</strong> though it still works</p>
<p><code><li><a href="#/about">about</a></li></code></p>
<p><strong>Do this</strong></p>
<pre><code><li><a ui-sref="about">about</a></li>
</code></pre>
|
Bower not installing locally but to my appdata folder on Windows <p>I have this bower.json:</p>
<pre><code>{
"name": "project",
"version": "0.1.0",
"private": true,
"dependencies": {
"requirejs": "2.1.17",
}
}
</code></pre>
<p>When running <code>bower install bower.json</code> it installs it somewhere else. How do I get it to install in current folder <code>bower_components</code>?</p>
<p>I tried to install just the one from command line too but it's not installed locally.</p>
<pre><code>bower install requirejs#2.1.17
</code></pre>
| <p>For anyone having the same issue please note that it should always be <code>bower install</code>.</p>
<p>To run the local bower.json add config:</p>
<pre><code>bower install --config.directory=mylocalfolder --config.cwd=drive:/..../folder
</code></pre>
<p>Available configs are described at <a href="https://github.com/bower/spec/blob/master/config.md" rel="nofollow" title="Bower configuration">Bower configuration</a></p>
|
Replace String values with value in Hash Map in Java <p>I have created a hash map that contains my Key Value pairs to utilize in replacing user input with the value corresponding to the respective key.
For exp i have multiple Strings like</p>
<pre><code> String pattern = "a+b";
String pattern = "C__a_plus_b+d"
String pattern = "d+C__a_plus_b+F__c_plus_d"
</code></pre>
<p>and i have hashmap which contains there value like</p>
<pre><code>HashMap<String, String> vals = new HashMap<>();
vals.put("a", "123");
vals.put("b", "13");
vals.put("C__a_plus_b", "123");
vals.put("d", "1623");
vals.put("C__a_plus_b", "5");
vals.put("F__c_plus_d", "15");
</code></pre>
<p>now i want to replace in string with there values from HashMap in my String and i want my output like</p>
<pre><code>String pattern = "a+b";
123+13
String pattern = "C__a_plus_b+d"
123+1623
</code></pre>
| <p>With Java 8 streams it should be something like:</p>
<pre><code>String result = String.join(
"+",
Arrays.asList(pattern.split("\\+"))
.stream()
.map((String s) -> vals.get(s))
.collect(Collectors.toList())
);
</code></pre>
|
ng-view doesn't show in angularjs <p>i want to make route with angularjs. but when i run my app, ng-view doesnt show anything. i'm new in angularjs.</p>
<p>index :</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<title>CRUD</title>
</head>
<body ng-App="myAPP">
<a href='#/'/>List</a>
<a href='#/addData'/>Add Data</a>
<div>
<div ng-view></div>
</div>
<script src="js/angular.js"></script>
<script src="js/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="controller/controller.js"></script>
</body>
</html>
</code></pre>
<p>app.js :</p>
<pre><code>var app=angular.module('myAPP',['ngRoute']);
</code></pre>
<p>route.js :</p>
<pre><code>app.config(['$routeProvider',function($routeProvider){
$routeProvider.when('/',{
templateURL : 'crud/pages/list.html',
controller : 'controller'
})
.when('/addData',{
templateURL : 'crud/pages/coba.html',
controller : 'controller'
})
.otherwise({
redirectTo : '/'
})
}])
</code></pre>
| <p>You have not closed the <code>js/angular-route.js</code> tag</p>
<pre><code> <script src="js/angular.js"></script>
<script src="js/angular-route.js"></script>
<script src="js/app.js"></script>
</code></pre>
<p><strong><a href="https://plnkr.co/edit/yllShhhuH1wimgSCqrF7?p=preview" rel="nofollow">DEMO</a></strong></p>
|
Maintain object visbility on height increase <p>How to fix object visibility on height scroll.</p>
<p>I have the following code below which grows height of the div based on user scroll. When you scroll down the spider image become invisible. </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> $(window).scroll(function() {
var bh = 100;
var height = $(window).scrollTop();
var sch = bh + height;
$('.webscroll').stop().animate({
'height': sch
}, 400)
if (height <= 19) {
$('.webscroll').stop().animate({
'height': 200
}, 600)
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
background-color: #000;
height: 1200px;
}
.bottom_left_spider {
position: absolute;
width: 180px;
height: 200px;
left: 0;
top: 0;
z-index: 998
}
.webscroll {
height: 200px;
width: 1px;
border-right: 2px solid #2e2e2e;
position: absolute;
top: 0;
left: 101px;
z-index: 9999
}
.spidy {
position: absolute;
bottom: -51px;
left: -29px
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="bottom_left_spider">
<img src="https://s17.postimg.org/cc243pkrz/spiderweb.png">
<!-- spider web lines -->
<div class="webscroll">
<!-- spider line vertical -->
<img src="https://s21.postimg.org/tbdww9hzr/spidy.png" class="spidy">
<!-- spider image -->
</div>
</div></code></pre>
</div>
</div>
</p>
<p>A woking jsfiddle sample is here: <a href="https://jsfiddle.net/ppw9z6y2/" rel="nofollow">https://jsfiddle.net/ppw9z6y2/</a></p>
| <p>Try moving the spider outside of its parent div and giving it a fixed position in the bottom corner; it should stay there regardless of scrolling. (You may need to tweak the behavior of the scroll/web line to look right.)</p>
|
Two model Popup in bootstrap webpage <p>enter image description here</p>
<p><a href="https://i.stack.imgur.com/udH0L.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/udH0L.jpg" alt="![SignIn popup"></a></p>
<p><a href="https://i.stack.imgur.com/IrxSa.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/IrxSa.jpg" alt="SignUp popup"></a></p>
<h2>I have used two Popup model when I click on signIn button in my website one signIn Popup model will open... If user is not registered it will ask for Create Account ... I have given one href in signin which will open another popup and close first one... The same thing is with second popup window.When user is in second popup there is another href to signIn...</h2>
<p>Code For SignIn Popup Model Start</p>
<pre><code><div class="modal fade" id="signIn" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="colorStrips">
<div class="col-sm-3 colorStrips1">
</div>
<div class="col-sm-3 colorStrips2">
</div>
<div class="col-sm-3 colorStrips3">
</div>
<div class="col-sm-3 colorStrips4">
</div>
</div>
<div class="modal-body model-padding">
<!-- <div class="col-sm-6"> -->
<div class="form-group form-area">
<input type="email" class= "form-control form-field" id="popupSignInEmail" placeholder="Email Address">
</div>
<div class="form-group form-area">
<input type="password" class= "form-control form-field" id="popupSignInEmail" placeholder="Password">
</div>
<div class="one-block-item form-inline">
<div class="checkbox col-sm-6">
<label>
<input type="checkbox"> Remember me
</label>
</div>
<div class="col-sm-offset-2 col-sm-4">
<a href="#forgotPwd">Forgot Pasword ? </a>
</div>
</div>
<div class="radial-signin">
<center>
<a type="submit" href="#signInData" class="btn btn-signin wow fadeInUp" data-wow-duration="1200ms" data-wow-delay="300ms" data-role="popup-link wow fadeInUp" data-wow-duration="1000ms" data-wow-delay="800ms">SIGN IN</a>
</center>
</div>
<!-- </div> -->
<div class="toggleTosignUp">
<center>
<span class="textofsignin">Are you a new user ? <a onclick="launch_modal('#signUp');" data-toggle="modal" href="#signUp" id="signUpClicked" class="markuptext-S">Create Account</a>
</center>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<hr>
<p>Code for signup popup start</p>
<pre><code><div class="modal fade" id="signUp" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="colorStrips">
<div class="col-sm-3 colorStrips1">
</div>
<div class="col-sm-3 colorStrips2">
</div>
<div class="col-sm-3 colorStrips3">
</div>
<div class="col-sm-3 colorStrips4">
</div>
</div>
<div class="modal-body model-padding">
<!-- <div class="col-sm-6"> -->
<div class="form-group form-area">
<input type="email" class= "form-control form-field" id="popupSignInEmail" placeholder="Email Address">
</div>
<div class="form-group form-area">
<input type="password" class= "form-control form-field" id="popupSignInEmail" placeholder="Password">
</div>
<div class="one-block-item form-inline">
<div class="checkbox col-sm-6">
<label>
<input type="checkbox"> Remember me
</label>
</div>
<div class="col-sm-offset-2 col-sm-4">
<a href="#forgotPwd">Forgot Pasword ? </a>
</div>
</div>
<div class="radial-signin">
<center>
<a type="submit" href="#signInData" class="btn btn-signin wow fadeInUp" data-wow-duration="1200ms" data-wow-delay="300ms" data-role="popup-link wow fadeInUp" data-wow-duration="1000ms" data-wow-delay="800ms">SIGN IN</a>
</center>
</div>
<!-- </div> -->
<div>
<center class="toggleTosignIn">
<span class="textofsignin">Already have an account ?<a onclick="launch_modal('#signIn');" href="javascript:void(null);" class="markuptext-S" id="signInClicked">Sign In</a>
</center>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<hr>
<p>I have tried Following JS :</p>
<pre><code>function launch_modal(id) {
$('.modal').modal('hide');
$('#'+id).modal('show');
$('body').css({"padding-right" : "0 !important"});
}
$('#signIn').on('show.bs.modal', function (e) {
$('body').addClass('test');
});
$('#signUp').on('show.bs.modal', function (e) {
$('body').addClass('test');
});
</code></pre>
<hr>
<p>Now comes to the problem:
When I go to second model first is closed. But When I want to come at First Model i.e. a signIn Popup from Second popup i.e. a signUp Popup It can't do that.. </p>
| <p>remove the # from the selector:</p>
<pre><code>function launch_modal(id) {
$('.modal').not(id).modal('hide');
$(id).modal('show');
}
</code></pre>
|
Android HttpURLConnection, load only first 4066 symbol, and breaks request <p>The problem is that I do not get a full result. And only some part, that is not part of the sales, and the first 4066 characters.The problem is the same, IOException not seem to be caused by</p>
<pre><code>private class GetContent extends AsyncTask<Void, Void, String>{
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";
@Override
protected String doInBackground(Void... params) {
try{
URL url = new URL("http://www.json-generator.com/api/json/get/bSFiRdwiSq?indent=2");
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null){
buffer.append(line);
}
resultJson = buffer.toString();
Log.d("Result:", resultJson);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}`
</code></pre>
<p>Result</p>
<p><code>D/RESULT:: [ { "guid": "fdaefcc1-6469-4e3a-9d03-722f8de768d9", "index": 0, "favoriteFruit": "banana", "latitude": 52.644930000000002, "company": "DECRATEX", "email": "jodiecollier@decratex.com", "picture": "http://placehold.it/32x32", "tags": [ "esse", "tempor", "fugiat", "labore", "eu", "aliquip", "fugiat" ], "registered": "2015-06-07T09:21:48 -06:00", "eyeColor": "blue", "phone": "+1 (870) 541-3015", "address": "503 Rugby Road, Defiance, Alaska, 2923", "friends": [ { "id": 0, "name": "Melton Reese" }, { "id": 1, "name": "Sara Gilbert" }, { "id": 2, "name": "Nicholson Weber" } ], "isActive": false, "about": "Fugiat Lorem mollit in pariatur incididunt est cupidatat veniam sit officia. Dolor dolor velit ex fugiat dolore officia enim quis in pariatur do ea. Ipsum cillum duis aliquip ut occaecat qui sint est aliqua consequat reprehenderit non. Velit pariatur aute voluptate minim in deserunt amet duis laborum laborum amet. Fugiat nostrud culpa ipsum Lorem proident pariatur aliqua fugiat culpa. Et aliquip magna exercitation ipsum aute voluptate. Dolore magna sint duis ipsum eu consectetur.\r\n", "balance": "$3,384.03", "name": "Jodie Collier", "gender": "female", "age": 27, "greeting": "Hello, Jodie Collier! You have 3 unread messages.", "longitude": 173.90763799999999, "_id": "58046a786230071a551569b9" }, { "guid": "badaf4d6-54fa-46e3-8a6d-6b6997483b00", "index": 1, "favoriteFruit": "strawberry", "latitude": 39.709885, "company": "DRAGBOT", "email": "alstonmays@dragbot.com", "picture": "http://placehold.it/32x32", "tags": [ "elit", "ea", "ipsum", "velit", "amet", "laborum", "duis" ], "registered": "2016-06-01T05:06:26 -06:00", "eyeColor": "green", "phone": "+1 (911) 423-3011", "address": "248 Forbell Street, Mathews, Vermont, 4994", "friends": [ { "id": 0, "name": "Liza Day" }, { "id": 1, "name": "Catherine Palmer" }, { "id": 2, "name": "Beryl Conway" } ], "isActive": false, "about": "Proident id fugiat pariatur et incididunt commodo est irure in duis ullamco veniam est magna. Id enim qui commodo exercitation labore adipisicing excepteur adipisicing dolor veniam. Qui quis minim commodo mollit est sit.\r\n", "balance": "$1,375.60", "name": "Alston Mays", "gender": "male", "age": 33, "greeting": "Hello, Alston Mays! You have 10 unread messages.", "longitude": -67.445130000000006, "_id": "58046a78a50c13da27ab0d11" }, { "guid": "e328c11c-f948-42a6-aede-179ec44a7873", "index": 2, "favoriteFruit": "apple", "latitude": 17.807843999999999, "company": "INSOURCE", "email": "cassandramcintyre@insource.com", "picture": "http://placehold.it/32x32", "tags": [ "et", "anim", "dolor", "magna", "quis", "occaecat", "dolor" ], "registered": "2015-09-11T03:36:24 -06:00", "eyeColor": "blue", "phone": "+1 (865) 558-2301", "address": "189 Cranberry Street, Riverton, Arkansas, 5369", "friends": [ { "id": 0, "name": "Whitley Howe" }, { "id": 1, "name": "Roseann Perez" }, { "id": 2, "name": "Sasha Richard" } ], "isActive": false, "about": "Consequat adipisicing ut dolor in. Id enim consectetur qui incididunt non amet laboris. Veniam amet dolore proident est proident dolor sunt nulla est quis veniam commodo anim. Ut exercitation excepteur enim quis et ea veniam non laboris duis. Dolore cillum commodo dolore reprehenderit aliqua labore.\r\n", "balance": "$3,678.92", "name": "Cassandra Mcintyre", "gender": "female", "age": 29, "greeting": "Hello, Cassandra Mcintyre! You have 8 unread messages.", "longitude": 93.</code></p>
| <p>Your read logic should be something like this:</p>
<pre><code>InputStream in = mConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, enconding));
int ch;
StringBuilder sb = new StringBuilder();
while ((ch=reader.read()) > 0) {
sb.append((char)ch);
}
String resultjson= sb.toString().trim();
Log.d("Result:", resultJson);
</code></pre>
|
Upgrade Apache Spark version from 1.6 to 2.0 <p>Currently I have Spark version 1.6.2 installed.</p>
<p>I want to upgrade the Spark version to the newest 2.0.1. How do I do this without losing the existing configurations? </p>
<p>Any help would be appreciated.</p>
| <p>If its maven or sbt application you simply change dependency version of spark and also migrate your code according to 2.0 so you will not lose you configurations. and for spark binary you can take backup of config folder.</p>
|
SQLAlchemy ORM update value by checking if other table value in list <p>I have a Kanji (Japanese characters) list which looks like:</p>
<pre><code>kanji_n3 = ['æ¿', 'è°', 'æ°', 'é£'] # But then with 367 Kanji
</code></pre>
<p>and I have 2 tables: <code>TableKanji</code> and <code>TableMisc</code>. <code>TableMisc</code> has a column called 'jlpt', from which some currently have the value <code>2</code>, but this has to be updated to value <code>3</code>, if the Kanji is in <code>kanji_n3</code>.</p>
<p>tableclass.py</p>
<pre><code>import sqlalchemy as sqla
from sqlalchemy.orm import relationship
import sqlalchemy.ext.declarative as sqld
sqla_base = sqld.declarative_base()
class TableKanji(sqla_base):
__tablename__ = 'Kanji'
id = sqla.Column(sqla.Integer, primary_key=True)
character = sqla.Column(sqla.String, nullable=False)
misc = relationship("TableMisc", back_populates='kanji')
class TableMisc(sqla_base):
__tablename__ = 'Misc'
kanji_id = sqla.Column(sqla.Integer, sqla.ForeignKey('Kanji.id'), primary_key=True)
jlpt = sqla.Column(sqla.Integer)
kanji = relationship("TableKanji", back_populates="misc")
</code></pre>
<p>So the query I came up with is, kanjiorigin_index.py:</p>
<pre><code>import sqlalchemy as sqla
import sqlalchemy.orm as sqlo
from tableclass import TableKanji, TableMisc
kanji_n3 = ['æ¿', 'è°', 'æ°', 'é£'] # But then with 367 Kanji
session.query(TableMisc)\
.filter(TableMisc.jlpt == 2).filter(TableKanji.character in kanji_n3)\
.update({TableMisc.jlpt: TableMisc.jlpt + 1}, synchronize_session='fetch')
</code></pre>
<p>This runs succesfully, but doesn't update anything. The output:</p>
<pre><code>2016-10-18 04:05:53,908 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1
2016-10-18 04:05:53,908 INFO sqlalchemy.engine.base.Engine ()
2016-10-18 04:05:53,908 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1
2016-10-18 04:05:53,909 INFO sqlalchemy.engine.base.Engine ()
2016-10-18 04:05:53,909 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2016-10-18 04:05:53,909 INFO sqlalchemy.engine.base.Engine SELECT "Misc".kanji_id AS "Misc_kanji_id"
FROM "Misc"
WHERE 0 = 1
2016-10-18 04:05:53,909 INFO sqlalchemy.engine.base.Engine ()
2016-10-18 04:05:53,910 INFO sqlalchemy.engine.base.Engine UPDATE "Misc" SET jlpt=("Misc".jlpt + ?) WHERE 0 = 1
2016-10-18 04:05:53,910 INFO sqlalchemy.engine.base.Engine (1,)
2016-10-18 04:05:53,911 INFO sqlalchemy.engine.base.Engine COMMIT
</code></pre>
<h2>Question</h2>
<p>How do I update <code>TableMisc.jlpt</code> where the current value is 2 and where TableKanji.character is in <code>kanji_n3</code>? Does my <code>in kanji_n3</code> statement not work like this? I also tried to add an <code>.outerjoin(TableKanji)</code>, but this results in:</p>
<pre><code>sqlalchemy.exc.InvalidRequestError: Can't call Query.update() or Query.delete() when join(), outerjoin(), select_from(), or from_self() has been called
</code></pre>
| <p>Seems like that your intention is to make an update on joined tables. Not all databases support this.</p>
<p>First of all you should use <a href="http://stackoverflow.com/questions/8603088/sqlalchemy-in-clause"><code>in_</code></a> method instead of <code>in</code> operator.</p>
<p>You can make select first and than update all selected records like this:</p>
<pre><code>records = session.query(TableMisc).\
join(TableKanji).\
filter(TableMisc.jlpt == 2).\
filter(TableKanji.character.in_(kanji_n3)).\
all()
for record in records:
record.jlpt += 1
session.commit()
</code></pre>
|
PDO, $_GET, and SELECTing from MySQL Database <p>So I'm working on a PHP Pastebin-esque project on my freetime to learn PHP and server management, and I've run into a LOT of issues, and I haven't been able to solve them. I decided to restart from sratch on my own with the information I've gathered so far, and threw this code together.</p>
<pre><code><?php
require 'connection.php';
$getid = $_GET["id"];
$sql = 'SELECT paste FROM pasteinfo WHERE id=:id';
$stmt = $con->prepare($sql);
$stmt->bind_param(':id', trim($_GET["id"], PDO::PARAM_INT));
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['paste'];
}
?>
</code></pre>
<p>What I'm trying to achieve with this code is a system where a user can type the <strong>id</strong> of whatever paste they're interested in viewing in the url and have it display the pasteinfo row, which is the row that holds the paste itself. The format they should have is viewpaste.php?id=(user input).</p>
<p>How can I fix this code? I would also greatly appreciate if you explain whatever code you might end up putting in the comments so I can learn from it. Thanks!</p>
| <p>Try this;</p>
<p>connection.php</p>
<pre><code>try{
$db = new PDO('mysql:host=localhost;dbname=database_name;charset=utf8mb4', 'database_username', 'database_password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $ex){
echo $ex->getMessage();return false;
}
function retrieve($query,$input) {
global $db;
$stmt = $db->prepare($query);
$stmt->execute($input);
$stmt->setFetchMode(PDO::FETCH_OBJ);
return $stmt;
}
</code></pre>
<p>To retrieve data, call the retrieve() function</p>
<p>Retrieval page, say display.php</p>
<pre><code>require 'connection.php';
$getid = $_GET["id"];
$result=retrieve("SELECT paste FROM pasteinfo WHERE id=?",array($getid));
$row=$result->fetch();
//To get paste column of that id
$paste=$row->paste;
echo $paste;
</code></pre>
|
String and 2 letters <p>Hello I am a student and my question in better detail is this.</p>
<blockquote>
<p>Given a string and two letters (c1 and c2), return a count of the number of times "axb" occurs in the string, where x is any character. For example, given the string "antiaircraft" and the letters 'a' and 't', your method should return 2. The three-letter patterns may overlap. For example, "aaaa" has two occurrences of "axa".</p>
</blockquote>
<p>Now what I have written down so far is </p>
<pre><code>public int countAxA(String str, char c1, char c2) {
int count = 0;
for (int i=0; i < str.length(); i++)
{
if (str.charAt(i) == c2)
{
count++;
}
}
return count;
}
</code></pre>
<p>So according to the my homework some of the inputs work but others do not. Is there anything I am missing?</p>
| <p>Just iterate once and keep track, and if you happen to find the first character then do a lookahead:</p>
<pre><code>public int countAxA(String s, char one, char two) {
char[] cs = s.toCharArray();
int count = 0;
for (int i = 0; i < cs.length - 2; i++) { //don't need to go beyond 3rd last char
if (cs[i] == one && cs[i + 2] == two) {
count++;
}
}
return count;
}
</code></pre>
|
Cannot get Relay to make GraphQL Call over the network <p>I am new to Relay, and I am having problems making it work with a GraphQL server. </p>
<p>I have adapted the <a href="https://facebook.github.io/relay/" rel="nofollow">Tea</a> sample from the relay homepage to the SWAPI relay service. I cloned <a href="https://github.com/graphql/swapi-graphql" rel="nofollow">swapi-graphql</a>, and added cors to the express server. I tested the link with this code:</p>
<pre><code>var query = `
{
allFilms {
edges {
node {
id
}
}
}
}
`
fetch("http://localhost:50515/graphiql?query=" + query)
.then(response=>response.json())
.then(json=>console.log(json))
</code></pre>
<p>I got a response from the server, I saw some network action, it worked! I can communicate with the graphiql service.</p>
<p>Next, I created a query that was structured similar to the TeaStoreQuery. I <a href="https://graphql-swapi.parseapp.com/?query=query%20AllFilmQuery%20%7B%0A%20%20allFilms%20%7B%0A%20%20%20%20...filmListFragment%0A%20%20%7D%0A%7D%0A%0Afragment%20filmListFragment%20on%20FilmsConnection%20%7B%0A%20%20edges%20%7B%0A%20%20%20%20node%20%7B%0A%20%20%20%20%20%20...filmFragment%0A%20%20%20%20%7D%0A%20%20%7D%0A%7D%0A%0Afragment%20filmFragment%20on%20Film%20%7B%0A%20%20id%0A%20%20title%0A%20%20releaseDate%0A%7D&operationName=AllFilmQuery" rel="nofollow">tested</a> it, and it returned the expected results.</p>
<pre><code>query AllFilmQuery {
allFilms {
...filmListFragment
}
}
fragment filmListFragment on FilmsConnection {
edges {
node {
...filmFragment
}
}
}
fragment filmFragment on Film {
id
title
releaseDate
}
</code></pre>
<p><strong>HOW DO YOU MAKE THIS WORK WITH RELAY??</strong></p>
<p>I cannot figure out how to use Relay to query the server. Here is the code that I adapted from the Tea sample.</p>
<pre><code>import { render } from 'react-dom'
import {
RootContainer,
createContainer,
Route,
injectNetworkLayer
} from 'react-relay'
// React component for each star wars film
const Film = ({ id, title, releaseDate }) =>
<li key={id}>
{title} (<em>{releaseDate}</em>)
</li>
// Relay container for each film
const FilmContainer = createContainer(Film, {
fragments: {
film: () => Relay.QL`
fragment on Film {
id,
title,
releaseDate
}
`
}
})
// React component for listing films
const FilmList = ({ films=[] }) =>
<ul>
{films.map(
film => <Film {...film} />
)}
</ul>
// Relay container for Listing all Films
const FilmListContainer = createContainer(FilmList, {
fragments: {
films: () => Relay.QL`
fragment on FilmsConnection {
edges {
node {
${ Film.getFragment('film') }
}
}
}
`
}
})
// The Home Route
class FilmHomeRoute extends Route {
static routeName = 'Home'
static queries = {
allFilms: (Component) => Relay.QL`
query AllFilmQuery {
allFilms {
${Component.getFragment('allFilms')}
}
}
`
}
}
// Is this how you setup a network layer
// I am using CORS, and I testing the graphql service with fetch
// The graphql service works but Relay never seems to try to connect
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer('http://localhost:50515/graphiql')
)
render(
<RootContainer
Component={FilmListContainer}
route={new FilmHomeRoute()}
/>,
document.getElementById('react-container')
)
</code></pre>
<p>When I run this sample (<a href="http://output.jsbin.com/kayofi/edit" rel="nofollow">source</a> | <a href="http://output.jsbin.com/kayofi/quiet" rel="nofollow">output</a>) I do not see any attempts at making network requests. I do see an error "Cannot render map of null". It seems like it cannot map the allfilms data.</p>
<p>What am I doing wrong?</p>
| <p>According to section 5.1 of <a href="https://facebook.github.io/relay/graphql/objectidentification.htm#sec-Fields" rel="nofollow">this document</a>, the "Relay Object Identification Specification":</p>
<blockquote>
<p>Relayâcompliant servers may expose root fields that are not plural identifying root fields; the Relay client will just be unable to use those fields as root fields in its queries.</p>
</blockquote>
<p>Based on this specification, Relay can not query plural fields at the root of a query unless the field takes a list of arguments that exactly maps to the results. That means the <code>allFilms</code> field cannot be used with Relay. You can read more about the limitations in this other StackOverflow answer: <a href="http://stackoverflow.com/questions/32491117/how-to-get-relayjs-to-understand-that-a-response-from-graphql-is-an-array-of-ite">How to get RelayJS to understand that a response from GraphQL is an array of items, not just a single item</a></p>
<p>If you would like to have a GraphQL schema with root fields that return arrays, you might want to use a different GraphQL client, since Relay is particularly restrictive in what kinds of schemas it works with. graphql.org has a list: <a href="http://graphql.org/code/#graphql-clients" rel="nofollow">http://graphql.org/code/#graphql-clients</a></p>
|
Integrate Magento API V2 to ASP.NET <p>I want to Integrate Magento API V2 which is installed in my localhost and call the V2 API in ASP.NET Visual Studio 2015</p>
| <p>To Integrate Magento API V2 in ASP.NET you can use Web Service with SOAP protocol. SOAP is a W3C submitted note (as of May 2000) that uses standards based technologies (XML for data description and HTTP for transport) to encode and transmit application data.</p>
<p><a href="https://msdn.microsoft.com/en-us/library/ms972326.aspx/%22Web%20Services%20with%20ASP.NET%22" rel="nofollow">Web Services with ASP.NET</a></p>
<p><a href="http://www.tejaprakash.com/2014/08/magento-api-soap-call-in-c-integration.html" rel="nofollow">Magento API SOAP call in C#</a></p>
<p><a href="http://doghouse.agency/article/consume-magento-web-services-net" rel="nofollow">Consume Magento Web Services with .NET</a></p>
|
How to turn EditText to editable text-file like NotePad <p><strong>Hi</strong></p>
<p>My problem is, that when I have a blank screen with <code>ScrollView</code> and <code>EditText</code>.
I wanted my app to allow user to write what ever and where ever he/she wants, <strong>BUT</strong> when I ran the app, you were only allowed to type in the middle. (I stretched the EditText to cover the whole screen)</p>
<p>Here is my screen:</p>
<p><a href="https://i.stack.imgur.com/wkzLW.png" rel="nofollow"><img src="https://i.stack.imgur.com/wkzLW.png" alt="enter image description here"></a></p>
<p>Here is the screen I should/need to have:</p>
<p><a href="https://i.stack.imgur.com/v9RSa.png" rel="nofollow"><img src="https://i.stack.imgur.com/v9RSa.png" alt="enter image description here"></a></p>
<p>Here is the code:</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="onhar.personalnote.Writing_Table">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="1000dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="1000dp">
</RelativeLayout>
</ScrollView>
</RelativeLayout>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@drawable/plusicon" />
<include layout="@layout/content_writing__table" />
</android.support.design.widget.CoordinatorLayout>
</code></pre>
<p><strong><em>Is this possible?</em></strong></p>
| <p>In your XML you need <code>android:gravity="top|start"</code> on your EditText.</p>
<p>If you want to do it in Java code then it's: <code>myEditText.setGravity(Gravity.TOP | Gravity.START);</code></p>
|
String replace method issue in java <p>My problem is to replace only the last occurrence of a character in the string with another character. When I used the String.replace(char1, char2), it replaces all the occurrences of the character in the string.</p>
<p>For example, I have an address string like </p>
<p><code>String str = "Addressline1,Addressline2,City,State,Country,";</code>. </p>
<p>I need to replace the occurrence of ',' at the end of the string with '.'.</p>
<p>My code to replace the character is</p>
<pre><code>str = str.replace(str.charAt(str.lastIndexOf(",")),'.');
</code></pre>
<p>After replacing, the string looks like:</p>
<p><strong>Addressline1.Addressline2.City.State.Country.</strong></p>
<p>Is there the problem in Java SDK?. If yes, how to resolve it?</p>
| <p>You should use <code>String.replaceAll</code> which use regex</p>
<pre><code>str = str.replaceAll (",$", ".");
</code></pre>
<p>The <code>$</code> mean the end of the String</p>
|
Cannot read property 'emit' of undefined error using React/Socket.IO <p>I'm trying to build a basic chat app using React and Socket.Io based on the React tutorial <a href="https://facebook.github.io/react/docs/tutorial.html" rel="nofollow">https://facebook.github.io/react/docs/tutorial.html</a> but keep getting an error "Cannot read property 'emit' of undefined". It's probably something trivial that I overlooked but I can't figure it out.</p>
<p>The function that triggers the error is: </p>
<pre><code> handleSubmit: function (e) {
e.preventDefault();
var author = this.state.author.trim();
var text = this.state.text.trim();
if (!text || !author) {
return;
}
this.props.onCommentSubmit({ author: author, text: text });
this.setState({ author: '', text: '' });
this.socket.emit('message', comment);
},
</code></pre>
<p>The full code is </p>
<pre><code>import React, { Component, PropTypes } from 'react';
import ReactDom from 'react-dom';
import io from 'socket.io-client'
/********************************************************************************************************/
var CommentBox = React.createClass({
getInitialState: function () {
return { data: [] };
},
handleCommentSubmit: function (comment) {
this.setState({ data: [comment, ...this.state.data] });
},
componentDidMount: function (data) {
this.socket = io.connect();
this.socket.on('message', function (comment) {
this.setState({ data: [comment, ...this.state.data] });
});
},
render: function () {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
</div>
);
}
});
/********************************************************************************************************/
var CommentList = React.createClass({
render: function () {
var commentNodes = this.props.data.map(function (comment) {
return (
<Comment author={comment.author} key={comment.id}>{comment.text}</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
});
/********************************************************************************************************/
var CommentForm = React.createClass({
getInitialState: function () {
return { author: '', text: '' };
},
handleAuthorChange: function (e) {
this.setState({ author: e.target.value });
},
handleTextChange: function (e) {
this.setState({ text: e.target.value });
},
handleSubmit: function (e) {
e.preventDefault();
var author = this.state.author.trim();
var text = this.state.text.trim();
if (!text || !author) {
return;
}
this.props.onCommentSubmit({ author: author, text: text });
this.setState({ author: '', text: '' });
this.socket.emit('message', comment);
},
render: function () {
return (
<div>
<form className='commentForm' onSubmit={this.handleSubmit}>
<input type='text' placeholder='Name' value={this.state.author} onChange={this.handleAuthorChange} />
<input type='text' placeholder='Enter Message' value={this.state.text} onChange={this.handleTextChange} />
<input type='submit' value='Post' />
</form>
</div>
);
}
});
/********************************************************************************************************/
var Comment = React.createClass({
render: function () {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{this.props.children}
</div>
);
}
});
/********************************************************************************************************/
ReactDom.render(
<CommentBox />,
document.getElementById('container')
);
</code></pre>
| <p>The call to <code>this.socket.emit('message', comment)</code> is at the wrong place neither this.socket nor comment is defined in your <code>CommentForm</code> Component.</p>
<p>You have to call <code>this.socket.emit('message', comment)</code> in the <code>handleCommentSubmit</code> Method in the <code>CommentBox</code> Component. (Line 14 in the second code example)</p>
|
Sed command keeps on throwing error "Unrecognized Command" <p>I'm having trouble on executing sed command. I would like to know first if sed command is really working on ksh script. I'm using putty as my tool to execute ksh script. </p>
<p>If it really works, my command that I am using is <code>sed -e [^a-zA-Z0-9] <file></code>.</p>
<p>I actually do this command for grep, <code>grep [^a-zA-Z0-9] <file></code>.</p>
<p>My goal is to get all special characters in my text file and return it to a variable or another file. I'm searching for this one for this site and all other site but I never found any that really works for me. </p>
| <p>Yours is not a valid <code>sed</code> script. The problem is exacerbated by the lack of quoting.</p>
<p>Without quotes, the shell attempts to expand the expression <code>[^a-zA-Z0-9]</code> to a list of matching file names. If you have files named, say, <code>,</code> and <code>?</code> in the current directory, the glob will be expanded to <code>grep , ? <file></code> even before <code>grep</code> runs (depending also on your shell's settings -- with <code>shopt -s nullglob</code> the pattern will disappear if there are no matches, for example).</p>
<p>The syntax of <code>sed</code> is different. To match a regular expression with <code>sed</code>, use</p>
<pre><code>sed '/[^a-zA-Z0-9]/' <file>
</code></pre>
<p>The slash is configurable; for example, if you have a regular expression which contains slashes, you can use a different separator by prefixing it with a backslash:</p>
<pre><code>sed '\#[^a-zA-Z0-9/]#' <file>
</code></pre>
<p>If you want to extract just the <em>characters</em> which match, try <code>grep -o</code> -- and again, take care to quote your variables properly.</p>
<pre><code>chars=$(grep -o '[^a-zA-Z0-9]' <file>)
echo "$chars" # double quotes are *absolutely* *crucial*
</code></pre>
<p>Without the double quotes, again, the shell would attempt to expand any <code>*</code> in <code>chars</code> to a list of files in the current directory.</p>
|
Gridview row doesn't save on Modification <p>I have a <code>gridview</code> in which I insert one row for the first time and save it. Till this it works properly as expected.</p>
<p>But when I see the saved data, and wanted to modify/Add one more data, I get error as</p>
<blockquote>
<p>Column 'EXP_TYPE_ID' does not belong to table .</p>
</blockquote>
<p>I don't know why it is giving me this error, as it saves properly whenever I add fresh record.</p>
<p>Here is my Insert code.</p>
<pre><code> protected void GrdPartyInfo_InsertCommand(object sender, GridRecordEventArgs e)
{
int iRowCount = 0;
if (Session["partyInfo"] != null)
{
dtPartyInfo = (DataTable)Session["partyInfo"];
}
else
{
BindDataTable();
}
iRowCount = dtPartyInfo.Rows.Count;
DataRow newRow = dtPartyInfo.NewRow();
newRow["SR_NO"] = iRowCount + 1;
newRow["EXP_TYPE_ID"] = Convert.ToString(e.Record["EXP_TYPE"]);
newRow["EXP_TYPE"] = CF.ExecuteScaler2("Select Type_desc from type_mst where Type_Code = 'PAR' and Type_Abbr ='" + Convert.ToString(e.Record["EXP_TYPE"]) + "'").ToString();
newRow["TITLE"] = Convert.ToString(e.Record["TITLE"]);
newRow["F_NAME"] = Convert.ToString(e.Record["F_NAME"]);
newRow["M_NAME"] = Convert.ToString(e.Record["M_NAME"]);
newRow["L_NAME"] = Convert.ToString(e.Record["L_NAME"]);
newRow["GENDER"] = Convert.ToString(e.Record["GENDER"]);
newRow["EMAIL_ID"] = Convert.ToString(e.Record["EMAIL_ID"]);
newRow["MOB_NUM"] = Convert.ToString(e.Record["MOB_NUM"]);
newRow["PAN_NO"] = Convert.ToString(e.Record["PAN_NO"]);
newRow["ADHAAR_NO"] = Convert.ToString(e.Record["ADHAAR_NO"]);
newRow["ADDRESS"] = Convert.ToString(e.Record["ADDRESS"]);
dtPartyInfo.Rows.Add(newRow);
GrdPartyInfo.DataSource = dtPartyInfo;
GrdPartyInfo.DataBind();
AddToViewState("GrdPartyInfo");
}
</code></pre>
<p>and Aspx of gridview</p>
<pre><code><cc1:Grid ID="GrdPartyInfo" AllowDataAccessOnServer="true" runat="server" CallbackMode="true"
Serialize="true" FolderStyle="../Styles/Grid/style_12" AllowAddingRecords="true"
AutoGenerateColumns="false" Width="100%" ShowFooter="true" ShowHeader="true"
OnInsertCommand="GrdPartyInfo_InsertCommand" OnRebind="GrdPartyInfo_Rebind" OnRowDataBound="GrdPartyInfo_RowDataBound"
OnUpdateCommand="GrdPartyInfo_UpdateCommand">
<ClientSideEvents OnClientEdit="GrdPartyInfo_OnClientEdit" OnClientDblClick="GrdPartyInfo_OnClientDblClick" />
<TemplateSettings RowEditTemplateId="tplRowEdit" />
<Columns>
<cc1:Column ID="Column1" DataField="MKEY" ReadOnly="true" Width="0%" runat="server"
Visible="false">
<TemplateSettings TemplateId="gtchkConfirm" HeaderTemplateId="HTConfirm" />
</cc1:Column>
<cc1:Column ID="Column2" DataField="SR_NO" HeaderText="Sr No" Visible="true" Width="5%">
<TemplateSettings TemplateId="tplNumbering1" />
</cc1:Column>
<cc1:Column ID="Column41" DataField="EXP_TYPE_ID" HeaderText="Expense Type" Visible="false"
Width="10%">
</cc1:Column>
<cc1:Column ID="Column3" DataField="EXP_TYPE" HeaderText="Expense Type" Visible="true"
Width="10%">
<TemplateSettings RowEditTemplateControlId="cmbExpType" RowEditTemplateControlPropertyName="value" />
</cc1:Column>
<cc1:Column ID="Column4" DataField="TITLE" HeaderText="Title" Visible="true" Width="6%">
<TemplateSettings RowEditTemplateControlId="cmbTitle" RowEditTemplateControlPropertyName="value" />
</cc1:Column>
<cc1:Column ID="Column5" DataField="F_NAME" HeaderText="First Name" Visible="true"
Width="8%">
<TemplateSettings RowEditTemplateControlId="txtFname" RowEditTemplateControlPropertyName="value" />
</cc1:Column>
<cc1:Column ID="Column6" DataField="M_NAME" HeaderText="Middle Name" Visible="true"
Width="9%">
<TemplateSettings RowEditTemplateControlId="txtMname" RowEditTemplateControlPropertyName="value" />
</cc1:Column>
<cc1:Column ID="Column7" DataField="L_NAME" HeaderText="Last Name" Visible="true"
Width="8%">
<TemplateSettings RowEditTemplateControlId="txtLName" RowEditTemplateControlPropertyName="value" />
</cc1:Column>
<cc1:Column ID="Column8" DataField="GENDER" HeaderText="Gender" Visible="true" Width="7%">
<TemplateSettings RowEditTemplateControlId="cmbGender" RowEditTemplateControlPropertyName="value" />
</cc1:Column>
<cc1:Column ID="Column22" DataField="EMAIL_ID" HeaderText="Email Id" Visible="true"
Width="10%">
<TemplateSettings RowEditTemplateControlId="txtEmailid" RowEditTemplateControlPropertyName="value" />
</cc1:Column>
<cc1:Column ID="Column23" DataField="MOB_NUM" HeaderText="Mob No" Visible="true"
Width="8%">
<TemplateSettings RowEditTemplateControlId="txtMobNo" RowEditTemplateControlPropertyName="value" />
</cc1:Column>
<cc1:Column ID="Column33" DataField="PAN_NO" HeaderText="Pan No" Visible="true" Width="8%">
<TemplateSettings RowEditTemplateControlId="txtPanno" RowEditTemplateControlPropertyName="value" />
</cc1:Column>
<cc1:Column ID="Column34" DataField="ADHAAR_NO" HeaderText="Adhaar No" Visible="true"
Width="9%">
<TemplateSettings RowEditTemplateControlId="txtAdhaar" RowEditTemplateControlPropertyName="value" />
</cc1:Column>
<cc1:Column ID="Column35" DataField="ADDRESS" HeaderText="Address" Visible="true"
Width="12%">
<TemplateSettings RowEditTemplateControlId="txtAddress" RowEditTemplateControlPropertyName="value" />
</cc1:Column>
<cc1:Column ID="Column36" DataField="ATTACHMENT" HeaderText="Attachment" Visible="true"
Width="8%">
<TemplateSettings RowEditTemplateControlId="FlAttach" RowEditTemplateControlPropertyName="value" />
</cc1:Column>
</Columns>
<Templates>
<cc1:GridTemplate runat="server" ID="tplRowEdit">
<Template>
<table class="rowEditTable">
<tr>
<td valign="top">
<fieldset style="width: 900px; height: 250px;">
<legend>Party Information</legend>
<table cellpadding="2" cellspacing="2" border="0">
<tr>
<%--<td>
Sr No:
</td>
<td>
<input type="text" id="txtsrno" disabled="disabled" style="width: 150px;" class="ob_gEC" />
</td>--%>
<td>
Type:
</td>
<td>
<asp:DropDownList ID="cmbExpType" runat="server" DataSourceID="sd_Type" DataTextField="TYPE_DESC"
DataValueField="TYPE_ABBR" Width="150px">
<asp:ListItem Value="--Select--">--Select--</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
Title:
</td>
<td>
<asp:DropDownList ID="cmbTitle" runat="server" DataSourceID="sd_Type_Title" DataTextField="TITLE"
DataValueField="TITLE_CODE" Width="150px">
<asp:ListItem Value="--Select--">--Select--</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
First Name:
</td>
<td>
<input type="text" id="txtFname" style="width: 150px; height: 18px; font-size: 11px;"
class="ob_gEC" />
</td>
<td>
Middle Name:
</td>
<td>
<input type="text" id="txtMname" style="width: 150px; height: 18px; font-size: 11px;"
class="ob_gEC" />
</td>
<td>
Last Name:
</td>
<td>
<input type="text" id="txtLName" style="width: 150px; height: 18px; font-size: 11px;"
class="ob_gEC" />
</td>
</tr>
<tr>
<td>
Gender:
</td>
<td>
<select id="cmbGender">
<option value="0" selected="selected">--Select--</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</td>
<td>
Email Id:
</td>
<td>
<input type="text" id="txtEmailid" style="width: 150px; height: 18px; font-size: 11px;"
class="ob_gEC" />
</td>
<td>
Mobile No:
</td>
<td>
<input type="text" id="txtMobNo" style="width: 150px; height: 18px; font-size: 11px;"
class="ob_gEC" />
</td>
</tr>
<tr>
<td>
Pan No:
</td>
<td>
<input type="text" id="txtPanno" style="width: 150px; height: 18px; font-size: 11px;"
class="ob_gEC" />
</td>
<td>
Adhaar No:
</td>
<td>
<input type="text" id="txtAdhaar" style="width: 150px; height: 18px; font-size: 11px;"
class="ob_gEC" />
</td>
</tr>
<tr>
<td>
Address:
</td>
<td>
<%--<input type="text" id="txtAddress" style="width: 150px;" class="ob_gEC" />--%>
<asp:TextBox ID="txtAddress" CssClass="ob_gEC" runat="server" Style="width: 240px;
height: 50px; font-size: 11px;" TextMode="MultiLine"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Attachment:
</td>
<td>
<input type="file" id="FlAttach" style="width: 250px; height: 18px;" class="ob_gEC" />
</td>
</tr>
</table>
</fieldset>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="button" value="Save" onclick="GrdPartyInfo.save()" class="tdText" />
<input type="button" value="Cancel" onclick="GrdPartyInfo.cancel()" class="tdText" />
</td>
</tr>
</table>
</Template>
</cc1:GridTemplate>
</Templates>
<Templates>
<cc1:GridTemplate runat="server" ID="tplNumbering1">
<Template>
<b>
<%# (Container.RecordIndex + 1) %></b>
</Template>
</cc1:GridTemplate>
</Templates>
</cc1:Grid>
</code></pre>
| <p>Here as per discussed in a comments, <code>EXP_TYPE_ID</code> does not in exist as column.</p>
<p>So change it: </p>
<pre><code>newRow["EXP_TYPE_ID"] = Convert.ToString(e.Record["EXP_TYPE"]);
</code></pre>
<p>To </p>
<pre><code>newRow["EXP_TYPE"] = Convert.ToString(e.Record["EXP_TYPE"]);
</code></pre>
|
ERROR 1111 (HY000): Invalid use of group function in MySQL Cluster 7.3 <pre><code>select count(*) from student
group by branch
</code></pre>
<p>This query is perfectly working for me,and i got the output like this. </p>
<pre>
+----------+
| count(*) |
+----------+
| 32 |
| 27 |
| 50 |
| 52 |
| 58 |
| 57 |
| 59 |
+----------+
</pre>
<p>7 rows in set (0.00 sec)
But when i use </p>
<pre><code>select max(count(*)) from student group by branch;
</code></pre>
<p>It result an error </p>
<blockquote>
<p>ERROR 1111 : Invalid use of group function</p>
</blockquote>
<p>Please help me.</p>
<p>I am using MySQL Cluster 7.3</p>
| <p>You can't nest aggregate functions. You need to use a subquery.</p>
<pre><code>SELECT MAX(c)
FROM (SELECT COUNT(*) AS c
FROM student
GROUP BY branch) AS t1
</code></pre>
|
javascript attempting to set element display to none after page load echos 'none' <p>When typing the following into a browser url bar once a page has been displayed, I would expect the referenced element to be hidden. However, what actually happens is the contents of the window is cleared and the word "none" is echoed out to the screen (as if I had issued a document.write command)</p>
<pre><code>javascript: {document.getElementById('footer').style.display="none";}
</code></pre>
<p>This has worked for me in the past. What am I doing wrong?</p>
| <p>Which browser and version are you use?</p>
<p>According to Mozilla, the function you mentioned is disabled on Firefox version 40 and later.</p>
<p><a href="https://developer.mozilla.org/en/docs/Tools/Browser_Console" rel="nofollow">Browser Console - Firefox Developer Tools | MDN</a></p>
<blockquote>
<p>NB: The Browser Console command line (to execute JavaScript expressions) is disabled by default. To enable it set the devtools.chrome.enabled preference to true in about:config, or set the "Enable browser chrome and add-on debugging toolboxes" (Firefox 40 and later) option in the developer tool settings.</p>
</blockquote>
<p>If you want to enable it, you must change the setting. This link page might be helpful for you.</p>
<p><a href="https://developer.mozilla.org/en/docs/Tools/Settings" rel="nofollow">Settings - Firefox Developer Tools | MDN</a></p>
<ol>
<li>Open the development tools setting</li>
<li>Look up the advanced setting</li>
<li>Tick on the <code>Enable browser chrome and add-on debugging toolboxes</code></li>
</ol>
|
Flickering effect when hovering title. Title over opacity background <p>Having this html:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Image hover</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<style>
.gecoitems {list-style-type: none !important;margin:0 auto !important;width:1200px;}
.gecoitems .gecoitem {margin-bottom:20px;display:block;}
.gecoitems .column {float:left;}
.gecoitems {width:1200px;}
.gecoitems .gecoitem.normal {width:1200px;height:252px;background:#006505;color:#fff;}
/* links */
.gecoitems .gecoitem:hover {opacity:1;}
.image-listitem-wrapper {position:relative;}
.image-listitem-wrapper .title {position:absolute;top:40%;left:0;opacity:1.0;color:#ffffff;text-transform: uppercase;width:100%;text-align:center;font-size:35px;line-height:normal;}
.image-listitem-wrapper .title.hover {display:none;color:#000000;top:35%;}
.image-listitem-wrapper .title.hover .services {text-transform: lowercase;display:block;}
.gecoitems .gecoitem.wrapper-title.hover:hover {opacity:0.4;}
.gecoitems .gecoitem.wrapper-title.hover:hover + .title.hover {display:block;}
.slow-fade {
opacity: 0.8;
-webkit-transition: opacity .25s ease-in-out;
-moz-transition: opacity .25s ease-in-out;
-o-transition: opacity .25s ease-in-out;
transition: opacity .25s ease-in-out;
}
</style>
</head>
<body>
<ul class="gecoitems">
<li>
<div class="image-listitem-wrapper default-image">
<a href="#" class="wrapper-title hover slow-fade gecoitem normal"></a>
<span class="title hover">TITLE<span class="services">Subtitle</span></span>
</div>
</li>
</ul>
</body>
</html>
</code></pre>
<p>I get almost what I want. When I hover the area I get opacity 0.4 background with a title above, but when I hover the title/subtitle I get a "flickering effect".I dont want this "flickering effect". How do I get rid of that? (I'm quite sure it's this:</p>
<p><code>.gecoitems .gecoitem.wrapper-title.hover:hover + .title.hover {display:block;}</code> that's the issue but how do I solve this? I don't want anything top happen when I hover the title (just want the opacity 0.4 to "stay there")</p>
<p>A jsFiddle to explain further: <a href="https://jsfiddle.net/1rLzeht9/" rel="nofollow">https://jsfiddle.net/1rLzeht9/</a></p>
<p>If you want to downvote question, it's ok, but please tell why! :-)</p>
| <p>You can try the following snippet, I changed some of the <code>display:block</code> to <code>opacity:1</code>, and added a z-index property to the <code>.title</code></p>
<p>Also I moved your css, got rid of the body, meta etc tags for the purpose of this snippet</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.gecoitems {
list-style-type: none !important;
margin: 0 auto !important;
width: 1200px;
}
.gecoitems .gecoitem {
margin-bottom: 20px;
display: block;
}
.gecoitems .column {
float: left;
}
.gecoitems {
width: 1200px;
}
.gecoitems .gecoitem.normal {
width: 1200px;
height: 252px;
background: #006505;
color: #fff;
}
/* links */
.gecoitems .gecoitem:hover {
opacity: 1;
}
.image-listitem-wrapper {
position: relative;
}
.image-listitem-wrapper .title {
position: absolute;
top: 40%;
left: 0;
opacity: 1.0;
color: #ffffff;
text-transform: uppercase;
width: 100%;
text-align: center;
font-size: 35px;
line-height: normal;
z-index:-1;
}
.image-listitem-wrapper .title.hover {
opacity: 0;
color: #000000;
top: 35%;
}
.image-listitem-wrapper .title.hover .services {
text-transform: lowercase;
display: block;
}
.gecoitems .gecoitem.wrapper-title.hover:hover {
opacity: 0.4;
}
.gecoitems .gecoitem.wrapper-title.hover:hover + .title.hover {
opacity: 1;
}
.title:hover {
opacity: 1 !important;
}
.slow-fade {
opacity: 0.8;
-webkit-transition: opacity .25s ease-in-out;
-moz-transition: opacity .25s ease-in-out;
-o-transition: opacity .25s ease-in-out;
transition: opacity .25s ease-in-out;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<ul class="gecoitems">
<li>
<div class="image-listitem-wrapper default-image">
<a href="#" class="wrapper-title hover slow-fade gecoitem normal"></a>
<span class="title hover">TITLE<span class="services">Subtitle</span></span>
</div>
</li>
</ul>
</body></code></pre>
</div>
</div>
</p>
<p>You may also add <a href="https://css-tricks.com/almanac/properties/p/pointer-events/" rel="nofollow"><code>pointer-events:none</code></a> to the <code>.title</code> element, see <a href="https://jsfiddle.net/1rLzeht9/1/" rel="nofollow">This Fiddle</a>. This removes the title being the target of mouse events</p>
|
gzip decompression issue on OSX with TIdHTTP and TIdCompressorZLib <p>I'm trying to fetch a page with gzip compression enabled, using <code>TIdHTTP</code> and <code>TIdCompressorZLib</code>.
On Windows, the code works fine and the data is decompressed. But the exact same code on OSX is returning garbage data that looks like its still compressed. I can't really see where it's going wrong?</p>
<p>This is the code I'm testing with:</p>
<pre><code>with TIdHTTP.Create(nil) do begin
HandleRedirects := true;
Compressor := TIdCompressorZLib.Create(nil);
Request.AcceptEncoding := 'gzip, deflate';
Data := Get('http://google.com.au');
Compressor.Free;
Free;
WriteLn(Data);
end;
</code></pre>
<p><code>Data</code> looks like the original compressed garbage on OSX, while it is plain decompressed HTML on Windows.</p>
<p>I'm using Delphi 10.1 Berlin Update 1 and OSX 10.11.</p>
| <p>You are <em>manually</em> setting the <code>TIdHTTP.Request.AcceptEncoding</code> property to tell the webserver that it is OK to send a compressed response <strong>even if <code>TIdCompressorZLib</code> is not actually ready to handle it</strong>. In your case, the <code>TIdCompressorZLib.IsReady</code> property is likely reporting False on OSX, but True on Windows.</p>
<p>In January 2016, Indy was updated to dynamically load the ZLib library on-demand the first time ZLib is used (SVN rev 5330). That change broke <code>TIdCompressorZLib</code>, which was later fixed in February 2016 (SVN rev 5343). I do not know if that fix is in Berlin or not. Try installing the latest SVN rev and see if the problem continues (<a href="http://www.indyproject.org/Sockets/Docs/Indy10Installation.aspx" rel="nofollow">instructions</a> and <a href="http://www.indyproject.org/Sockets/Download/DevSnapshot.aspx" rel="nofollow">download</a>).</p>
<p>When using the <code>TIdHTTP.Compressor</code> property, <strong>DO NOT</strong> set the <code>Request.AcceptEncoding</code> property manually at all:</p>
<pre><code>with TIdHTTP.Create(nil) do begin
HandleRedirects := true;
Compressor := TIdCompressorZLib.Create(nil);
// Request.AcceptEncoding := 'gzip, deflate'; // <-- here
Data := Get('http://google.com.au');
Compressor.Free;
Free;
WriteLn(Data);
end;
</code></pre>
<p>Leave <code>Request.AcceptEncoding</code> blank, and let <code>TIdHTTP</code> update it internally if the assigned <code>Compressor</code> is actually ready to handle compressed responses.</p>
<hr>
<p>BTW, you are leaking the <code>TIdHTTP</code> and <code>TIdCompressorZLib</code> objects if <code>TIdHTTP.Get()</code> raises an exception on failure. You should be using <code>try/finally</code> blocks:</p>
<pre><code>with TIdHTTP.Create(nil) do
try
HandleRedirects := true;
Compressor := TIdCompressorZLib.Create(nil);
try
// Request.AcceptEncoding := 'gzip, deflate';
Data := Get('http://google.com.au');
finally
Compressor.Free;
end;
finally
Free;
end;
WriteLn(Data);
</code></pre>
|
Android app . fetching data from database <p>I am a new Android app developer and need some help. I want to develop a simple login app just for understanding the working.
Using sqlite we can create tables and insert records in our application , but how to keep the table centralised for username and password so that all the users can access the same table from the app for login instead of creating the database on your device.
Please help with some tips or any links which will help me clearify my doubts.
Thanks in advance.</p>
| <p>Are you aware of the backend and frontend? sqlitedatabase doesnot stores the universal data which is available for all the users. the database you are talking about needs to be stored in the server side or what people also say backend. that is the "centralised part" you are talking about. read about frontend and backend, and then about http requests. </p>
|
Osmdroid maps not loading on my device <p>I have an Alcatel One Touch 7040, when i test my sample of osmdroid on it, the maps don't render. I have tested on other devices, the maps are rendering in them properly, only on this device they are not. I thought my device memory was low so I deleted some apps from my device, still nothing improved, can someone please tell me what could be the reason?</p>
<p>Following is my logcat(some parts of it has been removed because word limit exceeded) :</p>
<pre><code>10-17 23:03:27.688 26424-26424/marine.com.osmsample I/OsmDroid: Using tile source: Mapnik
10-17 23:03:27.702 26424-26424/marine.com.osmsample E/OsmDroid: unable to create a nomedia file. downloaded tiles may be visible to the gallery. open failed: ENOENT (No such file or directory)
10-17 23:03:27.715 26424-26424/marine.com.osmsample E/SQLiteLog: (14) cannot open file at line 30202 of [00bb9c9ce4]
10-17 23:03:27.715 26424-26424/marine.com.osmsample E/SQLiteLog: (14) os_unix.c:30202: (2) open(/storage/sdcard0/osmdroid/tiles/cache.db) -
10-17 23:03:27.729 26424-26424/marine.com.osmsample E/SQLiteDatabase: Failed to open database '/storage/sdcard0/osmdroid/tiles/cache.db'.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:709)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:702)
at org.osmdroid.tileprovider.modules.SqlTileWriter.<init>(SqlTileWriter.java:44)
at org.osmdroid.tileprovider.MapTileProviderBasic.<init>(MapTileProviderBasic.java:76)
at org.osmdroid.tileprovider.MapTileProviderBasic.<init>(MapTileProviderBasic.java:50)
at org.osmdroid.views.MapView.<init>(MapView.java:170)
at org.osmdroid.views.MapView.<init>(MapView.java:200)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at android.view.LayoutInflater.createView(LayoutInflater.java:587)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:285)
at android.app.Activity.setContentView(Activity.java:1882)
at marine.com.osmsample.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:5121)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1146)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2446)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5434)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:834)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
10-17 23:03:27.731 26424-26424/marine.com.osmsample E/OsmDroid: Unable to start the sqlite tile writer. Check external storage availability.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:709)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:702)
at org.osmdroid.tileprovider.modules.SqlTileWriter.<init>(SqlTileWriter.java:44)
at org.osmdroid.tileprovider.MapTileProviderBasic.<init>(MapTileProviderBasic.java:76)
at org.osmdroid.tileprovider.MapTileProviderBasic.<init>(MapTileProviderBasic.java:50)
at org.osmdroid.views.MapView.<init>(MapView.java:170)
at org.osmdroid.views.MapView.<init>(MapView.java:200)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at android.view.LayoutInflater.createView(LayoutInflater.java:587)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:285)
at android.app.Activity.setContentView(Activity.java:1882)
at marine.com.osmsample.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:5121)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1146)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2446)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5434)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:834)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
10-17 23:03:27.732 26424-26424/marine.com.osmsample D/dalvikvm: create interp thread : stack size=128KB
10-17 23:03:27.732 26424-26424/marine.com.osmsample D/dalvikvm: create new thread
10-17 23:03:27.732 26424-26424/marine.com.osmsample D/dalvikvm: new thread created
10-17 23:03:27.732 26424-26424/marine.com.osmsample D/dalvikvm: update thread list
10-17 23:03:27.732 26424-26944/marine.com.osmsample D/dalvikvm: threadid=17: interp stack at 0x5f42b000
10-17 23:03:27.732 26424-26944/marine.com.osmsample D/dalvikvm: threadid=17: created from interp
10-17 23:03:27.732 26424-26424/marine.com.osmsample D/dalvikvm: start new thread
10-17 23:03:27.733 26424-26944/marine.com.osmsample D/dalvikvm: threadid=17: notify debugger
10-17 23:03:27.733 26424-26944/marine.com.osmsample D/dalvikvm: threadid=17 (Thread-2646): calling run()
10-17 23:03:27.733 26424-26944/marine.com.osmsample D/dalvikvm: threadid=17: exiting
10-17 23:03:27.733 26424-26944/marine.com.osmsample D/dalvikvm: threadid=17: bye!
10-17 23:03:27.739 26424-26424/marine.com.osmsample I/OsmDroid: sdcard state: mounted
10-17 23:03:27.745 26424-26424/marine.com.osmsample I/OsmDroid: sdcard state: mounted
10-17 23:03:27.746 26424-26424/marine.com.osmsample E/SQLiteLog: (14) cannot open file at line 30202 of [00bb9c9ce4]
10-17 23:03:27.746 26424-26424/marine.com.osmsample E/SQLiteLog: (14) os_unix.c:30202: (2) open(/storage/sdcard0/osmdroid/tiles/cache.db) -
10-17 23:03:27.749 26424-26424/marine.com.osmsample E/SQLiteDatabase: Failed to open database '/storage/sdcard0/osmdroid/tiles/cache.db'.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:709)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:702)
at org.osmdroid.tileprovider.modules.SqlTileWriter.<init>(SqlTileWriter.java:44)
at org.osmdroid.tileprovider.modules.MapTileSqlCacheProvider.<init>(MapTileSqlCacheProvider.java:57)
at org.osmdroid.tileprovider.modules.MapTileSqlCacheProvider.<init>(MapTileSqlCacheProvider.java:63)
at org.osmdroid.tileprovider.MapTileProviderBasic.<init>(MapTileProviderBasic.java:88)
at org.osmdroid.tileprovider.MapTileProviderBasic.<init>(MapTileProviderBasic.java:50)
at org.osmdroid.views.MapView.<init>(MapView.java:170)
at org.osmdroid.views.MapView.<init>(MapView.java:200)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at android.view.LayoutInflater.createView(LayoutInflater.java:587)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:285)
at android.app.Activity.setContentView(Activity.java:1882)
at marine.com.osmsample.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:5121)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1146)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2446)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5434)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:834)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
10-17 23:03:27.753 26424-26424/marine.com.osmsample E/OsmDroid: Unable to start the sqlite tile writer. Check external storage availability.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:709)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:702)
at org.osmdroid.tileprovider.modules.SqlTileWriter.<init>(SqlTileWriter.java:44)
at org.osmdroid.tileprovider.modules.MapTileSqlCacheProvider.<init>(MapTileSqlCacheProvider.java:57)
at org.osmdroid.tileprovider.modules.MapTileSqlCacheProvider.<init>(MapTileSqlCacheProvider.java:63)
at org.osmdroid.tileprovider.MapTileProviderBasic.<init>(MapTileProviderBasic.java:88)
at org.osmdroid.tileprovider.MapTileProviderBasic.<init>(MapTileProviderBasic.java:50)
at org.osmdroid.views.MapView.<init>(MapView.java:170)
at org.osmdroid.views.MapView.<init>(MapView.java:200)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at android.view.LayoutInflater.createView(LayoutInflater.java:587)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:285)
at android.app.Activity.setContentView(Activity.java:1882)
at marine.com.osmsample.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:5121)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1146)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2446)
at android.app.ActivityThread.access$600(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5434)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:834)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
10-17 23:03:39.774 26424-27015/marine.com.osmsample D/OsmDroid: Unable to store cached tile from Mapnik /14/9291/6359, database not available.
10-17 23:03:39.792 26424-27015/marine.com.osmsample I/System.out: [CDS]rx timeout:0
10-17 23:03:39.819 26424-27003/marine.com.osmsample D/OsmDroid: Unable to store cached tile from Mapnik /14/9292/6359, database not available.
10-17 23:03:39.823 26424-27003/marine.com.osmsample I/System.out: [CDS]rx timeout:0
10-17 23:03:39.846 26424-27015/marine.com.osmsample D/OsmDroid: Unable to store cached tile from Mapnik /14/9290/6359, database not available.
10-17 23:03:39.852 26424-27015/marine.com.osmsample I/System.out: [CDS]rx timeout:0
</code></pre>
| <p>What API level is the device? It could be a permissions issues. Sometimes android also mounts <code>Environment.getExternalStorageDir()</code> as read only, which is wrong. One of these days I'm going to fix this with a work around.</p>
<p>Does the example application provided by osmdroid work? Not only do you have to start it, you have to zoom in a bit. The sample app comes with a few cached tiles.</p>
<p>Looking at the stack trace, <code>Environment.getExternalStorageDir()</code> is returning a read only mount point. So the only reasonable solution would be to tell osmdroid to use a different location for the cache on that type of device. It can be done easily but it must be BEFORE the mapview is created. This link has the API calls to make with osmdroid</p>
<p><a href="http://stackoverflow.com/questions/39019687/using-osmdroid-without-getting-access-to-external-storage/39028053#39028053">Using osmdroid without getting access to external storage</a></p>
<p>This answer <a href="http://stackoverflow.com/a/15612964/1203182">http://stackoverflow.com/a/15612964/1203182</a> has some great code to return a list of mount points/paths that are writable. It might be a good idea to prompt the user to ask where to store the cache</p>
|
AWS : Play Custom Sound When Push Messages are received <p>I have implemented Amazon Web Service(AWS) for notification messages in my app, I am able to send message from Amazon SNS Server successfully.</p>
<p>Now i want to implement <strong>default/custom</strong> sound, when any messages are received from AWS.</p>
<p>In Amazon SNS Server there are two options fro sending pus messages, those are Raw and JSON. I am using Raw Message Format.</p>
<pre><code>{
"aps":{
"badge":0,
"alert":"APNS test",
"sound":"default"
},
}
</code></pre>
<p>by above format i m getting same format as push notification in my app.</p>
<p><strong>If i use JSON Message Format</strong></p>
<p>I m getting in Amazon SNS Page that - </p>
<blockquote>
<p>Invalid parameter: Message Structure - JSON message body failed to
parse (Service: AmazonSNS; Status Code: 400; Error Code:
InvalidParameter; Request ID: b34a</p>
</blockquote>
<p>Any One could tell tell how to send sound default/custom by using AWS Notification.</p>
| <p>Try as bellow</p>
<p>Please make sure to change the JSON according to your need</p>
<pre><code>{
"aps" : {
"category" : "NEW_MESSAGE_CATEGORY"
"alert" : {
"body" : "Acme message received from Johnny Appleseed",
"action-loc-key" : "VIEW"
},
"badge" : 3,
"sound" : "chime.aiff"
},
"acme-account" : "jane.appleseed@apple.com",
"acme-message" : "message123456"
}
</code></pre>
|
Bash function comment extraction from sourced file <p>I have a bash script with functions I have sourced from a random file, that I no longer retain the original path.</p>
<pre><code>#!/bin/bash
my_awesome_function()
{
#- Usage: my_awesome_function <key> <to> <success>
echo "I'm doing something great."
}
declare -x -f my_awesome_function
</code></pre>
<p>I have previously ran:</p>
<pre><code>$ source ./some_random_file_i_dont_know_where_it_is
</code></pre>
<p>And followed up with (in the same shell):</p>
<pre><code>$ type my_awesome_function
my_awesome_function is a function
my_awesome_function ()
{
echo "I'm doing something great."
}
</code></pre>
<p>I'm asking because I would like to include automated usage for this function. In the ideal case:</p>
<pre><code> exceptional_help()
{
echo ; type $1 | grep "#-" | tr -d "#-"
}
</code></pre>
<p>Which could be used like follows:</p>
<pre><code> $ exceptional_help "my_awesome_function"
Usage: my_awesome_function <key> <to> <success>
</code></pre>
<p>I have tried <code>type</code> and <code>declare</code> and <code>which</code> and a few other builtins, but nothing seems to retain the original formatting including comments, or a reference to the original function that I could then parse again.</p>
| <p>Try:</p>
<pre><code>my_awesome_function() {
[ "$1" = "--help" ] && {
echo 'Usage: my_awesome_function <key> <to> <success>'
return
}
echo "I'm doing something great."
}
</code></pre>
<p>Example:</p>
<pre class="lang-none prettyprint-override"><code>$ my_awesome_function
I'm doing something great.
$ my_awesome_function --help
Usage: my_awesome_function <key> <to> <success>
</code></pre>
|
Inapp purchases disappear on android ionic app <p>I'm trying to implement inapp purchases with the plugin <code>cordova-plugin-inapppurchase</code> The products load, but after the products are loaded the products doesn't show. </p>
<p>What's my mistake?</p>
<p>This is my code: </p>
<pre><code><h3 class="inapp_textw" ng-click="loadProducts()" ng-if="!products">Or Inappp purchases</h3>
<h3 class="inapp_textw" ng-repeat="product in products" ng-click="buy(product.productId)">Or Inappp purchases</h3>
</code></pre>
<p>JS</p>
<pre><code>var productIds = ["com.domain.example"]; //I have the correct ID
var spinner = '<ion-spinner icon="dots" class="spinner-stable"></ion-spinner><br/>';
$scope.loadProducts = function() {
console.log("loaded inapp products"); // This logs
$ionicLoading.show({
template: spinner + 'Loading...'
});
inAppPurchase
.getProducts(productIds)
.then(function(products) {
$ionicLoading.hide();
$scope.products = products;
})
.catch(function(err) {
$ionicLoading.hide();
console.log(err);
});
};
$scope.buy = function(productId) {
console.log("buy clicked");
$ionicLoading.show({
template: spinner + 'Acquisto in corso...'
});
inAppPurchase
.buy(productId)
.then(function(data) {
console.log(JSON.stringify(data));
console.log('consuming transactionId: ' + data.transactionId);
return inAppPurchase.consume(data.type, data.receipt, data.signature);
})
.then(function() {
localStorage.setItem('sold', 'true');
$ionicLoading.hide();
if (state == "l2") {
$state.go("12")
}
})
.catch(function(err) {
$ionicLoading.hide();
console.log(err);
});
};
$scope.restore = function() {
console.log("IT WORKS");
$ionicLoading.show({
template: spinner + 'Ripristino degli acquisti in corso...'
});
inAppPurchase
.restorePurchases()
.then(function(purchases) {
$ionicLoading.hide();
console.log(JSON.stringify(purchases));
localStorage.setItem('sold', 'true');
$state.go("12")
})
.catch(function(err) {
$ionicLoading.hide();
console.log(err);
$ionicPopup.alert({
title: 'Something went wrong',
template: 'Check your console log for the error details'
});
});
};
</code></pre>
| <p>You are just loading product that's why its not appearing.</p>
<p>you have to print it to show as below.</p>
<pre><code><h3 class="inapp_textw" ng-repeat="product in products" ng-click="buy(product.productId)">{{product}}</h3>
</code></pre>
|
angular without dependencies is not working <p>I just started angular js and l started with the basic declaration of a module without services and factories. It was working well before adding services and factories. Now after adding services and factories its not working anymore.</p>
<p>The first declaration that is not working anymore:</p>
<pre class="lang-js prettyprint-override"><code>angular.module('root',[])
.controller("index",["$scope",function ($scope){
$scope.message="My name";
$scope.favouriteWord;
$scope.favouriteColor;
$scope.favouriteShape;
$scope.value = 1;
$scope.isBold = function() {
return ($scope.value % 2===0);
}
$scope.isUnderlined = function() {
return ($scope.value % 5===0);
}
$scope.products=[
{id: 1, name:"House Jockey"},
{id: 2, name:"Golf club"},
{id: 3, name:"Baseball Bat"},
{id: 4, name:"Lacrosse stick"}];
$scope.favsha = true;
$scope.factor = 6;
$scope.product = $scope.factor * 2;
}]);
</code></pre>
<p>The factory added:</p>
<pre class="lang-js prettyprint-override"><code>angular.module('root',["services"])
.controller("index",["$scope","square",function ($scope,square){
$scope.product=square;
}]);
</code></pre>
<p>The service added:</p>
<pre class="lang-js prettyprint-override"><code>angular.module('root',["services"])
.controller("index",["$scope","message",function ($scope,message){
$scope.message=message;
}]);
</code></pre>
| <p>You are redeclaring the module 'root' instead of adding a new module 'services', since you´ve again added 'services' to your to the dependencies. You don´t have to redeclare 'root' in the new module, since it should be standalone and portable. Check out the module documentation:
<a href="https://docs.angularjs.org/guide/module" rel="nofollow">https://docs.angularjs.org/guide/module</a></p>
<p>Your 'services' module should be declared like this:</p>
<pre><code>angular.module('services'])
.controller("index",["$scope","message",function ($scope,message){
$scope.message=message;
}]);
</code></pre>
|
Cannot add asset: Process : Task node [2] has no task type <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<!-- origin at X=0.0 Y=0.0 -->
<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:java="http://www.java.com/javaTypes" xmlns:tns="http://www.jboss.org/drools" xmlns="http://www.jboss.org/drools" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd http://www.jboss.org/drools drools.xsd http://www.bpsim.org/schemas/1.0 bpsim.xsd" id="Definition" exporter="org.eclipse.bpmn2.modeler.core" exporterVersion="1.2.5.Final-v20160831-1132-B114" expressionLanguage="http://www.mvel.org/2.0" targetNamespace="http://www.jboss.org/drools" typeLanguage="http://www.java.com/javaTypes">
<bpmn2:itemDefinition id="ItemDefinition_79" isCollection="false" structureRef="java.lang.String"/>
<bpmn2:process id="com.hp.AsyncProcess" tns:packageName="com.hp" name="AsyncProcess" isExecutable="true" processType="Private">
<bpmn2:startEvent id="StartEvent_1" name="StartProcess">
<bpmn2:extensionElements>
<tns:metaData name="elementname">
<tns:metaValue><![CDATA[StartProcess]]></tns:metaValue>
</tns:metaData>
</bpmn2:extensionElements>
<bpmn2:outgoing>SequenceFlow_4</bpmn2:outgoing>
</bpmn2:startEvent>
<bpmn2:task id="Task_1" name="AsyncService">
<bpmn2:extensionElements>
<tns:metaData name="elementname">
<tns:metaValue><![CDATA[AsyncService]]></tns:metaValue>
</tns:metaData>
</bpmn2:extensionElements>
<bpmn2:incoming>SequenceFlow_5</bpmn2:incoming>
<bpmn2:outgoing>SequenceFlow_9</bpmn2:outgoing>
<bpmn2:ioSpecification id="InputOutputSpecification_2">
<bpmn2:dataInput id="DataInput_1" itemSubjectRef="ItemDefinition_79" name="tableName"/>
<bpmn2:inputSet id="InputSet_2" name="Input Set 2">
<bpmn2:dataInputRefs>DataInput_1</bpmn2:dataInputRefs>
</bpmn2:inputSet>
<bpmn2:outputSet id="OutputSet_2" name="Output Set 2"/>
</bpmn2:ioSpecification>
<bpmn2:dataInputAssociation id="DataInputAssociation_1">
<bpmn2:targetRef>DataInput_1</bpmn2:targetRef>
<bpmn2:assignment id="Assignment_2">
<bpmn2:from xsi:type="bpmn2:tFormalExpression" id="FormalExpression_6">userinfo</bpmn2:from>
<bpmn2:to xsi:type="bpmn2:tFormalExpression" id="FormalExpression_4">DataInput_1</bpmn2:to>
</bpmn2:assignment>
</bpmn2:dataInputAssociation>
</bpmn2:task>
<bpmn2:scriptTask id="ScriptTask_1" name="Script Task 1" scriptFormat="http://www.java.com/java">
<bpmn2:extensionElements>
<tns:metaData name="elementname">
<tns:metaValue><![CDATA[Script Task 1]]></tns:metaValue>
</tns:metaData>
</bpmn2:extensionElements>
<bpmn2:incoming>SequenceFlow_6</bpmn2:incoming>
<bpmn2:outgoing>SequenceFlow_7</bpmn2:outgoing>
<bpmn2:script>System.out.println(&quot;Srript task 1&quot;);</bpmn2:script>
</bpmn2:scriptTask>
<bpmn2:scriptTask id="ScriptTask_2" name="Script Task 2" scriptFormat="http://www.java.com/java">
<bpmn2:extensionElements>
<tns:metaData name="elementname">
<tns:metaValue><![CDATA[Script Task 2]]></tns:metaValue>
</tns:metaData>
</bpmn2:extensionElements>
<bpmn2:incoming>SequenceFlow_7</bpmn2:incoming>
<bpmn2:outgoing>SequenceFlow_8</bpmn2:outgoing>
<bpmn2:script>System.out.println(&quot;Srript task 2&quot;);</bpmn2:script>
</bpmn2:scriptTask>
<bpmn2:parallelGateway id="ParallelGateway_1" name="Parallel Gateway 1" gatewayDirection="Diverging">
<bpmn2:incoming>SequenceFlow_4</bpmn2:incoming>
<bpmn2:outgoing>SequenceFlow_5</bpmn2:outgoing>
<bpmn2:outgoing>SequenceFlow_6</bpmn2:outgoing>
</bpmn2:parallelGateway>
<bpmn2:sequenceFlow id="SequenceFlow_4" tns:priority="1" sourceRef="StartEvent_1" targetRef="ParallelGateway_1"/>
<bpmn2:sequenceFlow id="SequenceFlow_5" tns:priority="1" sourceRef="ParallelGateway_1" targetRef="Task_1"/>
<bpmn2:sequenceFlow id="SequenceFlow_6" tns:priority="1" sourceRef="ParallelGateway_1" targetRef="ScriptTask_1"/>
<bpmn2:sequenceFlow id="SequenceFlow_7" tns:priority="1" sourceRef="ScriptTask_1" targetRef="ScriptTask_2"/>
<bpmn2:parallelGateway id="ParallelGateway_2" name="Parallel Gateway 2" gatewayDirection="Converging">
<bpmn2:incoming>SequenceFlow_8</bpmn2:incoming>
<bpmn2:incoming>SequenceFlow_9</bpmn2:incoming>
<bpmn2:outgoing>SequenceFlow_10</bpmn2:outgoing>
</bpmn2:parallelGateway>
<bpmn2:sequenceFlow id="SequenceFlow_8" tns:priority="1" sourceRef="ScriptTask_2" targetRef="ParallelGateway_2"/>
<bpmn2:sequenceFlow id="SequenceFlow_9" tns:priority="1" sourceRef="Task_1" targetRef="ParallelGateway_2"/>
<bpmn2:endEvent id="EndEvent_1" name="End Event 1">
<bpmn2:extensionElements>
<tns:metaData name="elementname">
<tns:metaValue><![CDATA[End Event 1]]></tns:metaValue>
</tns:metaData>
</bpmn2:extensionElements>
<bpmn2:incoming>SequenceFlow_10</bpmn2:incoming>
</bpmn2:endEvent>
<bpmn2:sequenceFlow id="SequenceFlow_10" tns:priority="1" sourceRef="ParallelGateway_2" targetRef="EndEvent_1"/>
</bpmn2:process>
<bpmndi:BPMNDiagram id="BPMNDiagram_1">
<bpmndi:BPMNPlane id="BPMNPlane_Process_1" bpmnElement="com.hp.AsyncProcess">
<bpmndi:BPMNShape id="BPMNShape_StartEvent_1" bpmnElement="StartEvent_1">
<dc:Bounds height="36.0" width="36.0" x="450.0" y="11.0"/>
<bpmndi:BPMNLabel>
<dc:Bounds height="15.0" width="71.0" x="433.0" y="47.0"/>
</bpmndi:BPMNLabel>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="BPMNShape_Task_1" bpmnElement="Task_1">
<dc:Bounds height="50.0" width="110.0" x="324.0" y="231.0"/>
<bpmndi:BPMNLabel>
<dc:Bounds height="15.0" width="72.0" x="343.0" y="248.0"/>
</bpmndi:BPMNLabel>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="BPMNShape_ScriptTask_1" bpmnElement="ScriptTask_1">
<dc:Bounds height="50.0" width="110.0" x="555.0" y="170.0"/>
<bpmndi:BPMNLabel>
<dc:Bounds height="15.0" width="71.0" x="574.0" y="187.0"/>
</bpmndi:BPMNLabel>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="BPMNShape_ScriptTask_2" bpmnElement="ScriptTask_2">
<dc:Bounds height="50.0" width="110.0" x="555.0" y="280.0"/>
<bpmndi:BPMNLabel>
<dc:Bounds height="15.0" width="71.0" x="574.0" y="297.0"/>
</bpmndi:BPMNLabel>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="BPMNShape_ParallelGateway_1" bpmnElement="ParallelGateway_1" isMarkerVisible="true">
<dc:Bounds height="50.0" width="50.0" x="445.0" y="65.0"/>
<bpmndi:BPMNLabel>
<dc:Bounds height="30.0" width="57.0" x="442.0" y="115.0"/>
</bpmndi:BPMNLabel>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="BPMNShape_ParallelGateway_2" bpmnElement="ParallelGateway_2" isMarkerVisible="true">
<dc:Bounds height="50.0" width="50.0" x="475.0" y="365.0"/>
<bpmndi:BPMNLabel>
<dc:Bounds height="30.0" width="57.0" x="472.0" y="415.0"/>
</bpmndi:BPMNLabel>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="BPMNShape_EndEvent_1" bpmnElement="EndEvent_1">
<dc:Bounds height="36.0" width="36.0" x="482.0" y="482.0"/>
<bpmndi:BPMNLabel labelStyle="#//@definitions/@diagrams.0/@labelStyle.0">
<dc:Bounds height="15.0" width="65.0" x="468.0" y="518.0"/>
</bpmndi:BPMNLabel>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_4" bpmnElement="SequenceFlow_4" sourceElement="BPMNShape_StartEvent_1" targetElement="BPMNShape_ParallelGateway_1">
<di:waypoint xsi:type="dc:Point" x="468.0" y="47.0"/>
<di:waypoint xsi:type="dc:Point" x="468.0" y="56.0"/>
<di:waypoint xsi:type="dc:Point" x="470.0" y="56.0"/>
<di:waypoint xsi:type="dc:Point" x="470.0" y="65.0"/>
<bpmndi:BPMNLabel/>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_5" bpmnElement="SequenceFlow_5" sourceElement="BPMNShape_ParallelGateway_1" targetElement="BPMNShape_Task_1">
<di:waypoint xsi:type="dc:Point" x="445.0" y="90.0"/>
<di:waypoint xsi:type="dc:Point" x="379.0" y="90.0"/>
<di:waypoint xsi:type="dc:Point" x="379.0" y="231.0"/>
<bpmndi:BPMNLabel/>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_6" bpmnElement="SequenceFlow_6" sourceElement="BPMNShape_ParallelGateway_1" targetElement="BPMNShape_ScriptTask_1">
<di:waypoint xsi:type="dc:Point" x="495.0" y="90.0"/>
<di:waypoint xsi:type="dc:Point" x="610.0" y="90.0"/>
<di:waypoint xsi:type="dc:Point" x="610.0" y="170.0"/>
<bpmndi:BPMNLabel/>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_7" bpmnElement="SequenceFlow_7" sourceElement="BPMNShape_ScriptTask_1" targetElement="BPMNShape_ScriptTask_2">
<di:waypoint xsi:type="dc:Point" x="610.0" y="220.0"/>
<di:waypoint xsi:type="dc:Point" x="610.0" y="235.0"/>
<di:waypoint xsi:type="dc:Point" x="610.0" y="235.0"/>
<di:waypoint xsi:type="dc:Point" x="610.0" y="280.0"/>
<bpmndi:BPMNLabel/>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_8" bpmnElement="SequenceFlow_8" sourceElement="BPMNShape_ScriptTask_2" targetElement="BPMNShape_ParallelGateway_2">
<di:waypoint xsi:type="dc:Point" x="610.0" y="330.0"/>
<di:waypoint xsi:type="dc:Point" x="610.0" y="390.0"/>
<di:waypoint xsi:type="dc:Point" x="525.0" y="390.0"/>
<bpmndi:BPMNLabel/>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_9" bpmnElement="SequenceFlow_9" sourceElement="BPMNShape_Task_1" targetElement="BPMNShape_ParallelGateway_2">
<di:waypoint xsi:type="dc:Point" x="379.0" y="281.0"/>
<di:waypoint xsi:type="dc:Point" x="379.0" y="390.0"/>
<di:waypoint xsi:type="dc:Point" x="475.0" y="390.0"/>
<bpmndi:BPMNLabel/>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_10" bpmnElement="SequenceFlow_10" sourceElement="BPMNShape_ParallelGateway_2" targetElement="BPMNShape_EndEvent_1">
<di:waypoint xsi:type="dc:Point" x="500.0" y="415.0"/>
<di:waypoint xsi:type="dc:Point" x="500.0" y="448.0"/>
<di:waypoint xsi:type="dc:Point" x="500.0" y="482.0"/>
<bpmndi:BPMNLabel/>
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
<bpmndi:BPMNLabelStyle>
<dc:Font name="arial" size="9.0"/>
</bpmndi:BPMNLabelStyle>
</bpmndi:BPMNDiagram>
</bpmn2:definitions></code></pre>
</div>
</div>
</p>
<p>i am new to jbpm and using jbpm 6.4 version. I tried to execute a asyncronus service task but im getting below error.</p>
<p>i have written junit as well as main class to execute this. both gives the same error. Kindly help.</p>
<p>Thanks in advance. </p>
<pre><code>Oct 17, 2016 4:27:53 PM org.drools.compiler.kie.builder.impl.ClasspathKieProject notifyKieModuleFound
INFO: Found kmodule: file:/C:/Amoolya/workspace/maventest/AsyncProcess/bin/META-INF/kmodule.xml
Oct 17, 2016 4:27:53 PM org.drools.compiler.kie.builder.impl.ClasspathKieProject getPomPropertiesFromFileSystem
WARNING: Unable to find pom.properties in /C:/Amoolya/workspace/maventest/AsyncProcess/bin
Oct 17, 2016 4:27:53 PM org.drools.compiler.kie.builder.impl.ClasspathKieProject generatePomPropertiesFromPom
WARNING: As folder project tried to fall back to pom.xml, but could not find one for null
Oct 17, 2016 4:27:53 PM org.drools.compiler.kie.builder.impl.ClasspathKieProject getPomProperties
WARNING: Unable to load pom.properties from/C:/Amoolya/workspace/maventest/AsyncProcess/bin
Oct 17, 2016 4:27:53 PM org.drools.compiler.kie.builder.impl.ClasspathKieProject fetchKModule
WARNING: Cannot find maven pom properties for this project. Using the container's default ReleaseId
Oct 17, 2016 4:27:53 PM org.drools.compiler.kie.builder.impl.KieRepositoryImpl addKieModule
INFO: KieModule was added: FileKieModule[releaseId=org.default:artifact:1.0.0-SNAPSHOT,file=C:\Amoolya\workspace\maventest\AsyncProcess\bin]
Oct 17, 2016 4:27:53 PM org.drools.compiler.kie.builder.impl.ClasspathKieProject notifyKieModuleFound
INFO: Found kmodule: jar:file:/C:/Amoolya/jbpm-installer/runtime/drools-pmml-6.3.0.Final.jar!/META-INF/kmodule.xml
Oct 17, 2016 4:27:53 PM org.drools.compiler.kie.builder.impl.KieRepositoryImpl addKieModule
INFO: KieModule was added: ZipKieModule[releaseId=org.drools:drools-pmml:6.3.0.Final,file=C:\Amoolya\jbpm-installer\runtime\drools-pmml-6.3.0.Final.jar]
Oct 17, 2016 4:27:54 PM org.drools.compiler.kie.builder.impl.AbstractKieModule buildKnowledgePackages
WARNING: No files found for KieBase kbase, searching folder C:\Amoolya\workspace\maventest\AsyncProcess\bin
0 [main] WARN org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl - HHH000402: Using Hibernate built-in connection pool (not for production use!)
Oct 17, 2016 4:27:57 PM bitronix.tm.BitronixTransactionManager logVersion
INFO: Bitronix Transaction Manager version 2.1.4
Oct 17, 2016 4:27:57 PM bitronix.tm.Configuration buildServerIdArray
WARNING: cannot get this JVM unique ID. Make sure it is configured and you only use ASCII characters. Will use IP address instead (unsafe for production usage!).
Oct 17, 2016 4:27:57 PM bitronix.tm.Configuration buildServerIdArray
INFO: JVM unique ID: <16.169.150.163>
Oct 17, 2016 4:27:58 PM bitronix.tm.journal.DiskJournal open
WARNING: active log file is unclean, did you call BitronixTransactionManager.shutdown() at the end of the last run?
Oct 17, 2016 4:28:00 PM bitronix.tm.recovery.Recoverer run
INFO: recovery committed 0 dangling transaction(s) and rolled back 0 aborted transaction(s) on 1 resource(s) [jdbc/jbpm-ds] (restricted to serverId '16.169.150.163')
Oct 17, 2016 4:28:01 PM org.drools.core.xml.ExtensibleXmlParser error
SEVERE: (null: 123, 82): cvc-datatype-valid.1.2.1: '#//@definitions/@diagrams.0/@labelStyle.0' is not a valid value for 'QName'.
Oct 17, 2016 4:28:01 PM org.drools.core.xml.ExtensibleXmlParser error
SEVERE: (null: 123, 82): cvc-attribute.3: The value '#//@definitions/@diagrams.0/@labelStyle.0' of attribute 'labelStyle' on element 'bpmndi:BPMNLabel' is not valid with respect to its type, 'QName'.
Exception in thread "main" java.lang.IllegalArgumentException: Cannot add asset: Process 'AsyncProcess' [com.hp.AsyncProcess]: Task node 'AsyncService' [2] has no task type.,
at org.jbpm.runtime.manager.impl.SimpleRuntimeEnvironment.addAsset(SimpleRuntimeEnvironment.java:171)
at org.jbpm.runtime.manager.impl.RuntimeEnvironmentBuilder.addAsset(RuntimeEnvironmentBuilder.java:341)
at org.jbpm.runtime.manager.impl.RuntimeEnvironmentBuilder.addAsset(RuntimeEnvironmentBuilder.java:74)
at com.hp.main.ProcessMain.createRuntimeManager(ProcessMain.java:92)
at com.hp.main.ProcessMain.main(ProcessMain.java:38)
</code></pre>
| <p>It seems that you have an invalid process definition. Try to use validation in the Designer to see all the errors you need to fix.</p>
|
Is calling $scope.$digest within $scope.$on fundamentally incorrect? <p>I have inherited some AngularJS code, and I know very little about it (the code and Angular both). The code that I inherited contains several places where <code>$scope.$digest</code> is called within a <code>$scope.$on</code> method within a controller. For example:</p>
<pre><code>$scope.$on("ScriptEditorEnabled", function (e, enabled) {
$scope.scriptEditorDisabled = !enabled;
$scope.$digest();
});
</code></pre>
<p>In my context, this is causing the popular <code>$digest</code> already in progress error (<a href="http://stackoverflow.com/questions/12729122/angularjs-prevent-error-digest-already-in-progress-when-calling-scope-apply">AngularJS : Prevent error $digest already in progress when calling $scope.$apply()</a>). Isn't an <code>$on</code> method part of the <code>$scope</code> object, and thus, any changes to its data would be picked up automatically? If so, doesn't that mean that calling <code>$digest</code> within one (either directly or indirectly), just plain incorrect?</p>
<p>I've been simply removing these calls, seemingly without any loss in functionality, and the errors go away. Is there any dangers I should be aware of when doing this?</p>
| <p><a href="https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$on" rel="nofollow"><code>$scope.$on</code></a> gets called in response to <a href="https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$broadcast" rel="nofollow"><code>$scope.$broadcast</code></a> or <a href="https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$emit" rel="nofollow"><code>$scope.$emit</code></a>. The <code>$scope.$on</code> should always assume that it runs inside a digest loop. Neither <code>$apply</code> nor <code>$digest</code> calls should be needed inside the <code>$on</code> handler.</p>
<p>Angular is pretty clear about it in the <a href="https://github.com/angular/angular.js/wiki/When-to-use-$scope.$apply()" rel="nofollow">When to use $scope.$apply()</a>. If you dispatch events from non-angular environments, you should wrap the <code>$emit</code> or <code>$broadcast</code> call in <code>$apply</code> instead of calling it in the event handler. Example:</p>
<pre><code>$rootScope.$apply($rootScope.$broadcast('recievedMsg', msg));
</code></pre>
<p>It's dispatcher responsibility to enter the digest loop if it knows there isn't one started already.</p>
|
Angular 2: How to use Observable filter <p>I have a service that calls the API like this:</p>
<pre><code>return this._http
.post(appSettings.apiUrl + 'SomeController/SomeAction', params, {withCredentials: true, headers: this.headers})
.timeoutWith(appSettings.maxTimeHttpCalls, Observable.defer(() => Observable.throw(this._feedbackService.timeout())))
.map((response: Response) => response.json().data);
</code></pre>
<p>Now I want to implement a filter function on that call using <code>rxjs/add/operator/filter</code>, but I can't get it to work properly. </p>
<p>This is the approach I have taken:</p>
<pre><code>return this._http
.post(appSettings.apiUrl + 'SomeController/SomeAction', params, {withCredentials: true, headers: this.headers})
.timeoutWith(appSettings.maxTimeHttpCalls, Observable.defer(() => Observable.throw(this._feedbackService.timeout())))
.filter(response => response.json().data.Type === 5)
.map((response: Response) => response.json().data);
</code></pre>
<p>But no matter what I filter on, the <code>ngFor</code> loop produces nothing as long as the filter is in there. If I remove it, everything works as expected. </p>
<p>Am I supposed to add the filter before or after the <code>map</code>?</p>
<p>Can I filter on the response JSON like that, or do I need to use another syntax?</p>
<p><strong>Example JSON</strong></p>
<p>Here's an example of what the response JSON looks like:</p>
<pre><code>data: [
{
"Type": 5,
"Description": "Testing",
"ID": "001525"
}
]
</code></pre>
| <p>Whether <code>filter()</code> should be before or after <code>map()</code> depends on what you want to do.</p>
<p>I guess in your case <code>map()</code> should go before <code>filter()</code> because you want to first decode data from JSON and then filter it. The way you have it now won't return anything if the condition in <code>filter()</code> resolves to <code>false</code> because you're using in on the entire <code>response</code>. Maybe this is what you're going for...</p>
<p>I don't know what your response structure is but I'd go with something like this which makes more sense:</p>
<pre><code>.map((response: Response) => response.json().data)
.filter(data => data.Type === 5)
</code></pre>
<p>Edit:</p>
<p>I'd use <code>concatMap()</code> with <code>Observable.from()</code> to transform the array to an Observable stream:</p>
<pre><code>.map(content => response.json().data)
.concatMap(arr => Observable.from(arr))
.filter(item => item.Type === 5)
.subscribe(val => console.log(val))
</code></pre>
<p>See live demo: <a href="http://plnkr.co/edit/nu7jL7YsExFJMGpL3YuS?p=preview" rel="nofollow">http://plnkr.co/edit/nu7jL7YsExFJMGpL3YuS?p=preview</a></p>
|
How to calculate the timer while items at added runtime in tabcontrol <p>we have test the automation teascase.so i have added tabcotrol and using the button click event to add the 40 tabitem at Runtime.In our requirement how to calculate the timer at while adding the tabitem. </p>
| <p>A simple way to solve it is to compare the time before and after.</p>
<pre><code>DateTime now = DateTime.Now; // When you start.
for (int i = 0; i < 40; i++)
{
// Your logic for adding the tab here...
AddTab();
}
TimeSpan elapsed = DateTime.Now - now; //When you're done.
Console.WriteLine(elapsed.TotalMilliseconds);
</code></pre>
<p><code>elapsed.TotalMilliseconds</code> will be the total number of milliseconds it took to complete the action. Give or take a few milliseconds for handling the time compare.</p>
|
c# Base64 Encoding Decoding wrong result <p>I need to create a hash-signature in c#. </p>
<p>The pseudo-code example that i need to implement in my c# code: </p>
<pre><code>Signatur(Request) = new String(encodeBase64URLCompatible(HMAC-SHA-256(getBytes(Z, "UTF-8"), decodeBase64URLCompatible(getBytes(S, "UTF-8")))), "UTF-8")
</code></pre>
<p>Z: apiSecret
S: stringToSign </p>
<p>The coding for <code>expectedSignatur</code> and <code>apiSecret</code> is <code>Base64 URL Encoding [RFC 4648 Section 5]</code></p>
<p>My problem is that I always get the wrong result.</p>
<pre><code>public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = Convert.FromBase64String(base64EncodedData);
return Encoding.UTF8.GetString(base64EncodedBytes);
}
public static string Base64Encode(string plainText)
{
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
return Convert.ToBase64String(plainTextBytes);
}
private static byte[] HmacSha256(string data, string key)
{
using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
{
return hmac.ComputeHash(Encoding.UTF8.GetBytes(data));
}
}
static void Main(string[] args)
{
var apiSecret = "JrXRHCnUegQJAYSJ5J6OvEuOUOpy2q2-MHPoH_IECRY=";
var stringToSign = "f3fea5f3-60af-496f-ac3e-dbb10924e87a:20160201094942:e81d298b-60dd-4f46-9ec9-1dbc72f5b5df:Qg5f0Q3ly1Cwh5M9zcw57jwHI_HPoKbjdHLurXGpPg0yazdC6OWPpwnYi22bnB6S";
var expectedSignatur = "ps9MooGiTeTXIkPkUWbHG4rlF3wuTJuZ9qcMe-Y41xE=";
apiSecret = apiSecret.Replace('-', '+').Replace('_', '/').PadRight(apiSecret.Length + (4 - apiSecret.Length % 4) % 4, '=');
var secretBase64Decoded = Base64Decode(apiSecret);
var hmac = Convert.ToBase64String(HmacSha256(secretBase64Decoded, stringToSign));
var signatur = hmac.Replace('+', '-').Replace('/', '_');
Console.WriteLine($"signatur: {signatur}");
Console.WriteLine($"expected: {expectedSignatur}");
Console.WriteLine(signatur.Equals(expectedSignatur));
Console.ReadLine();
}
</code></pre>
| <p>You're assuming that your key was originally text encoded with UTF-8 - but it looks like it wasn't. You should keep logically binary data <em>as</em> binary data - you don't need your <code>Base64Encode</code> and <code>Base64Decode</code> methods at all. Instead, your <code>HmacSha256</code> method should take a <code>byte[]</code> as a key, and you can just use <code>Convert.FromBase64String</code> to get at those bytes from the base64-encoded secret:</p>
<pre><code>using System;
using System.Text;
using System.Security.Cryptography;
class Test
{
private static byte[] HmacSha256(byte[] key, string data)
{
using (var hmac = new HMACSHA256(key))
{
return hmac.ComputeHash(Encoding.UTF8.GetBytes(data));
}
}
static void Main(string[] args)
{
var apiSecret = "JrXRHCnUegQJAYSJ5J6OvEuOUOpy2q2-MHPoH_IECRY=";
var stringToSign = "f3fea5f3-60af-496f-ac3e-dbb10924e87a:20160201094942:e81d298b-60dd-4f46-9ec9-1dbc72f5b5df:Qg5f0Q3ly1Cwh5M9zcw57jwHI_HPoKbjdHLurXGpPg0yazdC6OWPpwnYi22bnB6S";
var expectedSignatur = "ps9MooGiTeTXIkPkUWbHG4rlF3wuTJuZ9qcMe-Y41xE=";
apiSecret = apiSecret.Replace('-', '+').Replace('_', '/').PadRight(apiSecret.Length + (4 - apiSecret.Length % 4) % 4, '=');
var secretBase64Decoded = Convert.FromBase64String(apiSecret);
var hmac = Convert.ToBase64String(HmacSha256(secretBase64Decoded, stringToSign));
var signatur = hmac.Replace('+', '-').Replace('/', '_');
Console.WriteLine($"signatur: {signatur}");
Console.WriteLine($"expected: {expectedSignatur}");
Console.WriteLine(signatur.Equals(expectedSignatur));
}
}
</code></pre>
<p>Personally I'd change your <code>HmacSha256</code> method to:</p>
<pre><code>private static byte[] ComputeHmacSha256Hash(byte[] key, byte[] data)
{
using (var hmac = new HMACSHA256(key))
{
return hmac.ComputeHash(data);
}
}
</code></pre>
<p>so that it's more general purpose, maybe adding another method to compute the hash after encoding as UTF-8 for convenience. That way you can sign <em>any</em> data, not just strings.</p>
|
String to template type via Object.factory(...) <p>Can a string be converted to a template parameter, or alternatively, is there an idiomatic D way to achieve the concept of passing deserialized classes as class/function template parameters.</p>
<p>The concept is based on <a href="http://cqrs.nu/tutorial/cs/02-domain-logic" rel="nofollow">DDD, CQRS and Eventsourcing</a>.</p>
<pre><code>import std.stdio;
void main()
{
auto aggregate = new UserAggregate();
auto command = new CreateUser();
// in a command bus, aggregates are loaded based on the aggregate type, then commands and events are applied.
aggregate.handle(command);
// NOTE typecast cannot be used as events will be loaded from an event stream and deserialized - only the
// class name (fully qualified module path) is known at runtime.
auto userCreated = Object.factory("app.UserCreated");
// .... deserialization of event ....
aggregate.apply(userCreated); // <-- compile error - type not specific enough and casting is not possible
}
// interfaces
interface IHandleCommand(TCommand : ICommand)
{
void handle(TCommand command);
}
interface IApplyEvent(TEvent : IEvent)
{
void apply(TEvent event);
}
interface ICommand
{
// ....
}
interface IEvent
{
// ....
}
// Implementation
class UserAggregate :
IHandleCommand!CreateUser,
IHandleCommand!ChangeUserStatus,
IApplyEvent!UserCreated,
IApplyEvent!UserStatusChanged
{
void handle(CreateUser createUser)
{
writeln("createUser...");
}
void handle(ChangeUserStatus changeUserStatus)
{
writeln("changeUserStatus...");
}
void apply(UserCreated userCreated)
{
writeln("userCreated...");
}
void apply(UserStatusChanged userStatusChanged)
{
writeln("userStatusChange...");
}
}
// Commands
class CreateUser : ICommand
{
// ....
}
class ChangeUserStatus : ICommand
{
// ....
}
// Events
class UserCreated : IEvent
{
// ....
}
class UserStatusChanged : IEvent
{
// ....
}
</code></pre>
| <p>You cannot use runtime values as template parameters. But you have options:</p>
<ol>
<li><p>Cast it to IEvent and let the event initiate <code>apply</code> with an overloaded function. (<a href="https://en.wikipedia.org/wiki/Visitor_pattern" rel="nofollow">Visitor pattern</a>)</p>
<pre><code>class UserCreated : IEvent
{
override void apply(Aggregate aggregate){
aggregate.apply(this);
}
}
</code></pre></li>
<li><p>Use runtime type information to dispatch the event accordingly.</p>
<pre><code>void dispatch(Object event){
if(auto casted = cast(UserCreated)event){
apply(casted);
}
// ...
}
</code></pre></li>
</ol>
|
Installer framework on Ubuntu <p>I'm trying to create an installer for a C++ program on Ubuntu. One requisite is that once something is installed if the installer is run again, it will remove the old version and re-install the new one.</p>
<p>I've tried the Qt Installer Framework, which was very easy to set up but does not have this capability:
<a href="https://bugreports.qt.io/browse/QTIFW-573" rel="nofollow">https://bugreports.qt.io/browse/QTIFW-573</a></p>
<p>I've also thought about using Debian packages, but I'd rather keep the software out of the Linux system and be installed to the users home directory (as the Qt Installer framework does). I'm packaging a lot of shared libraries that could conflict with the system ones and don't want to give users a headache.</p>
<p>Is anyone aware of a framework / package that allows this?</p>
| <p>If you don't want to use the distributions' package manager:</p>
<ul>
<li><p>Write a shell script that copies the files using <code>install</code> (as @MD XF sugessted).</p></li>
<li><p>Write a <code>Makefile</code> (<a href="https://www.gnu.org/software/make/" rel="nofollow">https://www.gnu.org/software/make/</a>), and install your tool using e.g. <code>make install</code>.</p></li>
<li><p><a href="http://stephanepeter.com/makeself/" rel="nofollow">http://stephanepeter.com/makeself/</a> seems to be a nice solution, i never used it tho.</p></li>
</ul>
|
How to set "CheckBoxes" to checked from treeview using javascript? <p>I'm using kendo mvvm frameworks. I would like to check certain checkbox with an array contain the checkbox value.
Example </p>
<pre><code>var checkboxValue=["a","c"]
[x]a
[ ]b
[x]c
</code></pre>
| <p>Try this:</p>
<pre><code>var values = ["A", "C"];
var setTreeViewValues = function(values) {
var tv = $("#treeview").data("kendoTreeView");
tv.dataItems().forEach(function(dataItem) {
if (values.indexOf(dataItem.text) > -1) {
dataItem.set("checked", true);
}
});
};
setTreeViewValues(values);
</code></pre>
<p><a href="http://dojo.telerik.com/AGOnI" rel="nofollow">Demo</a></p>
<p>It will check the node if the array contains its text. You better call this method on <code>dataBound</code> event if your treeView get its data from an async request.</p>
|
What is the impact of async action method on IIS? <p>I need help in understanding how async action method can improve performance of IIS (and eventually my application).</p>
<p><strong>First I tried to create Server Unavailable (503) with following code and setup</strong></p>
<ul>
<li>Application Queue Length: 10</li>
<li>IIS - Threads per processor limit: 2</li>
<li>Processors: 4</li>
</ul>
<p><a href="https://i.stack.imgur.com/KZ5FR.png" rel="nofollow"><img src="https://i.stack.imgur.com/KZ5FR.png" alt="enter image description here"></a></p>
<p>Sent 20 requests with SOAP UI and when tried from the browser, the browser showed 503, which is what I expected.</p>
<p>Then I made following changes in code</p>
<p><a href="https://i.stack.imgur.com/JCwkm.png" rel="nofollow"><img src="https://i.stack.imgur.com/JCwkm.png" alt="enter image description here"></a></p>
<p>Sent 20 requests again with SOAP UI and when tried from the browser, the browser again showed 503, which I wasnt expecting.</p>
<p><strong>Wouldn't the async and await release the thread to accept new connections?</strong> </p>
<p>Is my understanding correct on following</p>
<ol>
<li>Maximum number of concurrent requests the server can accept at any given time is : (IIS Threads per processor limit * Number of processors + Application Queue Length) 18 in my case?</li>
<li>19th request would get a 503 in case of synchronous action methods?</li>
</ol>
| <p>Defining an async action method <strong>does not affect how many requests IIS can serve of the same type</strong>. You are correct when you say that the thread itself is released during the Task.Delay call, but the <em>request</em> is still there in the queue. </p>
<p>You would see a difference only if you sent a few requests to the async TimeOnServer action like this one, and a few <strong>other requests</strong> of a different type that could use more threads - e.g. performing some parallel work with PLINQ. In that case your 'other' requests would be served at a higher rate.</p>
<p>Here is an old but really useful article that describes the benefits clearly:</p>
<p><a href="https://msdn.microsoft.com/en-us/magazine/dn802603.aspx" rel="nofollow">Async Programming : Introduction to Async/Await on ASP.NET</a> by Stephen Cleary</p>
|
Get notification when added / updated any single contact in phone book in android <p>I want to sync contact whenever new contact added or updated. don't want to sync any specific time. </p>
| <p>You can add ContentObserver with service this will notify you on contact data changes. Just register contact uri with ContentObserver
Ref -<a href="https://developer.android.com/reference/android/database/ContentObserver.html" rel="nofollow">https://developer.android.com/reference/android/database/ContentObserver.html</a></p>
<p>Example -<a href="http://www.adityathakker.com/android-content-observer-react-on-content-change/" rel="nofollow">http://www.adityathakker.com/android-content-observer-react-on-content-change/</a></p>
|
session not created exception for chrome in Protractor <p>I get below error when try to run Protractor test against chrome.</p>
<p>My conf.ts</p>
<pre><code>import {Config} from 'protractor'
export let config: Config = {
framework: 'jasmine',
// capabilities: { browserName: 'chrome'},
multiCapabilities: [
// {browserName: 'firefox'},
{
browserName: 'chrome',
chromeOptions: {
args: ['--start-maximized']
},
}],
seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
seleniumPort: null,
seleniumArgs: [],
specs: [
'./Protractor/Login/*.spec.js',
</code></pre>
<p>Error:</p>
<pre><code>Protractor conf.js
[17:19:07] I/hosted - Using the selenium server at http://127.0.0.1:4444/wd/hub
[17:19:07] I/launcher - Running 1 instances of WebDriver
[17:19:09] E/launcher - session not created exception
from unknown error: Runtime.executionContextCreated has invalid 'context': {"auxData":{"frameId":"8800.1","isDefault":true},"id":1,"name":"","origin":"://"}
(Session info: chrome=54.0.2840.59)
(Driver info: chromedriver=2.22.397933 (1cab651507b88dec79b2b2a22d1943c01833cc1b),platform=Windows NT 6.3.9600 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 1.07 seconds
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
System info: host: 'MAL000009416062', ip: '192.168.1.4', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_73'
Driver info: org.openqa.selenium.chrome.ChromeDriver
[17:19:09] E/launcher - SessionNotCreatedError: session not created exception
from unknown error: Runtime.executionContextCreated has invalid 'context': {"auxData":{"frameId":"8800.1","isDefault":true},"id":1,"name":"","origin":"://"}
(Session info: chrome=54.0.2840.59)
(Driver info: chromedriver=2.22.397933 (1cab651507b88dec79b2b2a22d1943c01833cc1b),platform=Windows NT 6.3.9600 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 1.07 seconds
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
System info: host: 'MAL000009416062', ip: '192.168.1.4', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_73'
Driver info: org.openqa.selenium.chrome.ChromeDriver
at WebDriverError (C:\Users\392811\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\error.js:27:5)
at SessionNotCreatedError (C:\Users\392811\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\error.js:308:5)
</code></pre>
<p><strong>conf.ts</strong></p>
<pre><code>multiCapabilities: [
{
browserName: 'chrome',
chromeOptions: {
args: ['--start-maximized']
},
}],
</code></pre>
<p>Most of the discussion on the web is around version. I am currently using up-to-date versions</p>
<p>Any clue please?</p>
<p>Cheers</p>
| <p>I don't have enough rep yet to leave a comment under Sudharsan's answer but the location of the config file he is telling you to modify is actually at </p>
<pre><code>node_modules/protractor/node_modules/webdriver-manager/config.json
</code></pre>
<p>It's not the protractor tsconfig but the webdriver-manager <code>config.json</code> that you want to modify. </p>
<p>That being said, I've run into this problem before and taken a different approach to solving it. The solution that Sudharsan provided would work if you only needed to install it once. We have our builds running in TFS which cleans out the build agents working directory and pulls in a fresh repo on each build. Changing the webdriver config would not work in this situation because we <code>npm install</code> all the things before each build. In this case it would always revert back to the older version of chromedriver. </p>
<p>What I did instead was added chromedriver to my devDependencies in the <code>package.json</code> and then I delete the version of chromedriver that webdriver-manager installs and move the updated version of chromedriver into the correct location with a gulp task. So in the package.json I have this listed under devDependencies:</p>
<pre><code>"chromedriver": "~2.24.1"
</code></pre>
<p>and then I have a gulp task that deletes and moves the files like this:</p>
<pre><code>var gulp = require('gulp');
var del = require('del');
var chromeDriverFilesToMove = [
'./node_modules/chromedriver/lib/chromedriver/**'
];
var chromeDriverFilesToDelete = [
'./node_modules/protractor/node_modules/webdriver-manager/selenium/chromedriver*.exe',
'./node_modules/protractor/node_modules/webdriver-manager/selenium/chromedriver*.zip'
];
gulp.task('delete-chromedriver', function() {
return del(chromeDriverFilesToDelete);
});
gulp.task('move-chromedriver', function() {
gulp.src(chromeDriverFilesToMove)
.pipe(gulp.dest('node_modules/protractor/node_modules/webdriver-manager/selenium/'));
});
gulp.task('chromedriver-update', ['delete-chromedriver', 'move-chromedriver']);
</code></pre>
<p>And because protractor will still be looking for the older version of chromedriver that was installed when you ran <code>webdriver-manager update</code> you have to tell it where to look for the chromedriver.exe so add this to your protractor conf.js and it should start working. </p>
<pre><code>chromeDriver: "../node_modules/protractor/node_modules/webdriver-manager/selenium/chromedriver.exe",
</code></pre>
<p>It's kind of silly that we have to go through all this trouble to get it to work but chromedriver 2.22 doesn't seem to work with Chrome 53+. At least not in my experience. </p>
<p>TL;DR </p>
<p>If you only have to install it once use Sudharsan's solution (given you modify the correct config), it's easier. If you are in my situation and will have to install protractor continuously try my solution. It has worked well for me and I haven't run into this error since.</p>
|
HTML5 input - pattern with required="true" attribute still allows form submission <p>I have text box as below</p>
<pre><code><input type="text" name="country_code" pattern="[A-Za-z0-9|]{1,50}" title="Three letter country code" required="true">
</code></pre>
<p>When I submit the form without entering any value in the text box, empty string <strong>""</strong> gets submitted. I was hoping <strong>required="true"</strong> to catch it and throw an error. I think the combination of required and pattern attribute is causing it behave wrong.</p>
<p>Any thoughts</p>
| <p>Your syntax is wrong. Only <code>required</code> is required.</p>
<pre><code><input type="text" name="country_code" pattern="[A-Za-z0-9|]{1,50}" title="Three letter country code" required>
</code></pre>
<p>It's actually <code>required="required"</code> but you can ommit the second one and use the shorthand instead.</p>
|
StringBuilder returning list of strings + a NewLine at the end when copying to clipboard? <p>I have a loop which is appending a new line every time it loops. By the time it finishes, and I copy to clipboard the <code>StringBuilder.ToString()</code> and I paste it in notepad, the blinking cursor remains on a new line below it, instead of at the end of the last string. How can I prevent this from happening and the cursor remaining at the end of the last string, and not below it in a new line?</p>
<pre><code>StringBuilder sbItems = new StringBuilder();
for (int i = 0; i < 10; i++)
{
sbItems.AppendLine("Item #" + i.ToString());
}
Clipboard.SetText(sbItems.ToString());
</code></pre>
| <p>I see that the string you copy to the clipboard ends with a new line. Of course this new line is pasted and thus your cursor is on the new line.</p>
<p>Somehow you have to get rid of this new line. The method to do this depends on your precise specifications:</p>
<blockquote>
<p>If the string is copied to the clipboard, the complete string is copied to the clipboard</p>
</blockquote>
<p>If this is your specification, then everyone who pastes your copied string will end with the new line at the end of your string. If the paster is a program that you can't control, you can't do anything about it.</p>
<p>Another specification could be:</p>
<blockquote>
<p>If the string is copied to the clipboard, all but a possible terminating new line is copied to the clipboard</p>
</blockquote>
<p>This way you'll get what you want, pasters won't see the terminating new line. But be aware that this way the string on the clipboard is not the original string.</p>
<p>Code (of course this can be optimized, just showing small steps)</p>
<pre><code>StringBuilder sbItems = FillStringBuilder(...);
// before copying, remove a possible new line character
// for this we use property System.Environment.NewLine
var stringToCopyToClipboard = sbItems.ToString();
if (stringToCopyToClipboard.EndsWith(Environment.NewLine)
{
int newLineIndex = stringToCopyToClipboard.LastIndexOf(Environment.NewLine);
stringToCopyToClipboard = stringToCopyToClipboard.Substring(0, newLineIndex);
}
Clipboard.SetText(stringToCopyToClipboard);
</code></pre>
|
Get child name from Firebase? <p>If I have something like:</p>
<pre><code>child name: "value"
</code></pre>
<p>How can I get the childname? I know its possible to get the value, but what about the other?</p>
| <p>Yes! The child name in this situation is the "KEY" of that value. So use the reference object and simple called getKey() on it.</p>
<pre><code>String name = ref.getKey();
</code></pre>
|
Andorid - Big Picture Style image not showing properly <p>Image in big picture style not showing in proper way. From top and bottom it cuts.</p>
<p>Here is code to generate notification:</p>
<pre><code>private void notificationWithImage(String url, String msg, int smallLogo) {
try {
Bitmap icon1 = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setAutoCancel(true)
.setContentTitle("XXXXXXXAPP")
.setSmallIcon(smallLogo)
.setLargeIcon(icon1);
NotificationCompat.BigPictureStyle bigPicStyle = new NotificationCompat.BigPictureStyle();
// bigPicStyle.bigPicture(Picasso.with(getApplicationContext()).load(url).resize(320, 256).centerInside().get());
Bitmap bitmap_image = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_edited_noti);
bigPicStyle.bigPicture(bitmap_image);
bigPicStyle.setBigContentTitle("XXXXXXXAPP");
bigPicStyle.setSummaryText(msg);
mBuilder.setStyle(bigPicStyle);
if (getLoginDetailFromPrefs())
resultIntent = new Intent(this, Perspective.class);
else
resultIntent = new Intent(this, LoginActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
if (getLoginDetailFromPrefs())
stackBuilder.addParentStack(Perspective.class);
else
stackBuilder.addParentStack(LoginActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
} catch (Exception e) {
e.printStackTrace();
}
}
</code></pre>
<p>I added screen shot with question
<a href="https://i.stack.imgur.com/FuGEr.png" rel="nofollow"><img src="https://i.stack.imgur.com/FuGEr.png" alt="enter image description here"></a></p>
<p>Help to resolve. Thanks in advance.</p>
| <p>The thing that you want can be done perfectly by the use RemoteView in Notification & then Apply customView in Builder. </p>
<p>This is a template code to use RemoteViews : - </p>
<pre><code> RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(), R.layout.notification_layout);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.notification_small)
.setColor(getApplicationContext().getResources().
getColor(R.color.colorPrimary))
.setCustomBigContentView(remoteViews)
.setLargeIcon(bitmap)
.setContent(remoteViews)
.setOngoing(true)
.setContentTitle("")
.setAutoCancel(false)
.setTicker(getString(R.string.app_name), remoteViews)
.setPriority(Notification.PRIORITY_HIGH)
.setContentText("");
NotificationManager mNotificationManager =(NotificationManager)
getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
</code></pre>
|
how do I calculate a rolling idxmax <p>consider the <code>pd.Series</code> <code>s</code></p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed([3,1415])
s = pd.Series(np.random.randint(0, 10, 10), list('abcdefghij'))
s
a 0
b 2
c 7
d 3
e 8
f 7
g 0
h 6
i 8
j 6
dtype: int64
</code></pre>
<p>I want to get the index for the max value for the rolling window of 3</p>
<pre><code>s.rolling(3).max()
a NaN
b NaN
c 7.0
d 7.0
e 8.0
f 8.0
g 8.0
h 7.0
i 8.0
j 8.0
dtype: float64
</code></pre>
<p>What I want is</p>
<pre><code>a None
b None
c c
d c
e e
f e
g e
h f
i i
j i
dtype: object
</code></pre>
<p>What I've done</p>
<pre><code>s.rolling(3).apply(np.argmax)
a NaN
b NaN
c 2.0
d 1.0
e 2.0
f 1.0
g 0.0
h 0.0
i 2.0
j 1.0
dtype: float64
</code></pre>
<p>which is obviously not what I want</p>
| <p>There is no simple way to do that, because the argument that is passed to the rolling-applied function is a plain numpy array, not a pandas Series, so it doesn't know about the index. Moreover, the rolling functions must return a float result, so they can't directly return the index values if they're not floats.</p>
<p>Here is one approach:</p>
<pre><code>>>> s.index[s.rolling(3).apply(np.argmax)[2:].astype(int)+np.arange(len(s)-2)]
Index([u'c', u'c', u'e', u'e', u'e', u'f', u'i', u'i'], dtype='object')
</code></pre>
<p>The idea is to take the argmax values and align them with the series by adding a value indicating how far along in the series we are. (That is, for the first argmax value we add zero, because it is giving us the index into a subsequence starting at index 0 in the original series; for the second argmax value we add one, because it is giving us the index into a subsequence starting at index 1 in the original series; etc.)</p>
<p>This gives the correct results, but doesn't include the two "None" values at the beginning; you'd have to add those back manually if you wanted them.</p>
<p>There is <a href="https://github.com/pandas-dev/pandas/issues/9481">an open pandas issue</a> to add rolling idxmax.</p>
|
Generate JSON file using JavaScript code <p>I'm new to Web Development and just created a simple form in HTML and using some JavaScript I can submit the form by HTTP Post. I wanted to know whether there is a way to generate a JSON file with JSoN objects in it and then upload it to a JSON based database like firebase? Thanks</p>
| <p><strong>Short answer:</strong> yes, just use var <code>json = JSON.stringify(array);</code></p>
<p><strong>Long answer:</strong> You need an array, or better: an object array.
If you assign keys it will be much easier to work on serverside.
However just stringify the array and you are done.</p>
|
Python/Math Find Previous Value in Fibonacci Sequence with a Function/Equation <p>This is slightly less code related...<br>
I am making a function that calculates a Fibonacci number backwards. </p>
<p>Not just print it backwards but do the math itself backwards.<br>
I did a little research using Phi and phi... </p>
<p>I think I mostly got it,<br>
but how do I calculate a previous number in the sequence? </p>
<p>I.E. F6 is 8 and F5 is 5. I need a function to find "5" (The previous number).</p>
<p>Any help?</p>
<p>Thanks in advance!</p>
| <pre><code> def FingFactorial(n):
if n == 1:
return 1
else:
res = n * FingFactorial(n-1)
return res
n=int(input("Factorial Of : "))
print("Factorial Of",n,"Is :",FingFactorial(n-1))
</code></pre>
<p>this code may give your desired result .. :) <a href="http://blog.iamovi.me/function-in-python/" rel="nofollow">CLICK HERE THIS MAY HELP YOU</a></p>
|
combine two element in an array perl <p>I want to compare two sequences using <code>standalone blastn</code>. </p>
<p>But before I can do that I have to cut the sequence into 1020nt of each fragment. If the last fragment is less than 1020nt, i have to merge (the sequence) in the last fragment with sequence in the previous fragment . For example I cut a sequence into 1020nt and get 7 fragments. But the 7th fragment is less than 1020nt, so i have to merged it into the 6th fragment. Is anyone know how to do this using <code>Perl language?</code></p>
<p>This is my code:</p>
<pre><code>while(<QR>){
chomp;
s/>//g;
my ($scaf,$seq)= split /\n/,$_,2;
my $scaf_name = (split /\s+/,$scaf)[0];
$seq =~ s/\s+//g;
my @cut = ($seq =~ /(.{1,$chop_len})/g);
if (length($#cut) < 1020) {
$#cut="@cut[-2 .. -1]"; # i get error here
}
else {
}
print $#cut;
for my $cut_num (0..$#cut){
my $sgmID = "$scaf_name\_$cut_num";
print CR ">$sgmID\n$cut[$cut_num]\n";
}
}
close QR;
close CR;
</code></pre>
<p>Actually I found this Perl script on the internet, and modified it so that I can merged the last two fragments.</p>
| <p>You need to remove the last cut and append it to the second-to-last cut using the <code>.=</code> concatenation operator:</p>
<p>Here is a simplified example:</p>
<pre><code>#!/usr/bin/env perl
use warnings;
use strict;
my $total_length = 100;
my $chop_length = 14;
my @letters = qw( A C G T );
my $long_string = join '', map { $letters[ int rand scalar @letters ] } ( 1 .. $total_length );
print "Long string ($total_length chars) :\n$long_string\n";
print '-'x$total_length . "\n";
my @cut = ($long_string =~ /(.{1,$chop_length})/g);
my $last_cut = pop @cut; # Take last one off
if (length $last_cut < $chop_length) {
$cut[$#cut] .= $last_cut; # Concatenate it to the (now) last one
} else {
push @cut, $last_cut; # Put it back, it has the right length
}
print "Parts cut into >= $chop_length char length pieces.\n";
for my $part (@cut) {
print $part . "\n";
}
</code></pre>
<p><strong>Output</strong></p>
<pre><code>Long string (100 chars) :
CCATCCTGCACATTCGGTGATTTATCAGAAGTAAGATCCTCGTCCCACTGACCGTGCGGGGATACGGAGCTCAAACAGAGAGAAACGGTTGGTCTGTAGA
----------------------------------------------------------------------------------------------------
Parts cut into >= 14 char length pieces.
CCATCCTGCACATT
CGGTGATTTATCAG
AAGTAAGATCCTCG
TCCCACTGACCGTG
CGGGGATACGGAGC
TCAAACAGAGAGAA
ACGGTTGGTCTGTAGA
</code></pre>
|
How to make "ld" link in 32bit mode? <p>I've got assembly source file under ubuntu 64bit version. I wish to compile a 32bit version.</p>
<pre><code>$ cat 1.s
.code32
.text
.globl _start
_start:
movl $2,%ebx
movl $1,%eax
int $0x80
$ as 1.s
$ readelf -h 1.o
ELF 头ï¼
Magicï¼ 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
Typeå«: ELF32
...
Architecture: Intel 80386
</code></pre>
<p>Everything seems OK.
Now I link it, it tells 32bit/64bit incompatability:</p>
<pre><code>$ ld 1.o -o my
ld: i386 architect input file 1.o is not compatible with i386:x86-64
ld: warning: unable to find symbol item _start; default is 00000000004000b0
</code></pre>
<p>Well, I don't quite understand this, I've specified ".code32" in my assembly source code. </p>
<p>I tried to add "-32" or "-m32" to "ld" command, but it's not accepted.
How to make my link successful? I wish to use "ld" not "gcc".</p>
<p>Thanks.</p>
| <p>Just change your output ELF format with the <code>-melf_i386</code> flag:</p>
<pre><code>ld 1.o -o my -melf_i386
</code></pre>
|
How to convert large UTF-8 encoded char* string to CStringW (UTF-16)? <p>I have a problem with converting a UTF-8 encoded string to a UTF-16 encoded <code>CStringW</code>.</p>
<p>Here is my source code:</p>
<pre><code>CStringW ConvertUTF8ToUTF16( __in const CHAR * pszTextUTF8 )
{
_wsetlocale( LC_ALL, L"Korean" );
if ( (pszTextUTF8 == NULL) || (*pszTextUTF8 == '\0') )
{
return L"";
}
const size_t cchUTF8Max = INT_MAX - 1;
size_t cchUTF8;
HRESULT hr = ::StringCbLengthA( pszTextUTF8, cchUTF8Max, &cchUTF8 );
if ( FAILED( hr ) )
{
AtlThrow( hr );
}
++cchUTF8;
int cbUTF8 = static_cast<int>( cchUTF8 );
int cchUTF16 = ::MultiByteToWideChar(
CP_UTF8,
MB_ERR_INVALID_CHARS,
pszTextUTF8,
-1,
NULL,
0
);
CString strUTF16;
strUTF16.GetBufferSetLength(cbUTF8);
WCHAR * pszUTF16 = new WCHAR[cchUTF16];
int result = ::MultiByteToWideChar(
CP_UTF8,
0,
pszTextUTF8,
cbUTF8,
pszUTF16,
cchUTF16
);
ATLASSERT( result != 0 );
if ( result == 0 )
{
AtlThrowLastWin32();
}
strUTF16.Format(_T("%s"), pszUTF16);
return strUTF16;
}
</code></pre>
<p><code>pszTextUTF8</code> is htm file's content in UTF-8.
When htm file's volume is less than 500kb, this code works well.
but, when converting over 500kb htm file, (ex 648KB htm file that I have.)
<code>pszUTF16</code> has all content of file, but <code>strUTF16</code> is not. (about half)
I guess File open is not wrong.</p>
<p>In <code>strUTF16 m_pszData</code> has all content how to I get that?
<code>strUTF16.Getbuffer();</code> dosen't work.</p>
| <p>The code in the question is stock full of bugs, somewhere in the order of 1 bug per 1-2 lines of code.</p>
<p>Here is a short summary:</p>
<pre><code>_wsetlocale( LC_ALL, L"Korean" );
</code></pre>
<p>Changing a global setting in a conversion function is unexpected, and will break code calling that. It's not even necessary either; you aren't using the locale for the encoding conversion.</p>
<pre><code>HRESULT hr = ::StringCbLengthA( pszTextUTF8, cchUTF8Max, &cchUTF8 );
</code></pre>
<p>This is passing the wrong <code>cchUTF8Max</code> value (according to the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms647509.aspx" rel="nofollow">documentation</a>), and counts the number of <strong>bytes</strong> (vs. the number of characters, i.e. code units). Besides all that, you do not even need to know the number of code units, as you never use it (well, you are, but that is just another bug).</p>
<pre><code>int cbUTF8 = static_cast<int>( cchUTF8 );
</code></pre>
<p>While that fixes the prefix (<strong>c</strong>ount of <strong>b</strong>ytes as opposed to <strong>c</strong>ount of <strong>ch</strong>aracters), it won't save you from using it later on for something that has an unrelated value.</p>
<pre><code>strUTF16.GetBufferSetLength(cbUTF8);
</code></pre>
<p>This resizes the string object that should eventually hold the UTF-16 encoded characters. But it doesn't use the correct number of characters (the previous call to <code>MultiByteToWideChar</code> would have provided that value), but rather chooses a completely unrelated value: The number of <strong>bytes</strong> in the UTF-8 encoded source string.</p>
<p>But it doesn't just stop there, that line of code also throws away the pointer to the internal buffer, that was ready to be written to. Failure to call <code>ReleaseBuffer</code> is only a natural consequence, since you decided against reading the <a href="https://msdn.microsoft.com/en-us/library/614k79sd.aspx" rel="nofollow">documentation</a>.</p>
<pre><code>WCHAR * pszUTF16 = new WCHAR[cchUTF16];
</code></pre>
<p>While not a bug in itself, it needlessly allocates another buffer (this time passing the correct size). You already allocated a buffer of the required size (albeit wrong) in the previous call to <code>GetBufferSetLength</code>. Just use that, that's what the member function is for.</p>
<pre><code>strUTF16.Format(_T("%s"), pszUTF16);
</code></pre>
<p>That is probably <em>the</em> anti-pattern associated with the <code>printf</code> family of functions. It is the convoluted way to write <a href="https://msdn.microsoft.com/en-us/library/y0cka9es.aspx" rel="nofollow"><code>CopyChars</code></a> (or <a href="https://msdn.microsoft.com/en-us/library/99t9bs1b.aspx" rel="nofollow"><code>Append</code></a>).</p>
<p>Now that that's cleared up, here is the correct way to write that function (or at least one way to do it):</p>
<pre><code>CStringW ConvertUTF8ToUTF16( __in const CHAR * pszTextUTF8 ) {
// Allocate return value immediately, so that (N)RVO can be applied
CStringW strUTF16;
if ( (pszTextUTF8 == NULL) || (*pszTextUTF8 == '\0') ) {
return strUTF16;
}
// Calculate the required destination buffer size
int cchUTF16 = ::MultiByteToWideChar( CP_UTF8,
MB_ERR_INVALID_CHARS,
pszTextUTF8,
-1,
nullptr,
0 );
// Perform error checking
if ( cchUTF16 == 0 ) {
throw std::runtime_error( "MultiByteToWideChar failed." );
}
// Resize the output string size and use the pointer to the internal buffer
wchar_t* const pszUTF16 = strUTF16.GetBufferSetLength( cchUTF16 );
// Perform conversion (return value ignored, since we just checked for success)
::MultiByteToWideChar( CP_UTF8,
MB_ERR_INVALID_CHARS, // Use identical flags
pszTextUTF8,
-1,
pszUTF16,
cchUTF16 );
// Perform required cleanup
strUTF16.ReleaseBuffer();
// Return converted string
return strUTF16;
}
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.