Id int64 34.6M 60.5M | Title stringlengths 15 150 | Body stringlengths 33 36.7k | Tags stringlengths 3 112 | CreationDate stringdate 2016-01-01 00:21:59 2020-02-29 17:55:56 | Y stringclasses 3 values |
|---|---|---|---|---|---|
36,142,265 | How to find out which player has closest bid in Price is Right game java? | <p>My Price Is Right program is still incomplete as I need to find out who my winner is each time. </p>
<p>The game's winner must have the highest bid that is most closest to the object's value, but cannot be more than the object's value.</p>
<p>How can I add the winner into my program?
Here is my code so far:</p>
<pre><code>public class PriceisRight
{
public static void main(String args[])
{
new PriceisRight();
}
public PriceisRight()
{
System.out.println("Welcome to the Price is Right!\n");
String name1 = IBIO.inputString("Name of contestant #1: ");
String name2 = IBIO.inputString("Name of contestant #2: ");
String name3 = IBIO.inputString("Name of contestant #3: ");
String name4 = IBIO.inputString("Name of contestant #4: ");
System.out.println("");
char again = 'y';
while (again == 'Y' || again == 'y')
{
String THING = item ();
System.out.println("The item to bid on is a "+ THING +".");
System.out.println("The contestant who is the closest without going");
System.out.println("over wins. The maximum bid is $1000.\n");
int bid1 = IBIO.inputInt ( name1 +", what is your bid? ");
int bid2 = IBIO.inputInt ( name2 +", what is your bid? ");
int bid3 = IBIO.inputInt ( name3 +", what is your bid? ");
int bid4 = IBIO.inputInt ( name4 +", what is your bid? ");
again = IBIO.inputChar ("Play again? (y/n) ");
System.out.println ("");
}
}
public String item ()
{
int num = (int)(Math.random() * 5);
int price = 0;
String object = "";
if (num == 1)
{
object = ("sofa");
price = 987;
}
else if (num == 2)
{
object = ("TV");
price = 560;
}
else if(num == 3)
{
object = ("bed");
price = 226;
}
else if(num == 4)
{
object = ("table");
price = 354;
}
else
{
object = ("chair");
price = 70;
}
return object;
}
}
</code></pre>
| <java><loops><math> | 2016-03-21 21:48:59 | LQ_CLOSE |
36,142,293 | ArrayList duplicates removal | <p>I have an Arraylist with pings, these are dates linked to a name, I want to delete all duplicates of the names and keep the closest date of the name.</p>
<p><strong>Code</strong></p>
<pre><code>private ArrayList <String> deleteDuplicates() {
ArrayList <Ping> tempPings = new ArrayList < Ping > ();
tempPings.addAll(jaws.pastMonth());
for (int i = 0; i < tempPings.size(); i++) {
Ping tempPing = tempPings.get(i);
for (int j = i + 1; j < tempPings.size() - 1; j++) {
Ping tempPing2 = tempPings.get(j);
if (tempPing.getName().equals(tempPing2.getName())) {
if (changePingToDate(tempPing2).before(changePingToDate(tempPing))) {
tempPings.remove(j);
}
}
}
}
return pingToNames(tempPings);
}
</code></pre>
<p>changePingToDate() is a method to convert the date string into a gregorian calendar.</p>
<p>When I use this code it deletes a high proportion of the duplicates but there are still some remaining each time through the loop. I have also tried it without comparing the dates and still the same problem. Can anyone help?</p>
<p>Thanks for the help!</p>
| <java><date><arraylist><duplicates> | 2016-03-21 21:50:28 | LQ_CLOSE |
36,142,331 | check http status code using nightwatch | <p>how do I check the HTTP status code using nightwatch.js? I tried </p>
<pre><code> browser.url(function (response) {
browser.assert.equal(response.statusCode, 200);
});
</code></pre>
<p>but of course that does not work.</p>
| <selenium><nightwatch.js> | 2016-03-21 21:52:47 | HQ |
36,142,576 | View being blocked by UITransitionView after being presented | <p>I have a side navigation controller and present it via a UIButton. When I make this NC the root view controller directly by <code>[self presentviewcontroller: NC animated: YES completion: nil]</code>, some reason the menu side of the NC is blocked by a <code>UITransitionView</code> that I cannot get to disappear.</p>
<p>I've attached an image of the <a href="https://i.stack.imgur.com/qnlng.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qnlng.png" alt="view hierarchy"></a>. <a href="https://i.stack.imgur.com/07Muy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/07Muy.png" alt="Here"></a> is another.</p>
<p>I have tried the following:</p>
<pre><code>UIWindow *window = [(AppDelegate *)[[UIApplication sharedApplication] delegate] window];
window.backgroundColor = kmain;
CATransition* transition = [CATransition animation];
transition.duration = .5;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromTop;
[nc.view.layer addAnimation:transition forKey:kCATransition];
[UIView transitionWithView:window
duration:0.5
options:UIViewAnimationOptionTransitionNone
animations:^{ window.rootViewController = nc; }
completion:^(BOOL finished) {
for (UIView *subview in window.subviews) {
if ([subview isKindOfClass:NSClassFromString(@"UITransitionView")]) {
[subview removeFromSuperview];
}
}
}];
</code></pre>
<p>But it is very hacky, and as the rootviewcontroller of the window changes during the transition, it's a little choppy and part of the navigationcontroller and the top right corner turn black. It looks very bad.</p>
| <ios><uiviewcontroller><uinavigationcontroller><uiviewanimationtransition><catransition> | 2016-03-21 22:09:59 | HQ |
36,142,639 | Gulp: how to delete a folder? | <p>I use del package to delete folder:</p>
<pre><code>gulp.task('clean', function(){
return del('dist/**/*', {force:true});
});
</code></pre>
<p>But if there are many subdirectory in dist folder and I want to delete dist folder and all its files, is there any easy way to do it?</p>
<p>Ps: I don't want to do in this way: <code>dist/**/**/**/**/**/**/...</code> when there are so many subdirectories.</p>
| <gulp> | 2016-03-21 22:13:21 | HQ |
36,143,020 | The colored image turned to have no color and just a grey vector in drawable? | <p>I have created a new Image Assets in the Drawable cus I need to insert a new image in my app, but every time I create a new image asset, the output turns to be no colour at all. I've attached the pic of it.<a href="https://i.stack.imgur.com/LQvKD.jpg"><img src="https://i.stack.imgur.com/LQvKD.jpg" alt="enter image description here"></a></p>
<p>It's confusing and whenever I import it in my layout, it's just grey all over as you can see in the image. Why is it cus I can't find any ready solutions? Let me know if I'm overlooked. </p>
| <android><image><android-studio><drawable> | 2016-03-21 22:43:54 | HQ |
36,143,767 | React.js - Communicating between sibling components | <p>I'm new to React, and I'd like to ask a strategy question about how best to accomplish a task where data must be communicated between sibling components.</p>
<p>First, I'll describe the task:</p>
<p>Say I have multiple <code><select></code> components that are children of a single parent that passes down the select boxes dynamically, composed from an array. Each box has exactly the same available options in its initial state, but once a user selects a particular option in one box, it must be disabled as an option in all other boxes until it is released. </p>
<p>Here's an example of the same in (silly) code. (I'm using <code>react-select</code> as a shorthand for creating the select boxes.)</p>
<p>In this example, I need to disable (ie, set <code>disabled: true</code>) the options for "It's my favorite" and "It's my least favorite" when a user selects them in one select box (and release them if a user de-selects them).</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var React = require('react');
var Select = require('react-select');
var AnForm = React.createClass({
render: function(){
// this.props.fruits is an array passed in that looks like:
// ['apples', 'bananas', 'cherries','watermelon','oranges']
var selects = this.props.fruits.map(function(fruit, i) {
var options = [
{ value: 'first', label: 'It\'s my favorite', disabled: false },
{ value: 'second', label: 'I\'m OK with it', disabled: false },
{ value: 'third', label: 'It\'s my least favorite', disabled: false }
];
return (
<Child fruit={fruit} key={i} options={options} />
);
});
return (
<div id="myFormThingy">
{fruitSelects}
</div>
)
}
});
var AnChild = React.createClass({
getInitialState: function() {
return {
value:'',
options: this.props.options
};
},
render: function(){
function changeValue(value){
this.setState({value:value});
}
return (
<label for={this.props.fruit}>{this.props.fruit}</label>
<Select
name={this.props.fruit}
value={this.state.value}
options={this.state.options}
onChange={changeValue.bind(this)}
placeholder="Choose one"
/>
)
}
});</code></pre>
</div>
</div>
</p>
<p>Is updating the child options best accomplished by passing data back up to the parent through a callback? Should I use refs to access the child components in that callback? Does a redux reducer help?</p>
<p>I apologize for the general nature of the question, but I'm not finding a lot of direction on how to deal with these sibling-to-sibling component interactions in a unidirectional way.</p>
<p>Thanks for any help.</p>
| <javascript><reactjs><flux> | 2016-03-21 23:47:51 | HQ |
36,143,835 | Storage of user data | <p>When looking at how websites such as Facebook stores profile images, the URLs seem to use randomly generated value. For example, Google's Facebook page's profile picture page has the following URL:</p>
<pre><code>https://scontent-lhr3-1.xx.fbcdn.net/hprofile-xft1/v/t1.0-1/p160x160/11990418_442606765926870_215300303224956260_n.png?oh=28cb5dd4717b7174eed44ca5279a2e37&oe=579938A8
</code></pre>
<p>However why not just organise it like so:</p>
<pre><code>https://scontent-lhr3-1.xx.fbcdn.net/{{ profile_id }}/50x50.png
</code></pre>
<p>Clearly this would be much easier in terms of storage and simplicity. Am I missing something? Thanks.</p>
| <storage><user-data> | 2016-03-21 23:54:19 | HQ |
36,143,838 | looping through javascript object | <p>How do you access properties of a javascript object like the following?
Please explain each step if possible.</p>
<pre><code>var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
}
];
function lookUp(firstName, prop){
//code here
}
</code></pre>
<p>I would like to be able to access the name of a contact. So for example</p>
<pre><code> lookUp("Akira", "likes")
</code></pre>
<p>should give me the name and the likes. And also
lookUp("Drew", "like")
should give me back
"No such contact".</p>
<p>Thanks a lot in advance!</p>
| <javascript> | 2016-03-21 23:54:42 | LQ_CLOSE |
36,143,840 | Regular expressions doubts | <p>I have a few doubts that I have not managed to clear up by research and am hoping for some help.</p>
<p>1) What does the <code>m</code> do, and what do the <code>/ /</code> before the m and at the end do?
$var =~ m/[^0-9]+/</p>
<p>2) <code>/[^0-9]+/</code> Which of the following lines does this regex match?</p>
<pre><code> A) `123`
B) `4`
C) `I see 5 dogs`
D) `I see five dogs`
</code></pre>
<p>My answer to 2): It matches <code>C</code> and <code>D</code>, and not <code>A</code> and <code>B</code> because there is no character or wold that does not contain <code>0-9</code>.</p>
| <regex><perl> | 2016-03-21 23:54:45 | LQ_CLOSE |
36,143,925 | React js - How to mock Context when testing component | <p>I'm trying to test a component which inherits context from a root component, without loading/rendering everything from the root down. I've tried and searched for examples on how to mock the context but can't find anything (at least that doesn't use jest).</p>
<p>Here's a simplified example of what I'm trying to achieve.</p>
<p>Is there a simple way I can mock reactEl.context for the test?</p>
<pre><code>/**
* Root Element that sets up & shares context
*/
class Root extends Component {
getChildContext() {
return {
language: { text: 'A String'}
};
}
render() {
return (
<div>
<ElWithContext />
</div>
);
}
}
Root.childContextTypes = { language: React.PropTypes.object };
/**
* Child Element which uses context
*/
class ElWithContext extends React.Component{
render() {
const {language} = this.context;
return <p>{language.text}</p>
}
}
ElWithContext.contextTypes = { language: React.PropTypes.object }
/**
* Example test where context is unavailable.
*/
let el = React.createElement(ElWithContext)
element = TestUtils.renderIntoDocument(el);
// ERROR: undefined is not an object (evaluating 'language.text')
describe("ElWithContext", () => {
it('should contain textContent from context', () => {
const node = ReactDOM.findDOMNode(element);
expect(node.textContent).to.equal('A String');
});
})
</code></pre>
| <javascript><reactjs> | 2016-03-22 00:02:44 | HQ |
36,144,877 | Rolify Table Error (user.add_role :admin Unknown Key Error) | <p>I'm attempting to setup the rolify gem and I'm running into an issue assigning a role to a user in the console.</p>
<p>Here's my error: </p>
<pre><code>2.2.1 :007 > user.add_role :admin
ArgumentError: Unknown key: :optional.
</code></pre>
<p>I'm running devise with cancancan and rolify. I'm also running the Koudoku gem for subscription payment support. I'm suspecting this error might be caused by the fact that my "subscriptions" table also has a "user_id" column. Is there anything I can do to correct this issue?</p>
<p>Here's my schema.</p>
<pre><code>create_table "subscriptions", force: :cascade do |t|
t.string "stripe_id"
t.integer "plan_id"
t.string "last_four"
t.integer "coupon_id"
t.string "card_type"
t.float "current_price"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "first_name"
t.string "string"
t.string "last_name"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name:
"index_users_on_reset_password_token", unique: true
create_table "users_roles", id: false, force: :cascade do |t|
t.integer "user_id"
t.integer "role_id"
end
add_index "users_roles", ["user_id", "role_id"], name: "index_users_roles_on_user_id_and_role_id"
end
</code></pre>
<p>Thanks.</p>
| <ruby-on-rails><devise><key><cancancan><rolify> | 2016-03-22 01:50:04 | HQ |
36,144,892 | Send Email using only Angular JS | <p>I have created a web application using angularJS and firebase. Now, I want to send E-mail to the users once they are authenticated from app. Is there any way to send email using only angular JS?</p>
| <angularjs><firebase><angularfire> | 2016-03-22 01:52:15 | LQ_CLOSE |
36,144,993 | Data augmentation techniques for small image datasets? | <p>Currently i am training small logo datasets similar to <a href="http://www.multimedia-computing.de/flickrlogos/" rel="noreferrer">Flickrlogos-32</a> with deep CNNs. For training larger networks i need more dataset, thus using augmentation. The best i'm doing right now is using affine transformations(featurewise normalization, featurewise center, rotation, width height shift, horizontal vertical flip). But for bigger networks i need more augmentation. I tried searching on kaggle's national data science bowl's <a href="https://www.kaggle.com/c/datasciencebowl/forums/t/11360/data-augmentation" rel="noreferrer">forum</a> but couldn't get much help. There's code for some methods given <a href="https://github.com/benanne/kaggle-galaxies/blob/master/realtime_augmentation.py" rel="noreferrer">here</a> but i'm not sure what could be useful. What are some other(or better) image data augmentation techniques that could be applied to this type of(or in any general image) dataset other than affine transformations? </p>
| <image-processing><machine-learning><computer-vision><neural-network><deep-learning> | 2016-03-22 02:06:53 | HQ |
36,145,049 | File manipulation using Python | <p>I recently started working in a lab that generate a lot of data. I need to manipulate files very often for various needs. I have learnt awk programming but it seems not enough for my work. I know python but not to that extent where I can comfortably work on files. Could anyone please suggest to me any book or online tutorial where I can find exclusively the use of Python on files. most of the python books do not dwell intensively on this subject.
thanks</p>
| <python> | 2016-03-22 02:12:24 | LQ_CLOSE |
36,145,636 | Is there a Pythonic way to delete common indexes in multiple lists? | <p>Say I want to delete index <code>i</code> from <code>alist</code> and <code>blist</code>. Is there a clean, Pythonic way to achieve this?</p>
| <python><list> | 2016-03-22 03:30:11 | LQ_CLOSE |
36,146,031 | The shortest path int a directed graph that through some specified vertexs | There is a weighted directed graph.How to get the shortest path to the directed graph that through some specified vertexs. | <algorithm><optimization><graph-algorithm><evolutionary-algorithm> | 2016-03-22 04:21:51 | LQ_EDIT |
36,146,295 | how to create a alert box in android alternative presents? | <p><strong>Create an alert box that show alternative during application run</strong>
I want to alert box that appear even time when my app is open </p>
| <java><android> | 2016-03-22 04:49:09 | LQ_CLOSE |
36,146,458 | Find shortest path between multiple locations c# | <p>I have list of location with their coordinates and also current location with lat long.
Now,i want to find shortest route according to my list of locations(lat-longs)</p>
<p>Just i need to sort the location according to route wise.</p>
<p>Any help will be appreciated.</p>
| <c#><shortest-path> | 2016-03-22 05:03:11 | LQ_CLOSE |
36,146,491 | node 0.12.x const in strict mode issue | <p>I'm running node v0.12.7, and installed protractor through npm.
Now I'm trying to run the conf.js using this <a href="https://angular.github.io/protractor/#/tutorial">simple tutorial</a>, and I get the following error when executing the command <code>protractor conf.js</code>:</p>
<pre><code>[launcher] Process exited with error code 1
C:\Users\ramtin\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\index.js:25
const builder = require('./builder');
^^^^^
SyntaxError: Use of const in strict mode.
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (C:\Users\ramtin\AppData\Roaming\npm\node_modules\protractor\built\protractor.js:3:17)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
</code></pre>
<p>Can't update node due to dependency issues it will produce (I'm working on an already-built project which used node 0.12.17).</p>
<p>Using <code>--harmony</code> flag on protractor doesn't work. Do I need to install a specific version of protractor to be compatible with node 0.12.7? Or should I use <code>babeljs</code> to compile <code>ES6</code> to <code>ES5</code>?</p>
<p>If <code>babeljs</code> is the answer, how would I use it for protractor?</p>
| <node.js><selenium-webdriver><protractor><ecmascript-6><babeljs> | 2016-03-22 05:06:05 | HQ |
36,146,896 | difference between Private slots and private method in QT | <p>I am new to QT and I want to know the difference between</p>
<p>1) private slot vs private class methods</p>
<p>When we need to use private slot and when we need to use private methods</p>
| <c++><qt> | 2016-03-22 05:37:44 | LQ_CLOSE |
36,147,082 | react-native style opacity for parent and child | <p>react-native : I have one View and the child of View is an Image , I applied opacity: 0.5 for View and opacity: 0.9 for an Image but it doesn't apply for Image ,the parent opacity is applying for child , the child doesn't take independent opacity </p>
| <react-native> | 2016-03-22 05:52:27 | HQ |
36,147,203 | Generate sequence number in android | <p>I want to generate sequence number that starts from 001,002 and continue like that.I want it to get incremented on each visit of that screen..Any help appreciated.Thank you.</p>
| <android> | 2016-03-22 06:00:42 | LQ_CLOSE |
36,147,252 | How resize image in vb.net | <p>My code resize Image, but it only can reduce size.</p>
<pre><code> For Each oFile In My.Computer.FileSystem.GetFiles(parm_strTargetPath)
If oFile.ToString.ToLower.Contains(".png") Or oFile.ToString.ToLower.Contains(".jpg") Or oFile.ToString.ToLower.Contains(".jpeg") Then
Dim strFileName = System.IO.Path.GetFileName(oFile)
Try
Dim original As Image = Image.FromFile(oFile)
Dim resized As Image = ResizeImage(original, New Size(h, w))
Dim memStream As MemoryStream = New MemoryStream()
resized.Save(memStream, ImageFormat.Jpeg)
Dim file As New FileStream(result & "/" & strFileName , FileMode.Create, FileAccess.Write)
memStream.WriteTo(file)
file.Close()
memStream.Close()
Catch ex As Exception
End Try
End If
Next
</code></pre>
<p>My image size: <code>1028x 172</code>, i want resize to <code>500 x 500</code>
But result is a image size : <code>500x84</code>
How Resize image from <code>1028x 172</code> to <code>500 x 500</code> ?
Thanks all.</p>
| <.net><vb.net> | 2016-03-22 06:05:37 | LQ_CLOSE |
36,147,276 | How to validate TextInput values in react native? | <p>for example, While entering an email in the TextInput, it should validate and display the error message. where the entered email is valid or not </p>
<p><a href="https://i.stack.imgur.com/bVIha.png"><img src="https://i.stack.imgur.com/bVIha.png" alt="enter image description here"></a> </p>
| <javascript><android><validation><reactjs><react-native> | 2016-03-22 06:07:01 | HQ |
36,147,809 | Angular2 Get reference to element created in ngFor | <p>How would I go for referencing an Element in the dom which was created in a ngFor loop.</p>
<p>e.g. I have a list of elements which I iterate over:</p>
<pre><code>var cookies: Cookie[] = [...];
<div *ngFor="#cookie of cookies" id="cookie-tab-button-{{cookie.id}}" (click)="showcookie(cookie);">Cookie tab</div>
<div *ngFor="#cookie of cookies" id="cookie-tab-content-{{cookie.id}}" ">Cookie Details</div>
</code></pre>
<p>How would I reference these divs, so I could add a css class like "is-active".
Or is my approach just wrong.</p>
| <angular> | 2016-03-22 06:45:42 | HQ |
36,148,741 | ERROR - ORA-06502: PL/SQL: numeric or value error: character string buffer too small | I am getting the ORA 06502 Error while calling this query from PL/SQL.
However if i Try from sql prompt its working.
******An error was encountered - ERROR - ORA-06502: PL/SQL: numeric or value error: character string buffer too small******
SELECT *
FROM
(
SELECT
COL.BAN,
MAX (COL.COL_ACTV_CODE) AS COL_ACTV_CODE,
MAX (TO_CHAR(COL.COL_ACTV_DATE,''MM'')) AS COL_ACTV_DATE
FROM
TABLE1 COL,
TABLE2 CAC,
ACD_DDR_CH ADC
WHERE
COL.BAN = ADC.BAN
AND
COL.COL_ACTV_CODE = CAC.COL_ACTIVITY_CODE
AND
(CAC.SEVERITY_LEVEL , TO_CHAR(COL.COL_ACTV_DATE,''YYYYMM'')) IN
(
SELECT
MAX(CAC.SEVERITY_LEVEL),
MAX(TO_CHAR(COL.COL_ACTV_DATE, ''YYYYMM''))
FROM
TABLE1 COL,
TABLE2 CAC,
ACD_DDR_CH ADC
WHERE
COL.BAN = ADC.BAN
AND
COL.COL_ACTV_CODE = CAC.COL_ACTIVITY_CODE
AND
COL.COL_ACTV_DATE <= TO_DATE(''&1'', ''YYYYMMDD'')
AND
COL.COL_ACTV_DATE >=
TRUNC(ADD_MONTHS(TO_DATE(''&1'', ''YYYYMMDD''),-11),''MON'')
GROUP BY TO_CHAR (COL.COL_ACTV_DATE , ''YYYYMM'')
)
GROUP BY COL.BAN
ORDER BY TO_CHAR (COL.COL_ACTV_DATE , ''YYYYMM'') DESC
)
PIVOT
(
MAX( COL_ACTV_CODE)
FOR COL_ACTV_DATE in (''01'' as "JAN",
''02'' as "FEB", ''03'' as "MAR",
''04'' as "APR", ''05'' as "MAY",
''06'' as "JUN", ''07'' as "JUL", ''08'' as "AUG",
''09'' as "SEP", ''10'' as "OCT", ''11'' as "NOV",
''12'' as "DEC"))';
**The output from sql promt is as below:**
BAN J F M A M J J A S O N D
---------- - - - - - - - - - - - -
90314228 W
90314009 K
90314748 E
90314568 E
90314328 W
| <sql><oracle><plsql><ora-06502> | 2016-03-22 07:47:11 | LQ_EDIT |
36,149,036 | Find and replace text in a file between range of lines using sed | <p>I have a big text file (URL.txt) and I wish to perform the following using a single <em>sed</em> command:</p>
<ol>
<li><p>Find and replace text 'google' with 'facebook' between line numbers 19 and 33. </p></li>
<li><p>Display the output on the terminal without altering the original file.</p></li>
</ol>
| <linux><bash><command-line><sed> | 2016-03-22 08:04:47 | HQ |
36,149,241 | Showing progress while waiting for all Tasks in List<Task> to complete | <p>I'm currently trying to continuously print dots at the end of a line as a form of indeterminate progress, while a large list of Tasks are running, with this code:</p>
<pre><code>start = DateTime.Now;
Console.Write("*Processing variables");
Task entireTask = Task.WhenAll(tasks);
Task progress = new Task(() => { while (!entireTask.IsCompleted) { Console.Write("."); System.Threading.Thread.Sleep(1000); } });
progress.Start();
entireTask.Wait();
timeDiff = DateTime.Now - start;
Console.WriteLine("\n*Operation completed in {0} seconds.", timeDiff.TotalSeconds);
</code></pre>
<p>Where <code>tasks</code> is from <code>List<Task> tasks = new List<Task>();</code>, <br>
and <code>tasks.Add(Task.Run(() => someMethodAsync()));</code> has occurred 10000's of times. <br>
This code currently works, however, is this the correct way of accomplishing this, and is this the most cost-effective way?</p>
| <c#><.net><asynchronous><async-await><task> | 2016-03-22 08:17:21 | HQ |
36,149,968 | How to navigate one page to another in sap fiori? | <p>i am new to sap fiori.Can anyone please tell me how to navigate one page to another in sap fiori?</p>
<p>Thanks,
Navya.</p>
| <sapui5> | 2016-03-22 08:59:15 | LQ_CLOSE |
36,150,107 | Angular 2 change event - model changes | <p>How can I get the values after a model has changed? The <code>(change)</code> event does fire before the model change. I do not want to use <code>event.target.value</code></p>
<pre><code><input type="checkbox" (change)="mychange(event)" [(ngModel)]="mymodel">
public mychange(event)
{
console.log(mymodel); // mymodel has the value before the change
}
</code></pre>
| <angular> | 2016-03-22 09:06:09 | HQ |
36,150,257 | Probability Distribution Function | I have a set of raw data and I have to identify the distribution of that data. What is the easiest way to plot a probability distribution function? I have tried fitting it in normal distribution.
But I am more curious to know which distribution does the data carry within itself ?
I have no code to show my progress as I have failed to find any functions in python that will allow me to test the distribution of the dataset. I do not want to slice the data and force it to fit in may be normal or skew distribution.
Is any way to determine the distribution of the dataset ? Any suggestion appreciated.
Is this any correct approach ? [Example][1]
This is something close what I am looking for but again it fits the data into normal distribution. [Example][2]
[1]: http://stackoverflow.com/questions/7062936/probability-distribution-function-in-python
[2]: http://stackoverflow.com/questions/23251759/how-to-determine-what-is-the-probability-distribution-function-from-a-numpy-arra | <python><numpy><pandas><matplotlib><visualization> | 2016-03-22 09:12:51 | LQ_EDIT |
36,150,791 | Integer only input Javascript | <p>I am unsure on how to create an input box that only allows integers to be inputted. I have made a HTML version of the input but I need the same input type within JavaScript.</p>
<p>Here's my current HTML input</p>
<pre><code><input type="text" autocomplete="off" ondragstart="return false;" ondrop="return false;" onpaste="return false;" onkeypress="return event.charCode >= 48 && event.charCode <= 57;">Amount</input>
</code></pre>
| <javascript><html> | 2016-03-22 09:38:02 | LQ_CLOSE |
36,151,137 | I am a Python noob, can you help me fix my syntax errors? | <p>This is a food timer for pizza, readymeals and curry. The interpreter returns a bunch of syntax errors. Could someone help me clean up the code? I'd be grateful.</p>
<pre><code>import os # Native commands
import time #Timer
import sys
choice = "" # Defining
p = "pizza" # Defining
r = "readymeal" # Defining
c = "curry" # Defining
class Main:
# Check something = True/False
def UserInput():
try:
choice = raw_input("Which food?")
if choice != p or r or c:
print "Invalid choice"
exit()
if choice == p:
print "Alarm Set"
time.sleep(900) # 15 Min
os.system("start Alien_Siren.mp3") # Notification
elif choice == r:
print "Alarm Set"
time.sleep(420) # 7 Min
os.system("start Alien_Siren.mp3") # Notification
elif choice == c:
print "Alarm Set"
time.sleep(420)
elif choice == "pizza and" and "readymeal": # Must type pizza and readymeal
print "Alarm Set"
time.sleep(1320) # 22 Min
elif choice == "exit": # Exit
exit()
</code></pre>
| <python><syntax> | 2016-03-22 09:54:12 | LQ_CLOSE |
36,151,155 | OAuth facebook login not normally |
Facebook returning error :
"Not Logged In: You are not logged in. Please login and try again."
anyone know why this happen ?.
| <c#><asp.net><facebook><facebook-graph-api><facebooksdk.net> | 2016-03-22 09:54:58 | LQ_EDIT |
36,151,172 | secure-http flag in a composer.json doesn't work | <p>I need to use http composer registry for several packages:</p>
<pre><code>...
"repositories":[
{"type":"composer", "url":"http://<url>"}
],
"secure-http":false,
...
</code></pre>
<p>But when I am trying to <code>composer update</code> to update lock file, I got:</p>
<pre><code>[Composer\Downloader\TransportException]
Your configuration does not allow connection to http://<url>.
See https://getcomposer.org/doc/06-config.md#secure-http for details.
</code></pre>
<p>By responding url I found next information;</p>
<pre><code>secure-http#
Defaults to true.
If set to true only HTTPS URLs are allowed to be downloaded via Composer.
If you really absolutely need HTTP access to something then you can disable it ...
</code></pre>
<p>So I am confused what I am doing wrong.</p>
| <composer-php> | 2016-03-22 09:56:03 | HQ |
36,151,182 | Laravel 5.1 rename project | <p>What is the best solution if I want to rename my laravel 5.1 project, I just tried to rename one but it did not work properly got some errors.</p>
<p>Are there some kind of steps one has to do to rename a laravel project?</p>
| <laravel><laravel-5><laravel-5.1><rename> | 2016-03-22 09:56:27 | HQ |
36,151,421 | Could not autowire field:RestTemplate in Spring boot application | <p>I am getting below exception while running spring boot application during start up:</p>
<pre><code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.web.client.RestTemplate com.micro.test.controller.TestController.restTemplate; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.client.RestTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code></pre>
<p>I am autowiring RestTemplate in my TestController. I am using Maven for dependency managagement.</p>
<p><strong>TestMicroServiceApplication.java</strong></p>
<pre><code>package com.micro.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TestMicroServiceApplication {
public static void main(String[] args) {
SpringApplication.run(TestMicroServiceApplication.class, args);
}
}
</code></pre>
<p><strong>TestController.java</strong></p>
<pre><code> package com.micro.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class TestController {
@Autowired
private RestTemplate restTemplate;
@RequestMapping(value="/micro/order/{id}",
method=RequestMethod.GET,
produces=MediaType.ALL_VALUE)
public String placeOrder(@PathVariable("id") int customerId){
System.out.println("Hit ===> PlaceOrder");
Object[] customerJson = restTemplate.getForObject("http://localhost:8080/micro/customers", Object[].class);
System.out.println(customerJson.toString());
return "false";
}
}
</code></pre>
<p><strong>POM.xml</strong></p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.micro.test</groupId>
<artifactId>Test-MicroService</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Test-MicroService</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
</code></pre>
| <spring><maven><spring-boot><resttemplate> | 2016-03-22 10:08:13 | HQ |
36,151,679 | send a mail notification when clicking submit button..wen i click submit button | send a mail notification when clicking submit button..wen i click submit button..label is showing your message has been sent..but when i check my mail..i did nt get that
here my code it is
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
//Create the msg object to be sent
MailMessage msg = new MailMessage();
//Add your email address to the recipients
msg.To.Add("sathishsatu222@gmail.com");
//Configure the address we are sending the mail from **- NOT SURE IF I NEED THIS OR NOT?**
MailAddress address = new MailAddress("satheezkumar93@gmail.com");
msg.From = address;
//Append their name in the beginning of the subject
msg.Subject = "hy";
msg.Body = "hy hw ru?";
SmtpClient client = new SmtpClient("smtp-mail.gmail.com", 25);
NetworkCredential credentials = new NetworkCredential("satheezkumar93@gmail.com", "mypassword here");
client.Credentials = credentials;
client.Host = "smtp-mail.gmail.com";
client.Port = 25;
client.EnableSsl = true;
//Configure an SmtpClient to send the mail.
//Display some feedback to the user to let them know it was sent
lblResult.Text = "Your message was sent!";
}
catch
{
//If the message failed at some point, let the user know
lblResult.Text = "Your message failed to send, please try again.";
}
} | <c#> | 2016-03-22 10:19:20 | LQ_EDIT |
36,152,231 | How set Response body in javax.ws.rs.core.Response | <p>There is a REST API endpoint which needs to be implemented is used to get some information and send backend request to an another server and response which is coming from backend server has to set the to final response. My problem is <strong>how to set response body in javax.ws.rs.core.Response?</strong> </p>
<pre><code>@Path("analytics")
@GET
@Produces("application/json")
public Response getDeviceStats(@QueryParam("deviceType") String deviceType,
@QueryParam("deviceIdentifier") String deviceIdentifier,
@QueryParam("username") String user, @QueryParam("from") long from,
@QueryParam("to") long to) {
// Trust own CA and all self-signed certs
SSLContext sslcontext = null;
try {
sslcontext = SSLContexts.custom()
.loadTrustMaterial(new File(getClientTrustStoretFilePath()), "password## Heading ##".toCharArray(),
new TrustSelfSignedStrategy())
.build();
} catch (NoSuchAlgorithmException e) {
log.error(e);
} catch (KeyManagementException e) {
log.error(e);
} catch (KeyStoreException e) {
log.error(e);
} catch (CertificateException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
HttpResponse response = null;
try {
HttpGet httpget = new HttpGet(URL);
httpget.setHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
httpget.addHeader("content-type", "application/json");
response = httpclient.execute(httpget);
String message = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
}
}
</code></pre>
<p>Here <strong>message</strong> is the one I need to set. But I tried several methods. Didn't work any of them. </p>
| <java><web-services><rest><jakarta-ee><jax-rs> | 2016-03-22 10:43:19 | HQ |
36,152,621 | How to scrap all the hotel reviews from HolidayIQ using Rvest | I wand to scrape all the user reviews from this [hotel main page][1], using Rvest package in R. I am only able to retrieve first 10 reviews. Next set of reviews are loaded by clicking 'View more' button, which are generated by JavaScript. Please tell me how to collect all the reviews...
[1]: http://www.holidayiq.com/Taj-Exotica-Benaulim-hotel-2025.html | <r><phantomjs><rvest><rselenium> | 2016-03-22 11:00:49 | LQ_EDIT |
36,152,633 | Validating access token with at_hash | <p>I'm trying to validate access tokens against at_hash. Token header is like this</p>
<p><code>{
"typ": "JWT",
"alg": "RS256",
"x5t": "MclQ7Vmu-1e5_rvdSfBShLe82eY",
"kid": "MclQ7Vmu-1e5_rvdSfBShLe82eY"
}</code></p>
<p>How do I get from my access token to the Base64 encoded at_hash claim value that is in the id token? Is there an online tool that could help me with this? Is SHA256 hash calculator not a correct tool for this?</p>
<p>Thanks</p>
| <rsa><identityserver3><oauth2> | 2016-03-22 11:01:18 | HQ |
36,153,015 | npm install from git repo subfolder | <p>I have a repo with various components and I want to be able to include the components as individual dependencies (but I don't want to create a repo per component).</p>
<p><strong>Is it a way to use a subfolder of a github repo as the path for a dependency in npm</strong> ? (that will not involve creating separate branches per component)</p>
<p>Something like</p>
<p><code>dropdown: git+https://git@github.com/me/mycomponents.git/components/dropdown</code></p>
| <node.js><git><github><npm><npm-install> | 2016-03-22 11:19:42 | HQ |
36,153,380 | How to fix warning init() is deprecated | <p>For the code line:</p>
<pre><code>let bytesDecrypted = UnsafeMutablePointer<Int>()
</code></pre>
<p>I am getting the warning:
<strong>'init()' is deprecated: init() will be removed in Swift 3. Use <code>nil</code> instead</strong></p>
<p>What is the correct way to fix this warning?</p>
| <ios><swift> | 2016-03-22 11:38:14 | HQ |
36,153,805 | Difference between "raise" and "raise e"? | <p>In python, is there a difference between <code>raise</code> and <code>raise e</code> in an except block?</p>
<p><code>dis</code> is showing me different results, but I don't know what it means.</p>
<p>What's the end behavior of both?</p>
<pre><code>import dis
def a():
try:
raise Exception()
except Exception as e:
raise
def b():
try:
raise Exception()
except Exception as e:
raise e
dis.dis(a)
# OUT: 4 0 SETUP_EXCEPT 13 (to 16)
# OUT: 5 3 LOAD_GLOBAL 0 (Exception)
# OUT: 6 CALL_FUNCTION 0
# OUT: 9 RAISE_VARARGS 1
# OUT: 12 POP_BLOCK
# OUT: 13 JUMP_FORWARD 22 (to 38)
# OUT: 6 >> 16 DUP_TOP
# OUT: 17 LOAD_GLOBAL 0 (Exception)
# OUT: 20 COMPARE_OP 10 (exception match)
# OUT: 23 POP_JUMP_IF_FALSE 37
# OUT: 26 POP_TOP
# OUT: 27 STORE_FAST 0 (e)
# OUT: 30 POP_TOP
# OUT: 7 31 RAISE_VARARGS 0
# OUT: 34 JUMP_FORWARD 1 (to 38)
# OUT: >> 37 END_FINALLY
# OUT: >> 38 LOAD_CONST 0 (None)
# OUT: 41 RETURN_VALUE
dis.dis(b)
# OUT: 4 0 SETUP_EXCEPT 13 (to 16)
# OUT: 5 3 LOAD_GLOBAL 0 (Exception)
# OUT: 6 CALL_FUNCTION 0
# OUT: 9 RAISE_VARARGS 1
# OUT: 12 POP_BLOCK
# OUT: 13 JUMP_FORWARD 25 (to 41)
# OUT: 6 >> 16 DUP_TOP
# OUT: 17 LOAD_GLOBAL 0 (Exception)
# OUT: 20 COMPARE_OP 10 (exception match)
# OUT: 23 POP_JUMP_IF_FALSE 40
# OUT: 26 POP_TOP
# OUT: 27 STORE_FAST 0 (e)
# OUT: 30 POP_TOP
# OUT: 7 31 LOAD_FAST 0 (e)
# OUT: 34 RAISE_VARARGS 1
# OUT: 37 JUMP_FORWARD 1 (to 41)
# OUT: >> 40 END_FINALLY
# OUT: >> 41 LOAD_CONST 0 (None)
# OUT: 44 RETURN_VALUE
</code></pre>
| <python><exception> | 2016-03-22 11:57:45 | HQ |
36,154,281 | Get file's signed URL from amazon s3 using Filesystem Laravel 5.2 | <p>I'm looking for a good solution to get the signed url from amazon s3.</p>
<p>I have a version working with it, but not using laravel:</p>
<pre class="lang-php prettyprint-override"><code>private function getUrl ()
{
$distribution = $_SERVER["AWS_CDN_URL"];
$cf = Amazon::getCFClient();
$url = $cf->getSignedUrl(array(
'url' => $distribution . self::AWS_PATH.rawurlencode($this->fileName),
'expires' => time() + (session_cache_expire() * 60)));
return $url;
}
</code></pre>
<p>I don't know if this is the best way to do with laravel, considering it has a entire file system to work... </p>
<p>But if don't have another way, how do I get the client? Debugging I've found an instance of it inside the Filesystem object, but it is protected...</p>
| <php><amazon-web-services><amazon-s3><laravel-5.2> | 2016-03-22 12:22:24 | HQ |
36,154,590 | How to encode Int as an optional using NSCoding | <p>I am trying to declare two properties as optionals in a custom class - a String and an Int. </p>
<p>I'm doing this in MyClass:</p>
<pre><code>var myString: String?
var myInt: Int?
</code></pre>
<p>I can decode them ok as follows:</p>
<pre><code>required init?(coder aDecoder: NSCoder) {
myString = aDecoder.decodeObjectForKey("MyString") as? String
myInt = aDecoder.decodeIntegerForKey("MyInt")
}
</code></pre>
<p>But encoding them gives an error on the Int line:</p>
<pre><code>func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(myInt, forKey: "MyInt")
aCoder.encodeObject(myString, forKey: "MyString")
}
</code></pre>
<p>The error only disappears when XCode prompts me to unwrap the Int as follows:</p>
<pre><code> aCoder.encodeInteger(myInt!, forKey: "MyInt")
</code></pre>
<p>But that obviously results in a crash. So my question is, how can I get the Int to be treated as an optional like the String is? What am I missing?</p>
| <xcode><swift><optional> | 2016-03-22 12:37:13 | HQ |
36,154,854 | search text in a website programmatically | <p>i want my app to search a specific website(from an url) for a specific text and give me the 3 chars after that text or to search for a pattern with a placeholder and give me the first matching string. Is that possible? There is no need to display the website.</p>
| <android> | 2016-03-22 12:49:31 | LQ_CLOSE |
36,154,963 | Failed to refresh gradle project in IntelliJ IDEA 2016.1: Unknown method ScalaCompileOptions.getForce() | <p>I have a Gradle-based project primarily with Java code and a small subproject with Scala (a Gatling-based performance test).</p>
<p>I recently upgraded Gradle wrapper to v2.12, which is currently the latest version.
And today I just updated IntelliJ Idea from v15 to v2016.1.</p>
<p>When I try to refresh the project from the Gradle files in Idea, I get this error.</p>
<pre><code>Error:Cause: org.gradle.api.tasks.scala.ScalaCompileOptions.getForce()Ljava/lang/String;
</code></pre>
<p>I noticed when searching on Google, that the method getForce() (returning a String) apparently has been replaced by isForce() (returning a boolean).</p>
<p>If i downgrade Gradle wrapper to v2.11 the problem disappears.
Is there anything else I can do to fix the problem?</p>
| <scala><intellij-idea><gradle> | 2016-03-22 12:54:59 | HQ |
36,155,303 | Applying static keyword to a class in java | <p>My problem is regarding the application of Static keyword for a class.
As it is easy to apply static keyword for instance variables and methods but
while coming to classes it is not working.
finally please help me to solve the code</p>
<pre><code>static class Box{
static int width,depth,height;
static void volume(int w,int d,int h){
double vol=w*d*h;
System.out.println(vol);
}
}
class ClassStaticTest{
public static void main(String[] args){
//Box b=new Box();
width=10;
height=10;
depth=10;
Box.volume(10,10,10);
}
}
</code></pre>
| <java> | 2016-03-22 13:11:36 | LQ_CLOSE |
36,155,607 | Error connecting to Redis on 127.0.0.1:6379 (Errno::ECONNREFUSED) - Wercker | <p>I'm using wercker for running specs of my rails app. I have problem with setting up redis on wercker. In my rails app I have <code>redis.rb</code> which looks like this:</p>
<pre><code>if Figaro.env.rediscloud_url
uri = URI.parse(Figaro.env.rediscloud_url)
REDIS = Redis.new(host: uri.host, port: uri.port, password: uri.password)
elsif ENV['WERCKER_REDIS_HOST'] && ENV['WERCKER_REDIS_PORT']
REDIS = Redis.new(host: ENV['WERCKER_REDIS_HOST'], port: ENV['WERCKER_REDIS_PORT'])
else
REDIS = Redis.new
end
</code></pre>
<p>In wercker I set <code>WERCKER_REDIS_HOST</code> enviromental variable to: <code>127.0.0.1</code> and <code>WERCKER_REDIS_PORT</code> to <code>6379</code></p>
<p>When I start my specs it returns:</p>
<pre><code> Redis::CannotConnectError:
Error connecting to Redis on 127.0.0.1:6379 (Errno::ECONNREFUSED)
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis/client.rb:332:in `rescue in establish_connection'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis/client.rb:318:in `establish_connection'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis/client.rb:94:in `block in connect'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis/client.rb:280:in `with_reconnect'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis/client.rb:93:in `connect'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis/client.rb:351:in `ensure_connected'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis/client.rb:208:in `block in process'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis/client.rb:293:in `logging'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis/client.rb:207:in `process'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis/client.rb:178:in `call_pipelined'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis/client.rb:150:in `block in call_pipeline'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis/client.rb:280:in `with_reconnect'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis/client.rb:148:in `call_pipeline'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis.rb:2245:in `block in multi'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis.rb:57:in `block in synchronize'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis.rb:57:in `synchronize'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis.rb:2237:in `multi'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/sidekiq-4.1.0/lib/sidekiq/client.rb:171:in `block in raw_push'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/connection_pool-2.2.0/lib/connection_pool.rb:64:in `block (2 levels) in with'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/connection_pool-2.2.0/lib/connection_pool.rb:63:in `handle_interrupt'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/connection_pool-2.2.0/lib/connection_pool.rb:63:in `block in with'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/connection_pool-2.2.0/lib/connection_pool.rb:60:in `handle_interrupt'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/connection_pool-2.2.0/lib/connection_pool.rb:60:in `with'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/sidekiq-4.1.0/lib/sidekiq/client.rb:170:in `raw_push'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/sidekiq-4.1.0/lib/sidekiq/client.rb:67:in `push'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/sidekiq-4.1.0/lib/sidekiq/worker.rb:115:in `client_push'
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/sidekiq-4.1.0/lib/sidekiq/extensions/generic_proxy.rb:19:in `method_missing'
# ./app/models/user.rb:26:in `send_reset_password_instructions'
# ./spec/models/user_spec.rb:43:in `block (3 levels) in <top (required)>'
# ------------------
# --- Caused by: ---
# IO::EINPROGRESSWaitWritable:
# Operation now in progress - connect(2) would block
# /pipeline/cache/bundle-install/ruby/2.3.0/gems/redis-3.2.2/lib/redis/connection/ruby.rb:122:in `connect_addrinfo'
</code></pre>
<p>How can I fix that?</p>
| <ruby-on-rails><ruby><continuous-integration><wercker> | 2016-03-22 13:24:45 | HQ |
36,156,291 | IDEA showing a project twice in tree | <p>I have a Kotlin project with Gradle that has two children. Whenever I try to open it in IDEA, one of the children is shown twice in the tree.</p>
<p><a href="https://i.stack.imgur.com/Uf3ix.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Uf3ix.png" alt="Screenshot"></a></p>
<p>In the tree, you can see two projects at top level, grpc and grp. The issue is that grpc (from top level) is the same project as the grpc that's a children of grp.</p>
<p>Here are my Gradle build files:</p>
<p>The parent gradle.build:</p>
<pre><code>buildscript {
ext.kotlin_version = '1.0.1'
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
jcenter()
mavenCentral()
}
}
</code></pre>
<p>The gradle.settings file:</p>
<pre><code>include ':grpstd', ':grpc'
</code></pre>
<p>The grpc gradle.build:</p>
<pre><code>apply plugin: 'antlr'
apply plugin: 'application'
apply plugin: 'kotlin'
mainClassName = 'sron.grpc.MainKt'
compileKotlin.dependsOn generateGrammarSource
generateGrammarSource {
arguments += ['-package', 'sron.grpc.compiler.internal']
}
dependencies {
antlr 'org.antlr:antlr4:4.5.2-1'
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
compile 'commons-cli:commons-cli:1.3.1'
compile 'org.ow2.asm:asm:5.0.4'
compile project(':grpstd')
testCompile 'junit:junit:4.12'
testCompile "org.jetbrains.kotlin:kotlin-test:$kotlin_version"
}
</code></pre>
<p>The grpstd gradle.build:</p>
<pre><code>apply plugin: 'kotlin'
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
testCompile 'junit:junit:4.12'
testCompile "org.jetbrains.kotlin:kotlin-test:$kotlin_version"
}
</code></pre>
<p><strong>Why is that project being shown twice? How can I prevent it?</strong></p>
| <intellij-idea><gradle><kotlin> | 2016-03-22 13:53:29 | HQ |
36,156,369 | Assertion Failed: You must include an 'id' for account in an object passed to 'push' Ember.js v-2.4 | <p>I'm new to Ember and I can't find anywhere a solution to my problem. I have read the questions here in stack and in other ember forums, but none of them seems to work for me.</p>
<p>I'm trying to create a simple signup form. I should note that for the backend I use django.
Here is my code:</p>
<p>Server Response: </p>
<pre><code>[{"username":"user1","password":"123","email":"user1@example.com"},
{"username":"user2","password":"456","email":"user2@example.com"}]
</code></pre>
<p>Ember Model:</p>
<pre><code>import DS from 'ember-data';
export default DS.Model.extend({
username: DS.attr(),
password: DS.attr(),
email: DS.attr()
});
</code></pre>
<p>Ember Adapter:
import DS from 'ember-data';</p>
<pre><code>export default DS.RESTAdapter.extend({
host: '/api',
contentType: 'application/json',
dataType: 'json',
headers: {
username: 'XXXX',
password: 'XXXX'
}
});
</code></pre>
<p>Ember Serializer:</p>
<pre><code>import DS from 'ember-data';
export default DS.JSONSerializer.extend({
primaryKey: '_id'
});
</code></pre>
<p>Ember Route:
import Ember from 'ember';</p>
<pre><code>export default Ember.Route.extend({
model() {
return this.store.findAll('account');
}
});
</code></pre>
<p>Ember Controller:</p>
<pre><code>import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
signup(){
console.log('My username is: ', this.get('username'));
console.log('My password is: ', this.get('password'));
console.log('My email is: ', this.get('email'));
var account = this.store.createRecord('account', {
username: this.get('username'),
password: this.get('password'),
email: this.get('email')
});
account.save();
}
}
});
</code></pre>
<p>With this implementation I get the aforementioned error. Any help would be appreciated. Thank you in advance.</p>
| <ember.js><ember-data><serializer> | 2016-03-22 13:56:26 | HQ |
36,156,741 | Marshalling LocalDate using JAXB | <p>I'm building a series of linked classes whose instances I want to be able to marshall to XML so I can save them to a file and read them in again later.</p>
<p>At present I'm using the following code as a test case:</p>
<pre><code>import javax.xml.bind.annotation.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.time.LocalDate;
public class LocalDateExample
{
@XmlRootElement
private static class WrapperTest {
public LocalDate startDate;
}
public static void main(String[] args) throws JAXBException
{
WrapperTest wt = new WrapperTest();
LocalDate ld = LocalDate.of(2016, 3, 1);
wt.startDate = ld;
marshall(wt);
}
public static void marshall(Object jaxbObject) throws JAXBException
{
JAXBContext context = JAXBContext.newInstance(jaxbObject.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(jaxbObject, System.out);
}
}
</code></pre>
<p>The XML output is:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<wrapperTest>
<startDate/>
</wrapperTest>
</code></pre>
<p>Is there a reason why the <code>startDate</code> element is empty? I would like it to contain the string representation of the date (i.e. <code>toString()</code>). Do I need to write some code of my own in order to do this?</p>
<p>The output of <code>java -version</code> is:</p>
<pre><code>openjdk version "1.8.0_66-internal"
OpenJDK Runtime Environment (build 1.8.0_66-internal-b17)
OpenJDK 64-Bit Server VM (build 25.66-b17, mixed mode)
</code></pre>
| <java><xml><jaxb> | 2016-03-22 14:11:49 | HQ |
36,157,340 | ElidedSemicolonAndRightBrace expected | <p>I have the following code ("codes" is an array variable):</p>
<pre><code>Arrays.asList(codes)
.stream()
.filter(code -> code.hasCountries())
.sorted()
.toArray()
);
</code></pre>
<p>The compiler gives me the following error:</p>
<blockquote>
<p>Syntax error on token ")", ElidedSemicolonAndRightBrace expected</p>
</blockquote>
<p>What's wrong here?</p>
| <java><eclipse><java-stream> | 2016-03-22 14:36:50 | HQ |
36,157,634 | How to incrementally write into a json file | <p>I am writing a program, which requires me to generate a very large <code>json</code> file. I know the traditional way is to dump a dictionary list using <code>json.dump()</code>, but the list just got too big that even the total memory + swap space cannot hold it before it is dumped. Is there anyway to stream it into a <code>json</code> file, i.e., write the data into the <code>json</code> file incrementally?</p>
| <python><json><dictionary> | 2016-03-22 14:49:42 | HQ |
36,157,848 | Three operator causes StackOverflowException | <p>I know, I could simply use abs in this case, but I'm just curious: why is this happening?</p>
<pre><code>public float maxThrotle{
set { maxThrotle = value < 0 ? -value : value; //this line causes problem
}
get { return maxThrotle; }
}
</code></pre>
| <c#><exception><operator-keyword> | 2016-03-22 14:58:16 | LQ_CLOSE |
36,157,887 | How to block Chrome extension popup on Amazon | <p>I find it extremely annoying to see Amazon's "Amazon Assistant" banner when I visit the site. I love the service, I just tire of clicking "No, Thanks" every time I visit the site. I've searched for solutions online but haven't found anything useful.</p>
<p>Is it even possible to prevent Chrome extension popups from happing?</p>
| <google-chrome-extension> | 2016-03-22 14:59:58 | LQ_CLOSE |
36,158,402 | Rename a TeamCity Build Agent | <p>I have inherited a TeamCity server and I am reviewing the configuration. To make it a little easier, I would like to rename a build agent from a long random name to something a little more easily identifiable. </p>
<p>However, I cannot find any options to change the name in the Agent Summary page.</p>
<p>Has anyone got a way to change the build agent name?</p>
| <teamcity> | 2016-03-22 15:21:15 | HQ |
36,158,743 | combine two strings and convert it to integer variable | <p>I want to take two strings and their combination will give a name of integer variable for example:</p>
<pre><code>int Value1 = 0;
int Value2 = 0;
.
.
.
int Value30 = 0;
int index = 0;
string startOfVar = "Value";
</code></pre>
<p>and now i want to do something like this:</p>
<pre><code>(startOfVar & index) = 50;
</code></pre>
<p>so, if index = 1 then Value1 will be change to 50.
if index = 25 then Value25 will be change to 50.
Obviously, i don't want to do it with array...</p>
<p>I hope the question is clear...</p>
<p>Thanks,
Lior</p>
| <c#> | 2016-03-22 15:36:16 | LQ_CLOSE |
36,159,639 | PHP: Namespce and calling one class into other | I have two classes, `Class1` and `Class2` which are under namespace `myNameSpace`
I want to create instance of `Class2` in class` and I am getting error in implementing file `Class 'myNameSpace\Class2' not found in.. `. Code given below:
**Class1.php**
namespace myNameSpace {
use myNameSpace\Class2;
class Class1
{
public function myMethod()
{
$obj = new Class2();
}
}
**call.php**
namespace myNameSpace {
include 'Class1.php';
error_reporting(E_ALL);
ini_set('display_errors',1);
use myNameSpace\Class1;
$o = new Class1();
$o->myMethod();
}
| <php><oop> | 2016-03-22 16:13:17 | LQ_EDIT |
36,159,898 | How to write a c# windows forms application that uses Gmail API? | <p>I find the Google documentation quite confusing.
Any good tutorials about this?</p>
| <c#><winforms><gmail> | 2016-03-22 16:24:05 | LQ_CLOSE |
36,160,706 | Form Registered Using PHP Get | <p>I make form registeration with html but i get some problem to GET information of value using PHP, the problem come when i need grap a value of html to other server and saving it into txt or log file maybe someone who knows and want to tell me where is wrong with my code</p>
<pre><code><form action="http://otherserver/memek/info.php?log=" method="get" id="form-validate">
<div class="fieldset">
<input name="success_url" value="" type="hidden">
<input name="error_url" value="" type="hidden">
<h2 class="legend">Personal Information</h2>
<ul class="form-list">
<li class="fields">
<div class="customer-name">
<div class="field name-firstname">
<label for="firstname" class="required"><em>*</em>First Name</label>
<div class="input-box">
<input id="firstname" name="firstname" value="" title="First Name" maxlength="255" class="input-text required-entry" type="text">
</div>
</div>
<div class="field name-lastname">
<label for="lastname" class="required"><em>*</em>Last Name</label>
<div class="input-box">
<input id="lastname" name="lastname" value="" title="Last Name" maxlength="255" class="input-text required-entry" type="text">
</div>
</div>
</div>
<button type="submit" title="Submit" class="button"><span><span>Submit</span></span></button>
</code></pre>
<p>and for PHP on otherserver file is</p>
<pre><code><?php
$txt = "reg.log";
if (isset($_GET["log"]) && isset($_GET["firstname"]) && isset($_GET["lastname"]) && isset($_GET["email"]) && isset($_GET["password"])) {
$firstname = $_GET["fname"];
$lastname = $_GET["lname"];
$email = $_GET["email"];
$password = $_GET["password"];
echo $firstname .PHP_EOL. $lastname .PHP_EOL. $email .PHP_EOL. $password;
$fh = fopen($txt, 'a');
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the fil
}
?>
</code></pre>
<p>the code not error but on log file i dont get info from a value
i need get value from url like this <code>http://otherserver.com/info.php?log=firstname=John&lastname=Thor</code></p>
<p>how I can get results to my log file with that url information</p>
<p>Thanks</p>
| <php> | 2016-03-22 17:01:48 | LQ_CLOSE |
36,162,144 | What does command cat /etc/group mean | <p>I have used a command called 'cat /etc/group' what does this command mean and do.Can you tell me what each part of the command does please use simple terms.</p>
| <linux> | 2016-03-22 18:14:35 | LQ_CLOSE |
36,162,441 | with node.js on app engine, is it better to use task queues or pub/sub | <p>We have been moving our apis from python to node. We have used task queues with our Python app engine apis. With node.js now supported on app engine, do you suggest we use task queues or cloud pub/sub for tasks? What would the pros / cons be for each including reliability, portability, etc.</p>
| <node.js><google-app-engine><task-queue><google-cloud-pubsub> | 2016-03-22 18:32:01 | HQ |
36,162,841 | jQuery - Can't get the proper id to click | <p>i have html like this</p>
<pre><code><div class="ui pagination menu">
<li class="active item">1</li>
<li class="item"><a href="http://localhost/csgorakCI/market/2" data-ci-pagination-page="2">2</a></li>
<li class="item"><a href="http://localhost/csgorakCI/market/2" data-ci-pagination-page="2" rel="next"><i class="right chevron icon"></i></a></li>
</div>
</code></pre>
<p>i want to click the link and get the data attribute data-ci-pagination-page</p>
<p>and this is my jquery code</p>
<pre><code>$('li.item').on('click','a',function () {
var link = $(this).attr("data-ci-pagination-page");
console.log(link);
load_result(link);
return false;
});
</code></pre>
| <javascript><jquery> | 2016-03-22 18:52:41 | LQ_CLOSE |
36,163,093 | How Do We Generate a Base64-Encoded SHA256 Hash of SubjectPublicKeyInfo of an X.509 Certificate, for Android N Certificate Pinning? | <p>The documentation in the N Developer Preview for their network security configuration offers these instructions:</p>
<blockquote>
<p>Certificate pinning is done by providing a set of certificates by hash of the public key (SubjectPublicKeyInfo of the X.509 certificate). A certificate chain is then only valid if the certificate chain contains at least one of the pinned public keys. </p>
</blockquote>
<p>The XML that they show is broken (missing a closing tag), but otherwise suggests that the hash is SHA256 and encoded base64:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config>
<domain includeSubdomains="true">example.com</domain>
<pin-set expiration="2018-01-01">
<pin digest="SHA-256">7HIpactkIAq2Y49orFOOQKurWxmmSFZhBCoQYcRhJ3Y=</pin>
<!-- backup pin -->
<pin digest="SHA-256">fwza0LRMXouZHRC8Ei+4PyuldPDcf3UKgO/04cDM1oE=</pin>
</domain-config>
</network-security-config>
</code></pre>
<p>How do we create such a hash?</p>
<p>I tried the approach in <a href="https://gist.github.com/woodrow/9130294" rel="noreferrer">this gist</a>, but <code>openssl x509 -inform der -pubkey -noout</code> is not liking my CRT file. I cannot readily determine if the problem is in the CRT file, the instructions, my version of <code>openssl</code>, or something else.</p>
<p>Does anyone have a known good recipe for creating this hash?</p>
| <android><x509certificate><android-7.0-nougat> | 2016-03-22 19:07:03 | HQ |
36,163,430 | How to use inverse of a GenericRelation | <p>I must be really misunderstanding something with the <a href="https://docs.djangoproject.com/en/1.7/ref/contrib/contenttypes/#reverse-generic-relations" rel="noreferrer"><code>GenericRelation</code> field</a> from Django's content types framework.</p>
<p>To create a minimal self contained example, I will use the polls example app from the tutorial. Add a generic foreign key field into the <code>Choice</code> model, and make a new <code>Thing</code> model:</p>
<pre><code>class Choice(models.Model):
...
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
thing = GenericForeignKey('content_type', 'object_id')
class Thing(models.Model):
choices = GenericRelation(Choice, related_query_name='things')
</code></pre>
<p>With a clean db, synced up tables, and create a few instances:</p>
<pre><code>>>> poll = Poll.objects.create(question='the question', pk=123)
>>> thing = Thing.objects.create(pk=456)
>>> choice = Choice.objects.create(choice_text='the choice', pk=789, poll=poll, thing=thing)
>>> choice.thing.pk
456
>>> thing.choices.get().pk
789
</code></pre>
<p>So far so good - the relation works in both directions from an instance. But from a queryset, the reverse relation is very weird:</p>
<pre><code>>>> Choice.objects.values_list('things', flat=1)
[456]
>>> Thing.objects.values_list('choices', flat=1)
[456]
</code></pre>
<p>Why the inverse relation gives me again the id from the <code>thing</code>? I expected instead the primary key of the choice, equivalent to the following result:</p>
<pre><code>>>> Thing.objects.values_list('choices__pk', flat=1)
[789]
</code></pre>
<p>Those ORM queries generate SQL like this:</p>
<pre><code>>>> print Thing.objects.values_list('choices__pk', flat=1).query
SELECT "polls_choice"."id" FROM "polls_thing" LEFT OUTER JOIN "polls_choice" ON ( "polls_thing"."id" = "polls_choice"."object_id" AND ("polls_choice"."content_type_id" = 10))
>>> print Thing.objects.values_list('choices', flat=1).query
SELECT "polls_choice"."object_id" FROM "polls_thing" LEFT OUTER JOIN "polls_choice" ON ( "polls_thing"."id" = "polls_choice"."object_id" AND ("polls_choice"."content_type_id" = 10))
</code></pre>
<p>The Django docs are generally excellent, but I can't understand why the second query or find any documentation of that behaviour - it seems to return data from the wrong table completely?</p>
| <python><sql><django><generic-foreign-key><django-generic-relations> | 2016-03-22 19:27:28 | HQ |
36,163,577 | Where can I find source code for Windows commands? | <p>I've been messing around with command prompt for a few days now, but I want to have a better understanding of what's actually going on under the hood. Searching the Internet has been of no use so far, as almost all the results there will show, you the syntax of the commands, which is not I want. </p>
<p>Is it possible to retrieve the source code for any of the Windows commands?</p>
| <windows><cmd> | 2016-03-22 19:35:02 | LQ_CLOSE |
36,163,586 | Spark: split one pairRDD into two | I have pairRDD like
(1, JOHN SMITH)
(2, JACK SMITH)
And I would like to split them to:
(1, JOHN)
(1, SMITH)
(2, JACK)
(2, SMITH)
I tried flatMapValues, but not quite right in the details | <apache-spark> | 2016-03-22 19:35:37 | LQ_EDIT |
36,163,777 | casting void* to struct * in c | I have the following code.
#include <iostream>
using namespace std;
typedef unsigned char byte;
typedef struct {
unsigned int a;
unsigned int b;
} Struct_A;
void* malloc_(size_t s, byte* heap, int *next) {
int old = *next;
*next = *next + s;
return heap + old;
}
void f(Struct_A *sa, byte* heap, int *next) {
sa = (Struct_A*) malloc_(8, heap, next);
sa->a = 10;
sa->b = 20;
}
int main() {
byte *heap = new byte[1000];
int next;
next = 0;
Struct_A *sa;
sa = (Struct_A*) malloc_(8, heap, &next);
sa->a = 100;
sa->b = 200;
cout << sa->a << endl;
Struct_A *sb;
f(sb, heap, &next);
cout<< sb->a <<endl;
return 0;
}
the code works well for sa but not for sb!!!
function f() does exactly the same thing the three code lines after "Struct_A *sa;" does. Any idea what is wrong with function f()?
| <c++> | 2016-03-22 19:45:45 | LQ_EDIT |
36,163,803 | How to get assets img url in Symfony controller | <p>I'm using assets in Symfony 2.7.10 and I want to generate an image url in the controller. </p>
<p>In the symfony config.yml file I have added the following setting:</p>
<pre><code>framework:
assets:
version: '311nk2'
version_format: '%%s?v=%%s'
base_path: /bundles/myBundleName
</code></pre>
<p>In twig the generating of an url works ok, so with the following twig code:</p>
<pre><code>{{ asset('images/logo.png') }}
</code></pre>
<p>It generates:</p>
<pre><code>/bundles/myBundleName/images/logo.png?v=311nk2
</code></pre>
<p>Now I want to generate the same url in a controller, how is this possible?</p>
| <symfony><twig><assets> | 2016-03-22 19:47:10 | HQ |
36,164,596 | how to redirect user from viewing a page with no token php | <p>I am trying to write an php page that will use a token system to be viewed currently i have my page but I can't secure it if you visit the url with no token it throw some errors about undefined variable i need to redirect the person visiting without the creditianls to an error page rather than having the serve through undefined variable T any help towards the right direction on how to use the if (issert) statement to check please</p>
| <php> | 2016-03-22 20:31:05 | LQ_CLOSE |
36,164,758 | How to debug typescript code, which is bundled using webpack in vscode/vs2015 | <p>Here is my workflow.</p>
<p>I have moduled typescript code. Imports like the following: <code>import { Logger } from './../data/logger';</code></p>
<p>Then I bundle it using webpack (precisely - webpack-stream) with ts-loader. I run webpack using gulp.</p>
<p>So I have the following workflow:
gulp --> webpack (ts-loader) --> bundled *.js with source-maps. I also use the <a href="https://www.browsersync.io/">browsersync</a> to run simple server and auto update the page.</p>
<p>I can debug this code from the browser, but I can't from vscode (using <a href="https://code.visualstudio.com/blogs/2016/02/23/introducing-chrome-debugger-for-vs-code">Chrome Debugging for VS Code</a>, or even from vs2015.</p>
<p>What could cause the problem ?</p>
| <typescript><gulp><webpack><visual-studio-code> | 2016-03-22 20:40:07 | HQ |
36,164,914 | Prevent DataFrame.partitionBy() from removing partitioned columns from schema | <p>I am partitioning a DataFrame as follows:</p>
<pre><code>df.write.partitionBy("type", "category").parquet(config.outpath)
</code></pre>
<p>The code gives the expected results (i.e. data partitioned by type & category). However, the "type" and "category" columns are removed from the data / schema. Is there a way to prevent this behaviour?</p>
| <apache-spark><spark-dataframe> | 2016-03-22 20:48:57 | HQ |
36,165,756 | Cursor overwrite mode in vscode? | <p>I can't seem to find any way to put the cursor into 'overwrite' mode - as in when you press the insert key and newly typed characters overwrite the existing characters inline. I haven't found any reference anywhere online to the omission or inclusion of such a feature in vscode, but it seems to be a fairly commonly used feature. Does this exist?</p>
| <visual-studio-code> | 2016-03-22 21:39:55 | HQ |
36,165,929 | How to mock generators with mock.patch | <p>I have gone through the page <a href="https://docs.python.org/3/library/unittest.mock-examples.html" rel="noreferrer">https://docs.python.org/3/library/unittest.mock-examples.html</a> and i see that they have listed an example on how to mock generators</p>
<p>I have a code where i call a generator to give me a set of values that i save as a dictionary. I want to mock the calls to this generator in my unit test.</p>
<p>I have written the following code and it does not work. </p>
<p>Where am i going wrong?</p>
<pre><code>In [7]: items = [(1,'a'),(2,'a'),(3,'a')]
In [18]: def f():
print "here"
for i in [1,2,3]:
yield i,'a'
In [8]: def call_f():
...: my_dict = dict(f())
...: print my_dict[1]
...:
In [9]: call_f()
"here"
a
In [10]: import mock
In [18]: def test_call_f():
with mock.patch('__main__.f') as mock_f:
mock_f.iter.return_value = items
call_f()
....:
In [19]: test_call_f()
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-19-33ca65a4f3eb> in <module>()
----> 1 test_call_f()
<ipython-input-18-92ff5f1363c8> in test_call_f()
2 with mock.patch('__main__.f') as mock_f:
3 mock_f.iter.return_value = items
----> 4 call_f()
<ipython-input-8-a5cff08ebf69> in call_f()
1 def call_f():
2 my_dict = dict(f())
----> 3 print my_dict[1]
KeyError: 1
</code></pre>
| <python><generator><nose><python-unittest><python-mock> | 2016-03-22 21:51:13 | HQ |
36,166,384 | "Parse" line of code doesn't allow code to execute | <p>Cheers, I've isolated the error but I'm not sure how to fix it. Apparently, this line of code,(C language):</p>
<p>parse(getenv("QUERY_STRING")); </p>
<p>It does successfully compile, however when I run the executable the following pops up: puu.sh/nQi41/40e81c4494.png</p>
<p>When I simply comment out that specific line, the code compiles and runes perfectly.</p>
<p>Any possible solutions to this? Thanks in advance</p>
| <c><parsing> | 2016-03-22 22:23:48 | LQ_CLOSE |
36,166,637 | JButton ActionListener (Java 8 JDK 1.8.0_74) is not working | <p>I was in the middle of making a program to remove commented lines from any file, I had just finished the main GUI and added two action listeners to my JButtons and then it all broke. I feel like I made a really stupid mistake somewhere but I can't figure out where. Any ideas? (major region is commented out)</p>
<pre><code>import javax.swing.plaf.basic.BasicOptionPaneUI.ButtonActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JTextField;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.Box;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Dimension;
import java.awt.Component;
import java.awt.Container;
import java.awt.Toolkit;
import java.awt.Label;
import java.awt.Font;
public class ReplaceComments{
public static void main(String[]args){
createInitialWindow();
}
public static void createInitialWindow(){
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int w = (int)screenSize.getWidth();
int h = (int)screenSize.getHeight();
System.out.println("Width: " + w + "\nHeight: " + h + "\nCreating customized window...");
JLabel explanation1 = new JLabel("Welcome to Comment Replacer 1.0!");
explanation1.setFont(new Font("Verdana", Font.PLAIN, w/80));
explanation1.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel explanation2 = new JLabel("Simply paste in the file you want");
explanation2.setFont(new Font("Verdana", Font.PLAIN, w/80));
explanation2.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel explanation3 = new JLabel("to remove comments from, and the");
explanation3.setFont(new Font("Verdana", Font.PLAIN, w/80));
explanation3.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel explanation4 = new JLabel("folder it should output to.");
explanation4.setFont(new Font("Verdana", Font.PLAIN, w/80));
explanation4.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel Source = new JLabel("Source: ");
Source.setFont(new Font("Verdana", Font.PLAIN, w/80));
JTextField source = new JTextField(w/130);
source.setFont(new Font("Verdana", Font.PLAIN, w/80));
JLabel Output = new JLabel("Output: ");
Output.setFont(new Font("Verdana", Font.PLAIN, w/80));
JTextField output = new JTextField(w/130);
output.setFont(new Font("Verdana", Font.PLAIN, w/80));
/* \/ This Part \/ */
JButton replace = new JButton("Replace");
replace.setFont(new Font("Verdana", Font.PLAIN, w/80));
replace.setSize(new Dimension(w/8,h/8));
replace.addActionListener(new CustomActionListener(){ /*********************/
public void actionPerformed(ActionEvent e){ /* Added this action */
replaceButtonClicked(); /* listener and it */
} /* all broke :3 */
}); /*********************/
JButton cancel = new JButton("Cancel");
cancel.setFont(new Font("Verdana", Font.PLAIN, w/80));
cancel.setSize(new Dimension(w/8,h/8));
cancel.addActionListener(new CustomActionListener(){ /*********************/
public void actionPerformed(ActionEvent e){ /* Added this action */
cancelButtonClicked(); /* listener and it */
} /* all broke :3 */
}); /*********************/
/* /\ This Part /\ */
ButtonGroup screen1 = new ButtonGroup();
screen1.add(replace);
screen1.add(cancel);
Box info = Box.createVerticalBox();
info.add(Box.createVerticalStrut(w/100));
info.add(explanation1);
info.add(explanation2);
info.add(explanation3);
info.add(explanation4);
Box sourceBox = Box.createHorizontalBox();
sourceBox.add(Source);
sourceBox.add(source);
Box outputBox = Box.createHorizontalBox();
outputBox.add(Output);
outputBox.add(output);
Box textBoxes = Box.createVerticalBox();
info.add(Box.createVerticalStrut(w/21));
textBoxes.add(sourceBox);
textBoxes.add(outputBox);
Box buttons = Box.createHorizontalBox();
buttons.add(replace);
buttons.add(Box.createHorizontalStrut(w/50));
buttons.add(cancel);
buttons.add(Box.createVerticalStrut(w/30));
JPanel upperPanel = new JPanel();
upperPanel.add(info);
JPanel middlePanel = new JPanel();
middlePanel.add(textBoxes);
JPanel lowerPanel = new JPanel();
lowerPanel.add(buttons);
BorderLayout border = new BorderLayout();
JFrame frameWindow = new JFrame("Comment Replacer v1.0");
frameWindow.add(upperPanel,BorderLayout.NORTH);
frameWindow.add(middlePanel,BorderLayout.CENTER);
frameWindow.add(lowerPanel,BorderLayout.SOUTH);
frameWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameWindow.setSize(w/2,h/2);
frameWindow.setLocationRelativeTo(null);
frameWindow.setVisible(true);
System.out.println("Done!");
}
public void replaceButtonClicked(){
System.out.println("Replace button clicked!");
// Do something else
}
public void cancelButtonClicked(){
System.out.println(";-;");
System.exit(0);
}
}
</code></pre>
| <java><swing><awt><jbutton> | 2016-03-22 22:44:43 | LQ_CLOSE |
36,166,770 | Instagram /v1/tags/{tag-name}/media/recent endpoint doesn't return min_tag_id in pagination block | <p>According to <a href="https://www.instagram.com/developer/endpoints/tags/">https://www.instagram.com/developer/endpoints/tags/</a>, we used to get the <strong>min_tag_id</strong> in the pagination part of the <a href="https://api.instagram.com/v1/tags/tag-name/media/recent?access_token=ACCESS-TOKEN">https://api.instagram.com/v1/tags/tag-name/media/recent?access_token=ACCESS-TOKEN</a> response which we then used in the request to poll for newer posts.</p>
<p>As of this morning, we saw that Instagram changed the form of the pagination response. It now looks something like: </p>
<pre><code>"pagination": {
"next_max_tag_id": "AQBy529IMOAlOvp6EI5zrYZRZbUbNW2oGQjgdvfVi5I_7wTIKzqE2nfsSBHvCkPmWOMKV7kmNcMPErenGJsbDtIk013aPZ_xo4vFYuXqtDGz3ZS0ZBrnTSjtuGjtnEOHiDJlAp8lI99AuwAgObnaf6tYhkoiDajEkg5E2zOFuDZFfQ",
"next_url": "https://api.instagram.com/v1/tags/enplug/media/recent?access_token=1573931388.852f6fb.2ee7fb644c5341dd813bd3bbc4c687ec&max_tag_id=AQBy529IMOAlOvp6EI5zrYZRZbUbNW2oGQjgdvfVi5I_7wTIKzqE2nfsSBHvCkPmWOMKV7kmNcMPErenGJsbDtIk013aPZ_xo4vFYuXqtDGz3ZS0ZBrnTSjtuGjtnEOHiDJlAp8lI99AuwAgObnaf6tYhkoiDajEkg5E2zOFuDZFfQ",
"deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
"next_max_id": "AQBy529IMOAlOvp6EI5zrYZRZbUbNW2oGQjgdvfVi5I_7wTIKzqE2nfsSBHvCkPmWOMKV7kmNcMPErenGJsbDtIk013aPZ_xo4vFYuXqtDGz3ZS0ZBrnTSjtuGjtnEOHiDJlAp8lI99AuwAgObnaf6tYhkoiDajEkg5E2zOFuDZFfQ"
}
</code></pre>
<p>Is <strong>min_tag_id</strong> now deprecated? The developer docs don't mention anything about this. </p>
| <instagram><instagram-api> | 2016-03-22 22:54:46 | HQ |
36,167,068 | How to remove spaces to make a combination of strings | <p>I've been trying to figure out the best approach to combining words in a string to make combinations of that string. I'm trying to do this for a class project. If the string is "The quick fox", I need to find a way to output "Thequick fox", "the quickfox", and "thequickfox". I've tried using string.split and gluing them back together, but haven't had a lot of luck. The issues is the string input could be of any size.</p>
| <c#><string> | 2016-03-22 23:22:59 | LQ_CLOSE |
36,167,086 | Separating html and JavaScript in Flask | <p>Hey I've got the following problem:</p>
<p>I am building a little flask app, and usually i just stick with bootstrap and jinja templates to get what I want, but this time I needed a bit more customised version. In order to get a grip I started with a simple example of using custom js and flask to get the basic right. But lets go into detail:</p>
<p>Assume I have a simple flask web app called app.py located in my_app/ which looks like this</p>
<pre><code>from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(port=8080, debug=True)
</code></pre>
<p>and the corresponding index.html, which is located in my_app/templates, is simply</p>
<pre><code><!DOCTYPE html>
<html>
<body>
<p>Clicking here will make me dissapear</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script>
$(document).ready(function() {
$("p").click(function(event){
$(this).hide();
});
});
</script>
</body>
</html>
</code></pre>
<p>then I see the expected result, that is, i can click on the paragraph to make it disappear. </p>
<p>BUT: I would like to put the javascript part into a main.js file under static/js/. like so:</p>
<pre><code>$(document).ready(function() {
$("p").click(function(event){
$(this).hide();
});
});
</code></pre>
<p>and the index.html becomes:</p>
<pre><code><!DOCTYPE html>
<html>
<body>
<p>Clicking here will make me dissapear</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src='/js/main.js'></script>
</body>
</html>
</code></pre>
<p>Unfortunately nothing will happen. I have tried other ways of referencing the script file as well but until now nothing works. I have the impression im missing something really simple. Thanks in advance!</p>
| <javascript><python><flask> | 2016-03-22 23:25:14 | HQ |
36,167,200 | How safe are Golang maps for concurrent Read/Write operations? | <p>According to the Go blog,</p>
<blockquote>
<p>Maps are not safe for concurrent use: it's not defined what happens when you read and write to them simultaneously. If you need to read from and write to a map from concurrently executing goroutines, the accesses must be mediated by some kind of synchronization mechanism.
(source: <a href="https://blog.golang.org/go-maps-in-action" rel="noreferrer">https://blog.golang.org/go-maps-in-action</a>)</p>
</blockquote>
<p>Can anyone elaborate on this? Concurrent read operations seem permissible across routines, but concurrent read/write operations may generate a race condition if one attempts to read from and write to the same key.</p>
<p>Can this last risk be reduced in some cases? For example: </p>
<ul>
<li>Function A generates k and sets m[k]=0. This is the only time A writes to map m. k is known to not be in m.</li>
<li>A passes k to function B running concurrently</li>
<li>A then reads m[k]. If m[k]==0, it waits, continuing only when m[k]!=0</li>
<li>B looks for k in the map. If it finds it, B sets m[k] to some positive integer. If it doesn't it waits until k is in m.</li>
</ul>
<p>This isn't code (obviously) but I think it shows the outlines of a case where even if A and B both try to access m there won't be a race condition, or if there is it won't matter because of the additional constraints.</p>
| <go><concurrency><hashmap> | 2016-03-22 23:35:36 | HQ |
36,167,512 | Ionic Android build: java.lang.IllegalStateException: buildToolsVersion is not specified | <p>Since today, somehow my ionic project is not longer able to build for some reason. I already tried to remove the platform and add it again, but it didn't work. I now almost spent three ours with upgrading, downgrading and reinstalling cordova and ionic but for some reason I always get the following error when I try to build the Android version: </p>
<pre><code>Failed to notify ProjectEvaluationListener.afterEvaluate(), but primary configuration failure takes precedence.
java.lang.IllegalStateException: buildToolsVersion is not specified.
at com.google.common.base.Preconditions.checkState(Preconditions.java:176)
at com.android.build.gradle.BasePlugin.createAndroidTasks(BasePlugin.java:599)
at com.android.build.gradle.BasePlugin$10$1.call(BasePlugin.java:566)
at com.android.build.gradle.BasePlugin$10$1.call(BasePlugin.java:563)
at com.android.builder.profile.ThreadRecorder$1.record(ThreadRecorder.java:55)
at com.android.builder.profile.ThreadRecorder$1.record(ThreadRecorder.java:47)
at com.android.build.gradle.BasePlugin$10.execute(BasePlugin.java:562)
at com.android.build.gradle.BasePlugin$10.execute(BasePlugin.java:559)
at org.gradle.listener.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:109)
at org.gradle.listener.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:98)
at org.gradle.listener.BroadcastDispatch.dispatch(BroadcastDispatch.java:83)
at org.gradle.listener.BroadcastDispatch.dispatch(BroadcastDispatch.java:31)
at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy12.afterEvaluate(Unknown Source)
at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:79)
at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:65)
at org.gradle.api.internal.project.AbstractProject.evaluate(AbstractProject.java:504)
at org.gradle.api.internal.project.AbstractProject.evaluate(AbstractProject.java:83)
at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:42)
at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:35)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:129)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:80)
at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:33)
at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:24)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:36)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:47)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:34)
at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:35)
at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:24)
at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)
at org.gradle.launcher.daemon.server.exec.StartStopIfBuildAndStop.execute(StartStopIfBuildAndStop.java:33)
at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:71)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:69)
at org.gradle.util.Swapper.swap(Swapper.java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:69)
at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:34)
at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:70)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:34)
at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)
at org.gradle.launcher.daemon.server.exec.DaemonHygieneAction.execute(DaemonHygieneAction.java:39)
at org.gradle.launcher.daemon.server.exec.DaemonCommandExecution.proceed(DaemonCommandExecution.java:119)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:46)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:246)
at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:64)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
FAILURE: Build failed with an exception.
</code></pre>
<p>I already tried to set the buildToolsVersion in the config.xml but without any success. Did anyone have the same problem before?</p>
| <android><cordova><ionic-framework> | 2016-03-23 00:04:52 | HQ |
36,167,571 | How to resolve java.lang.AssertionError when creating OkHttpClient in mockito? | <p>I'm trying to make some canned network respones. I have the json response for the actual request and I have Retrofit interfaces that serialize responses. I am beyond frustrated trying to set this up. What should I be doing here? It seems my options are, 1) Use a MockWebServer() 2) Use a RequestInterceptor().</p>
<p>While trying to use either 1 or 2, I can't for the life of me instantiate an OkHttpClient() without it failing, basically this puts every thing I try to death immediately. I get an java.lang.AssertionError because OkHttpClient is throwing this when it can't find a TLS algorithm.</p>
<pre><code> if (builder.sslSocketFactory != null || !isTLS) {
this.sslSocketFactory = builder.sslSocketFactory;
} else {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, null, null);
this.sslSocketFactory = sslContext.getSocketFactory();
} catch (GeneralSecurityException e) {
**throw new AssertionError(); // The system has no TLS. Just give up.**
}
}
</code></pre>
<p>I've tried to keep the "javax.net.ssl" class in the android.jar using unMock, but that didn't resolve the error.</p>
<pre><code>unMock {
// URI to download the android-all.jar from. e.g. https://oss.sonatype.org/content/groups/public/org/robolectric/android-all/
downloadFrom 'https://oss.sonatype.org/content/groups/public/org/robolectric/android-all/4.3_r2-robolectric-0/android-all-4.3_r2-robolectric-0.jar'
keep "android.util.Log"
keep "javax.net.ssl"
}
</code></pre>
<p>So basically, I've come across various examples of how to mock network requests with retrofit 2, but I can't get past this hurdle, and I'm feeling pretty defeated. I haven't seen anyone else with this problem, and I'm baffled as to how everyone is easily instantiating new OkHttpClients in all their tests.</p>
<p>Here are the relevant dependencies I am using.</p>
<pre><code> testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-all:1.10.19'
testCompile 'org.powermock:powermock-mockito-release-full:1.6.4'
testCompile 'org.powermock:powermock-module-junit4:1.6.4'
testCompile 'org.easymock:easymock:3.4'
testCompile 'org.powermock:powermock-api-easymock:1.6.4'
testCompile 'com.squareup.okhttp3:mockwebserver:3.2.0'
compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
compile 'com.google.code.gson:gson:2.4'
</code></pre>
| <android><junit><mockito><okhttp><retrofit2> | 2016-03-23 00:11:12 | HQ |
36,168,270 | Python - JavaScript Explanation | So if anyone is knowledgeable on Animal Shelter Manager, I'm looking for some help. I'm trying to figure out what each line of code means.. the first is
from animalcontrol.py
def get_animalcontrol_query(dbo):
return "SELECT ac.*, ac.ID AS ACID, s.SpeciesName, x.Sex AS SexName, " \
"co.OwnerName AS CallerName, co.HomeTelephone, co.WorkTelephone, co.MobileTelephone, " \
"o1.OwnerName AS OwnerName, o1.OwnerName AS OwnerName1, o2.OwnerName AS OwnerName2, o3.OwnerName AS OwnerName3, " \
"o1.OwnerName AS SuspectName, o1.OwnerAddress AS SuspectAddress, o1.OwnerTown AS SuspectTown, o1.OwnerCounty AS SuspectCounty, o1.OwnerPostcode AS SuspectPostcode, " \
"o1.HomeTelephone AS SuspectHomeTelephone, o1.WorkTelephone AS SuspectWorkTelephone, o1.MobileTelephone AS SuspectMobileTelephone, " \
"vo.OwnerName AS VictimName, vo.OwnerAddress AS VictimAddress, vo.OwnerTown AS VictimTown, vo.OwnerCounty AS VictimCounty, vo.OwnerPostcode AS VictimPostcode," \
"vo.HomeTelephone AS VictimHomeTelephone, vo.WorkTelephone AS VictimWorkTelephone, vo.MobileTelephone AS VictimMobileTelephone, " \
"ti.IncidentName, ci.CompletedName, pl.LocationName " \
"FROM animalcontrol ac " \
"LEFT OUTER JOIN species s ON s.ID = ac.SpeciesID " \
"LEFT OUTER JOIN lksex x ON x.ID = ac.Sex " \
"LEFT OUTER JOIN owner co ON co.ID = ac.CallerID " \
"LEFT OUTER JOIN owner o1 ON o1.ID = ac.OwnerID " \
"LEFT OUTER JOIN owner o2 ON o2.ID = ac.Owner2ID " \
"LEFT OUTER JOIN owner o3 ON o3.ID = ac.Owner3ID " \
"LEFT OUTER JOIN owner vo ON vo.ID = ac.VictimID " \
"LEFT OUTER JOIN pickuplocation pl ON pl.ID = ac.PickupLocationID " \
"LEFT OUTER JOIN incidenttype ti ON ti.ID = ac.IncidentTypeID " \
"LEFT OUTER JOIN incidentcompleted ci ON ci.ID = ac.IncidentCompletedID"
What does `return "SELECT ac.*, ac.ID AS ACID,` mean.
and if I wanted to differ this code from what it is currently what would I have to change. ei "ac." or "ACID"
I know I will have to change `def get_animalcontrol_query(dbo):` | <python><sql> | 2016-03-23 01:29:37 | LQ_EDIT |
36,168,658 | Mapbox-GL setStyle removes layers | <p>I'm building a mapping web application using Mapbox-GL. It has a lot of cool features. I've set up the buttons to switch base maps (ie. satellite, terrain, etc) following the example on the <a href="https://www.mapbox.com/mapbox-gl-js/example/setstyle/" rel="noreferrer">Mapbox website</a>.</p>
<p>The problem that I am having is that when I change the style it removes my polygons that are loaded as layers and reloads the map. I load in polygons from a Mongo database as layers based on user queries. I want to be able to change the base map and keep those layers.</p>
<p>Is there a way to change the style without reloading the map, or at least not droping the layers?</p>
<p>Here is my code for the switcher, its the same as the example but I added a condition for a custom style:</p>
<pre><code> var layerList = document.getElementById('menu');
var inputs = layerList.getElementsByTagName('input');
function switchLayer(layer) {
var layerId = layer.target.id;
if (layerId === 'outdoors') {
map.setStyle('/outdoors-v8.json');
} else {
map.setStyle('mapbox://styles/mapbox/' + layerId + '-v8');
}
}
for (var i = 0; i < inputs.length; i++) {
inputs[i].onclick = switchLayer;
}
</code></pre>
| <javascript><mapbox-gl><mapbox-gl-js> | 2016-03-23 02:15:25 | HQ |
36,168,702 | C Installed Library - What is this? | <p>I'm currently trying to install a library in c (specifically libsndfile). It's telling me that I need to 'install' and library. I'm confused, what exactly am I doing by 'installing' the library? </p>
<p>Why is it that I'm not just including header and source code files? </p>
<p>I've tried googling this but have not gotten too much success. Does anyone care to explain or recommend an article that discusses this?</p>
<p>Thank you,</p>
| <c> | 2016-03-23 02:22:58 | LQ_CLOSE |
36,168,724 | I want to find Ip address and Domain name of server whichever we connect by using Ruby.? | <p>Means I want to create method which will find Ip address and Domain name of server by using Ruby.</p>
| <ruby> | 2016-03-23 02:24:45 | LQ_CLOSE |
36,169,099 | Xcode 7.3 autocomplete is so frustrating | <p>There is a new autocomplete in Xcode. Probably might be useful because it checks not only beginning of names etc. But I found that very often it doesn't find a class name or a const name at all etc. I need to type in entire name by myself. Over all I found it makes my life harder and coding more time consuming. Is there a way to switch to the old way it used to work?</p>
| <autocomplete><xcode7.3> | 2016-03-23 03:08:55 | HQ |
36,169,264 | How to create a popup window in XCode Swift? | I have an iOS info app. The main screen of the app consists of rows of icons. I want that after tap on certain icon card with information appears and background blurs. To close the card I need to swipe up or down. It is very similar to Instagram's imageviewer.
Please help me create that.
P.S. This is my first project so please keep this in mind when you going to describe the method. Thank you.
[It should look like this][1]
[1]: http://i.stack.imgur.com/P3UJv.jpg | <ios><xcode><swift><popup> | 2016-03-23 03:26:07 | LQ_EDIT |
36,169,571 | Python subprocess .check_call vs .check_output | <p>My python script (python 3.4.3) calls a bash script via subprocess:</p>
<pre><code>import subprocess as sp
res = sp.check_output("bashscript", shell=True)
</code></pre>
<p>The <strong>bashscript</strong> contains the following line:</p>
<pre><code>ssh -MNf somehost
</code></pre>
<p>which opens a shared master connection to some remote host to allow some subsequent operations.</p>
<p>When executing the python script, it will prompt for password for the <code>ssh</code> line but then it blocks after the password is entered and never returns. When I ctrl-C to terminate the script, I see that the connection was properly established (so <code>ssh</code> line was successfully executed).</p>
<p>I don't have this blocking problem when using <code>check_call</code> instead of <code>check_output</code>, but <code>check_call</code> does not retrieve stdout. I'd like to understand what exactly is causing the blocking behavior for <code>check_output</code>, probably related to some subtlety with <code>ssh -MNf</code>.</p>
| <python><bash><ssh><subprocess> | 2016-03-23 03:56:41 | HQ |
36,169,680 | Google Login Failed, Failed to open stream Http request failed and Bad Request. | **How to change file_get_contents() to curl funtion**
Error occured in this below lines like .
Fatal error: Uncaught exception 'Exception' with message 'Required option not passed: access_token ' in E:\xampp\htdocs\google\application\libraries\oauth2\Token\Access.php:44 Stack trace: #0 E:\xampp\htdocs\google\application\libraries\oauth2\Token.php(30): OAuth2_Token_Access->__construct(NULL) #1 E:\xampp\htdocs\google\application\libraries\oauth2\Provider.php(224): OAuth2_Token::factory('access', NULL) #2 E:\xampp\htdocs\google\application\libraries\oauth2\Provider\Google.php(61): OAuth2_Provider->access('4/tJi51U-xhCSYo...', Array) #3 E:\xampp\htdocs\google\application\controllers\auth_oa2.php(32): OAuth2_Provider_Google->access('4/tJi51U-xhCSYo...') #4 [internal function]: Auth_oa2->session('google') ...
$opts = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($params),
)
);
$_default_opts = stream_context_get_params(stream_context_get_default());
$context = stream_context_create(array_merge_recursive($_default_opts['options'], $opts));
$response = file_get_contents($url, false, $context);
$return = json_decode($response, true);
| <php><codeigniter><curl><tankauth> | 2016-03-23 04:08:24 | LQ_EDIT |
36,170,049 | Use of string literal for Objective-C selectors is deprecated, use '#selector' instead | <p>I have the following code:</p>
<pre><code>func setupShortcutItems(launchOptions: [NSObject: AnyObject]?) -> Bool {
var shouldPerformAdditionalDelegateHandling: Bool = false
if (UIApplicationShortcutItem.respondsToSelector("new")) {
self.configDynamicShortcutItems()
// If a shortcut was launched, display its information and take the appropriate action
if let shortcutItem: UIApplicationShortcutItem = launchOptions?[UIApplicationLaunchOptionsShortcutItemKey] as? UIApplicationShortcutItem {
// When the app launched at the first time, this block can not called.
self.handleShortCutItem(shortcutItem)
// This will block "performActionForShortcutItem:completionHandler" from being called.
shouldPerformAdditionalDelegateHandling = false
} else {
// normal app launch process without quick action
self.launchWithoutQuickAction()
}
} else {
// Less than iOS9 or later
self.launchWithoutQuickAction()
}
return shouldPerformAdditionalDelegateHandling
}
</code></pre>
<p>I get the following "warning" on <code>UIApplicationShortcutItem.respondsToSelector("new")</code>, which says:</p>
<blockquote>
<p>Use of string literal for Objective-c selectors is deprecated, use '#selector' instead</p>
</blockquote>
<p>The warning replaces the code automatically with:</p>
<p><code>UIApplicationShortcutItem.respondsToSelector(#selector(FBSDKAccessToken.new))</code></p>
<p>However this doesn't compile because <code>new()</code> is unavailabe.
What am I supposed to use in this case?</p>
| <ios><objective-c><iphone><swift> | 2016-03-23 04:48:11 | HQ |
36,170,447 | Why printf() prints such a thing? | <p>I found a problem at internet such that there is a <strong>C</strong> program which like- <br></p>
<pre><code>int main(){
int a = 123;
printf("%d", printf("%d",a));
return 0;
}
</code></pre>
<p>I run this program at <strong>Codeblocks</strong> and find result <strong>1233</strong>.<br>
My question is that why printf() acts like this?</p>
| <c> | 2016-03-23 05:27:15 | LQ_CLOSE |
36,170,638 | How to access parameters of sys.argv Python? | <p>if given a command like:</p>
<p>python 1.py ab 2 34</p>
<p>How to print the next argument while you are currently sitting on the one before. e.g if x is ab then I want to print 2:</p>
<pre><code>import sys
for x in sys.argv[1:]:
print next element after x
</code></pre>
| <python> | 2016-03-23 05:43:13 | LQ_CLOSE |
36,171,115 | How can I make the client stays on until the server makes a connection..Java? | //Client
`enter code here` public class MyClient {
public static void main(String[] args) throws IOException, SocketException, ConnectException {
ServerSocket serverSocket = null;
Socket clientSocket = null;
BufferedReader in = null;
System.out.println("Welcome to the Daytime client.");
try{
clientSocket = new Socket("localhost", 4321);
while(true){
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String s = in.readLine();
System.out.println("Here is the timestamp received from the server: "+s);
System.out.println("The program terminated with no error and no exception");
in.close();
clientSocket.close();
clientSocket.close();
}
}catch (ConnectException e){
System.exit(0);
}catch (SocketException f){
System.exit(0);
}catch (IOException e) {
System.out.println("Error: " + e);
System.exit(0);
}
}
}
//SERVER
import java.io.*;
import java.net.*;
import java.util.*;
public class MyServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
Socket clientSocket = null;
PrintWriter out = null;
System.out.println("Daytime server ready.");
try {
serverSocket = new ServerSocket(4321);
while(true){
clientSocket = serverSocket.accept();
System.out.println("Request received.");
out = new PrintWriter(clientSocket.getOutputStream(), true);
Date timestamp = new Date ();
out.println(timestamp.toString());
}
} catch (IOException e) {
System.out.println("Error: " + e);
System.exit(0);
}
out.close();
clientSocket.close();
serverSocket.close();
System.out.println("3");
}
}
| <java><sockets><server><client> | 2016-03-23 06:22:23 | LQ_EDIT |
36,172,119 | Which atom python linting packages are stable? | <p>It seems that there are too many Python linting packages and I am wonder which one should we use. </p>
<p>I suspect installing two will provide a confusing experience, if not even triggering weird bugs.</p>
<ul>
<li><a href="https://atom.io/packages/python-autopep8" rel="noreferrer">python-autopep8</a> - 20+</li>
<li><a href="https://atom.io/packages/linter-python-pyflakes" rel="noreferrer">linter-python-flaks</a> - 6+</li>
<li><a href="https://atom.io/packages/linter-flake8" rel="noreferrer">linter-flake8</a> - 153+</li>
<li><a href="https://atom.io/packages/linter-pylint" rel="noreferrer">linter-pylint</a> - 119+</li>
</ul>
<p>Here are few areas I want to clarify:</p>
<ul>
<li>is ok to use more than one?</li>
<li>wouldn't be better to ask authors to join efforts and focus on a single one?<br>
What are the pros and cons for them?</li>
</ul>
| <python><atom-editor><flake8> | 2016-03-23 07:29:08 | HQ |
36,173,014 | Getting a Null Pointer Exception please | <p>my code is this I cant find the error null pointer exception onclick I am working with internal db and fragments for a project </p>
<p>public class FragmentAvion extends Fragment implements View.OnClickListener {</p>
<pre><code>private OnFragmentInteractionListener mListener;
private DataBaseManagerVuelo managerVuelo;
private Button button;
private EditText vaerolinea;
private EditText vdestino;
private EditText vconfirmacion;
private EditText vvuelo;
private Spinner spinner3;
private Button botonguardar;
public FragmentAvion() {
// Required empty public constructor
}
public void setDate(View view) {
DateDialog datedialog = new DateDialog();
datedialog.show(getFragmentManager(), "DateDialog");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment_avion, container, false);
Spinner spinner3 = (Spinner) view.findViewById(R.id.spinner3);
final String vaerolinea = spinner3.getSelectedItem().toString();
final EditText vvuelo = (EditText) view.findViewById(R.id.vvuelo);
final EditText vconfirmacion = (EditText) view.findViewById(R.id.vconfirmacion);
final EditText vdestino = (EditText) view.findViewById(R.id.vdestino);
DatePicker dpResult = (DatePicker) view.findViewById(R.id.dpResult);
TimePicker tpResult = (TimePicker) view.findViewById(R.id.tpResult);
Button bottonguardar = (Button) view.findViewById(R.id.bottonguardar);
bottonguardar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
managerVuelo.insertar_6parametros(null, vaerolinea, vvuelo.getText().toString(), vdestino.getText().toString(), null, null);
}
});
return (view);
}
@Override
public void onClick(View v) {
managerVuelo.insertar_6parametros(null, vaerolinea.getText().toString(), vvuelo.getText().toString(), vdestino.getText().toString(), null, null);
}
// Inflate the layout for this fragment
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
FragmentComidas.OnFragmentInteractionListener mListener = null;
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentViajeNuevo.OnFragmentInteractionListener) {
mListener = (FragmentAvion.OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
</code></pre>
<p>}</p>
| <android> | 2016-03-23 08:24:09 | LQ_CLOSE |
36,173,332 | Difference between @Valid and @Validated in Spring | <p>Spring supports two different validation methods: Spring validation and JSR-303 bean validation. Both can be used by defining a Spring validator that delegates to other delegators including the bean validator. So far so good.</p>
<p>But when annotating methods to actually request validation, it's another story. I can annotate like this</p>
<pre><code>@RequestMapping(value = "/object", method = RequestMethod.POST)
public @ResponseBody TestObject create(@Valid @RequestBody TestObject obj, BindingResult result) {
</code></pre>
<p>or like this</p>
<pre><code>@RequestMapping(value = "/object", method = RequestMethod.POST)
public @ResponseBody TestObject create(@Validated @RequestBody TestObject obj, BindingResult result) {
</code></pre>
<p>Here, @Valid is <a href="http://docs.oracle.com/javaee/7/api/javax/validation/Valid.html">javax.validation.Valid</a>, and @Validated is <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/annotation/Validated.html">org.springframework.validation.annotation.Validated</a>. The docs for the latter say</p>
<blockquote>
<p>Variant of JSR-303's Valid, supporting the specification of validation
groups. Designed for convenient use with Spring's JSR-303 support but
not JSR-303 specific.</p>
</blockquote>
<p>which doesn't help much because it doesn't tell exactly how it's different. If at all. Both seem to be working pretty fine for me.</p>
| <java><spring><validation><spring-mvc> | 2016-03-23 08:41:08 | HQ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.