title
stringlengths 10
150
| body
stringlengths 17
64.2k
| label
int64 0
3
|
---|---|---|
How do you dynamically create an AWS IAM policy document with a variable number of resource blocks using terraform? | <p>In my current terraform configuration I am using a static JSON file and importing into terraform using the file function to create an AWS IAM policy.</p>
<p>Terraform code:</p>
<pre><code>resource "aws_iam_policy" "example" {
policy = "${file("policy.json")}"
}
</code></pre>
<p>AWS IAM Policy definition in JSON file (policy.json):</p>
<pre><code>{
"Version": "2012-10-17",
"Id": "key-consolepolicy-2",
"Statement": [
{
"Sid": "Enable IAM User Permissions",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::111122223333:root"
},
"Action": "kms:*",
"Resource": "*"
},
{
"Sid": "Allow use of the key",
"Effect": "Allow",
"Principal": {
"AWS": [
"arn:aws:iam::777788889999:root"
]
},
"Action": [
"kms:Decrypt"
],
"Resource": "*"
},
{
"Sid": "Allow use of the key",
"Effect": "Allow",
"Principal": {
"AWS": [
"arn:aws:iam::444455556666:root"
]
},
"Action": [
"kms:Decrypt"
],
"Resource": "*"
}
]
}
</code></pre>
<p>My goal is to use a list of account numbers stored in a terraform variable and use that to dynamically build the aws_iam_policy resource in terraform. My first idea was to try and use the terraform jsonencode function. However, it looks like there might be a way to implement this using the new terraform dynamic expressions foreach loop.</p>
<p>The sticking point seems to be appending a variable number of resource blocks in the IAM policy. </p>
<p>Pseudo code below:</p>
<pre><code>var account_number_list = ["123","456","789"]
policy = {"Statement":[]}
for each account_number in account_number_list:
policy["Statement"].append(policy block with account_number var reference)
</code></pre>
<p>Any help is appreciated.</p>
<p>Best,
Andrew</p> | 0 |
input type number in html 5 is not working? | <pre><code><form name="form" method="get" action="" >
Number :
<input type="number" name="num" id="num" min="1" max="5" required="required"/> <br/>
Email :
<input type="email" name="email" id="email" required="required"/> <br />
<input type="submit" name="submit" id="submit" value="submit" />
</form>
</code></pre>
<p>It is taking alphabets too on submitting the form.
No error messages are generated
Number type is not working.</p> | 0 |
Cannot find entry symbol _start | <p>My c code on compiling on gcc is giving the error <code>Cannot find entry symbol _start defaulting to 00000</code>. Can anyone tell me why and how to correct it?</p>
<p>The command line is <code>arm-none-eabi-gcc -O3 -march=armv7-a -mtune=cortex-a8 -mfpu=neon -ftree-vectorize -mfloat-abi=softfp file path</code> and the target platform is a-8 sitara cortex processor.</p> | 0 |
Is JQuery namespace a good practice? | <p>Can anyone explain to me please that if using a namespace is a good coding practice. And why is it needed? If it was a good approach why JQuery didn't include it by default. There is a separate plugin to allow this functionality.</p>
<p>I saw this <a href="https://stackoverflow.com/questions/527089/is-it-possible-to-create-a-namespace-in-jquery">post</a> that mentions few ways to do it. Someone mentioned about memory leak in the post that is worrisome.</p>
<p>Lastly, what is the best way to organize JQuery libraries?</p>
<p>thanks,</p> | 0 |
Angular 7 - Reload / refresh data different components | <p>How to refresh data in different component 1 when changes made in component 2. These two components are not under same parentnode.</p>
<p><strong>customer.service.ts</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export class UserManagementService extends RestService {
private BASE_URL_UM: string = '/portal/admin';
private headers = new HttpHeaders({
'Authorization': localStorage.getItem('token'),
'Content-Type': 'application/json'
});
constructor(protected injector: Injector,
protected httpClient: HttpClient) {
super(injector);
}
getEapGroupList(): Observable < EapGroupInterface > {
return this.get < GroupInterface >
(this.getFullUrl(`${this.BASE_URL_UM}/groups`), {
headers: this.headers
});
}
updateGroup(body: CreateGroupPayload): Observable < CreateGroupPayload > {
return this.put < GroupPayload >
(this.getFullUrl(`${this.BASE_URL_UM}/group`), body, {
headers: this.headers
});
}
}</code></pre>
</div>
</div>
</p>
<p><strong>Component1.ts</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export class UserGroupComponent implements OnInit {
constructor(private userManagementService: UserManagementService) {}
ngOnInit() {
this.loadGroup();
}
loadGroup() {
this.userManagementService.getEapGroupList()
.subscribe(response => {
this.groups = response;
})
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><mat-list-item *ngFor="let group of groups?.groupList" role="listitem">
<div matLine [routerLink]="['/portal/user-management/group', group.groupCode, 'overview']" [routerLinkActive]="['is-active']">
{{group.groupName}}
</div>
</mat-list-item>
<mat-sidenav-content>
<router-outlet></router-outlet>
</mat-sidenav-content></code></pre>
</div>
</div>
</p>
<p><strong>component2.ts</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>setPayload() {
const formValue = this.newGroupForm.value
return {
'id': '5c47b24918a17c0001aa7df4',
'groupName': formValue.groupName,
}
}
onUpdateGroup() {
this.userManagementService.updateGroup(this.setPayload())
.subscribe(() => {
console.log('success);
})
}</code></pre>
</div>
</div>
</p>
<p>When I update onUpdateGroup() api in <strong>component1</strong>, loadGroup() should refresh in <strong>component2</strong></p> | 0 |
Installing wxPython on Ubuntu 12.04 | <p><strong>The Issue:</strong> I am having trouble installing wxPython on Ubuntu 12.04. <em>I would like to find a simple, straightforward way of doing this.</em></p>
<p><strong>What I've Done So Far:</strong> The most relevant instructions that I have been able to find so far can be found here: <a href="http://wiki.wxpython.org/InstallingOnUbuntuOrDebian" rel="noreferrer">http://wiki.wxpython.org/InstallingOnUbuntuOrDebian</a></p>
<p>The issue with these instructions is that there is no choice available for Precise 12.04. The most up-to-date distro shown is Natty 11.4. From what I can find, the proper way to do this is to manually build debian packages, which is explained here: <a href="http://wiki.wxpython.org/BuildingDebianPackages" rel="noreferrer">http://wiki.wxpython.org/BuildingDebianPackages</a></p>
<p>Upon attempting this and finally typing the command 'fakeroot debian/rules binary', I get the errors:</p>
<blockquote>
<p>debian/rules:14: /usr/share/quilt/quilt.make: No such file or directory<br>
pyversions: missing X(S)-Python-Version in control file, fall back to debian/pyversions<br>
pyversions: missing debian/pyversions file, fall back to supported versions<br>
make: *** No rule to make target `/usr/share/quilt/quilt.make'. Stop.</p>
</blockquote>
<p>I cannot seem to fix this error, or find any other applicable resources that work for me. I would post more links here, but since I am new, the spam filter is blocking me from doing so.</p>
<p><strong>Conclusion: <em>Does someone know a simple solution to properly installing wxPython on Ubuntu 12.04 Precise?</em></strong></p>
<p><strong>Update:</strong> I tried just simply using the apt-get command 'sudo apt-get install python-wxgtk2.8', and I received this (which seems good):</p>
<blockquote>
<p>Reading package lists... Done<br>
Building dependency tree<br><br>
Reading state information... Done<br>
python-wxgtk2.8 is already the newest version.<br>
The following packages were automatically installed and are no longer required:<br>
language-pack-zh-hans yaml-cpp language-pack-kde-en language-pack-kde-zh-hans language-pack-kde-en-base language-pack-zh-hans-base language-pack-kde-zh-hans-base<br>
Use 'apt-get autoremove' to remove them.<br>
0 upgraded, 0 newly installed, 0 to remove and 173 not upgraded.</p>
</blockquote>
<p>But once I attempt to run something, ie 'python test_gui.py', I get the following error:</p>
<blockquote>
<p>Traceback (most recent call last):<br>
File "test_gui.py", line 1, in <br>
import wx<br>
ImportError: No module named wx</p>
</blockquote> | 0 |
Wordpress wp-load.php | <p>I'm trying to reverse-engineer a plugin : <a href="http://wordpress.org/extend/plugins/wordpress-social-login/">http://wordpress.org/extend/plugins/wordpress-social-login/</a></p>
<p>In a part of it, there's this line:<br>
(I'm having a hard time understanding the first one, the rest are simply there for reference if they have something to do it.)</p>
<pre><code>require_once( dirname( dirname( dirname( dirname( __FILE__ )))) . '/wp-load.php' );
define( 'WORDPRESS_SOCIAL_LOGIN_PLUGIN_URL', plugins_url() . '/' . basename( dirname( __FILE__ ) ) );
define( 'WORDPRESS_SOCIAL_LOGIN_HYBRIDAUTH_ENDPOINT_URL', WORDPRESS_SOCIAL_LOGIN_PLUGIN_URL . '/hybridauth/' );
</code></pre>
<p>My question is... what exactly is in this <code>wp-load.php</code> file that it needs to be required by the code? By looking at it, all I understand is that it loads crucial core wordpress files for the site to be running correctly (<code>functions.php</code>, <code>wp-settings.php</code>, <code>wp-config.php</code> etc...)<br>
Doesn't the fact that the plugin runs already means <code>wp-load.php</code> is loaded?<br>
Also it's a complete waste of resources since it includes so many files that may include other files as well and it's like an endless loop of required files, each within another, which are being loaded twice.. (or even more if other plugins use this kind of method too)</p>
<p>So what exactly does it do?</p>
<p>P.S; All I found by Google-ing is HOW to include it correctly (since paths are change-able) - but that's not my problem/question.</p> | 0 |
Better way to select all columns from first table and only one column from second table on inner join | <h2>Graphical Explaination</h2>
<p>Table 1's columns:</p>
<pre><code>|a|b|c|d|e|
</code></pre>
<p>Table 2's columns:</p>
<pre><code>|a|x|y|z|
</code></pre>
<p>I want only a, b, c, d, e, x. I only want column 'a' from table 1, not column 'a' from table 2.</p>
<h2>Wordy Explaination</h2>
<p>I have two tables with one column sharing a common name. If I use a Select * and use an inner join, I get all the columns returned including two columns with the same name. </p>
<p>I want to select everything from the first table, and only one column from the second table. Right now I am specifing every single column I need, which is a drag. Is there an easier way to grab everything from the first table and only the one column I want from the second table?</p>
<p>Thanks in advance. </p> | 0 |
Printing array elements with a for loop | <p>This is a challenge question from my online textbook I can only get the numbers to prin forward... :(</p>
<p>Write a for loop to print all elements in courseGrades, following each element with a space (including the last). Print forwards, then backwards. End each loop with a newline.
Ex: If courseGrades = {7, 9, 11, 10}, print:
7 9 11 10
10 11 9 7 </p>
<p>Hint: Use two for loops. Second loop starts with i = NUM_VALS - 1. </p>
<p>Note: These activities may test code with different test values. This activity will perform two tests, the first with a 4-element array (int courseGrades[4]), the second with a 2-element array (int courseGrades[2]). </p>
<pre><code>import java.util.Scanner;
public class CourseGradePrinter {
public static void main (String [] args) {
final int NUM_VALS = 4;
int[] courseGrades = new int[NUM_VALS];
int i = 0;
courseGrades[0] = 7;
courseGrades[1] = 9;
courseGrades[2] = 11;
courseGrades[3] = 10;
/* Your solution goes here */
for(i=0; i<NUM_VALS; i++){
System.out.print(courseGrades[i] + " ");
}
for(i=NUM_VALS -1; i>3; i++){
System.out.print(courseGrades[i]+ " ");
}
return;
}
}
</code></pre> | 0 |
How to create docx file using java? | <p>I am trying to create a .docx file using java but for some reason I can't open the file. The error comes "Problem with the content of file". Does anyone knows how to fix this problem?</p> | 0 |
How to include js.erb file in view folder | <p>I have a JavaScript file to use with a view. There needs to be Ruby code in it, and I need to do <code>render</code> in Ruby, so I understand that I can't put the JavaScript file in the asset pipeline. I can put it in the same view folder as the <code>.html.erb</code> file.</p>
<p>How do I include the JavaScript file, or use that JavaScript file for that view file? I tried <code>javascript_include_tag</code> in my view (that uses the asset pipeline apparently), using script <code>src="myfile.js"</code> for the <code>myfile.js.erb</code> file (but it can't find <code>myfile.js</code>), and names my <code>js.erb</code> file (<code>users.js.erb</code>) the same as my <code>.html.erb</code> file (<code>users.html.erb</code>), but all to no avail.</p> | 0 |
Post-hoc test for glmer | <p>I'm analysing my binomial dataset with R using a generalized linear mixed model (glmer, lme4-package). I wanted to make the pairwise comparisons of a certain fixed effect ("Sound") using a Tukey's post-hoc test (glht, multcomp-package).</p>
<p>Most of it is working fine, but one of my fixed effect variables ("SoundC") has no variance at all (96 times a "1" and zero times a "0") and it seems that the Tukey's test cannot handle that. All pairwise comparisons with this "SoundC" give a p-value of 1.000 whereas some are clearly significant.</p>
<p>As a validation I changed one of the 96 "1"'s to a "0" and after that I got normal p-values again and significant differences where I expected them, whereas the difference had actually become smaller after my manual change.</p>
<p>Does anybody have a solution? If not, is it fine to use the results of my modified dataset and report my manual change?</p>
<p>Reproducible example:</p>
<pre><code>Response <- c(1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1,1,0,
0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,
1,1,0,1,1,0,1,1,1,1,0,0,1,1,0,1,1,0,1,1,0,1,1,0,1)
Data <- data.frame(Sound=rep(paste0('Sound',c('A','B','C')),22),
Response,
Individual=rep(rep(c('A','B'),2),rep(c(18,15),2)))
# Visual
boxplot(Response ~ Sound,Data)
# Mixed model
library (lme4)
model10 <- glmer(Response~Sound + (1|Individual), Data, family=binomial)
# Post-hoc analysis
library (multcomp)
summary(glht(model10, mcp(Sound="Tukey")))
</code></pre> | 0 |
C# Design Pattern for Database Helper classes | <p>I'm designing a WCF Service that will called by several hundred clients, and I have a question about the best architecture for the classes that will run by database queries. Today I only access SQL Server, so I have a static class that I call internally that does all the dirty work of creating connections and datareaders. Below is a simple example:</p>
<pre><code>namespace DBHelper.Utility
{
public static class SqlDBManager
{
public static void RunSql(String pSql, DBParamsHelper pDBParams, String pConnStringConfigName)
{
String sConnectionString = GetConnectionStringFromConfig(pConnStringConfigName);
SqlConnection oConn = new SqlConnectionsConnectionString
oConn.Open();
try
{
SqlCommand oCommand = new SqlCommand(pSql, oConn);
oCommand.CommandTimeout = 0;
if (pDBManagerParams != null)
{
foreach (SqlParameter sqlParam in pDBManagerParams)
{
oCommand.Parameters.Add(sqlParam);
}
}
oCommand.ExecuteNonQuery();
}
finally
{
oConn.Close();
}
}
}
}
</code></pre>
<p>Now, I need to add support for running both Sql Server and Oracle. My initial idea was to declare an interface, and have my existing <code>SqlDBManager</code> implement it, and then develop an <code>OracleDBManager</code> implementing the same interface. The problem is that my class is static, and static classes cannot implement an interface. I would like my helper class to remain as static, with it's a lot more practical, and I don't have to create a new object every time I need to run a query. I also thought of using class inheritance, but I can't have statis virtual methods, so not much use there. I considered some singleton implementations so I wouldn't have to create classes, but then I would have trouble on the multi-threaded access.<br>
What would be the best design pattern so I can have great performance on multiple threaded scenario (very important), not too much work coding for productivity (not have to create a lot of classes), and have a standard methods for both <code>OracleDBManager</code> and <code>SqlDBManager</code> classes? The standard method is very important, because I don't want to the code that uses these helper classes to know if they are connected to Oracle or Sql Server.<br>
I did consider using ORM solution, such as Entity Framework 4 and nHibernate, but the performance impact was too much. Since I will run simple queries, the query syntax difference between PL-SQL and TSQL won't matter.<br>
Any input and idea will be greatly appreciated. Tks</p> | 0 |
magento - quick search returns all products | <p>After upgrading from 1.4 to 1.5 the quick search returns all products. The advanced search works just fine. I've cleared the cache and re-indexed everything but still nothing. Any ideas why?</p>
<p>The search also doesn't apply the minimum query length set in the admin (ie, I can enter nothing and still be shown everything). Switching between LIKE or FULLTEXT search seems to do nothing.</p>
<p>I've seen this <a href="https://stackoverflow.com/questions/2926281/magento-search-returns-all-products">Magento Search returns All Products</a> but all my plugins are up to date (and I don't have any search plugins).</p> | 0 |
Java format hour and min | <p>I need to format my time string such as this: </p>
<pre><code>int time = 160;
</code></pre>
<p>Here's my sample code:</p>
<pre><code>public static String formatDuration(String minute) {
String formattedMinute = null;
SimpleDateFormat sdf = new SimpleDateFormat("mm");
try {
Date dt = sdf.parse(minute);
sdf = new SimpleDateFormat("HH mm");
formattedMinute = sdf.format(dt);
} catch (ParseException e) {
e.printStackTrace();
}
return formattedMinute;
// int minutes = 120;
// int h = minutes / 60 + Integer.parseInt(minute);
// int m = minutes % 60 + Integer.parseInt(minute);
// return h + "hr " + m + "mins";
}
</code></pre>
<p>I need to display it as 2hrs 40mins. But I don't have a clue how to append the "hrs" and "mins". The requirement is not to use any library.</p>
<p>If you've done something like this in the past, feel free to help out. Thanks a bunch!</p> | 0 |
mongodb 3.4.2 InvalidIndexSpecificationOption error: The field 'unique' is not valid for an _id index specification | <p>The command <code>db.testCollection.createIndex( { _id: 1 }, {name: "_id_2", unique: true, background: true} )</code> fails on mongo version 3.4.2, but not 3.2.11. The mongo documentation indicates the version 3.4 supports both the <code>unique</code> and <code>background</code> attributes.</p>
<p>Mongo 3.4.2 fails ...</p>
<pre><code>> use testDB
switched to db testDB
> db.testCollection.createIndex( { _id: 1 }, {name: "_id_2", unique: true, background: true} )
{
"ok" : 0,
"errmsg" : "The field 'unique' is not valid for an _id index specification. Specification: { ns: \"testDB.testCollection\", v: 1, key: { _id: 1.0 }, name: \"_id_2\", unique: true, background: true }",
"code" : 197,
"codeName" : "InvalidIndexSpecificationOption"
}
>
</code></pre>
<p>Mongo 3.2.11 works ...</p>
<pre><code>> use testDB
switched to db testDB
> db.testCollection.createIndex( { _id: 1 }, {name: "_id_2", unique: true, background: true} )
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 1,
"note" : "all indexes already exist",
"ok" : 1
}
>
</code></pre>
<p>Anyone know of a work around? </p>
<p>We're using the Mongoose Node.js wrapper to create the Mongo indexes, so not adding the <code>unique</code> and <code>background</code> attributes isn't an option.</p>
<p>Cheers!</p>
<p>Ed</p> | 0 |
Accessing JSON object within Object using React/Axios | <p>I’m working with an API that shows data for cryptocurrencies called CryptoCompare. I’m a React noob but I’ve managed to use Axios to do the AJAX request. However I’m having trouble accessing the JSON elements I want.</p>
<p>Here’s what the JSON looks like: <a href="https://min-api.cryptocompare.com/data/all/coinlist" rel="nofollow noreferrer">https://min-api.cryptocompare.com/data/all/coinlist</a></p>
<p>Here is my request:</p>
<pre><code>import React, { Component } from 'react';
import './App.css';
import axios from "axios";
var NumberFormat = require('react-number-format');
class App extends Component {
constructor(props) {
super(props);
this.state = {
coinList: []
};
}
componentDidMount() {
axios.get(`https://min-api.cryptocompare.com/data/all/coinlist`)
.then(res => {
const coins = res.data;
//console.log(coins);
this.setState({ coinList: coins});
});
}
// Object.keys is used to map through the data. Can't map through the data without this because the data is not an array. Map can only be used on arrays.
render() {
console.log(this.state.coinList.Data);
return (
<div className="App">
{Object.keys(this.state.coinList).map((key) => (
<div className="container">
<span className="left">{key}</span>
<span className="right"><NumberFormat value={this.state.coinList[key].CoinName} displayType={'text'} decimalPrecision={2} thousandSeparator={true} prefix={'$'} /></span>
</div>
))}
</div>
);
}
}
export default App;
</code></pre>
<p>I am able to output some JSON using console.log(this.state.coinList.Data);. It outputs the JSON object, but I am unable to console.log properties of the object itself.</p>
<p>How would I, for example, output the CoinName property of the first element 42?</p>
<p>console.log(this.state.coinList.Data.CoinName) doesn’t work</p>
<p>nor does console.log(this.state.coinList.Data[0].CoinName) etc…</p> | 0 |
Add embedded image in emails in AWS SES service | <p>I am trying to write a Java app which can send emails to specify emails. In the email i also want to attach some pic.</p>
<p>Please find my code below :-</p>
<pre><code>public class AmazonSESSample {
static final String FROM = "abc@gmail.com";
static final String TO = "def@gmail.com";
static final String BODY = "This email was sent through Amazon SES by using the AWS SDK for Java. hello";
static final String SUBJECT = "Amazon SES test (AWS SDK for Java)";
public static void main(String[] args) throws IOException {
Destination destination = new Destination().withToAddresses(new String[] { TO });
Content subject = new Content().withData(SUBJECT);
Message msg = new Message().withSubject(subject);
// Include a body in both text and HTML formats
//Content textContent = new Content().withData("Hello - I hope you're having a good day.");
Content htmlContent = new Content().withData("<h2>Hi User,</h2>\n"
+ " <h3>Please find the ABC Association login details below</h3>\n"
+ " <img src=\"logo.png\" alt=\"Mountain View\">\n"
+ " Click <a href=\"http://google.com">here</a> to go to the association portal.\n"
+ " <h4>Association ID - 12345</h4>\n" + " <h4>Admin UID - suny342</h4>\n"
+ " <h4>Password - poass234</h4>\n" + " Regards,\n" + " <br>Qme Admin</br>");
Body body = new Body().withHtml(htmlContent);
msg.setBody(body);
SendEmailRequest request = new SendEmailRequest().withSource(FROM).withDestination(destination)
.withMessage(msg);
try {
System.out.println("Attempting to send an email through Amazon SES by using the AWS SDK for Java...");
AWSCredentials credentials = null;
credentials = new BasicAWSCredentials("ABC", "CDF");
try {
// credentialsProvider.
} catch (Exception e) {
throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
+ "Please make sure that your credentials file is at the correct "
+ "location (/Users/iftekharahmedkhan/.aws/credentials), and is in valid format.", e);
}
AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials)).withRegion("us-west-2").build();
client.sendEmail(request);
System.out.println("Email sent!");
} catch (Exception ex) {
System.out.println("The email was not sent.");
System.out.println("Error message: " + ex.getMessage());
}
}
}
</code></pre>
<p>The image is placed in the resource directory but it is not being embeded in the email. Can anyone please help.</p> | 0 |
Use of SET ROWCOUNT in SQL Server - Limiting result set | <p>I have a sql statement that consists of multiple SELECT statements. I want to limit the total number of rows coming back to let's say 1000 rows. I thought that using the SET ROWCOUNT 1000 directive would do this...but it does not. For example:</p>
<pre><code>SET ROWCOUNT 1000
select orderId from TableA
select name from TableB
</code></pre>
<p>My initial thought was that SET ROWCOUNT would apply to the <strong>entire</strong> batch, not the individual statements within it. The behavior I'm seeing is it will limit the first select to 1000 and then the second one to 1000 for a total of 2000 rows returned. Is there any way to have the 1000 limit applied to the batch as a whole?</p> | 0 |
How to get distinct instance from a list by Lambda or LINQ | <p>I have a class like this:</p>
<pre><code>class MyClass<T> {
public string value1 { get; set; }
public T objT { get; set; }
}
</code></pre>
<p>and a list of this class. I would like to use .net 3.5 lambda or linq to get a list of MyClass by distinct value1. I guess this is possible and much simpler than the way in .net 2.0 to cache a list like this:</p>
<pre><code>List<MyClass<T>> list;
...
List<MyClass<T>> listDistinct = new List<MyClass<T>>();
foreach (MyClass<T> instance in list)
{
// some code to check if listDistinct does contain obj with intance.Value1
// then listDistinct.Add(instance);
}
</code></pre>
<p>What is the lambda or LINQ way to do it?</p> | 0 |
How to use -dontwarn in ProGuard? | <p>I am using android studio to build debug and release application.
When i build debug/release application</p>
<pre><code>./gradlew assembleDebug
./gradlew assembleRelease
</code></pre>
<p>both build are created perfectly and run as well. Shows appropriate dialog box for debug or release</p>
<p>now i have added proguard details in build.gradle:</p>
<pre><code>signingConfigs {
myConfig {
storeFile file("keystore.jks")
storePassword "abc123!"
keyAlias "androidreleasekey"
keyPassword "pqrs123!"
}
}
buildTypes {
release {
runProguard true
proguardFile getDefaultProguardFile('proguard-android-optimize.txt')
signingConfig signingConfigs.myConfig
}
}
productFlavors {
defaultFlavor {
proguardFile 'proguard-rules.txt'
}
}
</code></pre>
<p>Now it shows error in event log as</p>
<blockquote>
<p>Warning: there were 7 unresolved references to classes or interfaces.
You may need to add missing library jars or update their versions.
If your code works fine without the missing classes, you can suppress
the warnings with '-dontwarn' options.
(<a href="http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedclass">http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedclass</a>)</p>
<p>Warning: there were 2 unresolved references to program class members.
Your input classes appear to be inconsistent.
You may need to recompile the code.</p>
<p>(<a href="http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedprogramclassmember">http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedprogramclassmember</a>)
:Flash Sales:proguardDefaultFlavorRelease FAILED</p>
</blockquote>
<p>If i turn the runProguard option to false then its running.</p>
<p>I have these questions:</p>
<p>1) is it ok to release apk with runProguard = false?</p>
<p>2) How to use dontwarn while creating release build?</p> | 0 |
Can float (or double) be set to NaN? | <p>Note: Similar to <a href="https://stackoverflow.com/questions/3949457/c-can-int-be-nan">Can an integer be NaN in C++?</a></p>
<p>I understand this has little practical purpose, but can a <code>float</code> or <code>double</code> be set to <code>NaN</code>?</p> | 0 |
Fetch the value of a given column in Eloquent | <p>I am trying to get the <strong>value</strong> of a single column using Eloquent:</p>
<pre><code>MyModel::where('field', 'foo')->get(['id']); // returns [{"id":1}]
MyModel::where('field', 'foo')->select('id')->first() // returns {"id":1}
</code></pre>
<p>However, I am getting anything but the value <code>1</code>. How can get that <code>1</code>?</p>
<p>NOTE: <em>It is possible that the record with <code>field</code> of <code>foo</code> does not exist in the table!</em></p>
<h3>EDIT</h3>
<p>I am ideally looking for a <em>single statement</em> that either returns the value (e.g. <code>1</code>) or fails with a <code>''</code> or <code>null</code> or other. To give you some more context, this is actually used in <code>Validator::make</code> in one of the rules: </p>
<pre><code>'input' => 'exists:table,some_field,id,' . my_query_above...
</code></pre>
<h3>EDIT 2</h3>
<p>Using Adiasz's answer, I found that <code>MyModel::where('field', 'foo')->value('id')</code> does exactly what I need: returns an integer value or an empty string (when failed).</p> | 0 |
Laravel - Number with 4 decimals | <p>I want to store 1 number with 4 decimals, in my database.</p>
<p>If i use <strong>float</strong> i can add only 2 decimals</p>
<pre><code>$table->float('sell');
</code></pre>
<p><a href="https://i.stack.imgur.com/0ud10.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0ud10.png" alt="enter image description here"></a></p>
<hr>
<p>If I try with <strong>decimal</strong> i get an error</p>
<pre><code>$table->decimal('sell', 1, 4);
</code></pre>
<p>The first number must be greater than or equal to the second number.</p>
<pre><code>SQLSTATE[42000]: Syntax error or access violation: 1427 For float(M,D), double(M,D) or decimal(M,D), M must be >= D (column '
</code></pre>
<p>sell'). (SQL: create table <code>customers</code> (<code>id</code> int unsigned not null auto_increment primary key, <code>sell</code> decimal(1, 4) not null,<br>
<code>created_at</code> timestamp null, <code>updated_at</code> timestamp null) default character set utf8 collate utf8_unicode_ci)</p>
<p><strong>Any help?</strong></p>
<p><strong>Thanks</strong> </p> | 0 |
Changing the Projection of Shapefile | <p>I am trying to change or assign the projection of a Germany-Shapefile from <code>NA</code> to <code>+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0</code>, but somehow it doesn't work well.</p>
<p>Reproducible Example:
Shapefile and other files can be downloaded <a href="https://www.dropbox.com/s/oqofou8dc03udh9/shapefile.zip?dl=0" rel="noreferrer">here</a>:</p>
<p>What I tried is the following:</p>
<pre><code>library(maptools)
library(sp)
library(rgeos)
library(rgdal)
projection.x <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0")
mapG <- readShapePoly("vg2500_lan.shp", verbose=TRUE, proj4string=projection.x)
summary(mapG)
mapG <- spTransform(mapG, CRS("+proj=longlat +ellps=WGS84 +datum=WGS84"))
</code></pre>
<p>So, the problem is I cannot plot my observations on the map. See below</p>
<p><a href="https://i.stack.imgur.com/KFR3t.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KFR3t.png" alt="enter image description here"></a>
The ponits were detected using <code>geocode</code> function from <code>ggmap</code> package.
<a href="https://i.stack.imgur.com/Y4GB9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Y4GB9.png" alt="enter image description here"></a>
Any idea how to change the projection of the shapefile or the projection of the google coordinates would be highly appreciated!</p> | 0 |
How to get R to recognize your working directory as its working directory? | <p>I use R under Windows on several machines.</p>
<p>I know you can set the working directory from within an R script, like this</p>
<pre><code>setwd("C:/Documents and Settings/username/My Documents/x/y/z")
</code></pre>
<p>... but then this breaks the portability of the script. It's also annoying to have to reverse all the slashes (since Windows gives you backslashes)</p>
<p>Is there a way to start R in a particular working directory so that you don't need to do this at the script level?</p> | 0 |
Static variables persisting across sessions in WCF service | <p>I have a WCF service with sessions required</p>
<pre><code> [ServiceContract(SessionMode = SessionMode.Required) ]
</code></pre>
<p>and some static fields. I thought that by having sessions, the static fields would remain the same for each session, but have new instances for different sessions. However, what I'm seeing when I have two different clients use the service is that when one client changes a field's value, this change also affects the other client. Is this normal behavior for having different sessions? Or do you think my service might not even be creating different sessions?</p>
<p>I'm using netTCPbinding.</p> | 0 |
PHP - Getting URL from localhost and online | <p>OK, so localhost, I use <code>WAMP</code> and its <code>http://localhost/PROJECTNAME/</code> and online it's <code>http://PROJECTNAME.COM/</code></p>
<p>So, by using</p>
<p><code><?php echo "Load config file from: http://".$_SERVER['SERVER_NAME']?></code></p>
<p>I get this running on <code>localhost/quiz</code>: <code>Load config file from: http://localhost</code> while running it online I get it correct.</p>
<p>How would I get this URL to work both locally and online?</p> | 0 |
How to acess jvm default KeyStore? | <p>I want to use java key store to save keys and certificates. can anybody share some code to help me with this?</p> | 0 |
C++: Undefined symbols for architecture x86_64 | <p>I have read most of the other posts with this title, but I could not find a solution.</p>
<p>I have three files (I know the whole program doesn't make any sense, it is just for test purposes):</p>
<p>main.cpp</p>
<pre><code>#include "Animal.h"
Animal ape;
int main(int argc, char *argv[]){
ape.getRace();
return 0;
}
</code></pre>
<p>Animal.h</p>
<pre><code>class Animal{
public:
int getRace();
private:
int race;
};
</code></pre>
<p>Animal.cpp</p>
<pre><code>#include "Animal.h"
Animal::Animal(){
race = 0;
}
int Animal::getRace(){
race = 2;
return race;
}
</code></pre>
<p>When I run the main.cpp file I get this error:</p>
<pre><code>Undefined symbols for architecture x86_64:
"Animal::getRace()", referenced from:
_main in main-oTHqe4.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
[Finished in 0.1s with exit code 1]
</code></pre>
<p>What is wrong here?</p> | 0 |
How to create a user in Django? | <p>I'm trying to create a new User in a Django project by the following code, but the highlighted line fires an exception.</p>
<pre><code>def createUser(request):
userName = request.REQUEST.get('username', None)
userPass = request.REQUEST.get('password', None)
userMail = request.REQUEST.get('email', None)
# TODO: check if already existed
**user = User.objects.create_user(userName, userMail, userPass)**
user.save()
return render_to_response('home.html', context_instance=RequestContext(request))
</code></pre>
<p>Any help?</p> | 0 |
nginx configure default error pages | <p>First off, first time nginx user. So, I'm still learning the differences from Apache and nginx.</p>
<p>I have a stock install of nginx. (apt-get install nginx-full) I modified the default configuration found at '/etc/nginx/sites-enabled/default' for my setup. However, error pages just don't work. My docroot is /server/www, and my error pages are located within the directory /server/errors/. Below is my config.</p>
<pre><code>server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /server/www;
index index.html;
server_name website.com;
location / {
try_files $uri $uri/ /index.html;
}
error_page 403 404 405 /40x.html;
location /40x.html {
root /server/errors;
internal;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /server/errors;
internal;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
</code></pre>
<p>All pages that should generate a 403 or 404 page, just load the index.html file. I believe the something is probably happening with 500 errors, however, that's a bit harder to generate.</p>
<p>Also, if it's relevant, I moved the error pages above docroot, but they weren't working before that. I made that move as the 'internal' flag didn't appear to make the pages internal as the documentation claimed, as I could still access them directly.</p>
<p>Any advise/help you could give would be great!</p> | 0 |
Running multiple async queries with ADODB - callbacks not always firing | <p>I have an Excel workbook that fires three queries to a database to populate three tables on hidden sheets, and then runs three 'refresh' scripts to pull this data through to three visible presentation sheets (one per query). Running this synchronously is quite slow: The total time to refresh is the sum of the time of each of the three queries, plus the sum of the time for each 'refresh' script to run.</p>
<p>I'm aware that VBA isn't multi-threaded, but I thought it would be possible to speed things up a bit by firing the queries off asynchronously (thus allowing some clean-up work to be done whilst they were executing), and then doing the population / refresh work for each sheet as the data comes back.</p>
<p>I rewrote my script as follows (note that I've had to remove the connection strings, query strings etc and make the variables generic):</p>
<pre><code>Private WithEvents cnA As ADODB.Connection
Private WithEvents cnB As ADODB.Connection
Private WithEvents cnC As ADODB.Connection
Private Sub StartingPoint()
'For brevity, only listing set-up of cnA here. You can assume identical
'set-up for cnB and cnC
Set cnA = New ADODB.Connection
Dim connectionString As String: connectionString = "<my conn string>"
cnA.connectionString = connectionString
Debug.Print "Firing cnA query: " & Now
cnA.Open
cnA.Execute "<select query>", adAsyncExecute 'takes roughly 5 seconds to execute
Debug.Print "Firing cnB query: " & Now
cnB.Open
cnB.Execute "<select query>", adAsyncExecute 'takes roughly 10 seconds to execute
Debug.Print "Firing cnC query: " & Now
cnC.Open
cnC.Execute "<select query>", adAsyncExecute 'takes roughly 20 seconds to execute
Debug.Print "Clearing workbook tables: " & Now
ClearAllTables
TablesCleared = True
Debug.Print "Tables cleared: " & Now
End Sub
Private Sub cnA_ExecuteComplete(ByVal RecordsAffected As Long, ...)
Debug.Print "cnA records received: " & Now
'Code to handle the recordset, refresh the relevant presentation sheet here,
'takes roughly < 1 seconds to complete
Debug.Print "Sheet1 tables received: " & Now
End Sub
Private Sub cnB_ExecuteComplete(ByVal RecordsAffected As Long, ...)
Debug.Print "cnB records received: " & Now
'Code to handle the recordset, refresh the relevant presentation sheet here,
'takes roughly 2-3 seconds to complete
Debug.Print "Sheet2 tables received: " & Now
End Sub
Private Sub cnC_ExecuteComplete(ByVal RecordsAffected As Long, ...)
Debug.Print "cnC records received: " & Now
'Code to handle the recordset, refresh the relevant presentation sheet here,
'takes roughly 5-7 seconds to complete
Debug.Print "Sheet3 tables received: " & Now
End Sub
</code></pre>
<p>Typical expected debugger output:</p>
<pre><code>Firing cnA query: 21/02/2014 10:34:22
Firing cnB query: 21/02/2014 10:34:22
Firing cnC query: 21/02/2014 10:34:22
Clearing tables: 21/02/2014 10:34:22
Tables cleared: 21/02/2014 10:34:22
cnB records received: 21/02/2014 10:34:26
Sheet2 tables refreshed: 21/02/2014 10:34:27
cnA records received: 21/02/2014 10:34:28
Sheet1 tables refreshed: 21/02/2014 10:34:28
cnC records received: 21/02/2014 10:34:34
Sheet3 tables refreshed: 21/02/2014 10:34:40
</code></pre>
<p>The three queries can come back in different orders depending on which finishes first, of course, so sometimes the typical output is ordered differently - this is expected.</p>
<p>Sometimes however, one or two of the <code>cnX_ExecuteComplete</code> callbacks don't fire at all. After some time debugging, I'm fairly certain the reason for this is that if a recordset returns whilst one of the callbacks is currently executing, the call does not occur. For example:</p>
<ul>
<li>query A, B and C all fire at time 0</li>
<li>query A completes first at time 3, <code>cnA_ExecuteComplete</code> fires</li>
<li>query B completes second at time 5</li>
<li><code>cnA_ExecuteComplete</code> is still running, so <code>cnB_ExecuteComplete</code> never fires</li>
<li><code>cnA_ExecuteComplete</code> completes at time 8</li>
<li>query C completes at time 10, <code>cnC_ExecuteComplete</code> fires</li>
<li>query C completes at time 15</li>
</ul>
<p>Am I right in my theory that this is the issue? If so, is it possible to work around this, or get the call to 'wait' until current code has executed rather than just disappearing?</p>
<p>One solution would be to do something extremely quick during the <code>cnX_ExecuteComplete</code> callbacks (eg, a one-liner <code>Set sheet1RS = pRecordset</code> and a check to see if they're all done yet before running the refresh scripts synchronously) so the chance of them overlapping is about zero, but want to know if there's a better solution first.</p> | 0 |
How can I estimate the size of my gzipped script? | <p>How can I estimate the size of my JavaScript file after it is gzipped? Are there online tools for this? Or is it similar to using winzip for example?</p> | 0 |
Change the font path when using Font Awesome | <p>It works when I have my CSS file and the font files in the same folder.</p>
<p>But when I put my font files in side a folder, I can't get my icons.</p>
<p>Here is my CSS code..</p>
<pre><code> @font-face {
font-family: FontAwesome;
src: url(fontfile-webfont.eot?v=4.0.3);
src: url(fontfile-webfont.eot?#iefix&v=4.0.3) format('embedded-opentype')
,url(fontfile-webfont.woff?v=4.0.3) format('woff')
,url(fontfile-webfont.ttf?v=4.0.3) format('truetype')
,url(fontfile-webfont.svg?v=4.0.3#fontawesomeregular) format('svg');
font-weight: 400;
font-style: normal;
}
.att {
display: inline-block;
font-family: FontAwesome;
font-style: normal;
font-weight: 400;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.att-renren:before {
content: "\f18b";
}
</code></pre>
<p>And my folder structure...</p>
<p>CSS file</p>
<pre><code>Content/themes/common.css
</code></pre>
<p>Font files</p>
<pre><code>Content/themes/fonts/
</code></pre>
<p>Can I change the path of the font files in CSS??</p> | 0 |
ClassPathResource cannot access my spring properties file (using Spring web MVC) | <p>The actual location of the file is in "D:\eclipse\projects\issu\src\main\webapp\WEB-INF\spring\spring.properties"</p>
<p>I tried:</p>
<pre><code>Resource resource = new ClassPathResource("/src/main/webapp/WEB-INF/spring/spring.properties");
Resource resource = new ClassPathResource("/WEB-INF/spring/spring.properties");
Resource resource = new ClassPathResource("classpath:/WEB-INF/spring/spring.properties");
</code></pre>
<p>I also have added "/src/main/webapp" folder to my build path.</p>
<p>ClassPathResource cannot find it. Any ideas? thanks! :)</p>
<p><strong>my web.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>ISSU</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
</code></pre>
<p><strong>my spring-servlet.xml</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.myapps.issu" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<tx:annotation-driven />
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/spring/spring.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.databaseurl}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="${hibernate.config}" />
<property name="packagesToScan" value="com.myapps.issu" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" />
</bean>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions" value="/WEB-INF/tiles.xml" />
</bean>
<bean id="issuDao" class="com.myapps.issu.dao.IssuDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="issuService" class="com.myapps.issu.services.IssuServiceImpl">
<property name="issuDao" ref="issuDao" />
</bean>
</beans>
</code></pre> | 0 |
Stratified sampling with Random Forests in R | <p>I read the following in the documentation of <code>randomForest</code>:</p>
<blockquote>
<p>strata: A (factor) variable that is used for stratified sampling.</p>
<p>sampsize: Size(s) of sample to draw. For classification, if sampsize
is a vector of the length the number of strata, then sampling
is stratified by strata, and the elements of sampsize
indicate the numbers to be drawn from the strata.</p>
</blockquote>
<p>For reference, the interface to the function is given by:</p>
<pre><code> randomForest(x, y=NULL, xtest=NULL, ytest=NULL, ntree=500,
mtry=if (!is.null(y) && !is.factor(y))
max(floor(ncol(x)/3), 1) else floor(sqrt(ncol(x))),
replace=TRUE, classwt=NULL, cutoff, strata,
sampsize = if (replace) nrow(x) else ceiling(.632*nrow(x)),
nodesize = if (!is.null(y) && !is.factor(y)) 5 else 1,
maxnodes = NULL,
importance=FALSE, localImp=FALSE, nPerm=1,
proximity, oob.prox=proximity,
norm.votes=TRUE, do.trace=FALSE,
keep.forest=!is.null(y) && is.null(xtest), corr.bias=FALSE,
keep.inbag=FALSE, ...)
</code></pre>
<p>My question is: How exactly would one use <code>strata</code> and <code>sampsize</code>? Here is a minimal working example where I would like to test these parameters:</p>
<pre><code>library(randomForest)
iris = read.table("http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data", sep = ",", header = FALSE)
names(iris) = c("sepal.length", "sepal.width", "petal.length", "petal.width", "iris.type")
model = randomForest(iris.type ~ sepal.length + sepal.width, data = iris)
> model
500 samples
6 predictors
2 classes: 'Y0', 'Y1'
No pre-processing
Resampling: Bootstrap (7 reps)
Summary of sample sizes: 477, 477, 477, 477, 477, 477, ...
Resampling results across tuning parameters:
mtry ROC Sens Spec ROC SD Sens SD Spec SD
2 0.763 1 0 0.156 0 0
4 0.782 1 0 0.231 0 0
6 0.847 1 0 0.173 0 0
ROC was used to select the optimal model using the largest value.
The final value used for the model was mtry = 6.
</code></pre>
<p>I come to these parameters since I would like RF to use bootstrap samples that respect the proportion of positives to negatives in my data.</p>
<p><a href="https://stackoverflow.com/questions/8704681/random-forest-with-classes-that-are-very-unbalanced">This other thread</a>, started a discussion on the topic, but it was settled without clarifying how one would use these parameters.</p> | 0 |
Angular Material mat-tree with checkboxes select all | <p>I'm using <a href="https://stackblitz.com/angular/gabkadkvybq?file=app%2Ftree-checklist-example.html" rel="nofollow noreferrer">Tree with checkboxes</a>, and I want to add a button to check all checkboxes, I tried different methods but no good, the best thing i was able to achieve is this:</p>
<pre><code> selectAllFiscal() {
this.rootItems.forEach(node => {
this.todoItemSelectionToggle(node);
});
}
</code></pre>
<p>rootItems is an array of root nodes.</p>
<p>I can see that nodes are selected when I iterate <code>checklistSelection.selected</code>, but the checkboxes are not selected in the browser, can anybody point the problem, thanks.</p> | 0 |
Change 1's to 0 and 0's to 1 in numpy array without looping | <p>Let's say I have a numpy array where I would like to swap all the 1's to 0 and all the 0's to 1 (the array will have other values, and there is nothing special about the 0's and 1's). Of course, I can loop through the array and change the values one by one.</p>
<p>Is there an efficient method you can recommend using? Does the <code>np.where()</code> method have an option for this operation?</p> | 0 |
getter setter for Hashmap using generics | <p>I have the following two classes</p>
<p>Animal Class</p>
<pre><code>class Animal {
Map<String, A> data = new HashMap <String, A>();
public void setValue(HashMap<String, ?> val)
{
this.data = val;
}
public Map getValue()
{
return this.data;
}
}
</code></pre>
<p>Dog Class</p>
<pre><code>class Dog extends Animal {
public void index()
{
Map<String, A> map = new HashMap<String, A>();
map.put("name", "Tommy");
map.put("favfood", "milk"); // want to pass Lists, Integers also
setValue(map);
}
}
</code></pre>
<p>As you can see from the above code I am trying to set some values with keys in <code>index</code> method, but I am getting error warnings from eclipse in both two files. Error Messages are: </p>
<p>In Dog Class File: </p>
<pre><code>Multiple markers at this line
- A cannot be resolved
to a type
- A cannot be resolved
to a type
</code></pre>
<p>In Animal Class File :</p>
<pre><code>Multiple markers at this line
- A cannot be resolved to a type
- A cannot be resolved to a type
- Incorrect number of arguments for type Map<K,V>; it cannot be parameterized with arguments
<HashMap<String,A>>
</code></pre>
<p>The data type of the keys in HashMap will always be a String but the data types of values would be random, hence I am trying to use Generics. </p>
<p>Coming from PHP background I still haven't been able to grasp the concept of Java Generics. Could you please tell me where is the mistake in my code?</p> | 0 |
How to return on the same page after submitting a form in php.? | <p>I am making an e-commerce website where I have lots of products. If a user goes to any product items page and submits any form there then they should come on the same page. </p>
<p>So, how to come on the same page?</p> | 0 |
How to display polygon title while using google map api | <p>I have drawn polygon for each state over united states map.
I wish to display a value (text/int) on top of it. I couldnt find any polygon options able to display text on top of polygon. What are the ways to do this?</p>
<pre><code>var poly = new google.maps.Polygon({
clickable: true,
paths: pts,
strokeColor: '#000000',
strokeOpacity: 0.3,
strokeWeight: 1,
fillColor: colour,
fillOpacity: 0.8,
title: name
});
polys.push(poly);
poly.setMap(map);
</code></pre> | 0 |
empty() vs isEmpty() in Java Stack class | <p>Why does <code>Stack</code> in Java have an <code>empty()</code> method along with the usual <code>isEmpty()</code>? All abstract classes that <code>Stack</code> extends have an <code>isEmpty()</code> method.</p> | 0 |
In Javascript a dictionary comprehension, or an Object `map` | <p>I need to generate a couple of objects from lists in Javascript. In Python, I'd write this:</p>
<pre><code>{key_maker(x): val_maker(x) for x in a_list}
</code></pre>
<p>Another way to ask is does there exist something like <code>jQuery.map()</code> which aggregates objects? Here's my guess (doesn't work):</p>
<pre><code>var result = {}
$.map(a_list, function(x) {
$.extend(result, {key_maker(x): val_maker(x)})
})
</code></pre> | 0 |
Getting undefined components in React Router v4 | <p>Just upgraded to <code>react-router-dom 4.0.0</code>. All my components are either regular <code>class</code>es or fat arrows. They are all exported using <code>export default ThatComponent</code>. Yet I'm getting this:</p>
<p><em>Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) <strong>but got: undefined.</strong> You likely forgot to export your component from the file it's defined in. Check the render method of <code>Router</code>.</em></p>
<pre><code>// minimal showcase
import { BrowserRouter, Match, Miss } from 'react-router';
const Router = () => (
<BrowserRouter>
<div>
{/* both Match and Miss components below cause an error */}
<Match exactly pattern="/login" component={Login} />
<Match exactly pattern="/frontpage" component={Frontpage} />
<Match exactly pattern="/logout" render={() => (<div>logout</div>)} />
<Miss component={NoMatch} />
</div>
</BrowserRouter>
);
</code></pre>
<p>Why do the <code><Match></code> components think the other components are undefined?</p> | 0 |
Populate a column using if statements in r | <p>I have quite a simple question which I am currently struggling with. If I have an example dataframe:</p>
<pre><code>a <- c(1:5)
b <- c(1,3,5,9,11)
df1 <- data.frame(a,b)
</code></pre>
<p>How do I create a new column ('c') which is then populated using if statements on column b. For example:
'cat' for those values in b which are 1 or 2
'dog' for those values in b which are between 3 and 5
'rabbit' for those values in b which are greater than 6</p>
<p>So column 'c' using dataframe df1 would read: cat, dog, dog, rabbit, rabbit.</p>
<p>Many thanks in advance.</p> | 0 |
how to drag and drop files from a directory in java | <p>I want to implement dragging and dropping of files from a directory such as someones hard drive but can't figure out how to do it. I've read the java api but it talks of color pickers and dragging and dropping between lists but how to drag files from a computers file system and drop into my application. I tried writing the transferhandler class and a mouse event for when the drag starts but nothing seems to work. Now I'm back to just having my JFileChooser set so drag has been enabled but how to drop? </p>
<p>Any info or point in the right direction greatly appreciated.</p>
<pre><code> import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
public class FileChooserDemo
extends JPanel
implements ActionListener
{
JLabel selectedFileLabel;
JList selectedFilesList;
JLabel returnCodeLabel;
public FileChooserDemo()
{
super();
createContent();
}
void initFrameContent()
{
JPanel closePanel = new JPanel();
add(closePanel, BorderLayout.SOUTH);
}
private void createContent()
{
setLayout(new BorderLayout());
JPanel NorthPanel = new JPanel();
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenuItem quit = new JMenuItem("Quit");
menuBar.add(menu);
menu.add(quit);
NorthPanel.add(menu,BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(7,1 ));
JButton openButton = new JButton("Open...");
openButton.setActionCommand("OPEN");
openButton.addActionListener(this);
buttonPanel.add(openButton);
JButton saveButton = new JButton("Save...");
saveButton.setActionCommand("SAVE");
saveButton.addActionListener(this);
buttonPanel.add(saveButton);
JButton delete = new JButton("Delete");
delete.addActionListener(this);
delete.setActionCommand("DELETE");
buttonPanel.add(delete);
add(buttonPanel, BorderLayout.WEST);
// create a panel to display the selected file(s) and the return code
JPanel displayPanel = new JPanel(new BorderLayout());
selectedFileLabel = new JLabel("-");
selectedFileLabel.setBorder(BorderFactory.createTitledBorder
("Selected File/Directory "));
displayPanel.add(selectedFileLabel, BorderLayout.NORTH);
selectedFilesList = new JList();
JScrollPane sp = new JScrollPane(selectedFilesList);
sp.setBorder(BorderFactory.createTitledBorder("Selected Files "));
MouseListener listener = new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
JComponent comp = (JComponent) me.getSource();
TransferHandler handler = comp.getTransferHandler();
handler.exportAsDrag(comp, me, TransferHandler.MOVE);
}
};
selectedFilesList.addMouseListener(listener);
displayPanel.add(sp);
returnCodeLabel = new JLabel("");
returnCodeLabel.setBorder(BorderFactory.createTitledBorder("Return Code"));
displayPanel.add(returnCodeLabel, BorderLayout.SOUTH);
add(displayPanel);
}
public void actionPerformed(ActionEvent e)
{
int option = 0;
File selectedFile = null;
File[] selectedFiles = new File[0];
if (e.getActionCommand().equals("CLOSE"))
{
System.exit(0);
}
else if (e.getActionCommand().equals("OPEN"))
{
JFileChooser chooser = new JFileChooser();
chooser.setDragEnabled(true);
chooser.setMultiSelectionEnabled(true);
option = chooser.showOpenDialog(this);
selectedFiles = chooser.getSelectedFiles();
}
else if (e.getActionCommand().equals("SAVE"))
{
JFileChooser chooser = new JFileChooser();
option = chooser.showSaveDialog(this);
selectedFiles = chooser.getSelectedFiles();
}
// display the selection and return code
if (selectedFile != null)
selectedFileLabel.setText(selectedFile.toString());
else
selectedFileLabel.setText("null");
DefaultListModel listModel = new DefaultListModel();
for (int i =0; i < selectedFiles.length; i++)
listModel.addElement(selectedFiles[i]);
selectedFilesList.setModel(listModel);
returnCodeLabel.setText(Integer.toString(option));
}
public static void main(String[] args)
{
SwingUtilities.invokeLater
(new Runnable()
{
public void run()
{
FileChooserDemo app = new FileChooserDemo();
app.initFrameContent();
JFrame frame = new JFrame("LoquetUP");
frame.getContentPane().add(app);
frame.setDefaultCloseOperation(3);
frame.setSize(600,400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
//frame.pack();
frame.setVisible(true);
}
});
}
}
</code></pre> | 0 |
React Material UI - Export multiple higher order components | <p>I'm stuck on exporting material-ui styles with redux connector. Here is my code:</p>
<pre><code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import Drawer from 'material-ui/Drawer';
import { withStyles } from 'material-ui/styles';
import PropTypes from 'prop-types';
const mapStateToProps = state => ({});
const reduxConnector = connect(mapStateToProps, null);
const styles = theme => {
console.log(theme);
return ({
paper: {
top: '80px',
boxShadow: theme.shadows[9]
},
});
};
class Cart extends Component {
render() {
const { classes } = this.props;
return (
<Drawer
open
docked
anchor="right"
classes={{ paper: classes.paper }}
>
<p style={{ width: 250 }}>cart</p>
</Drawer>
);
}
}
export default withStyles(styles, {name: 'Cart'})(Cart);
export default reduxConnector(Cart); // I want to add this
</code></pre>
<p>I've tried:</p>
<pre><code>export default reduxConnector(withStyles(styles))(Cart); // return Uncaught TypeError: Cannot call a class as a function
export default withStyles(styles, {name: 'Cart'})(reduxConnector(Cart)); // return Uncaught Error: Could not find "store" in either the context or props of "Connect(Cart)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(Cart)".
</code></pre>
<p>Any solution?</p> | 0 |
SQL -- Assigning a bit variable in select statement | <p>For example:</p>
<pre><code>declare @bitHaveRows bit
select @bitHaveRows = count(*)
from table
where (predicate)
</code></pre>
<p>Are there any functions I can call on this line:</p>
<pre><code>select @bitHaveRows = count(*)
</code></pre>
<p>to assign this bit a value of 0 if there are no rows, or 1 if there are one or more rows?</p> | 0 |
Is too many Left Joins a code smell? | <p>If you have for example > 5 left joins in a query is that a code smell that there is ...</p>
<ul>
<li>something wrong with your design?</li>
<li>you're doing too much in one query?</li>
<li>you're database is too normalized?</li>
</ul> | 0 |
How to pass password to scp? | <p>I know it is not recommended, but is it at all possible to pass the user's password to scp?</p>
<p>I'd like to copy a file via scp as part of a batch job and the receiving server does, of course, need a password and, no, I cannot easily change that to key-based authentication.</p> | 0 |
No Module named django.core | <p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p>
<pre><code>Traceback (most recent call last):
File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in <module>
from django.core import management
ImportError: No module named django.core
</code></pre> | 0 |
Use jQuery to find the label for a selected control or textbox | <p>I want a bit of jQuery code that will allow me to find the label for a control when I click on the textbox... so in my HTML I have this:</p>
<pre><code><label id="ctl00_WebFormBody_lblProductMarkup" for="ctl00_WebFormBody_txtPriceAdjustment">This Is My Label Value</label>
<input type="text" style="width:29px;" onclick="alert('label value here');" title="Here is a title" id="ctl00_WebFormBody_txtPriceAdjustment" maxlength="3" name="ctl00$WebFormBody$txtPriceAdjustment">
</code></pre>
<p>So, when I click on my textbox, I want (for example) to do an alert... with the text that is within my label - so in this case it would alert "This is my label value"</p>
<p>Hope that makes sense :)</p> | 0 |
Base Class Doesn't Contain Parameterless Constructor? | <p>I'm making my constructors a bit more strict by removing some of my empty constructors. I'm pretty new to inheritance, and was perplexed with the error that I got: Base Class Doesn't Contain Parameterless Constructor. How can I make A2 inherit from A without there being an empty constructor in A. Also, for my own personal understanding, why is A2 requiring an empty constructor for A? </p>
<pre><code>Class A{
//No empty constructor for A
//Blah blah blah...
}
Class A2 : A{
//The error appears here
}
</code></pre> | 0 |
IE display: table-cell child ignores height: 100% | <p>I need to dynamically build a table to hold some data.<br>
I've followed the usual approach of using divs with <code>display: table</code>, <code>display: table-row</code> and <code>display: table-cell</code>:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tab {
display: table;
height:100%;
width: 200px;
}
.row {
height: 100%;
display: table-row;
}
.elem {
border: 1px solid black;
vertical-align: top;
display: table-cell;
height:100%;
background: blue;
}
.content {
height: 100%;
background: greenyellow;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tab">
<div class="row">
<div class="elem">
<div class="content">
Content
</div>
</div>
<div class="elem">
<div class="content">
Longer content that will need to wrap around eventually you know and don't you hate it when things don't end as you expect them octopus
</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p><a href="http://jsfiddle.net/eLo4ge1y/" rel="noreferrer"><strong>Or view on Jsfiddle.</strong></a></p>
<p>In most browsers I get the expected output:</p>
<p><img src="https://i.stack.imgur.com/Thue3.png" alt="Sample image"></p>
<p>However, in IE8 (and possibly later versions, I haven't tested later versions), I get the following:</p>
<p><img src="https://i.stack.imgur.com/UkZoe.png" alt="Sample image 2"></p>
<p>The <code>height: 100%</code> set on the div surrounding <em>"Content"</em> is ignored.</p>
<p>According to <a href="http://caniuse.com/#feat=css-table" rel="noreferrer">CanIUse</a>, IE8 should offer full support for the related display properties.</p>
<p>I've looked through a number of similar questions on SO without finding a working solution: most solutions either rely on Javascript (which I'm looking to avoid), use a fixed height (ibid previous) or don't work on IE8.</p> | 0 |
How to change visibility of layout programmatically | <p>There is a way to change the visibility of View in the XML, but how can I change programmatically visibility of the layout defined in XML? How to get the layout object?</p>
<pre><code><LinearLayout
android:id="@+id/contacts_type"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone">
</LinearLayout>
</code></pre> | 0 |
How to assign a PHP variable value to JavaScript variable | <p>In this code which I am posting i have one problem. I want my PHP variable to be stored in JavaScript variable but it shows error. The code is below.</p>
<pre><code><?php
$name="anurag singh";
echo '
<html>
<head>
<script type="text/javascript" src="jquery-2.0.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var name1=.$name.";"
$.post("main_page.php",{input1: name1}, function(msg){
alert("hi "+msg);
});
});
</script>
</head>
<body>
<h1>This is the demo!</h1>
<h2>In echo we can add more than one statements</h2>
</body>
</html>
';
?>
</code></pre>
<p>Now when I am assigning <code>$name</code> to the variable <code>name1</code> than I get an syntax error. Please let me know what changes I have to make. So that I get the value of the PHP variable <code>$name</code> stored in JavaScript variable <code>name1</code>.</p> | 0 |
Butterknife is unable to bind inside my Adapter Class | <p>I have an Adapter that draws the layouts for my Navigation Drawer. My navigation drawer contains two inner xml files: One being the <code>Header</code> and the other being the <code>Row</code>. I draw these out in a single adapter, but when I'm trying to <code>setText()</code> on my header, I get failure to bind. Here is my adapter class:</p>
<pre><code>public class DrawerAdapter extends RecyclerView.Adapter<DrawerAdapter.ViewHolder> {
private static final int HEADER_TYPE = 0;
private static final int ROW_TYPE = 1;
private static Context context;
private static DatabaseHelper databaseHelper;
private List<String> rows;
private List<Integer> icons;
private String driverName;
public DrawerAdapter(Context context, List<String> rows, List<Integer> icons, String driverName, DatabaseHelper databaseHelper) {
this.icons = icons;
this.rows = rows;
this.context = context;
this.driverName = driverName;
this.databaseHelper = databaseHelper;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == HEADER_TYPE) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.drawer_header, parent, false);
return new ViewHolder(view, viewType);
} else if (viewType == ROW_TYPE) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.drawer_row, parent, false);
return new ViewHolder(view, viewType);
}
return null;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
if (holder.viewType == ROW_TYPE) {
String rowText = rows.get(position - 1);
int imageView = icons.get(position - 1);
holder.textView.setText(rowText);
holder.imageView.setImageResource(imageView);
} else if (holder.viewType == HEADER_TYPE) {
holder.driverNameText.setText(driverName);
}
}
@Override
public int getItemCount() {
return rows.size() + 1;
}
@Override
public int getItemViewType(int position) {
if (position == 0)
return HEADER_TYPE;
return ROW_TYPE;
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected int viewType;
@Bind(R.id.drawer_row_icon)
ImageView imageView;
@Bind(R.id.drawer_row_text)
TextView textView;
@Bind(R.id.drawer_row_id)
FrameLayout listRow;
@Bind(R.id.driverName)
TextView driverNameText;
public ViewHolder(View itemView, int viewType) {
super(itemView);
this.viewType = viewType;
if (viewType == ROW_TYPE) {
ButterKnife.bind(this, itemView);
imageView.setOnClickListener(this);
textView.setOnClickListener(this);
listRow.setOnClickListener(this);
} else {
ButterKnife.bind(this, itemView);
}
}
}
</code></pre>
<p>As you can see in my <code>onCreateViewHolder</code> method, I'm checking for both <code>viewType</code>'s so I know which layout to draw. This in turn will create a new object for the <code>ViewHolder</code> class in which I "TRY" to bind the elements inside my xml depending on the <code>viewType</code>. Am I missing something, or doing something wrongly?</p> | 0 |
matplotlib centered bar chart with dates | <p>To get the bars where the x-axis are dates, I am doing something like this:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import datetime
x = [datetime.datetime(2010, 12, 1, 0, 0),
datetime.datetime(2011, 1, 1, 0, 0),
datetime.datetime(2011, 5, 1, 1, 0)]
y = [4, 9, 2]
ax = plt.subplot(111)
barWidth=20
ax.bar(x, y, width=barWidth)
ax.xaxis_date()
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/dkb2J.png" alt="enter image description here"></p>
<p>However, the plots are not centered around x. If have previously used ax.bar(x-barWidth/2.,y,width=barWidth) to get bar, which are centered around x. Is there a way to get the same when the x-axis values are dates?</p> | 0 |
Autorun.inf file not lunching the exe on Windows 7 environment | <p>I am writing code for autorun.inf file such as </p>
<pre><code>[autorun]
open=Viewer\viewer.exe
icon=Viewer\viewer.exe,1
</code></pre>
<p>.exe is inside the Viewer Folder but i want to run or lunch this exe automatically (as Autoplay) whenever user insert CD/DVD inside the CD/DVD Drive.</p>
<p>But actually this is not working. I dont know why?</p>
<p>OS: Windows 7 (32 Bit)</p> | 0 |
Printing the value of EOF | <p>In Kernighan and Ritchie (the C programming language):</p>
<p>'Write a program to print the value of EOF'</p>
<p>I wrote:</p>
<pre><code>#include <stdio.h>
main(){
int c;
c = getchar();
if ((c = getchar()) == EOF)
putchar(c);
}
</code></pre>
<p>but it doesn't output anything Why?</p> | 0 |
EditText vs TextView | <p>I read the API's and see that <code>TextView</code> is a super class to <code>EditText</code>, but I have a short and simple question: Generally speaking, <code>EditText</code> is used when the text displayed is subject to change, whether it's from the user or the app. <code>TextView</code> is used when the text displayed is to be constant/same forever. Is this correct?</p> | 0 |
Nested aggregate functions, Max(Avg()), in SQL | <p>I'm writing this query in SQL :</p>
<pre><code>select MAX(AVG(salary) ) from employees group by department_id;
</code></pre>
<p>First I will get groups by <code>department_id</code> , but next what will happen ?</p> | 0 |
Using SparseIntArray instead of HashMap <Integer, Integer> with putSerializable | <p>When I use a <code>HashMap</code> with an <code>Integer</code> key and data values in Android I get this message in Eclipse:</p>
<pre><code>Use new SparseIntArray(...) for better performance
</code></pre>
<p>Now the problem is that <code>SparseIntArray()</code> doesn't implement the <code>Serializable</code> interface and can't be used with <code>getSerializable()</code> and <code>putSerializable()</code> in <code>onRestoreInstanceState()</code>.</p>
<ol>
<li><p>How important is using <code>SparseIntArray()</code> instead of the <code>HashMap<Integer, Integer></code>? </p></li>
<li><p>Should I go through the trouble of making <code>SparseIntArray</code> serializable? (My first idea is making a wrapper class that implements <code>Serializable</code>, is this the right way to go?)</p></li>
</ol> | 0 |
Java -version shows java 8 while java 11 is installed | <p>After installing java 11 on my system, runtime continues to be 1.8 </p>
<p>Versions of java installed: </p>
<ul>
<li>C:\Program Files\Java\jre1.8.0_201</li>
<li>C:\Program Files\Java\jdk-11.0.3</li>
</ul>
<p>JAVA_HOME env variable value: <code>C:\Program Files\Java\jdk-11.0.3</code></p>
<p>From command prompt running <code>java -version</code> command, expecting to see java 11 info but instead I see java 8.</p>
<p>Changing environment variable value does not change the results, rebooting doesn't seem to be doing anything.</p>
<pre class="lang-bsh prettyprint-override"><code>C:\Users\user>java -version
java version "1.8.0_211"
Java(TM) SE Runtime Environment (build 1.8.0_211-b12)
Java HotSpot(TM) Client VM (build 25.211-b12, mixed mode)
</code></pre>
<p>expected is that java 11 runtime info is displayed</p> | 0 |
VSTS unable to load the service index for source 401 | <p>I'm aware of the other posts about the same signature. I still can't resolve my issue after going thru them.</p>
<p>My team uses VSTS's build definition for continuous integration.
<a href="https://i.stack.imgur.com/6VpzE.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/6VpzE.jpg" alt="enter image description here"></a></p>
<p>This build definition works fine until the lastes pull request.
I'm running into the error msg below during the Nuget Restore</p>
<blockquote>
<p>2018-06-20T00:37:27.6438127Z System.AggregateException: One or more errors occurred. ---> NuGet.Protocol.Core.Types.FatalProtocolException: Unable to load the service index for source <a href="https://microsoft.pkgs.visualstudio.com/_packaging/CBT/nuget/v3/index.json" rel="noreferrer">https://microsoft.pkgs.visualstudio.com/_packaging/CBT/nuget/v3/index.json</a>. ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).</p>
</blockquote>
<p>I do have <a href="https://microsoft.pkgs.visualstudio.com/_packaging/CBT/nuget/v3/index.json" rel="noreferrer">https://microsoft.pkgs.visualstudio.com/_packaging/CBT/nuget/v3/index.json</a> in the nuget.config, and there is <strong>nothing changed</strong> in the nuget.config in the failing PR</p>
<p>I can nuget restore and build the entire solution successfully on my local machine using VS2017. The only related change in the PR is that instead of using package.config, it uses packagereference to get the nuget package. I tried to move back to using package.config, the build would still fail with the same error msg.</p>
<p>Thanks in advance.</p> | 0 |
How to add bootstrap in Eclipse for jsp pages | <p>I'm having problem while including Bootstrap.jar lib in my eclipse project. I'm unable to access it in my JSP page. </p>
<p>Can anyone help me out so that i can access it in my jsp page.</p> | 0 |
error: expected unqualified-id before ‘int’ | <p>I'm getting the following error when I try to compile my code. I've read through other questions from people who get the same error but none of the answers are relevant to me.</p>
<pre><code>user.cpp:15:7: error: expected unqualified-id before ‘int’
User(int user_id, string user_name, int user_year, int user_zip)
^
user.cpp:15:7: error: expected ‘)’ before ‘int’
</code></pre>
<p>Any help would be appreciated.</p>
<p>user.cpp:</p>
<pre><code>#include "user.h"
using namespace std;
User(int user_id, string user_name, int user_year, int user_zip)
{
id = user_id;
name = user_name;
year = user_year;
zip = user_zip;
friends = {};
}
~User()
{
}
void User::add_friend(int id)
{
friends.push_back(id);
}
void User::delete_friend(int id)
{
for (int i = 0; i < friends.size();++i)
{
if (friends[i] == id)
{
friends.erase(vec.begin() + i);
}
}
}
int User::getID()
{
return id;
}
string User::getName()
{
return name;
}
int User::getYear()
{
return year;
}
int User::getZip()
{
return zip;
}
vector<int>* User::getFriends()
{
return &friends;
}
</code></pre>
<p>user.h:</p>
<pre><code>#ifndef USER_H
#define USER_H
#include <string>
#include <vector>
class User {
public:
User(int user_id, std::string user_name, int user_year, int user_zip);
~User();
void add_friend(int id);
void delete_friend(int id);
int getID();
std::string getName();
int getYear();
int getZip();
std::vector<int>* getFriends();
private:
int id;
std::string name;
int year;
int zip;
std::vector<int> friends;
};
#endif
</code></pre> | 0 |
The opposite of the modulo operator? | <p>I remember in java that, the modulo operator could be inverted so that rather than seeing what the remainder is of an operation, you could invert it, so instead it will tell you many times a number was divided by:</p>
<pre><code>Console.WriteLine(1000 % 90);
Console.WriteLine(100 % 90);
Console.WriteLine(81 % 80);
Console.WriteLine(1 % 1);
</code></pre>
<p><strong>Output:</strong></p>
<ul>
<li>10</li>
<li>10</li>
<li>1</li>
<li>0</li>
</ul>
<p><em>Examples courtesy of DotNetPerls</em></p>
<p>Rather than seeing the remainder, I want to see how many times '80' went into '81'. Which should be 1 with a remainder of 1.</p>
<p>Does the c# modulo operator support this behaviour? If not, how might achieve the desired behaviour? With minimal code please ... :D </p>
<p>EDIT:</p>
<p>I imagine the answer is going to be something simple like dividing the two numbers and getting rid of the '-.#' value and keeping the integer '1.-'. I know about this but there must be a slicker way of doing this?</p> | 0 |
How to install the ia32-libs in a 64-bit Linux? | <p>I wanna to install the ia32-libs in my linux mint, but when i use <code>apt-get</code> ,it told me sth like this:</p>
<pre><code>Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
gconf2 : Depends: gconf-service (= 3.2.6-1)
ia32-libs : Depends: ia32-libs-i386
libc6 : Breaks: locales (< 2.17)
libgconf2-4 : Depends: libgconf-2-4 (= 3.2.6-1) but 3.2.6-0ubuntu1 is to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).
</code></pre>
<p>is the locales package broken? then i use <code>apt-get -f install</code>:</p>
<pre><code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following packages were automatically installed and are no longer required:
dh-apparmor emacs23-bin-common emacs23-common emacs23-common-non-dfsg fonts-texgyre html2text language-pack-zh-hans language-pack-zh-hans-base latex-beamer latex-xcolor libimobiledevice2
libkrb5-dev libusbmuxd1 pgf prosper ps2eps systemtap-common systemtap-runtime tex-gyre texlive-extra-utils texlive-font-utils texlive-fonts-recommended texlive-fonts-recommended-doc
texlive-latex-recommended texlive-latex-recommended-doc texlive-pstricks texlive-pstricks-doc tipa ttf-marvosym
Use 'apt-get autoremove' to remove them.
The following extra packages will be installed:
gconf-service gconf2-common libgconf-2-4 locales
The following packages will be REMOVED:
gconf-service-backend language-pack-gnome-en language-pack-gnome-en-base language-pack-gnome-zh-hans language-pack-gnome-zh-hans-base ubuntu-minimal
The following packages will be upgraded:
gconf-service gconf2-common libgconf-2-4 locales
4 upgraded, 0 newly installed, 6 to remove and 1576 not upgraded.
4 not fully installed or removed.
Need to get 0 B/5,679 kB of archives.
After this operation, 4,895 kB disk space will be freed.
Do you want to continue [Y/n]? y
WARNING: The following packages cannot be authenticated!
locales gconf-service libgconf-2-4 gconf2-common
Install these packages without verification [y/N]? y
Preconfiguring packages ...
(Reading database ... 219432 files and directories currently installed.)
Preparing to replace locales 2.13+git20120306-9 (using .../locales_2.17-92_all.deb) ...
Unpacking replacement locales ...
dpkg: error processing /var/cache/apt/archives/locales_2.17-92_all.deb (--unpack):
**trying to overwrite '/usr/sbin/validlocale', which is also in package libc-bin 2.17-0ubuntu5**
dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Errors were encountered while processing:
/var/cache/apt/archives/locales_2.17-92_all.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)
</code></pre>
<p>is there any method to solve this problem ?</p> | 0 |
Reading a pickle file (PANDAS Python Data Frame) in R | <p>Is there an easy way to read pickle files (.pkl) from Pandas Dataframe into R? </p>
<p>One possibility is to export to CSV and have R read the CSV but that seems really cumbersome for me because my dataframes are rather large. Is there an easier way to do so?</p>
<p>Thanks!</p> | 0 |
Problems with unixODBC and FreeTDS config | <p>I have been working on this for way too long and can't seem to figure it out. I am sure I have something wrong in my freetds.conf, odbc.ini or odbcinst.ini. I can connect to my mssql 2008 server using tsql, but still can't with isql or of course through php.</p>
<p>I am on CentOS 5.6.</p>
<p>Can anyone offer some assistance?</p>
<p>Thanks!
Shawn</p>
<p>This is in my sqltrace.log:</p>
<pre><code> [ODBC][12249][1347850711.939084][__handles.c][459]
Exit:[SQL_SUCCESS]
Environment = 0x1b5fc6c0
[ODBC][12249][1347850711.939149][SQLAllocHandle.c][375]
Entry:
Handle Type = 2
Input Handle = 0x1b5fc6c0
[ODBC][12249][1347850711.939187][SQLAllocHandle.c][493]
Exit:[SQL_SUCCESS]
Output Handle = 0x1b5fcff0
[ODBC][12249][1347850711.939231][SQLConnect.c][3654]
Entry:
Connection = 0x1b5fcff0
Server Name = [MSSQL_DSN][length = 9 (SQL_NTS)]
User Name = [InetIndyArtsRemote][length = 18 (SQL_NTS)]
Authentication = [**********][length = 10 (SQL_NTS)]
UNICODE Using encoding ASCII 'ISO8859-1' and UNICODE 'UCS-2LE'
DIAG [01000] [FreeTDS][SQL Server]Unexpected EOF from the server
DIAG [01000] [FreeTDS][SQL Server]Adaptive Server connection failed
DIAG [S1000] [FreeTDS][SQL Server]Unable to connect to data source
[ODBC][12249][1347850711.949640][SQLConnect.c][4021]
Exit:[SQL_ERROR]
[ODBC][12249][1347850711.949694][SQLFreeHandle.c][286]
Entry:
Handle Type = 2
Input Handle = 0x1b5fcff0
[ODBC][12249][1347850711.949735][SQLFreeHandle.c][337]
Exit:[SQL_SUCCESS]
[ODBC][12249][1347850711.949773][SQLFreeHandle.c][219]
Entry:
Handle Type = 1
Input Handle = 0x1b5fc6c0
</code></pre>
<p>freetds.conf:</p>
<pre><code> # $Id: freetds.conf,v 1.12 2007/12/25 06:02:36 jklowden Exp $
#
# This file is installed by FreeTDS if no file by the same
# name is found in the installation directory.
#
# For information about the layout of this file and its settings,
# see the freetds.conf manpage "man freetds.conf".
# Global settings are overridden by those in a database
# server specific section
[global]
# TDS protocol version
tds version = 8.0
# Whether to write a TDSDUMP file for diagnostic purposes
# (setting this to /tmp is insecure on a multi-user system)
dump file = /tmp/freetds.log
debug flags = 0xffff
dump file append = yes
# Command and connection timeouts
; timeout = 10
; connect timeout = 10
# If you get out-of-memory errors, it may mean that your client
# is trying to allocate a huge buffer for a TEXT field.
# Try setting 'text size' to a more reasonable limit
text size = 64512
[IndyArtsDB]
host = xxx.xx.xxx.xx
port = 1433
tds version = 8.0
client charset = UTF-8
</code></pre>
<p>ODBC.INI</p>
<pre><code>[MSSQL_DSN]
Driver=FreeTDS
Description=IndyArts DB on Rackspace
Trace=No
Server=xxx.xx.xxx.xx
Port=1433
Database=DBName
</code></pre>
<p>ODCBINST.INI</p>
<pre><code>[ODBC]
DEBUG=1
TraceFile=/home/ftp/sqltrace.log
Trace=Yes
[FreeTDS]
Description=MSSQL Driver
Driver=/usr/local/lib/libtdsodbc.so
UsageCount=1
</code></pre> | 0 |
Can I delete a HttpSession manually in a servlet? | <p>I took a JSP class and we learnt that we should always remove all the attributes of the HttpSession before we use it. So one of my classmate asked - "How about we delete the HttpSession permanently after we've done using it?" </p>
<p>So, my question is "can a HttpSession be deleted?"</p>
<p>From what I understand so far.... HttpSession is created by the servlet container, same as HttpServletRequest and HttpServletResponse. We get it through the HttpServletRequest, but we cannot delete it manully. Instead, there is timeout we can set to make the session end. Since we cannot delete it, we need to make sure we clean the session before we use it. Am I correct?</p>
<p>Thanks!</p> | 0 |
Glossy gradient with android drawable xml | <p>I'm trying to bring out a glossy xml drawable gradient as a background to a layout. I am already using the start color and end color boring linear gradient. </p>
<pre><code><item>
<shape>
<gradient
android:angle="90"
android:startColor="#242424"
android:endColor="#4e4e4e"
android:type="linear" />
</shape>
</item>
</code></pre>
<p>Is there any way to control its range of flow? Please some one help.</p>
<p><strong>Edited:</strong></p>
<p>Ok, I have done a little hack around method to get a nice glossy looking title bar,</p>
<blockquote>
<p>Linear Layout (with a gradation - drawable background, specifying all
the start and end color values separately) Over this are the icons, (I
used Image buttons with transparent BG), and over this another Relative Layout (with may
be a drawable gradient or a fixed, grey color - for glossiness -
android:background="#20f0f0f0" ) Here 20 is defining the Alpha value.</p>
</blockquote>
<p>P.S, This might not be a correct work around, but I'm quiet satisfied with this because switching themes according to clients needs is much faster when compared to 9 patch PNG files (hey, BTW this is just my opinion on it)</p>
<p>And this <a href="http://www.dibbus.com/2011/08/even-more-gradient-buttons-for-android/" rel="noreferrer">link</a> is so informative on this,</p> | 0 |
How do I define Foreign Key Optional Relationships in FluentAPI/Data Annotations with the Entity Framework? | <p>I have a (sample) application with the following code:</p>
<pre><code>public class Posts
{
[Key]
[Required]
public int ID { get; set; }
[Required]
public string TypeOfPost { get; set; }
public int PollID { get; set; }
public virtual Poll Poll { get; set; }
public int PostID { get; set; }
public virtual Post Post { get; set; }
}
</code></pre>
<p>Basically, I don't know if there is a better way of doing this, but, I have a list of Posts, and, people can choose if it is a <code>Poll</code> or a <code>Post</code>, As Entity Framework doesn't work with Enums, I just store it as a string in <code>TypeOfPost</code> and then in the application, I programmatically query either Poll or Post based on the value of <code>TypeOfPost</code>.</p>
<p>I don't think there is anyway of setting "Only one required" or similar, so, I handle all the checking and stuff in the application. (If anyone knows a better way, please say!).</p>
<p>Anyway, the problem is, I can get this working fine by going in to SQL Management Studio and manually editing the schema to allow nulls - but, I just can't work out how to do this in the FluentAPI, and need some help.</p>
<p>I have tried both of the following:</p>
<pre><code>modelBuilder.Entity<Post>()
.HasOptional(x => x.Poll).WithOptionalDependent();
modelBuilder.Entity<Post>()
.HasOptional(x => x.Poll).WithOptionalPrincipal();
</code></pre>
<p>The first one seems to create an additional column in the database that allows nulls, and the second one doesn't appear to do anything.</p>
<p>I believe the first one is the one I need, but, I need to use it in combination with [ForeignKey] in the <code>Post</code> Class. If I am correct here, Should the [ForeignKey] go on the virtual property, or the ID of the property?</p>
<p>In addition, what is the actual difference between <code>WithOptionalDependent</code> and <code>WithOptionalPrincipal</code>? - I have read on MSDN, but, I really do not understand the difference.</p> | 0 |
jdbc spring security, apache commons dbcp | <p>In a Spring Security, I defined a jdbc auth manager:</p>
<pre><code><security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="securityDataSource"/>
</security:authentication-provider>
</security:authentication-manager>
<bean id="securityDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://127.0.0.1:5432/mydb"/>
... user and password props ...
</bean>
</code></pre>
<p>At this point I've discovered that I need Jakarta Commons DBCP.
I've added commons-dbcp-1.4, i get the following exception:</p>
<pre><code>...java.lang.NoClassDefFoundError: org/apache/commons/pool/KeyedObjectPoolFactory
</code></pre>
<p>This path actually isn't included in commons dbcp 1.4. <br />
What am I missing again? <br /></p>
<p>EDITED<br />
Ok, added the dependency to common pool, it works because with the right credentials I no more get the "bad credentials" page.
But I get an HTTP Status 403 - Access is denied. <br />
Seems like my user is authenticated , but isn't authorized. <br />
Any idea...? :-) <br />
<br />
My http element is:</p>
<pre><code><security:http auto-config="true" >
<security:intercept-url pattern="/**" access="ROLE_USER"/>
</security:http>
</code></pre>
<p>and I have a "test" user that is bind to the "USER" role in the "authorities" table.</p>
<p>thanks</p> | 0 |
extjs rowexpander how to expand all | <p>I'm using <code>Ext.ux.grid.RowExpander</code></p>
<pre><code>var expander = new Ext.ux.grid.RowExpander({
tpl : new Ext.Template(
'<p>{history}</p>'
)
});
</code></pre>
<p>it's used in my grid:</p>
<pre><code> var grid = new Ext.grid.GridPanel({
store: store,
columns: [
expander,
...
</code></pre>
<p>Now i want all expander rows to be expanded by deafult.</p>
<p>I'm trying to use <code>expander.expandRow(grid.view.getRow(0));</code> (i think if i make it, i'll be able to use a for loop :) but i get an error</p>
<pre><code>this.mainBody is undefined @ ***/ext/ext-all.js:11
</code></pre>
<p>Please, help me to expand all rows of my grid! Thanks!</p> | 0 |
How to disable some items of javaFX ComboBox? | <p>Can someone show me how to disable some item of my combobox (With FXML or Java code)? here is my ComboBox:</p>
<pre><code><ComboBox fx:id="cBox">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="Easy" />
<String fx:value="Normal" />
<String fx:value="Hard" />
</FXCollections>
</items>
</ComboBox>
</code></pre>
<p>Thanks!</p> | 0 |
How to use single & multiple comment line in twig | <p>I'm new in twig project. I need to comment some code like // or /**/. how to use comment in twig?</p>
<pre><code> {%if role=3 %}
<div class="col-md-6">
<div class="form-group">
<label class="control-label">&nbsp;</label>
<select multiple class="form-control" id="path_attachment" name="path_attachment[]"></select>
</div>
</div>
{% else %}
<div class="col-md-6"></div>
{% endif %}
</code></pre> | 0 |
Searching all cells in a column Excel with vbscript | <p>I wrote a vbScript to gather computer information for each user's computer on login, and Id like to have the script record the information to an Excel sheet on the server, with each computer having its own row.</p>
<p>I wrote this like 6 years ago but lost the script and havent touched vbScript since.</p>
<p>So what I need to do is, </p>
<ol>
<li>check all the cells in column B (which would be computer name) that have a value</li>
<li>compare that value to value saved for the computer's name</li>
<li>if it matches, write the computer info to that row</li>
<li>if there are no matches, then write the info to the first empty row</li>
</ol>
<p>I have no idea where to start since vbScript is pretty foreign to me.</p>
<p>Edit - I have this loop so far and that echo to test it, but it only goes to 1, while I have like 6 rows with values in column 0. I tried that conditional to check the cell value for a value I know exists and I get a runtime error.</p>
<pre><code>Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("test.xlsx")
Do While objExcel.ActiveCell.Offset(iRow,0).Value<>""
WScript.Echo iRow
If objExcel.Cells(iRow,0).Value = "three" Then
WScript.Echo "three"
End If
iRow = iRow+1
Loop
WScript.Quit
</code></pre> | 0 |
Generate a sequence of numbers with repeated intervals | <p>I am trying to create sequences of number of 6 cases, but with 144 cases intervals. </p>
<p>Like this one for example </p>
<pre><code>c(1:6, 144:149, 288:293)
1 2 3 4 5 6 144 145 146 147 148 149 288 289 290 291 292 293
</code></pre>
<p>How could I generate automatically such a sequence with </p>
<pre><code>seq
</code></pre>
<p>or with another function ? </p> | 0 |
'Can't create session Unable to connect to repo' when trying to migrate svn to git | <p>I'm trying to migrate my local svn repo to git. I've been following the steps on this post: <a href="https://stackoverflow.com/questions/79165/how-to-migrate-svn-repository-with-history-to-a-new-git-repository?noredirect=1&lq=1">How to migrate SVN repository with history to a new Git repository?</a></p>
<p>More specifically, <a href="https://stackoverflow.com/a/79188/365237">this answer</a> (seemed like the simplest). The problem is whenever I try and fetch from my svn repo I keep getting the :</p>
<p><em>Can't create session: Unable to connect to a repository at URL 'file:///mypathtorepo'</em> </p>
<p>My repo is currently sitting on my local computer which is why I'm using the 'file:///' directory path. I've also tried 'svn://localhost/mypathtorepo' to no avail. How do I fix this? </p> | 0 |
Which kind of pointer do I use when? | <p>Ok, so the last time I wrote C++ for a living, <code>std::auto_ptr</code> was all the std lib had available, and <code>boost::shared_ptr</code> was all the rage. I never really looked into the other smart pointer types boost provided. I understand that C++11 now provides some of the types boost came up with, but not all of them. </p>
<p>So does someone have a simple algorithm to determine when to use which smart pointer? Preferably including advice regarding dumb pointers (raw pointers like <code>T*</code>) and the rest of the boost smart pointers. (Something like <a href="https://stackoverflow.com/a/2139254/140719">this</a> would be great). </p> | 0 |
Is there a way to force Yii to reload module assets on every request? | <p>My website is divided into separate modules. Every module has it's own specific css or js files in <code>/protected/modules/my_module/assets/css</code> or <code>js</code> for js files. Yiis assets manager creates folder when I first use page that uses my assets.
Unfortunately if I change sth in my files - Yii does not reload my css or js file. I have to manually delete <code>/projects/assets</code> folder. It is really annoying when you are developing the app.</p>
<p>Is there a way to force Yii to reload assets every request?</p> | 0 |
Swashbuckle.AspNetCore: 'No operations defined in spec!' problem after update of 'Microsoft.AspNetCore.Mvc.ApiExplorer' package to 2.2.0 | <p>we have .net core 2.1 mvc webapi project which uses Swagger.
we use following packages:</p>
<pre><code><PackageReference Include="Swashbuckle.AspNetCore" Version="3.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="3.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Filters" Version="4.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.ApiExplorer" Version="2.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.1" />
</code></pre>
<p>swashbuckle is configured in following way:</p>
<pre><code>services.AddMvcCore().AddVersionedApiExplorer();
services.AddApiVersioning();
services.AddSwaggerGen();
</code></pre>
<p>everything woks in such setup (<code>/swagger/v1/swagger.json</code> has all operations and definitions and UI is rendered properly -> having all controllers and actions, etc)</p>
<p>we are trying to migrate our .net core project from 2.1 to 2.2 .net core.</p>
<p>In order to do that (without warnings) we need upgrade <code>Microsoft.AspNetCore.Mvc.ApiExplorer</code> nuget from 2.1.2 to 2.2.0.</p>
<p>After this nuget update swagger.json (<code>/swagger/v1/swagger.json</code>) doesn't contain any <code>"paths": {}</code> and <code>"definitions": {}</code> and this results in swagger UI showing no controllers/actions (it renders: <code>No operations defined in spec!</code></p>
<p>after upgrade package these package versions is updated:</p>
<pre><code><PackageReference Include="Microsoft.AspNetCore.Mvc.ApiExplorer" Version="2.2.0" /> //was 2.1.2
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.2.0" /> //was 2.1.1
</code></pre>
<p>I've tried to upgrade swashbuckle version to v4.0.0 but it did not resolved the issue.</p>
<p>what im missing which packages needs to be updated also so <code>swagger.json</code> would be generated properly when using <code>Microsoft.AspNetCore.Mvc.ApiExplorer 2.2.0</code> package ?
or i'm missing something else ?</p> | 0 |
split firstname and lastname but only on first space | <p>I'm trying to split a string in MSSQL by only the first whitespace
Considering here can have 2 spaces in their full name, I have no idea how to do this.</p>
<p>Example:</p>
<p><code>Henk de Vries</code></p>
<p>I would like to split it into:</p>
<pre><code>Firstname: Henk
Lastname: de Vries
</code></pre> | 0 |
Request-Promise throws "no auth mechanism defined" using async/await | <p>I was just trying out async/await with <code>request-promise</code> and ran into this error:</p>
<pre><code>RequestError: Error: no auth mechanism defined
at new RequestError (node_modules/request-promise-core/lib/errors.js:14:15)
at Request.plumbing.callback (node_modules/request-promise-core/lib/plumbing.js:87:29)
at Request.RP$callback [as _callback] (node_modules/request-promise-core/lib/plumbing.js:46:31)
at self.callback (node_modules/request/request.js:188:22)
at Auth.onRequest (node_modules/request/lib/auth.js:133:18)
at Request.auth (node_modules/request/request.js:1360:14)
at Context.<anonymous> (test/routes.js:37:41)
From previous event:
at Request.plumbing.init (node_modules/request-promise-core/lib/plumbing.js:36:28)
at Request.RP$initInterceptor [as init] (node_modules/request-promise-core/configure/request2.js:41:27)
at new Request (node_modules/request/request.js:130:8)
at request (node_modules/request/index.js:54:10)
at Context.<anonymous> (test/routes.js:37:24)
</code></pre>
<p>It is an API endpoint that I built recently that's supposed to create a new user in MongoDB. It uses Basic Auth provided by Passport strategy, and I've tested with Postman that it works. I'm not exactly sure why this error is being thrown.</p>
<p>My request code (using Mocha):</p>
<pre><code>it("creates a new user", async () => {
const options = {
method: "POST",
uri: `http://localhost:${process.env.PORT}/api/users`,
headers: {
"User-Agent": "Request-Promise",
"Content-Type": "application/json"
},
body: {
email: "test@domain.com",
password: "password",
firstName: "John",
lastName: "Smith"
},
json: true
};
const resp = await request(options).auth(APP_ID, SIGNATURE, false);
expect(resp).to.be.an("object");
});
</code></pre>
<p>Edit: I should probably also add that I'm using node 8.2.1 and npm 5.3.0.</p> | 0 |
Why is a while loop needed around pthread wait conditions? | <p>I'm learning pthread and wait conditions. As far as I can tell a typical waiting thread is like this:</p>
<pre><code>pthread_mutex_lock(&m);
while(!condition)
pthread_cond_wait(&cond, &m);
// Thread stuff here
pthread_mutex_unlock(&m);
</code></pre>
<p>What I can't understand is why the line <code>while(!condition)</code> is necessary even if I use <code>pthread_cond_signal()</code> to wake up the thread.</p>
<p>I can understand that if I use <code>pthread_cond_broadcast()</code> I need to test condition, because I wake up <em>all</em> waiting threads and one of them can make the condition false again before unlocking the mutex (and thus transferring execution to another waked up thread which should not execute at that point).
But if I use <code>pthread_cond_signal()</code> I wake up just <em>one</em> thread so the condition must be true. So the code could look like this:</p>
<pre><code>pthread_mutex_lock(&m);
pthread_cond_wait(&cond, &m);
// Thread stuff here
pthread_mutex_unlock(&m);
</code></pre>
<p>I read something about spurious signals that may happen. Is this (and only this) the reason? Why should I have spurious singnals? Or there is something else I don't get?</p>
<p>I assume the signal code is like this:</p>
<pre><code>pthread_mutex_lock(&m);
condition = true;
pthread_cond_signal(&cond); // Should wake up *one* thread
pthread_mutex_unlock(&m);
</code></pre> | 0 |
Create an assoc array with equal keys and values from a regular array | <p>I have an array that looks like</p>
<pre><code>$numbers = array('first', 'second', 'third');
</code></pre>
<p>I want to have a function that will take this array as input and return an array that would look like:</p>
<pre><code>array(
'first' => 'first',
'second' => 'second',
'third' => 'third'
)
</code></pre>
<p>I wonder if it is possible to use <code>array_walk_recursive</code> or something similar...</p> | 0 |
Converting Int to Color in C# for Silverlight's WriteableBitmap | <p>In Silverlight 3 there is now a WriteableBitmap which provides get/put pixel abilities. This can be done like so:</p>
<pre><code>// setting a pixel example
WriteableBitmap bitmap = new WriteableBitmap(400, 200);
Color c = Colors.Purple;
bitmap.Pixels[0] = c.A << 24 | c.R << 16 | c.G << 8 | c.B;
</code></pre>
<p>Basically, setting a Pixel involves setting its color, and that comes by bitshifting the alpha, red, blue, green values into an integer. </p>
<p>My question is, how would you turn an integer back to a Color? What goes in the missing spot in this example:</p>
<pre><code>// getting a pixel example
int colorAsInt = bitmap.Pixels[0];
Color c;
// TODO:: fill in the color c from the integer ??
</code></pre>
<p>Thanks for any help you might have, I'm just not up on my bit shifting and I'm sure others will run into this roadblock at some point.</p> | 0 |
Connection Timeout exception for a query using ADO.Net | <p><strong>Update</strong>: Looks like the query does not throw any timeout. The connection is timing out.</p>
<p>This is a sample code for executing a query. Sometimes, while executing time consuming queries, it throws a timeout exception.</p>
<p>I <strong>cannot</strong> use any of these techniques:
1) Increase timeout.
2) Run it asynchronously with a callback. This needs to run in a synchronous manner.</p>
<p>please suggest any other techinques to keep the connection alive while executing a time consuming query?</p>
<pre><code>private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
</code></pre> | 0 |
Getting SqlBulkCopy to honor column names | <p>I'm in the process of converting some stored procedure based reporting routines to run in C#. The general idea is to use all the wonders of C#/.NET Framework and then blast the results back into the DB. Everything has been going swimmingly, except for one issue I ran into yesterday and resolved today.</p>
<p>To do the import, I'm programmatically creating a DataTable and using SqlBulkCopy to move the results to the server.</p>
<p>e.g.</p>
<pre><code> DataTable detail = new DataTable();
detail.Columns.Add(new DataColumn("Stock", Type.GetType("System.Decimal")));
detail.Columns.Add(new DataColumn("Receipts", Type.GetType("System.Decimal")));
detail.Columns.Add(new DataColumn("Orders", Type.GetType("System.Decimal")));
</code></pre>
<p>The import table had the fields in the following order.</p>
<pre><code>...
Stock decimal(18,4),
Orders decimal(18,4),
Receipts decimal(18,4)
...
</code></pre>
<p>Essentially, the value for Receipts was going into Orders, and vice versa. </p>
<p>Evidently, this is because SqlBulkCopy doesn't seem to be honoring the column name I've told it to populate - it just goes by ordinal position.</p>
<p>This is a problem for me as we use Redgate's SQL Compare. When pushing changes from one database to another, the ordinal position of columns isn't necessarily maintained. ( e.g. if you insert a new column as the third ordinal field, SQL Compare will just append it to the table on a sync, making it the last column ).</p>
<p>This seriously messes with my solution. Now, these are only 'import' tables, so if need be, I can drop and recreate them as part of any migration script with the ordinal positions intact. I'd rather not do that though.</p>
<p>Is there a way to force SqlBulkCopy to honor the column names you tell it to fill?</p> | 0 |
Fastest way to find if int array contains a number | <p>This is an odd question. I have an integer array in Java, where each int represents a color. They will either be 0xFFFFFFFF or 0x0. What would be the FASTEST way to find if this array contains ANY values equal to 0xFFFFFFFF?</p>
<p>This is my current code: </p>
<pre><code>int length = w * h;
for (int i = 0; i < length; i++) {
if (pixels[i] == 0xFFFFFFFF) {
return true;
}
}
</code></pre>
<p>I have no clue if there is a faster way to do this or not. I imagine you vets could have a trick or two though.</p>
<p>EDIT: Seeing as it is just a dumb array of pixels from Bitmap.getPixels(), there's no way it would be sorted or transformed to another storage structure. Thanks for the input, everyone, it seems like looping through is the best way in this case.</p> | 0 |
Read data into Matlab using URL | <p>I want to read weather data from Weather Unground into Matlab directly. For a given site you can select to output the data in comma delimited format. How can I write a Matlab function that will read in the information into Matlab? I don't want to download the file but rather read it in from the URL. </p>
<p>For example, here is a <a href="http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=MC9780&format=1" rel="nofollow">URL</a> of some data. Is there some Matlab function that has a URL as an input and saves data from whatever it finds there? </p> | 0 |
Facing error of "The default schema does not exist." when executing runtime query inside sp using exec() | <p>i have made a runtime query inside a sp and am exceuting the query within the sp using exec(), but when creating the sp i am getting the error</p>
<pre><code>The default schema does not exist.
</code></pre>
<p>The SP is:</p>
<pre><code>CREATE PROCEDURE MySP
@tableName varchar(100)
AS
BEGIN
SET NOCOUNT ON;
declare @selectQuery varchar(MAX)
set @selectQuery = 'select * from ' + @tableName
exec(@selectQuery)
end
</code></pre>
<p>kindly help</p> | 0 |
how do I find where a executable is present in macosx? | <p>I have a command called youtube-dl .. but dont know where it is installed.. i can run it from shell.. how do i find where it is installed ? which youtube-dl doesnt say anything.. </p> | 0 |
How to get process's grandparent id | <p>How can i get process id of the current process's parent?<br>
In general given a process id how can I get its parent process id?<br>
e.g. os.getpid() can be used to get the proccess id, and os.getppid() for the parent, how do I get grandparent,</p>
<p>My target is linux(ubuntu) so platform specific answers are ok.</p> | 0 |
Run a loop in bash with timeout in a single line | <p>I need to have a single line command that does something in a loop with a timeout.</p>
<p>Something like</p>
<pre><code>export TIMEOUT=60
export BLOCK_SIZE=65536
COMMAND="timeout TIMEOUT while true; do dd if=/tmp/nfsometer_trace/mnt/TESTFILE of=/dev/null bs=BLOCK_SIZE; done"
</code></pre>
<p>The command will be executed in 'sh' by doing the following:</p>
<pre><code>echo $COMMAND > COMMAND_FILE
sh COMMAND_FILE
</code></pre>
<p>But this gives me a syntax error:</p>
<blockquote>
<p>syntax error near unexpected token `do'</p>
</blockquote>
<p>Is there any way to have a single line command to timeout an infinite loop?</p> | 0 |
jQuery Validation plugin: submitHandler not preventing default on submit when making ajax call to servlet - return false not working | <p>I have a simple form that uses jquery and a servlet. The jquery makes an ajax call to the servlet, the servlet makes some server side calculations, then displays the results on the same page via jQuery. I don't want the form to do a default submit (and go to the servlet) because I want to stay on the same page and display results dynamically. It works exactly how I want it to as is:</p>
<p>HTML:</p>
<pre><code><form name="form1" action="FormHandler1" method="POST" class="stats-form">
<input class="stats-input" id="number0" type="text" name="number0">
<input id="number1" type="text" name="number1">
<input id="number2" type="text" name="number2">
<input id="number3" type="text" name="number3">
<input type="submit" value="Calculate" class="calculate-stats" name="stats-submit">
</form>
</code></pre>
<p>jQuery:</p>
<pre><code>form.submit (function(event) {
$.ajax({
type: form.attr("method"), // use method specified in form attributes
url: form.attr("action"), // use action specified in form attributes (servlet)
data: form.serialize(), // encodes set of form elements as string for submission
success: function(data) {
// get response form servlet and display on page via jquery
}
});
event.preventDefault(); // stop form from redirecting to java servlet page
});
</code></pre>
<p>Now, I wanted to add form validation, since the servlet expects decimal numbers to do it's calculations. The user should only be allowed to enter numbers, no other characters. To do this I adopted the popular <a href="http://jqueryvalidation.org/" rel="nofollow">jQuery Validation</a> plugin. </p>
<p>The validation works as expected, but to make my ajax call to the servlet I have to use the submitHandler jQuery Validation provides, instead of the jQuery submit method shown above. When I use the validation submitHandler, the default action of the form on submit is executed, going to the servlet page instead of staying on the same page to display my results dynamically in jQuery. I have to pass the formHandler a form, instead of an event like before, which allowed me to prevent the default action. The only option is to return false, but it doesn't work. I've been trying to figure this out for the past two days, and have pretty much exhausted my google-fu. Here is the new code giving me grief:</p>
<pre><code>form.validate({
rules: {
number0: ruleSet,
number1: ruleSet,
number2: ruleSet,
number3: ruleSet,
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
success: function () {
// get response from servlet and display on page via jQuery
}
});
return false; // required to block normal submit ajax used
}
});
</code></pre>
<p>Any help would be appreciated, I'd like to use this neat jQuery form validation, but I may just write my own jQuery validation from scratch so that I can use the form submit method that I already have working.</p> | 0 |
How to println a string and variable within the same parameters | <p>I am writing some code right now and I haven't done this in a while, how would I use the println function to write both a string and a variable?</p>
<p>I tried the following:</p>
<pre><code>System.out.println("randomtext"var);
</code></pre>
<p>and </p>
<pre><code>System.out.println("randomtext",var);
</code></pre>
<p>Neither of those seemed to work, what am I doing wrong? How do I do this?</p> | 0 |