title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
error in C++: out-of-line definition | <p><strong>CustomerInfo.cpp</strong> </p>
<pre><code>#include "CustomerInfo.h" // <==== Funtion Definition
CustomerInfo::CustomerInfo() // <==== The Scope Resolution which is two colons :: gives me access to the class
{
newZipCode = 0;
}
CustomerInfo::CustomerInfo(string name, string address, int zipCode)
{
newName = name;
newAddress = address;
newZipCode = zipCode;
}
CustomerInfo::~CustomerInfo()
{
}
string CustomerInfo::getName() const
{
return newName;
}
string CustomerInfo::getAddress() const
{
return newAddress;
}
int CustomerInfo::getZipCode() const
{
return newZipCode;
}
</code></pre>
<p><strong>The main.cpp file</strong></p>
<pre><code>#include <iostream>
#include <string>
#include "CustomerInfo.h"
using namespace std;
int main()
{
string name;
string address;
int zipCode;
cout << "Enter your name: ";
getline (cin, name);
cout << "Enter your address" << endl;
getline (cin, address);
cout << "Enter your ZipCode: ";
cin >> zipCode;
CustomerInfo Real_1(name, address, zipCode);
cout << endl << " Name: " << Real_1.getName() << endl <<
"Address: " << Real_1.getAddress() << endl <<
"ZipCode: " << Real_1.getZipCode() << endl;
return 0;
}
</code></pre>
<p><strong>The CustomerInfo.h file</strong></p>
<pre><code>#ifndef CUSTOMERINFO_H
#define CUSTOMERINFO_H
// Header ==> Function Declaration
#include <iostream>
#include <string>
using namespace std;
class CustomerInfo
{
public:
CustomerInfo(); // <==== Default Constructor
CustomerInfo(string, int); // <==== Overload Constructor
~CustomerInfo(); // <===== Destructor - Done using an object it will be destroyed out of memory'
string getName() const; // <==== Accessor Functions - Return member variables one value at a time. In addition, no void function will be used.
// getName - returns name of person
string getAddress() const;
// getAddress - returns address of person
int getZipCode() const;
// getZipCode - returns zipcode of person
private:
//Member Variables
string newName;
string newAddress;
int newZipCode;
}; // <=== Requires semicolon after brackets for classes
#endif // CUSTOMERINFO_H
</code></pre>
<p>The error I receive is out-of-line definition of 'CustomerInfo' does not match any declaration in 'CustomerInfo'</p>
<p>The following line is the error
CustomerInfo::CustomerInfo(string name, string address, int zipCode)</p> | 1 |
Python initialize class with variables in init file and default constants file | <p>I have a class with a long list of variables (at least a dozen). In the module I first import a constants file which contains some helper methods and all of the default constants. </p>
<pre><code>from myConstants import *
class SomeClass(ParentClass):
def __init__(var1=VAR1, ..., varN=VARN):
super(SomeClass, self).init(var1, ...)
self.varM = varM
</code></pre>
<p><strong>PROBLEM:</strong> I would like to be able to specify a file when I initialize the class where the file contains a subset of the constants in <code>myConstants.py</code>. The variables not in the init file would be loaded from the defaults. Something like:</p>
<pre><code>sc = SomeClass(initFile='/path/to/file')
</code></pre>
<p>My thought was to have something like</p>
<pre><code>from myConstants import *
from ConfigParser import SafeConfigParser
class SomeClass(ParentClass):
def __init__(var1=VAR1, ..., varN=VARN, initFile=''):
if initFile:
parser = SafeConfigParser().read(initFile)
var1 = parser('constants', 'var1') if parser('constants', 'var1') else VAR1
var2 = parser('constants', 'var2') if parser('constants', 'var2') else VAR2
....
varN = parser('constants', 'varN') if parser('constants', 'varN') else VARN
else:
var1 = VAR1
...
varN = VARN
super(SomeClass, self).init(var1, ...)
self.varM = varM
</code></pre>
<p><strong>QUESTION:</strong> Is this the best way to do this? If not, what is? Seems a little long winded. I'm also not married to ConfigParser. </p> | 1 |
Jackson: Deserialize Object to Array with Generics | <p>I try to write a custom JsonDeserializer, but I can't figure out how to get the Generic type information of my class.</p>
<p><strong>I18NProperty.class:</strong></p>
<pre><code>public class I18NProperty<T> extends ArrayList<T> {
public static class Content<T> {
public Locale i18n;
public T val;
}
}
</code></pre>
<p>My desired JSON representation looks like this ( <code>name</code> is an instance of <code>I18NProperty<Content<String>></code> ) :</p>
<pre><code>{
"name": {
"en": "foo",
"jp": "bar"
}
}
</code></pre>
<p>Now I tried to write a <code>JsonDeserializer</code> and I'm able to read the field names and values, <strong>but</strong> I can't figure out how to create an instance of the generic type (in this example <code>String</code>):</p>
<pre><code>public static class I18NPropertyDeserializer extends StdDeserializer<I18NProperty<? extends Content<?>>> {
protected I18NPropertyDeserializer() {
super(I18NProperty.class);
}
@Override
public I18NProperty<? extends Content<?>> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
I18NProperty<Content<?>> result = new I18NProperty<>();
while(p.nextToken() != JsonToken.END_OBJECT) {
String lang = p.getCurrentName();
p.nextToken();
--> Object val = p.readValueAs(Object.class);
--> I18NProperty.Content<?> c = new I18NProperty.Content<>();
c.i18n = new Locale(lang);
--> c.val = null;
result.add(c);
}
return result;
}
}
</code></pre>
<p>I marked the lines with <code>--></code> where I need the Generic Type information.</p>
<p>This must be possible somehow, because normally I can give Jackson a arbitrary class which contains any generic fields and it will correctly deserialize it.</p>
<p>Thanks in advance,
Benjamin</p> | 1 |
sharedPref.getInt: java.lang.String cannot be cast to java.lang.Integer | <p>I have a <code>preferences.xml</code> which contains the following definition:</p>
<pre><code><ListPreference
android:title="@string/LimitSetting"
android:summary="@string/LimitSettingText"
android:key="limitSetting"
android:defaultValue="10"
android:entries="@array/limitArray"
android:entryValues="@array/limitValues" />
</code></pre>
<p>and with values defined as follows: </p>
<pre><code><string-array name="limitArray">
<item>1 %</item>
<item>3 %</item>
<item>5 %</item>
<item>10 %</item>
<item>20 %</item>
</string-array>
<string-array name="limitValues">
<item>1</item>
<item>3</item>
<item>5</item>
<item>10</item>
<item>20</item>
</string-array>
</code></pre>
<p>which is being called in an activity as follows: </p>
<pre><code>SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int offsetProgressInitial = sharedPref.getInt("limitSetting", 10);
</code></pre>
<p>So far so good, but when the code gets actually called I get this error: </p>
<pre><code>Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at android.app.SharedPreferencesImpl.getInt(SharedPreferencesImpl.java:239)
at com.test.app.NewEntryActivity.onCreate(NewEntryActivity.java:144)
at android.app.Activity.performCreate(Activity.java:5977)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2258)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2365)
at android.app.ActivityThread.access$800(ActivityThread.java:148)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
</code></pre>
<p>This error does not make any sense to me. The list only contain values that can be converted into an int, and the default values given in the xml file and in the code also represents just a number. So why do I get this error, and how to fix it?</p> | 1 |
Implicit file extension using fopen in C++ | <p>I'm working on a project where I'm required to take input from a file with an extension ".input". when run, the user gives the filename without the file extension as a command line argument. I then take that argument, argv[1] and open the file specified but I can't get it to work without the user typing in the entire filename</p>
<p>for example:</p>
<p>user enters> run file.input
//"run" is the executable, "file.input" is the filename</p>
<p>user is supposed to enter> run file</p>
<p>how do I get this file extension implied when using this code:</p>
<pre><code>fopen(argv[1],"r");
</code></pre>
<p>I tried using a string, setting it to argv[1] and then appending ".input" to it but fopen won't accept that string.</p> | 1 |
Render HTML without the extra "data-reactid" DOM attribute in React.js? | <p>So, I'm doing something like this in one of my react.js files:</p>
<pre><code> render: function() {
var stuff = this.props.stuff;
function getHtmlForKey(key_name, title) {
var key_name = key_name.toLowerCase();
return Object.keys(thing).filter(function(key) {
return key && key.toLowerCase().indexOf(key_name) === 0;
}).map(function(key, index) {
var group_title = index === 0 ? title : '';
if(profile[key] != null && thing[key] != "") {
return (
<span>
{group_title ? (
<li className="example-group-class">{group_title}</li>
) : null }
<li key={key} className="example-class">
{thing[key]}
</li>
</span>
);
}
}, this);
}
/** Grouping by keyword **/
var group1 = getHtmlForKey('stuff1', 'Group Title 1');
/** Return Facecards **/
if (stuff) {
return (
<div className="col-md-6">
<div className="media">
<div className="pull-left">
<a href="#" onClick={this.open}>
<img src={this.props.stuff} className="media" />
</a>
</div>
<div className="top">
{group1}
</div>
}
}
</code></pre>
<p>When this renders it outputs something like:</p>
<pre><code> <li class="example-group-title" data-reactid=".0.0.2.0.$2083428221.0.1.0:0.0">Group Title</li>
</code></pre>
<p>In my other react.js file, i've got:</p>
<pre><code> var StuffApp = require('./components/StuffApp.react');
ReactDOM.render(
<StuffApp />,
document.getElementById('main-content')
);
</code></pre>
<p>How do I render the HTML so it doesn't include all the extra DOM attribute markup (that is, the data-reactid)? I just want to try and save some bits, ya know? I've been reading this related to <a href="https://facebook.github.io/react/docs/top-level-api.html" rel="nofollow">https://facebook.github.io/react/docs/top-level-api.html</a> the ReactDomServer, but was wondering if there is an even easier way? If not, how would I integrate that?</p> | 1 |
How to declare an observable on angular2 | <p><br>
How can i declare an observable and how to add data to it in angular2 ?
I have 5 hours trying to figure out how to do it.
<br>I tryed this</p>
<pre><code>this.products : Observable<array>;
var object = {"item":item};
this.products.subscribe(object)
</code></pre>
<p>everything i tryed throws me an error</p>
<p><br>
I want to use it because i have an array of objects that is changing frequently and in the template the ngFor is not changing the values.
Any help?</p>
<p><a href="http://pastebin.com/1cFXJHHk" rel="nofollow">http://pastebin.com/1cFXJHHk</a>
Here is what i try to do</p> | 1 |
Test modules and injection in Dagger 2 | <p>I'm currently developing an Android MVP Application, and I'm trying to separate my dependencies in different Dagger2 Modules.</p>
<p>The problem I'm having is about changing a module in Unit Test Time. The scenario is the following:</p>
<ul>
<li>LoginComponent, which uses two modules: LoginModule and HTTPModule</li>
<li>LoginModule in one of its methods requires an OkHttp instance, which is provided by HTTPModule.</li>
</ul>
<p>The code is the following:</p>
<pre><code>@Singleton
@Component(modules = {LoginModule.class, HTTPModule.class})
public interface LoginComponent {
}
@Module(includes = {HTTPModule.class})
public class LoginModule {
@Provides
@Singleton
public MyThing provideMyThing(OkHttpClient client) {
// Do things with it
}
}
@Module
public class HTTPModule {
@Provides
@Singleton
public OkHttpClient provideOkHttpClient(){
// Return the OkHttpClient
}
}
</code></pre>
<p>The thing is, at test time I would need to change the OkHttpClient that is returned (by making it accept all the certificates, as when I run it on the JVM it does not accept the LetsEncrypt certificate).</p>
<p>Also I would need that because I need to declare that <code>MyTest.class</code> can be injected with module, and as <code>MyTest.class</code> is under the <code>app/src/test/</code> folder, it's not visible for the classes that are placed under <code>app/src/main/</code>. What I've done until now is to copy and paste the Component and the modules to the <code>/test/</code> folder, and make the injected class declaration there. But I know there must be a proper way to achieve what I'm looking for.</p>
<p>Another thing I've tried is annotating the methods with custom Scopes (creating a <code>@TestScope</code> annotation). However this leads me to the same problem that I had commented before: I cannot make the <code>MyTest.class</code> visible to the component, because it's placed under the <code>/test/</code> folder.</p>
<p>I've already checked other similar questions, such as <a href="https://stackoverflow.com/questions/26939340/how-do-you-override-a-module-dependency-in-a-unit-test-with-dagger-2-0?lq=1">this one</a> and <a href="https://stackoverflow.com/questions/29989245/android-unit-tests-with-dagger-2">this another one</a>, but this last one is for running tests with Robolectric, and by now I'm able to unit test most of my code with JUnit4 only (Android Studio 2-Beta 8).</p>
<p>If anyone could point me to the right direction, I would be more than grateful.</p>
<p>Thanks in advance!</p> | 1 |
R read all files in a directory | <p>I am trying to read and merge together all the csv files in a directory. I found this excellent SO answer: <a href="https://stackoverflow.com/questions/11433432/importing-multiple-csv-files-into-r">Importing multiple .csv files into R</a> but it doesn't seem to work for me.</p>
<p>I am able to list the files (they are in my home directory in a sub-folder called "test"):</p>
<pre><code>library(data.table)
files <- list.files(path = "test",pattern = ".csv")
print(files)
</code></pre>
<p>This correctly prints the content of the directory.</p>
<p>When I try to load them using</p>
<pre><code>temp <- lapply(files, fread, sep=",")
data <- rbindlist(temp)
</code></pre>
<p>I get <code>File 'xyz.csv' does not exist. Include one or more spaces to consider the input a system command.</code></p>
<p>Do I have to somehow specify the path again? I fought that this information is already contained in the file object. Thanks for any help!</p> | 1 |
Weird iOS UIWebView Crash called WTF Crash | <p>I am using UIWebViews in some of the screens, because I need a perfect Html text parsing.</p>
<p>According to crash reports a huge number of crashes, called WTF Crash, occur on these screens. Here is a trace of that crash</p>
<pre><code>Crashed: WebThread
EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x00000000bbadbeef
Thread : Crashed: WebThread
0 JavaScriptCore 0x184fd2710 WTFCrash + 72
1 JavaScriptCore 0x184fd2708 WTFCrash + 64
2 WebCore 0x1852b7d78 <redacted> + 362
3 WebCore 0x1852b7bec <redacted> + 44
4 CoreFoundation 0x1817d8588 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32
5 CoreFoundation 0x1817d632c __CFRunLoopDoObservers + 372
6 CoreFoundation 0x1817d6674 __CFRunLoopRun + 696
7 CoreFoundation 0x181705680 CFRunLoopRunSpecific + 384
8 WebCore 0x1852b5998 <redacted> + 456
9 libsystem_pthread.dylib 0x18148bb28 <redacted> + 156
10 libsystem_pthread.dylib 0x18148ba8c _pthread_start + 154
11 libsystem_pthread.dylib 0x181489028 thread_start + 4
</code></pre>
<p>There is no OS version, or device relation on this crash. </p>
<p>I am not doing anything fancy on using UIWebView as well. It is added to nib like every other component, and in the implementation file I use it like the following</p>
<pre><code>self.webView.scrollView.scrollEnabled = NO;
self.webView.scrollView.bounces = NO;
self.webView.opaque = NO;
self.webView.backgroundColor = [UIColor clearColor];
self.webView.delegate = self;
[self.webView loadHTMLString:htmlString baseURL:nil];
</code></pre>
<p>Any suggestions on how to solve WTF Crash?</p>
<p>Edit: Here is how htmlString looks like</p>
<pre><code>Printing description of htmlString:
<html><body style="font-family:HelveticaNeue; font-size:10; background-color:#E5E4E4; text-align:left; color:#696969 ">test string</body></html>
</code></pre> | 1 |
On mac OS X terminal, how to see what user created file | <p>I would like to see what user creates my log files for my php project. Strangely enough, PHP can create the files but it can't write to them so I have <code>chmod</code> them all the time. I would like to see what user is creating them and grant that user permission to write to the files in the folder as well.</p>
<p><code>echo exec('whoami');</code> currently returns <code>www-data</code> but I have no such user, just <code>_www</code>. I should note that I'm running it on docker from a v-machine.</p>
<p>Is there a terminal command that lets me see who created a specific file? Thanks.</p> | 1 |
angular2 failing lodash import | <p>I started simple Angular 2 app, all working. But when I add import of lodash and try to use it, I get errors and the app stops working, and can't figure out what is the problem.</p>
<p><strong>I am getting these 2 errors in console:</strong></p>
<blockquote>
<p>Uncaught SyntaxError: Unexpected token <__exec @ system.src.js:1374entry.execute @ system.src.js:3300linkDynamicModule @ system.src.js:2921link @ system.src.js:2764execute @ system.src.js:3096doDynamicExecute @ system.src.js:715link @ system.src.js:908doLink @ system.src.js:569updateLinkSetOnLoad @ system.src.js:617(anonymous function) @ system.src.js:430run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305
angular2-polyfills.js:138 </p>
<p>Uncaught SyntaxError: Unexpected token <
Evaluating <a href="http://localhost:3000/lodash" rel="nofollow">http://localhost:3000/lodash</a>
Error loading <a href="http://localhost:3000/app/app.jsrun" rel="nofollow">http://localhost:3000/app/app.jsrun</a> @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494lib$es6$promise$$internal$$publishRejection @ angular2-polyfills.js:1444(anonymous function) @ angular2-polyfills.js:243run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305</p>
</blockquote>
<p><strong>FILES</strong></p>
<p><strong>index.html</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>Angular 2 QuickStart</title>
<!-- 1. Load libraries -->
<!-- IE required polyfills, in this exact order -->
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<!-- 2. Configure SystemJS -->
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('app/app')
.then(null, console.error.bind(console));
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html></code></pre>
</div>
</div>
</p>
<p><strong>tsconfig.json</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
"compilerOptions": {
"target": "es5",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules"
]
}</code></pre>
</div>
</div>
</p>
<p><strong>package.json</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
"name": "angular2-quickstart",
"version": "1.0.0",
"scripts": {
"tsc": "tsc",
"tsc:w": "tsc -w",
"lite": "lite-server",
"start": "concurrent \"npm run tsc:w\" \"npm run lite\" "
},
"license": "ISC",
"dependencies": {
"angular2": "2.0.0-beta.2",
"es6-promise": "^3.0.2",
"es6-shim": "^0.33.3",
"lodash": "^4.1.0",
"reflect-metadata": "0.1.2",
"rxjs": "5.0.0-beta.0",
"systemjs": "0.19.6",
"zone.js": "0.5.10"
},
"devDependencies": {
"concurrently": "^1.0.0",
"lite-server": "^1.3.4",
"typescript": "^1.7.5"
}
}</code></pre>
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {bootstrap} from 'angular2/platform/browser'
import {Component} from 'angular2/core';
import * as _ from 'lodash';
@Component({
selector: 'my-app',
template: '<h1>My First Angular 2 App with lodash</h1>'
})
export class AppComponent {
constructor(){
console.log(_.last([1, 2, 3]));
console.log('hello');
}
}
bootstrap(AppComponent);</code></pre>
</div>
</div>
</p> | 1 |
StreamReader.ReadLine will hang in an infinite loop | <p>I have a simple program to read a file using the StreamReader and process it line by line. But the file I am reading may sometimes locate in a network folder. I came across while doing some testing with such a file, that if the network connection lost at some point while I am reading, it'll stay in the same line again and again looping in an infinite loop by resulting the same line as the result from stream.ReadLine().</p>
<p>Is there a way I can find when the fileHandle is not available from the stream itself? I was expecting a FileNotAvailableException kind of an exception would fire when the filehandle is lost from the StreamReader.</p>
<p>Here's my code snippet...</p>
<pre><code> string file = @"Z://1601120903.csv"; //Network file
string line;
StringBuilder stb = new StringBuilder();
StreamReader stream = new StreamReader(file, Encoding.UTF8, true, 1048576);
do
{
line = stream.ReadLine();
// Do some work here
} while (line != "");
</code></pre> | 1 |
Insert into two dependent tables in MySQL with node.js | <p>I am new to MySQL and node.js (as well as the callback). I try to insert data into table B, which depends on data in table A. Here is an example.</p>
<p>employee table (table A):</p>
<pre><code>CREATE TABLE employees (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50),
location varchar(50),
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
</code></pre>
<p>age table (table B, I do not include age column in table A on purpose):</p>
<pre><code>CREATE TABLE age (
id int(11) NOT NULL AUTO_INCREMENT,
index_id int(11),
age int(50),
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
</code></pre>
<p><strong>The problem</strong>:</p>
<p>For each row inserted into table A, I can get the id for it. I want to use the id as the index_id in table B, and insert the corresponding age info into age table B. The problem occurs when I have multiple rows to insert.</p>
<p><strong>The example</strong>:</p>
<p>I implement the following function to achieve above goal.</p>
<pre><code>var mysql = require("mysql");
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "sitepoint"
});
function insert_employees() {
var employees = [
{name: 'Jasmine', location: 'Australia', age: 24},
{name: 'Jay', location: 'India', age: 25},
{name: 'Jim', location: 'Germany', age: 26},
{name: 'Lesley', location: 'Scotland', age: 27}
];
var name_id;
for (var i = 0; i < 4; i++) {
var employee = employees[i];
var command = sprintf('INSERT INTO employees (name, location) VALUES ("%s", "%s");', employee.name, employee.location);
con.query(command, function (err, res) {
if (err) throw err;
name_id = res.insertId;
console.log('Last insert ID in employees:', res.insertID);
// insert age here
var age = employee.age;
var command = sprintf('INSERT INTO age (index_id, age) VALUES (%d, %d);', name_id, age);
con.query(command, function (err, res) {
if (err) throw err;
});
});
}
}
</code></pre>
<p><strong>The Output</strong>:</p>
<p><a href="https://i.stack.imgur.com/xzytW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xzytW.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/ArxUi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ArxUi.png" alt="enter image description here"></a></p>
<p>The employee table is fine, but for the age table, the age column is <strong>27</strong> for all fields, instead of <strong>24, 25, 26, 27</strong></p>
<p><strong>The Question</strong>:</p>
<p>I think the problem is on my misuse of callback feature, but I still don't know how to solve it. Could anyone help me with it? Thanks a lot!</p> | 1 |
passing double pointer as argument | <p>I wanted to use double pointer. But, please tell me what I did wrong here. The value n does not update after the function called. I am expecting 30 but still see 10.</p>
<pre><code>int main(int argc, char **argv) {
int n = 10;
int *ptr = &n;
int **ptr2ptr = &ptr;
function(&ptr2ptr);
printf("%d", n);
return 0;
}
void function(int *num) {
*num = 30;
}
</code></pre> | 1 |
how to Json encode in yii2? | <p>Attempting to encode json and receive <code>400: Bad Request</code> in <code>yii2</code>. I am trying to encode in Rest client but it is not working properly.</p>
<pre><code><?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\TblUserRegistration;
class UserController extends Controller
{
public function actionRegister()
{
$model = new TblUserRegistration();
$username = $_POST['username'];
echo json_encode($username);
}
}
?>
</code></pre>
<p>Error image.<a href="https://i.stack.imgur.com/BdtVl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BdtVl.png" alt="enter image description here"></a></p>
<p>Error image<a href="https://i.stack.imgur.com/BnZb2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BnZb2.png" alt="enter image description here"></a></p> | 1 |
How do I put a case class in an rdd and have it act like a tuple(pair)? | <p>Say for example, I have a simple case class</p>
<pre><code>case class Foo(k:String, v1:String, v2:String)
</code></pre>
<p>Can I get spark to recognise this as a tuple for the purposes of something like this, without converting to a tuple in, say a map or keyBy step.</p>
<pre><code>val rdd = sc.parallelize(List(Foo("k", "v1", "v2")))
// Swap values
rdd.mapValues(v => (v._2, v._1))
</code></pre>
<p>I don't even care if it looses the original case class after such an operation. I've tried the following with no luck. I'm fairly new to Scala, am I missing something?</p>
<pre><code>case class Foo(k:String, v1:String, v2:String)
extends Tuple2[String, (String, String)](k, (v1, v2))
</code></pre>
<p>edit: In the above snippet the case class extends Tuple2, this does not produce the desired effect that the RDD class and functions do not treat it like a tuple and allow PairRDDFunctions, such as mapValues, values, reduceByKey, etc.</p> | 1 |
How to sum up a list of tuples having the same first element? | <p>I have a list of tuples, for example:</p>
<pre><code> (1,3)
(1,2)
(1,7)
(2,4)
(2,10)
(3,8)
</code></pre>
<p>I need to be able to sum up the second values based upon what the first value is, getting this result for the example list:</p>
<pre><code> (1,12)
(2,14)
(3,8)
</code></pre>
<p>This question is very similar in nature to <a href="https://stackoverflow.com/questions/25740726/how-to-aggregate-elements-of-a-list-of-tuples-if-the-tuples-have-the-same-first">this one,</a> however, my solution may not use any imports or for loops, and all answers to that question use one or the other. It's supposed to rely on list and set comprehension.</p> | 1 |
Java POI XSSF VLookup formula | <p>I am trying to put simple VLookup formula in my ".xlsx" file using Java and Apache POI.<br>
This formula is having the external reference and that is NOT working for me. </p>
<p>So to give you more details I am using poi and poi-ooxml version 3.13 and excel 2007.<br>
I am placing the formula into cell this way (where cell is a Cell): </p>
<pre><code>cell.setCellType(Cell.CELL_TYPE_FORMULA);
cell.setCellFormula("StringContainingFormula");
</code></pre>
<p>And then evaluate the formula, I have tried three different ways but with NO luck. (wb is XSSFWorkbook). </p>
<p>1</p>
<pre><code>FormulaEvaluator mainWorkbookEvaluator = wb.getCreationHelper().createFormulaEvaluator();
Map<String,FormulaEvaluator> workbooks = new HashMap<String, FormulaEvaluator>();
workbooks.put("SpreadsheetName.xlsx", mainWorkbookEvaluator);
mainWorkbookEvaluator.setupReferencedWorkbooks(workbooks);
mainWorkbookEvaluator.evaluateAll();
</code></pre>
<p>2 </p>
<pre><code>XSSFEvaluationWorkbook.create(wb);
Workbook nwb = wb;
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
for (Sheet sheet : nwb) {
for (Row r : sheet) {
for (Cell c : r) {
if (c.getCellType() == Cell.CELL_TYPE_FORMULA) {
try {
//evaluator.evaluateFormulaCell(c);
evaluator.evaluate(c);
} catch (Exception e) {
System.out.println("Error occured in 'EvaluateFormulas' : " + e);
}
}
}
}
}
</code></pre>
<p>3</p>
<pre><code>XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
</code></pre>
<p>The problem is, it writes to Excel file and then while evaluating it throws error: </p>
<blockquote>
<p>java.lang.IllegalArgumentException: Invalid sheetIndex: -1</p>
</blockquote>
<p>Now if I open the Excel file, it gives me warning: </p>
<blockquote>
<p>Automatic update of links has been disabled</p>
</blockquote>
<p>If I enable the content, formula shows the result properly and if I do not do anything than formula resulting in <strong><code>#N/A</code></strong>.<br>
Now if I select the cell with formula in it and click formula bar and hit enter than formula shows the result. </p>
<p><strong>Update:</strong> </p>
<p>So, I disabled the warning message by going into Excel options and it started giving me the formula inside the cell.<br>
BUT, when I tried to get the result value from it using </p>
<pre><code>if (cell.getCachedFormulaResultType == Cell.CELL_TYPE_STRING) {
System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
}
</code></pre>
<p>It never gave me the <code>getCachedFormulaResultType</code> as <code>CELL_TYPE_STRING</code>, it always return <code>CELL_TYPE_NUMERIC</code>. It supposed to return string value. I am expacting URL and someother value (words seperated by "<strong>|</strong>" - "cat|dog|bird").</p>
<p>I appreciate any help/suggestion.</p> | 1 |
Adding comma after each word in JavaScript | <p>I have selected tag input and I can choose multiple items using <a href="http://nicolasbize.com/magicsuggest/" rel="nofollow noreferrer">MagicSuggest</a> plugin.</p>
<p>The problem is that the value that I get after the choice is a string separated without a comma.</p>
<p><strong>Like:</strong></p>
<blockquote>
<p>MVCPHPASP.Net</p>
</blockquote>
<p><strong>I want to change it to:</strong></p>
<blockquote>
<p>MVC,PHP,ASP.Net</p>
</blockquote>
<p>The result that I get when I choose multiple items :
<a href="https://i.stack.imgur.com/9VoXm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9VoXm.png" alt=""></a></p>
<p>The string that I get when I alert : </p>
<p><a href="https://i.stack.imgur.com/8D7LX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8D7LX.png" alt=""></a></p>
<p>So how can I do that?</p> | 1 |
How to Adjust Position of tkinter Canvas | <p>In my program, I want to create a tkinter canvas anchored at the top, left corner of my screen, but the canvas is defaulting to a different location on my screen. Here is an image of this happening:</p>
<p><a href="http://i.stack.imgur.com/6ij5l.png" rel="nofollow">Link to Image</a></p>
<p>Here is my current code: </p>
<pre><code> #!/usr/bin/python
import tkinter
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
root.title("Infrared Camera Interface")
root.resizable(width=FALSE, height=FALSE)
class MyApp:
def __init__(self, parent):
self.C = tkinter.Canvas(root, bg="white", height=560, width=450)
#Set the dimensions of the window
parent.minsize(width=600, height=600)
parent.maxsize(width=600, height=600)
#Prepare the image object being loaded into the stream camera
self.imgName = 'Dish.png'
self.img = Image.open(self.imgName)
self.img = self.img.resize((560, 450), Image.ANTIALIAS)
#Display the image onto the stream
self.displayimg = ImageTk.PhotoImage(self.img)
self.C.create_image(0,0,image = self.displayimg, anchor = NW)
self.C.pack()
myapp = MyApp(root)
root.mainloop()
</code></pre>
<p>How can I anchor this canvas to the top, left corner of the screen?</p> | 1 |
Return query with columns from multiple tables in SQLAlchemy | <p>I haven't been able to find an answer to this, but I'm sure it must be somewhere.
My question is similar to this question: <a href="https://stackoverflow.com/questions/6044309/sqlalchemy-how-to-join-several-tables-by-one-query">sqlalchemy: how to join several tables by one query?</a></p>
<p>But I need a query result, not a tuple. I don't have access to the models, so I can't change it, and I can't modify the functions to use a tuple.</p>
<p>I have two tables, <code>UserInformation</code> and <code>MemberInformation</code>, both with a foreign key and relationship to <code>Principal</code>, but not to each other.</p>
<p>How can I get all the records and columns from both tables in one query?
I've tried:</p>
<pre><code>query = DBSession.query(MemberInformation).join(UserInformation, MemberInformation.pId == UserInformation.pId)
</code></pre>
<p>but it only returns the columns of MemberInformation</p>
<p>and:</p>
<pre><code>query = DBSession.query(MemberInformation, UserInformation).join(UserInformation, MemberInformation.pId == UserInformation.pId)
</code></pre>
<p>but that returns a tuple.</p>
<p>What am I missing here?</p> | 1 |
Label doesn't work | <p>I have this code:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden_element {
height: 1px;
width: 1px;
overflow: hidden;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="">
<label for="file">
<button type="button" class="button red">Choose File</button>
</label>
<div class="hidden_element">
<input type="file" name="video" id="file" />
</div>
</form></code></pre>
</div>
</div>
</p>
<p>The problem is when I click choose file nothing happens.</p> | 1 |
How can i convert ISO time into IST and GMT in android? | <p>Here, is my code to convert ISO to IST and ISO to GMT.</p>
<pre><code>Log.e("ISO TIME",""+time);//The time which i got from JSON file.
//IST TIME ZONE
Date date=new Date();
DateFormat format=DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL);
SimpleDateFormat simpleDateFormat=new SimpleDateFormat();
simpleDateFormat.applyPattern("yyyy-MM-dd'T'HH:mm'+00':ss");
date = simpleDateFormat.parse(time.toString());
format.setTimeZone(simpleDateFormat.getTimeZone());
Log.e("IST TIME", "" + format.format(date));
//GMT TIME ZONE
Date date1=new Date();
SimpleDateFormat sdf=(SimpleDateFormat)DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL);
sdf.applyPattern("yyyy-MM-dd'T'HH:mm'+00':ss");
date1=sdf.parse(time);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Log.e("GMT TIME", "" + sdf.format(date1));
</code></pre>
<p>Here, is my output</p>
<pre><code>E/ISO TIME: 2016-01-18T08:40+00:00
E/GMT TIME: 2016-01-18T03:10+00:00
E/IST TIME: Jan 18, 2016 8:40:00 AM India Standard Time
</code></pre>
<p>Problem is the actual difference between IST and GMT is 5:30
But in my output i was got the difference exactly 5:30</p>
<p>Please, help me to solve out this problem.</p> | 1 |
a cash register object that simulates a real life cash register - Java | <p>I need to program a cash register that can perform transactions. </p>
<p>A transaction has the following steps:
(1) The transaction starts when the customer decides to purchase an item for a given price.</p>
<p>(2) The customer give the cashier a certain amount of money in bills and coins.</p>
<p>(3) The cashier calculates the exact change. The change is
calculated so that the total number of bills and coins given to the customer is minimized.</p>
<p>(4) The cashier gives the customer their change and the remaining
bills and coins are added to the register.
If the transaction must be cancelled for any reason, the cash
register returns to the state before the transaction began. </p>
<p>According to Web-Cat, 85% of my coding is correct. I am really struggling with the last part of my code which include <code>public void completePurchase()</code> and <code>public static String prettyPrint(int amount) { }</code>. My instructor has included small descriptions above all the methods.</p>
<p>I really hope that you can help me with these two methods. Certainly, I am not asking for solutions, but help to solve the problem.</p>
<p>The first class includes the cashregister.class. And the second class is a Junittester.</p>
<pre><code>> public class CashRegister
{
// ==========================================================
// Constants
// ==========================================================
/** The value of a dollar (100 cents) */
public static final int DOLLAR = 100;
/** The value of a quarter (25 cents) */
public static final int QUARTER = 25;
/** The value of a dime (10 cents) */
public static final int DIME = 10;
/** The value of a nickel (5 cents) */
public static final int NICKEL = 5;
/** The value of a penny (1 cent) */
public static final int PENNY = 1;
// ==========================================================
// Fields
// ==========================================================
private int purchasePrice;
private int[] registerMoney;
private int[] paymentMoney = { 0, 0, 0, 0, 0 };
private int[] changeMoney = { 0, 0, 0, 0, 0 };
private int transactionCount; // number of
// transactions
private int transactionTotal; // number of cents
// that I have made from transactions
// ==========================================================
// Constructors
// ==========================================================
/**
* Creates a new CashRegister object with the specified money in it. If the
* specified money array is not valid, an IllegalArgumentException is
* thrown. The money array is not valid if: - the length of the array is
* anything but 5 - the array contains a negative number in any of the cells
* - the array contains a 0 in _all_ of its cells /**
*
* @param money
* the money that will go into the new cash register
*/
public CashRegister(int[] money)
{
if (this.moneyHasNegative(money))
{
throw new IllegalArgumentException();
}
transactionCount = 0;
transactionTotal = 0;
purchasePrice = 0;
registerMoney = Arrays.copyOf(money, money.length);
}
/**
* @param money
* money has a negative integer.
*/
private boolean moneyHasNegative(int[] money)
{
if (money.length != 5)
{
return true;
}
if (money[0] < 0 || money[1] < 0 || money[2] < 0 || money[3] < 0
|| money[4] < 0)
{
return true;
}
if (money[0] == 0 && money[1] == 0 && money[2] == 0 && money[3] == 0
&& money[4] == 0)
{
return true;
}
return false;
}
// ==========================================================
// Public Accessor Methods
// ==========================================================
/**
* Returns the purchase price. Returns 0 if a purchase has not begun yet.
*
* @return purchase price.
*/
public int getPrice()
{
return purchasePrice;
}
/**
* @return the registerAmount
*/
public int getRegisterAmount()
{
return registerMoney[0] * DOLLAR + registerMoney[1] * QUARTER
+ registerMoney[2] * DIME + registerMoney[3] * NICKEL
+ registerMoney[4] * PENNY;
}
/**
* The value of payment amount multiplied by constants.
*/
private int paymentAmountValue()
{
return paymentMoney[0] * DOLLAR + paymentMoney[1] * QUARTER
+ paymentMoney[2] * DIME + paymentMoney[3] * NICKEL
+ paymentMoney[4] * PENNY;
}
// ----------------------------------------------------------
/**
* @return the amount of payment.
*/
public int getPaymentAmount()
{
return this.paymentAmountValue();
}
/**
* The value of change amount multiplied by constants.
*/
private int changeAmountValue()
{
return changeMoney[0] * DOLLAR + changeMoney[1] * QUARTER
+ changeMoney[2] * DIME + changeMoney[3] * NICKEL
+ changeMoney[4] * PENNY;
}
/**
* @return the change amount.
*/
public int getChangeAmount()
{
return this.changeAmountValue();
}
/**
* @return the register money as string.
*/
public String getRegisterMoney()
{
return "Dollars: " + registerMoney[0] + "\n" + "Quarters: "
+ registerMoney[1] + "\n" + "Dimes: " + registerMoney[2] + "\n"
+ "Nickels: " + registerMoney[3] + "\n" + "Pennies: "
+ registerMoney[4] + "\n";
}
/**
* get the payment money as a string.
*/
private String paymentMoneyString()
{
return "Dollars: " + paymentMoney[0] + "\n" + "Quarters: "
+ paymentMoney[1] + "\n" + "Dimes: " + paymentMoney[2] + "\n"
+ "Nickels: " + paymentMoney[3] + "\n" + "Pennies: "
+ paymentMoney[4] + "\n";
}
/**
* @return the payment money as a string.
*/
public String getPaymentMoney()
{
return this.paymentMoneyString();
}
/**
* The value of payment amount multiplied by constants.
*/
private String changeMoneyString()
{
return "Dollars: " + changeMoney[0] + "\n" + "Quarters: "
+ changeMoney[1] + "\n" + "Dimes: " + changeMoney[2] + "\n"
+ "Nickels: " + changeMoney[3] + "\n" + "Pennies: "
+ changeMoney[4] + "\n";
}
/**
* @return the change money as a string.
*/
public String getChangeMoney()
{
return this.changeMoneyString();
}
/**
* @return the transaction count.
*/
public int getTransactionCount()
{
return transactionCount;
}
/**
* @return the transaction in total.
*/
public int getTransactionTotal()
{
return transactionTotal;
}
// ==========================================================
// Public Mutator Methods
// ==========================================================
// Begins a transaction using the specified price.
// If a transaction is already in progress, throws an IllegalStateException
// If the specified price is not positive, throws an
// IllegalArgumentException
// ----------------------------------------------------------
/**
* Begins a transaction using the specified price.
*
* @param price
* the price of the item
*/
public void beginPurchase(int price)
{
if (transactionAlreadyInProgress())
{
throw new IllegalStateException();
}
if (price <= 0)
{
throw new IllegalArgumentException();
}
purchasePrice = price;
}
/**
* shows that the transaction is already in progress.
*/
private boolean transactionAlreadyInProgress()
{
return false;
}
// Records the specified payment.
// If the purchase has not begun yet, throws IllegalStateException
// If the specified money array is not valid (see the constructor),
// throws IllegalArgumentException
// If the amount of money given is not sufficient to cover the
// purchase price, the transaction is canceled.
// ----------------------------------------------------------
/**
* Records the specified payment.
*
* @param money
* payment money
*/
public void enterPayment(int[] money)
{
if (purchaseHasNotBegunYet())
{
throw new IllegalStateException();
}
if (this.notValidMoneyArray(money))
{
throw new IllegalArgumentException();
}
while (true)
{
if (money[0] != purchasePrice || money[1] != purchasePrice
|| money[2] != purchasePrice || money[3] != purchasePrice
|| money[4] != purchasePrice)
break;
}
paymentMoney = Arrays.copyOf(money, money.length);
}
/**
* purchase has not begun. Purchase will be canceled if true.
*/
private boolean purchaseHasNotBegunYet()
{
return false;
}
/**
* If money array or length is not valid, it will return false.
*/
private boolean notValidMoneyArray(int[] money)
{
if (money.length != 5)
{
return true;
}
if (money[0] < 0 || money[1] < 0 || money[2] < 0 || money[3] < 0
|| money[4] < 0)
{
return true;
}
if (money[0] == 0 && money[1] == 0 && money[2] == 0 && money[3] == 0
&& money[4] == 0)
{
return true;
}
{
return false;
}
}
// Calculates the change due to the customer using the largest bill
// and coin denominations first. Thus, the change given will use the
// maximum amount of dollars, then the maximum amount of quarters,
// then dimes, then nickels, then pennies. For example, if the change
// required is $15.84, the change will be 15 dollars, 3 quarters,
// 1 nickel, and 4 pennies. It will NOT be 12 dollars, 8 quarters,
// 10 dimes, 12 nickels and 24 pennies. If payment has not been entered
// yet, throws IllegalStateException.
// ----------------------------------------------------------
/**
* throws out the calculated change.
*
* @param money
* changeMoney
*/
public void calculateChange()
{
int changeToGiveBack = 1299;
int dollarsToGiveBack = 0;
int quartersToGiveBack = 0;
int dimesToGiveBack = 0;
int nickelsToGiveBack = 0;
int penniesToGiveBack = 0;
changeMoney[0] = dollarsToGiveBack;
changeMoney[1] = quartersToGiveBack;
changeMoney[2] = dimesToGiveBack;
changeMoney[3] = nickelsToGiveBack;
changeMoney[4] = penniesToGiveBack;
while (changeToGiveBack >= DOLLAR)
{ // check if >= works better or worse than >
changeMoney[0] = changeMoney[0] + 1;
changeToGiveBack = changeToGiveBack - DOLLAR;
}
while (changeToGiveBack >= QUARTER)
{
changeMoney[1] = changeMoney[1] + 1;
changeToGiveBack = changeToGiveBack - QUARTER;
}
while (changeToGiveBack >= DIME)
{
changeMoney[2] = changeMoney[2] + 1;
changeToGiveBack = changeToGiveBack - DIME;
}
while (changeToGiveBack >= NICKEL)
{
changeMoney[3] = changeMoney[3] + 1;
changeToGiveBack = changeToGiveBack - NICKEL;
}
while (changeToGiveBack >= PENNY)
{
changeMoney[4] = changeMoney[4] + 1;
changeToGiveBack = changeToGiveBack - PENNY;
}
if (paymentNotBeenEntered())
{
throw new IllegalStateException();
}
}
// Completes the transaction. Money in cash register is updated.
// The price, payment, and change all become 0. The transaction count
// is incremented and the total amount of money made in all transactions
// is updated. If the cashier does not have enough money to give change
// in the EXACT way it was calculated, the transaction is cancelled -
// the item is not purchased, and the customer gets their exact coins back.
// The amount and type of money in the register is unchanged from before
// the transaction began. If change has not been calculated yet,
// throws IllegalStateException
private boolean paymentNotBeenEntered()
{
return false;
}
/**
* Completes the transaction.
*
* @param money
* complete purchase money
*/
public void completePurchase()
{
}
// ==========================================================
// Public Static Methods
// ==========================================================
// Returns a string for the specified amount with a dollar sign
// at the beginning and a decimal two places from the end.
// For example, the amount 10538 cents becomes the string $105.38.
// No commas are printed in the string.
// public static String prettyPrint(int amount) { }
// ==========================================================
// Private Methods
// ==========================================================
// In this project you WILL have private methods. If you do not,
// it means you have redundant code in your class and the grader
// will take off points for it.
}
This is the part where CashregisterTest begins.
> public class CashRegisterTest
{
private CashRegister cr;
// ----------------------------------------------------------
/**
* throws an Exception
*
* @throws Exception
*/
@Before
public void setUp()
throws Exception
{
cr = new CashRegister(new int[] { 20, 20, 20, 20, 20 });
}
// ----------------------------------------------------------
/**
* Testing the Constructors
*/
// ==========================================================
// Constructor Tests
// ==========================================================
@Test
public void testConstructor()
{
assertEquals(2820, cr.getRegisterAmount());
cr.beginPurchase(1299);
assertEquals(1299, cr.getPrice());
int[] paymentMoney = { 30, 0, 0, 0, 0 };
cr.enterPayment(paymentMoney);
assertEquals(paymentMoney, cr.getPaymentAmount());
cr.calculateChange();
assertEquals(1288, cr.getChangeAmount());
assertEquals(0, cr.getChangeAmount());
assertEquals(0, cr.getTransactionCount());
assertEquals(0, cr.getTransactionTotal());
}
// ----------------------------------------------------------
/**
* Checks if constructor throws an illegal argument exception when array !=
* 5.
*/
// This test method checks that the constructor
// correctly throws an illegal argument exception when
// the array has a length other than five
@Test(
expected = IllegalArgumentException.class)
public void testConstructorArrayBadLength()
{
int[] money = { 20, 20, 20, 20 }; // bad parameter; only has length four
cr = new CashRegister(money); // this should throw an exception
fail(); // if we reach here, our constructor is wrong
}
// ----------------------------------------------------------
/**
* Test if the constructor throws illegal argument exception if array
* contains a negative integer.
*/
// Write a test method that checks if the constructor
// correctly throws an illegal argument exception when
// the array argument contains a negative integer
@Test(
expected = IllegalArgumentException.class)
public void testConstructorArrayNegativeLength()
{
int[] money = { -20, 20, 20, 20, 20 }; // bad parameter; only has
// length
// four
cr = new CashRegister(money); // this should throw an exception
fail(); // if we reach here, our constructor is wrong
}
// Write a test method that checks if the constructor
// correctly throws an illegal argument exception when
// the array argument contains all zeros
// ----------------------------------------------------------
/**
* Tests if the constructor correctly throws an illegal argument Exception
* when array = 0.
*
* @Test IllegalArgumentException
*/
@Test(
expected = IllegalArgumentException.class)
public void testConstructorArrayAllZeros()
{
int[] money = { 0, 0, 0, 0, 0 }; // bad parameter; only has length four
cr = new CashRegister(money); // this should throw an exception
fail(); // if we reach here, our constructor is wrong
}
// ==========================================================
// Accessor Tests
// ==========================================================
// ----------------------------------------------------------
/**
* Dont know yet
*/
@Test
public void testGetMoney()
{
// getRegisterMoney
// getPaymentMoney
// getChangeMoney
String registerMoney =
"Dollars: 20\n" + "Quarters: 20\n" + "Dimes: 20\n"
+ "Nickels: 20\n" + "Pennies: 20\n";
String zeroMoney =
"Dollars: 0\n" + "Quarters: 0\n" + "Dimes: 0\n"
+ "Nickels: 0\n" + "Pennies: 0\n";
assertEquals(registerMoney, cr.getRegisterMoney());
assertEquals(zeroMoney, cr.getPaymentMoney());
assertEquals(zeroMoney, cr.getChangeMoney());
}
// ==========================================================
// Mutator Tests
// ==========================================================
// ----------------------------------------------------------
/**
* Place a description of your method here.
*/
// ----------------------------------------------------------
/**
* Sunny day not yet
*/
@Test
public void testSunnyDay()
{
System.out.println(cr.getRegisterMoney());
cr.beginPurchase(1800);
assertEquals(1800, cr.getPrice());
int[] paymentMoney = { 30, 0, 0, 0, 0 };
cr.enterPayment(paymentMoney);
System.out.println(cr.getPaymentMoney());
cr.calculateChange();
System.out.println(cr.getChangeMoney());
// cr.completePurchase();
System.out.println(cr.getRegisterMoney());
String registerMoney =
"Dollars: 20\n" + "Quarters: 20\n" + "Dimes: 20\n"
+ "Nickels: 20\n" + "Pennies: 20\n";
assertEquals(registerMoney, cr.getRegisterMoney());
}
// ==========================================================
// Static Method Tests
// ==========================================================
}
</code></pre> | 1 |
How to charge Magento 2 Payment Fee | <p>I want to charge extra fee, according to the selected payment method. I've used following module to do it in magento 1.<br>
<a href="https://github.com/manishiitg/excellence_magento_blog/tree/master/Fee%20Module/app" rel="nofollow">https://github.com/manishiitg/excellence_magento_blog/tree/master/Fee%20Module/app</a></p>
<p>Is there a similar module for magento 2. </p> | 1 |
Can't Run Rails Server, Could Not Find Gem 'rails(4.2.5.1) x86-mingw32' | <p>I'm trying to learn Ruby on Rails. Currently been trying out Rails framework. I've installed it. Create new project, but when I try to run:</p>
<p>rails server</p>
<p>I get back an error:</p>
<p>Could not find gem 'rails (= 4.2.5.1) x86-mingw32' in any of the gem sources listed in your Gemfile or available on this machine.
Run <code>bundle install</code> to install missing gems.</p>
<p>I've installed bundle as suggested. Had few problems with installing it as well, but I've found a soultion on the internet.</p>
<p>Before bundle install I was getting another error saying that
could not find gem 'tzinfo-data (>=0) x86-mingw32'; so i installed this gem:
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw] ; and it worked.</p>
<p>I'm running windows 7, please help, BIG THANKS. </p> | 1 |
K-Nearest Neighbor Implementation for Strings (Unstructured data) in Java | <p>I'm looking for implementation for K-Nearest Neighbor algorithm in Java for unstructured data. I found many implementation for numeric data, however how I can implement it and calculate the Euclidean Distance for text (Strings).</p>
<p>Here is one example for double:</p>
<pre><code>public static double EuclideanDistance(double [] X, double []Y)
{
int count = 0;
double distance = 0.0;
double sum = 0.0;
if(X.length != Y.length)
{
try {
throw new Exception("the number of elements" +
" in X must match the number of elements in Y");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
count = X.length;
}
for (int i = 0; i < count; i++)
{
sum = sum + Math.pow(Math.abs(X[i] - Y[i]),2);
}
distance = Math.sqrt(sum);
return distance;
}
</code></pre>
<p>How I can implement it for Strings (unstructured data)? For example,</p>
<pre><code>Class 1:
"It was amazing. I loved it"
"It is perfect movie"
Class 2:
"Boring. Boring. Boring."
"I do not like it"
</code></pre>
<p>How can we implement KNN on such type of data and calculate Euclidean Distance?</p> | 1 |
Spring java.lang.NoClassDefFoundError: javax/persistence/EntityManagerFactory | <p>I am using Tomcat 7.0.67, Spring 4.2.0. I am <strong>not</strong> using Spring-JPA, Hibernate or JPA, but when I attempt to launch my Spring application it fails with this error saying the <code>javax/persistence/EntityManagerFactory</code> class is not found:</p>
<pre><code>23:39:43.836 ERROR org.springframework.web.context.ContextLoader[] - Context initialization failed
java.lang.NoClassDefFoundError: javax/persistence/EntityManagerFactory
at java.lang.Class.getDeclaredMethods0(Native Method) ~[na:1.8.0_66]
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) ~[na:1.8.0_66]
at java.lang.Class.getDeclaredMethods(Class.java:1975) ~[na:1.8.0_66]
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:606) ~[spring-core-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:518) ~[spring-core-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:504) ~[spring-core-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:241) ~[spring-beans-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineConstructorsFromBeanPostProcessors(AbstractAutowireCapableBeanFactory.java:1069) ~[spring-beans-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1042) ~[spring-beans-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) ~[spring-beans-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305) ~[spring-beans-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301) ~[spring-beans-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196) ~[spring-beans-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) ~[spring-beans-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834) ~[spring-context-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) ~[spring-context-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446) ~[spring-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328) ~[spring-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) [spring-web-4.2.0.RELEASE.jar:4.2.0.RELEASE]
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5077) [catalina.jar:7.0.67]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5591) [catalina.jar:7.0.67]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [catalina.jar:7.0.67]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574) [catalina.jar:7.0.67]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564) [catalina.jar:7.0.67]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_66]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_66]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_66]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_66]
Caused by: java.lang.ClassNotFoundException: javax.persistence.EntityManagerFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_66]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_66]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_66]
</code></pre>
<p>I tried adding the below to my pom.xml to include the persistence jar, but it did not make a difference.</p>
<pre><code><dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
</code></pre>
<p>This is the output of <code>mvn dependency:tree</code>: <a href="https://gist.github.com/eytanbiala/492d9af46f8990917e45" rel="nofollow">https://gist.github.com/eytanbiala/492d9af46f8990917e45</a></p> | 1 |
How to add Encoding type in FormData()? | <p>Following is my Javascript code, where I would like to set the content type as "multipart/form-data". Help me with how this can be done? Thanks </p>
<pre><code>var client = new XMLHttpRequest();
var formData = new FormData();
for(var i=0;i<file.files.length;i++)
formData.append("nodeDoc[]", file.files[i]);
formData.append('userId', readCookie('userId'));
formData.append('passwd', readCookie('passwd'));
formData.append('treeType', selectedTreeType);
formData.append('displayName', document.getElementById('displayName').value);
formData.append('nodeType', document.getElementById('nodeType').value);
formData.append('attrList', constructAttrList());
client.open("post", serverUrl + "node/addNode", true);
client.send(formData);
console.log("/node/addNode API called with file");
</code></pre> | 1 |
Why my Serverless Lambda unable to access S3 bucket and items? | <p>I'm sure I've set up my Lambda to have read/write access to the private bucket; more specifically, my lambda will execute <code>s3.headObject</code> and <code>s3.upload</code>. What am I missing to get this to work?</p>
<p>My Lambda's policy:</p>
<pre><code>{
"Statement": [
{
"Resource": "arn:aws:logs:us-east-1:*:*",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Effect": "Allow"
},
{
"Resource": "arn:aws:s3:::PRIVATE_BUCKET/folder_name/*",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Effect": "Allow"
}
],
"Version": "2012-10-17"
</code></pre>
<p>}</p>
<p>My S3 buckets policy:</p>
<pre><code> {
"AWSTemplateFormatVersion" : "2010-09-09",
"Description" : "Bucket that is read-accessible internally",
"Parameters" : {
"Environment" : {
"Description" : "dev",
"Type" : "String",
"Default" : "dev",
"AllowedValues" : [ "dev" ]
}
},
"Resources" : {
"PrivateBucket" : {
"Type" : "AWS::S3::Bucket",
"DeletionPolicy" : "Retain",
},
"PrivateBucketPolicy" : {
"Type" : "AWS::S3::BucketPolicy",
"Properties" : {
"PolicyDocument" : {
"Id" : "Make anonymous read-only access available on certain networks",
"Statement" : [
{
"Sid" : "IPAllow",
"Effect" : "Allow",
"Principal" : {
"AWS" : "*"
},
"Action" : [
"s3:ListBucket",
"s3:GetObject"
],
"Resource" : [
{ "Fn::Join" : [ "", [ "arn:aws:s3:::", { "Ref" : "PrivateBucket" } ] ] },
{ "Fn::Join" : [ "", [ "arn:aws:s3:::", { "Ref" : "PrivateBucket" }, "/*" ] ] }
],
"Condition" : {
"IpAddress" : {
"aws:SourceIp" : [
"ip/cid/r",
"ip/cid/r",
"ip/cid/r",
"ip/cid/r",
"ip/cid/r"
]
}
}
}
]
},
"Bucket" : { "Ref" : "PrivateBucket" }
}
}
}
}
</code></pre> | 1 |
Why is the camera preview rotated by 90 degrees in the Android emulator? | <p>I have attached the webcam to the emulator and I always see the camera rotated by 90 degrees.</p>
<p><a href="https://i.stack.imgur.com/tFQYD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tFQYD.png" alt="Barcode scanner demo app"></a></p>
<p>What I did is simply to set "Webcam0" as the device to be used as the rear camera in the emulator.</p>
<p>Background: I'm trying to fix an issue with an app I'm developing that uses ZXing: it fails to scan some QR codes on certain devices, and I'm wondering if it has anything to do with what I see on the emulator.</p>
<p>On the devices we use to test the image is displayed correctly, on the emulator however it is rotated. Besides making me wonder whether it can cause troubles on real devices it makes it very difficult to test the QR code scanning (i.e. when you move the QR code vertically on the app it moves horizontally and vice-versa).</p>
<p>Do you know how to solve it?</p>
<p>Thanks in advance</p> | 1 |
How to match a part of string before a character into one variable and all after it into another | <p>I have a problem with splitting string into two parts on special character.</p>
<p>For example:</p>
<pre><code>12345#data
</code></pre>
<p>or</p>
<pre><code>1234567#data
</code></pre>
<p>I have 5-7 characters in first part separated with <code>"#"</code> from second part, where are another data (characters,numbers, doesn't matter what)</p>
<p>I need to store two parts on each side of <code>#</code> in two variables:</p>
<pre><code>x = 12345
y = data
</code></pre>
<p>without <code>"#"</code> character.</p>
<p>I was looking for some Lua string function like <code>splitOn("#")</code> or substring until character, but I haven't found that.</p> | 1 |
Does linux user level (pthread) thread run on multiple cores? | <p>I know there are :</p>
<p>1) User level thread - Inside the same address space of the process but with different stacks.</p>
<p>2) Kernel level thread - Inside the kernel memory stack (I am guessing here).</p>
<p>So When I create user level threads, Kernels are not aware of them<a href="http://faculty.cs.tamu.edu/bettati/Courses/410/2014A/Slides/threads.pdf" rel="noreferrer"> [1]</a>. So how does the kernel know, how to schedule the different user level threads in different cores. This question is regards to pthread. If pthread is user level thread, how can it run on multiple core?</p>
<p><strong>Future Answer Seeker read :</strong> ( thank you to all who contributed )</p>
<p>1) Ziffusion's answer (below)</p>
<p>2) <a href="https://softwareengineering.stackexchange.com/questions/107938/threads-kernel-threads-vs-kernel-supported-threads-vs-user-level-threads">David Schwartz's answer</a> </p>
<p>3) <a href="http://www.tutorialspoint.com/operating_system/os_multi_threading.htm" rel="noreferrer">Tutorial point link</a> </p> | 1 |
Is there a maximum concurrency for AWS s3 multipart uploads? | <p><a href="http://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-s3.html" rel="nofollow">Referring to the docs</a>, you can specify the number of concurrent connection when pushing large files to Amazon Web Services s3 using the multipart uploader. While it does say the concurrency defaults to 5, it does not specify a maximum, or whether or not the size of each chunk is derived from the total filesize / concurrency.</p>
<p>I trolled the source code and the comment is pretty much the same as the docs:</p>
<blockquote>
<p>Set the concurrency level to use when uploading parts. This affects
how many parts are uploaded in parallel. You must use a local file as
your data source when using a concurrency greater than 1</p>
</blockquote>
<p>So my functional build looks like this (the vars are defined by the way, this is just condensed for example):</p>
<pre><code>use Aws\Common\Exception\MultipartUploadException;
use Aws\S3\Model\MultipartUpload\UploadBuilder;
$uploader = UploadBuilder::newInstance()
->setClient($client)
->setSource($file)
->setBucket($bucket)
->setKey($file)
->setConcurrency(30)
->setOption('CacheControl', 'max-age=3600')
->build();
</code></pre>
<p>Works great except a 200mb file takes 9 minutes to upload... with 30 concurrent connections? Seems suspicious to me, so I upped concurrency to 100 and the upload time was 8.5 minutes. Such a small difference could just be connection and not code.</p>
<p>So my question is whether or not there's a concurrency maximum, what it is, and if you can specify the size of the chunks or if chunk size is automatically calculated. My goal is to try to get a 500mb file to transfer to AWS s3 within 5 minutes, however I have to optimize that if possible.</p> | 1 |
How to log every GET And POST data in Codeigniter? | <p>I have a Server on which many IOS and Android Client send HTTP request, and based on that request i send them some response back.</p>
<p>Now I want to store all the incoming request in my logs so it can be helpful for debugging. Also i want to store what my server sent back in response.</p>
<p><strong>The Request i get on server:</strong></p>
<pre><code>$data = $this->license_m->array_from_get(array('request','device_id','product','software_version','platform_os','platform_model','platform'));
</code></pre>
<p><strong>The Response Server gives back</strong></p>
<pre><code> $response = array(
'response_code' =>200 ,
'request'=> $this->input->get('request'),
'device_id'=> $this->input->get('device_id'),
'allowed_hours'=> $remaining_hours,
'product'=>'mlc',
'url'=>NULL
);
return $this->output
->set_content_type('Content-Type: application/json')
->set_output(json_encode($response));
</code></pre>
<p>Now i want to log all this data into logs of my codeigniter. How to do that?</p>
<p>I tried this :</p>
<pre><code>log_message('debug',print_r($data,TRUE));
</code></pre>
<p>but this saves either request array or the response array not both of them</p>
<p>My License Class
:</p>
<pre><code><?php
/**
*
*/
class License extends Admin_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('license_m');
}
public function index($id = NULl)
{
$req = $this->input->get('request');
if($req =="trial")
{
$request = array(
'request' => $this->input->get('request'),
'device_id' => $this->input->get('device_id'),
'launch_date'=> $this->input->get('launch_date'),
'allowed_hours'=>$this->input->get('trial_usage'),
'product'=>$this->input->get('product'),
'software_version'=> $this->input->get('software_version'),
'platform_os'=> $this->input->get('platform_os'),
'platform'=> $this->input->get('platform'),
'platform_model'=> $this->input->get('platform_model')
);
/* checking if device id exists */
$data = $this->license_m->array_from_get(array('request','device_id','product','software_version','platform_os','platform_model','platform'));
$this->db->where('device_id',$data['device_id']);
$this->db->where('request','activation');
$query = $this->db->get('activation');
$response = array(
'response_code' =>200 ,
'device_id'=> $this->input->get('device_id'),
'expiry_date'=> '20201231-235959',
'product'=>'mlc',
'url'=>NULL ,
'request'=> $this->input->get('request')
);
return $this->output
->set_content_type('Content-Type: application/json')
->set_output(json_encode($response));
</code></pre> | 1 |
Could not dequeue a view of kind UICollectionElementKindCell with identifier | <p>I have a view controller with two collection views, each one has a cell with a different identifier, but for some reason, I am getting the 'could not dequeue' error.</p>
<blockquote>
<p>'could not dequeue a view of kind: UICollectionElementKindCell with >identifier Cell - must register a nib or a class for the identifier or >connect a prototype cell in a storyboard'</p>
</blockquote>
<p>I am not sure what I am doing wrong and its causing a runtime error on the AppDelegate. I registered the nibs, based on another stackoverflow question, but it didn't work. Can somebody provide some help?</p>
<pre><code>func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell2 = collectionView.dequeueReusableCellWithReuseIdentifier("Cell2", forIndexPath: indexPath)
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
if collectionView == collView {
if defaults.boolForKey("gotPL") {
let thumbIV = cell.viewWithTag(1) as! UIImageView
let playTitle = cell.viewWithTag(2) as! UILabel
thumbIV.image = UIImage(data: defaults.arrayForKey("playlistThumbnails")![indexPath.row] as! NSData)
playTitle.text = defaults.arrayForKey("playlistTitles")![indexPath.row] as? String
return cell } else { return cell }} else {
if defaults.boolForKey("gotRecom") {
let thumbIV = cell2.viewWithTag(3) as! UIImageView
let videoTitle = cell2.viewWithTag(4) as! UILabel
thumbIV.image = UIImage(data: defaults.arrayForKey("recomThumbs")![indexPath.row] as! NSData)
videoTitle.text = defaults.arrayForKey("recomTitles")![indexPath.row] as? String
return cell2
} else { return cell2 }}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/J5N0d.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J5N0d.png" alt="enter image description here"></a></p> | 1 |
Logcat error in android Studio | <p>when I run my project then error show in log cat which is not understandable for me please anyone can help me what is the meaning of these errors mean what mistakes I am making in my codes.
Even I download other projects from google, on the running same log cat is showing please help.</p>
<p>LogCat is here:-</p>
<pre><code>02-03 12:09:05.115 7614-7614/com.example.administrator.mainpage E/GMPM: GoogleService failed to initialize, status: 10, Missing an expected resource: 'R.string.google_app_id' for initializing Google services. Possible causes are missing google-services.json or com.google.gms.google-services gradle plugin.
02-03 12:09:05.115 7614-7614/com.example.administrator.mainpage E/GMPM: Scheduler not set. Not logging error/warn.
02-03 12:09:05.240 7614-7639/com.example.administrator.mainpage E/GMPM: Uploading is not possible. App measurement disabled
02-03 12:09:06.371 7614-7689/com.example.administrator.mainpage E/GED: Failed to get GED Log Buf, err(0)
02-03 12:09:06.471 7614-7614/com.example.administrator.mainpage E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.administrator.mainpage, PID: 7614
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.ListView.setAdapter(ListView.java:499)
at com.example.administrator.mainpage.MainActivity$JSONTask.onPostExecute(MainActivity.java:56)
at com.example.administrator.mainpage.MainActivity$JSONTask.onPostExecute(MainActivity.java:41)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5649)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
</code></pre>
<p>This is code:-</p>
<pre><code> public class MainActivity extends AppCompatActivity {
ListView lvCity;
private static String url="14.140.200.186/Hospital/get_city.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.arjuncontent_main);
new JSONTask().execute(url);
}
public class JSONTask extends AsyncTask<String,String, List<CityModel>>{
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Downloading Cities...");
dialog.show();
}
@Override
protected void onPostExecute( List<CityModel> result) {
super.onPostExecute(result);
CityAdapter adapter=new CityAdapter(getApplicationContext(),R.layout.city_single_row,result);
lvCity = (ListView) findViewById(R.id.lvCity);
lvCity.setAdapter(adapter);
}
public class CityAdapter extends ArrayAdapter {
private List<CityModel> cityModelList;
private int resource;
private LayoutInflater inflater;
public CityAdapter(Context context, int resource, List<CityModel> objects) {
super(context, resource, objects);
cityModelList=objects;
this.resource=resource;
inflater= (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView==null)
convertView=inflater.inflate(resource,null);
TextView cityname;
TextView cityid;
cityid= (TextView) convertView.findViewById(R.id.cityid);
cityid.setText(cityModelList.get(position).getCity_id());
cityname= (TextView)convertView.findViewById(R.id.cityname);
cityname.setText(cityModelList.get(position).getCity_name());
return convertView;
}
}
@Override
protected List<CityModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson=buffer.toString();
JSONObject parentObject=new JSONObject(finalJson);
JSONArray parentArray=parentObject.getJSONArray("Cities");
List<CityModel>cityModelList=new ArrayList<>();
for (int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
CityModel cityModel=new CityModel();
cityModel.setCity_name(finalObject.getString("city_name"));
cityModel.setCity_id(finalObject.getString("city_id"));
cityModelList.add(cityModel);
}
return cityModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
;
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
</code></pre>
<p>`</p> | 1 |
Are the strings in argv modifiable? | <p>I just wrote a small program that reads command line arguments in C, nothing too difficult. I was also modifying them, for example changing the first character of the parameter to uppercase. </p>
<p>I know that you shouldn't modify string literals as it can cause undefined behavior, so was just wondering if the strings in the <code>*argv[]</code> are literals that you shouldn't change.</p>
<pre><code>int main(int argc, char *argv[])
</code></pre> | 1 |
jmeter - Authorization header goes missing | <p>I have a fairly simple jmeter script for our site. As part of the flow through the site, I use our API in order to update the user's application.</p>
<p>The API uses OAuth authentication, which I'm familiar with using our own proprietary testing tool.</p>
<p>First I get a auth token via a call to our authorization endpoint. This returns a bit of JSON like this:</p>
<pre><code>{"access_token":"a really long auth token string"}
</code></pre>
<p>In my script I use a regex to capture this token string. As part of investigating this problem, I've used a Debug PostProcessor to check that I get the correct string out, which I do. It's saved as variable 'authToken'.</p>
<p>In the very next step in the script, I add a header via a HTTP Header Manager, like so:</p>
<p><img src="https://i.imgur.com/n9FGxAa.png" alt="Imgur"></p>
<p>I know this header is correct as we have many instances of it in our API tests.</p>
<p>The relevant part of the script looks like this:</p>
<p><img src="https://i.imgur.com/TYSuicb.png" alt="Imgur"></p>
<hr>
<p>Each time I run the script however, the step that uses the token/header returns a 401 unauthorized.</p>
<p>I've tested the actual URL and header in a Chrome plugin and the call works as expected.</p>
<p>In the 'View Results Tree' listener, there is no evidence at all that the Authorization header is set at all. I've tried hard-coding an auth token but no joy - it still doesn't seem to be part of the request.</p>
<p>From the results tree, the request looks like this:</p>
<pre><code>POST <correct URL>
POST data:{"id":"<item id>"}
Cookie Data: SessionProxyFilter_SessionId=<stuff>; sessionToken=<stuff>
Request Headers:
Content-Length: 52
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36
Connection: keep-alive
Content-Type: application/json
</code></pre>
<p><img src="https://i.imgur.com/8jcbJRn.png" alt="Imgur"></p>
<p>The results tree also shows no redirects.</p>
<p>I've tried the solutions <a href="https://stackoverflow.com/questions/24542747/jmeter-alter-http-headers-during-test">here</a> and <a href="https://stackoverflow.com/questions/14489310/adding-authentication-to-jmeter-rest-request">here</a> but neither of these worked.</p>
<p>Oddly, I'm almost certain that this worked about a month ago and as far as I can tell nothing has changed on the machine, in the script or with the jmeter installation. Obviously one of these is not true but I'm at my wit's end.</p> | 1 |
Prevent usage of index for a particular query in Postgres | <p>I have a slow query in a Postgres DB. Using <code>explain analyze</code>, I can see that Postgres makes bitmap index scan on two different indexes followed by bitmap AND on the two resulting sets.</p>
<p>Deleting one of the indexes makes the evaluation ten times faster (bitmap index scan is still used on the first index). However, that deleted index is useful in other queries.</p>
<p>Query:</p>
<pre><code>select
booking_id
from
booking
where
substitute_confirmation_token is null
and date_trunc('day', from_time) >= cast('01/25/2016 14:23:00.004' as date)
and from_time >= '01/25/2016 14:23:00.004'
and type = 'LESSON_SUBSTITUTE'
and valid
order by
booking_id;
</code></pre>
<p>Indexes:</p>
<pre><code>"idx_booking_lesson_substitute_day" btree (date_trunc('day'::text, from_time)) WHERE valid AND type::text = 'LESSON_SUBSTITUTE'::text
"booking_substitute_confirmation_token_key" UNIQUE CONSTRAINT, btree (substitute_confirmation_token)
</code></pre>
<p>Query plan:</p>
<pre><code>Sort (cost=287.26..287.26 rows=1 width=8) (actual time=711.371..711.377 rows=44 loops=1)
Sort Key: booking_id
Sort Method: quicksort Memory: 27kB
Buffers: shared hit=8 read=7437 written=1
-> Bitmap Heap Scan on booking (cost=275.25..287.25 rows=1 width=8) (actual time=711.255..711.294 rows=44 loops=1)
Recheck Cond: ((date_trunc('day'::text, from_time) >= '2016-01-25'::date) AND valid AND ((type)::text = 'LESSON_SUBSTITUTE'::text) AND (substitute_confirmation_token IS NULL))
Filter: (from_time >= '2016-01-25 14:23:00.004'::timestamp without time zone)
Buffers: shared hit=5 read=7437 written=1
-> BitmapAnd (cost=275.25..275.25 rows=3 width=0) (actual time=711.224..711.224 rows=0 loops=1)
Buffers: shared hit=5 read=7433 written=1
-> Bitmap Index Scan on idx_booking_lesson_substitute_day (cost=0.00..20.50 rows=594 width=0) (actual time=0.080..0.080 rows=72 loops=1)
Index Cond: (date_trunc('day'::text, from_time) >= '2016-01-25'::date)
Buffers: shared hit=5 read=1
-> Bitmap Index Scan on booking_substitute_confirmation_token_key (cost=0.00..254.50 rows=13594 width=0) (actual time=711.102..711.102 rows=2718734 loops=1)
Index Cond: (substitute_confirmation_token IS NULL)
Buffers: shared read=7432 written=1
Total runtime: 711.436 ms
</code></pre>
<p>Can I prevent using a particular index for a particular query in Postgres?</p> | 1 |
Compute MD5 hash of a UTF8 string | <p>I have an SQL table in which I store large string values that must be unique.
In order to ensure the uniqueness, I have a unique index on a column in which I store a string representation of the MD5 hash of the large string.</p>
<p>The C# app that saves these records uses the following method to do the hashing:</p>
<pre class="lang-csharp prettyprint-override"><code>public static string CreateMd5HashString(byte[] input)
{
var hashBytes = MD5.Create().ComputeHash(input);
return string.Join("", hashBytes.Select(b => b.ToString("X")));
}
</code></pre>
<p>In order to call this, I first convert the <code>string</code> to <code>byte[]</code> using the UTF-8 encoding:</p>
<pre class="lang-csharp prettyprint-override"><code>// this is what I use in my app
CreateMd5HashString(Encoding.UTF8.GetBytes("abc"))
// result: 90150983CD24FB0D6963F7D28E17F72
</code></pre>
<p>Now I would like to be able to implement this hashing function in SQL, using the <a href="https://msdn.microsoft.com/en-us/library/ms174415.aspx" rel="noreferrer"><code>HASHBYTES</code> function</a>, but I get a different value:</p>
<pre class="lang-sql prettyprint-override"><code>print hashbytes('md5', N'abc')
-- result: 0xCE1473CF80C6B3FDA8E3DFC006ADC315
</code></pre>
<p>This is because SQL computes the MD5 of the UTF-16 representation of the string.
I get the same result in C# if I do <code>CreateMd5HashString(Encoding.Unicode.GetBytes("abc"))</code>.</p>
<p>I cannot change the way hashing is done in the application.</p>
<p>Is there a way to get SQL Server to compute the MD5 hash of the UTF-8 bytes of the string?</p>
<p>I looked up similar questions, I tried using collations, but had no luck so far.</p> | 1 |
mkdir() works while inside internal flash storage, but not SD card? | <p>I am currently building a file management app that allows the user to browse the file system of their device. The user starts off in the root directory <code>/</code> of their device, but can browse to any location they want such as the internal flash storage or SD card.</p>
<p>One of the critical requirements of this app is to allow the user to create new folders anywhere. A feature like this would be immensely useful for the app. However, the <a href="http://developer.android.com/reference/java/io/File.html#mkdir()"><code>File#mkdir()</code></a> method does not work at all in the SD card directory.</p>
<p>I added the appropriate permissions to the manifest file. I also wrote a test to see which directories (all of which exist on my Lollipop 5.0 device) allow the creation of a new folder. From my observations, <a href="http://developer.android.com/reference/java/io/File.html#mkdir()"><code>File#mkdir()</code></a> only works when inside the internal flash storage directory.</p>
<p><strong>Note:</strong> please don't confuse <a href="http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory()"><code>Environment#getExternalStorageDirectory()</code></a> with the SD card location, as explained by <a href="https://commonsware.com/blog/2014/04/08/storage-situation-external-storage.html">this article</a>. Also on Lollipop 5.0, I believe <code>/storage/emulated/0/</code> and <code>/storage/sdcard0/</code> refer to the internal flash storage while <code>/storage/emulated/1/</code> and <code>/storage/sdcard1/</code> refer to the SD card (which is at least true for the device I am testing with).</p>
<p>How can I create new files and folders in areas outside the external storage path on non-rooted Android devices?</p>
<hr>
<p><strong>Manifest:</strong></p>
<pre><code>...
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</code></pre>
<p><strong>Test:</strong></p>
<pre><code>...
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String NEW_FOLDER_NAME = "TestFolder";
testPath(new File(Environment.getExternalStorageDirectory(), NEW_FOLDER_NAME));
testPath(new File("/storage/emulated/0/", NEW_FOLDER_NAME));
testPath(new File("/storage/emulated/1/", NEW_FOLDER_NAME));
testPath(new File("/storage/sdcard0/Download/", NEW_FOLDER_NAME));
testPath(new File("/storage/sdcard1/Pictures/", NEW_FOLDER_NAME));
}
private void testPath(File path) {
String TAG = "Debug.MainActivity.java";
String FOLDER_CREATION_SUCCESS = " mkdir() success: ";
boolean success = path.mkdir();
Log.d(TAG, path.getAbsolutePath() + FOLDER_CREATION_SUCCESS + success);
path.delete();
}
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>/storage/emulated/0/TestFolder mkdir() success: true
/storage/emulated/0/TestFolder mkdir() success: true
/storage/emulated/1/TestFolder mkdir() success: false
/storage/sdcard0/Download/TestFolder mkdir() success: true
/storage/sdcard1/Pictures/TestFolder mkdir() success: false
</code></pre> | 1 |
Sort Descriptor based on ordered to-many relationship | <p>Description of my core data model:</p>
<ul>
<li>Project and Issues entities</li>
<li>Project has an <strong>ordered one-to-many relationship</strong> to Issues named issues</li>
<li>Issue has one-to-one relationship with Project named parentProject</li>
</ul>
<p>Here is my code to obtain issues:</p>
<pre><code>let fetchRequest = NSFetchRequest(entityName: "Issue")
fetchRequest.predicate = NSPredicate(format: "parentProject CONTAINS[cd] %@", argumentArray: [project])
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
let frc = NSFetchedResultsController(
fetchRequest: fetchRequest,
managedObjectContext: dataManager.context,
sectionNameKeyPath: nil,
cacheName: nil)
return arc
</code></pre>
<p>Even though I have all issues from the project object, I prefer to obtain issues using fetched results controller, so they will always be updated and I like the integration with tables. I also like that in navigation controller screen before the projects are displayed using FRC as well.</p>
<p>As you see in the code the Issues are sorted by the name parameter. </p>
<p><strong>However I'd like them to be sorted by the order I keep them in the NSMutableOrderedSet of project.</strong></p>
<p>AFAIK I cannot use NSSortDescriptor with comparator/selector when it's used to Core Data.</p>
<p>Do you know how to do it? Thanks in advance.</p> | 1 |
Python mysql-connector converts some strings into bytearray | <p>I am using python3 and pandas to connect to some sql database:</p>
<pre><code>import pandas as pd
import mysql.connector
cnx = mysql.connector.connect(user='me', password='***',
host='***',
database='***')
df=pd.read_sql("select id as uid,refType from user where registrationTime>=1451606400",con=cnx)
cnx.close()
</code></pre>
<p>I am getting 2 columns: id and refType, both of them are of type string (varchar in SQL terminology). However, for some reason, refType column is correctly imported as string, but uid column is imported as bytearray.
This is how they look:</p>
<pre><code>df.head()
</code></pre>
<blockquote>
<pre><code> uid
</code></pre>
<p>0 [49, 54, 54, 57, 55, 54, 50, 55, 64, 97, 110]<br>
1 [49, 54, 54, 57, 55, 54, 50, 56, 64, 105, 111]<br>
2 [49, 48, 49, 53, 51, 50, 51, 50, 57, 53, 57, 5...<br>
3 [57, 53, 52, 52, 56, 57, 56, 56, 49, 50, 57, 5...<br>
4 [49, 54, 54, 57, 55, 54, 50, 57, 64, 105, 111] </p>
<pre><code> refType
</code></pre>
<p>0 adx_Facebook.IE_an_ph_u8_-.cc-ch.g-f.au-ret7.c...<br>
1 adx_Facebook.IE_io_ph_u4_-.cc-gb.g-f.au-toppay...<br>
2 ad_nan_1845589538__CAbroadEOScys_-.cc-ca.g-f.a...<br>
3 ad_offerTrialPay-DKlvl10-1009<br>
4 adx_Facebook.IE_io_ph_u4_-.cc-us.g-f.au-topspe... </p>
</blockquote>
<p>And this is how uid column is supposed to look:</p>
<pre><code>[i.decode() for i in df['uid'][1:5]]
</code></pre>
<blockquote>
<p>['16697628@io', '10153232959751867@fb', '954489881295911@fb', '16697629@io']</p>
</blockquote>
<p>I don't understand neither why was it converted to bytearray nor how to choose to convert it to string. I couldn't find anything about it or similar questions in internet or pandas documentation. Of course, I can always convert that column to string after importing, but that is not preferred, because the shown sql query is just an example, and in real table there can be hundreds of columns that would be incorrectly imported as bytearrays. It would be real pain in the ass to manually find those columns and convert to string</p>
<p>The connector itself outputs the same bytearray:</p>
<pre><code>cursor = cnx.cursor()
cursor.execute('select id as uid,refType from user where registrationTime>=1451606400 LIMIT 1')
cursor.fetchall()`
</code></pre>
<blockquote>
<p>[(bytearray(b'16697627@an'), 'adx_Facebook.IE_an_ph_u8_-.cc-ch.g-f.au-ret7.cr-cys.dt-all.csd-291215.-') </p>
</blockquote>
<p>The data types of the columns in SQL database are "Varchar(32)" for the first column (uid) and "Varchar(128)" for the second one (refType)</p> | 1 |
How to remove the `get` and `set` from IntelliJ getter/setter generation | <p>Given I have a POJO like:</p>
<pre><code>public class Person {
private String name;
}
</code></pre>
<p>How can I have IntelliJ generate getters and setters without the prefix <code>get</code> and <code>set</code>?</p>
<p>To get this:</p>
<pre><code>public String name() {
return this.name;
}
public void name(String name) {
this.name = name;
}
</code></pre>
<p>Instead of this:</p>
<pre><code>public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
</code></pre> | 1 |
Creating local database at run time with Visual Studio | <p>Beginner's question - please can I ask for advice on creating local database files programmatically at run time. I want to be able later to rename, delete them etc using Windows Explorer in the same way as for text and other files, and to copy them to other computers. </p>
<p>This is using Visual Studio Community 15 with C#, installed SQL server Data Tools 14.0.50616.0. The computer has Microsoft SQL Server 2014.</p>
<p>For an example I have removed the surplus parts of my program to leave the code below, which uses a Windows Form Application with 3 buttons (<code>btnCreateDb</code>, <code>btnDeleteDb</code>, and <code>btnDoesDbExist</code>) and a combobox <code>cbxDb</code> for the database name. It makes databases in an existing folder <code>C:\DbTemp</code>.</p>
<p>It will apparently create and delete a new database and make files, for example <code>mydb1.mdf</code> and <code>mydb1.ldf</code> in the folder, and state that they exist. However, if I delete the two files using Explorer, it throws an exception if an attempt is made to delete or to create the database; and <code>btnDoesDbExist</code> shows that it still exists.</p>
<p>Why does the database still appear to exist when the files have been deleted by Windows Explorer? The code under <code>btnDoesDatabaseExist</code> doesn't refer to the path of the files, so it must be seeing something else, but where? Is this a correct method for the user of the program to create, delete, and detect these databases?</p>
<pre><code>using System;
using System.Data;
using System.Windows.Forms;
//my additions
using System.Data.SqlClient;
namespace DataProg15
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static string form1ConnectionString = "Data Source = (LocalDB)\\MSSQLLocalDB; Integrated Security = True; Connect Timeout = 30; ";
private string form1DatabasePath = "C:\\DbTemp";
private void btnCreateDb_Click(object sender, EventArgs e)
{
string nameToCreate = cbxDb.Text;
SqlConnection myConn = new SqlConnection(form1ConnectionString);
string str = "CREATE DATABASE " +nameToCreate+ " ON PRIMARY " +
"(NAME = " +nameToCreate+ "_Data, " +
"FILENAME = '" +form1DatabasePath+ "\\" +nameToCreate+ ".mdf', " +
"SIZE = 4MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = " +nameToCreate+ "_Log, " +
"FILENAME = '" +form1DatabasePath+ "\\" +nameToCreate+ ".ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase '" + nameToCreate + "' was created successfully");
}
catch (System.Exception ex)
{
MessageBox.Show("Exception in CreateDatabase " + ex.ToString(), "Exception in CreateDatabase", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
private void btnDeleteDb_Click(object sender, EventArgs e)
{
string nameToDelete = cbxDb.Text;
string myConnectionString = form1ConnectionString + "AttachDBFileName = " + form1DatabasePath + "\\" + nameToDelete + ".mdf ";
string str = "USE MASTER DROP DATABASE " + nameToDelete;
SqlConnection myConn = new SqlConnection(myConnectionString);
SqlCommand myCommand = new SqlCommand(str, myConn);
myConn.Open();
try
{
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase '" + nameToDelete + "' was deleted successfully");
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "Exception in DeleteDatabase '" +nameToDelete+ "'", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
private void btnDoesDbExist_Click(object sender, EventArgs e)
{
string nameToTest = cbxDb.Text;
using (var connection = new SqlConnection(form1ConnectionString))
{
using (var command = new SqlCommand(string.Format(
"SELECT db_id('" +nameToTest+ "')", nameToTest), connection))
{
connection.Open();
if ((command.ExecuteScalar() != DBNull.Value))
{
MessageBox.Show("DataBase '" +nameToTest+ "' exists");
}
else
{
MessageBox.Show("Database '" +nameToTest+ "' does not exist");
}
}
}
}
}
</code></pre>
<p>}</p>
<p>Thank you to all for replies, and your trouble is greatly appreciated. </p>
<p>I now understand that I'm using the wrong database so I've tried to use <code>SQL Server Compact</code> instead. Have uninstalled, downloaded again, and reinstalled <code>SQL Server Compact</code> including <code>SP1</code>. Have also downloaded and installed <code>SQL Server Compact/SQLite Toolbox</code> from <code>https://visualstudiogallery.msdn.microsoft.com/0e313dfd-be80-4afb-b5e9-6e74d369f7a1</code> . But Visual Studio has throughout shown an error when I type <code>using System.Data.SqlServerCe</code> . Also when I type <code>SqlCeEngine</code> or <code>SqlCecommand</code>, I assume for the same reason.</p>
<p>In Visual Studio, <code>SQL Server Data Tools</code> and <code>SQL Server Compact & SQLite Toolbox</code> are shown as installed products, but not <code>SQL Server Compact</code>. Do I need to install this into Visual Studio, and if so how is it done?</p> | 1 |
How to return true if all values of array are true otherwise return false? | <p>I have a array like this:</p>
<pre><code>var arr = [ true, true, true ];
</code></pre>
<p>Now I want to get <code>true</code>, because all keys of array above are <code>true</code>.</p>
<p>another example:</p>
<pre><code>var arr = [ true, false, true ];
</code></pre>
<p>Now I need to get <code>false</code>, because there is one <code>false</code> in the array.</p>
<p>How can I do that?</p> | 1 |
SQL server trigger after insert auto increment of an int value | <p>I have a Client table with fields ClientID, UniqueId, Name, Address, etc. UniqueID, Name, Address and other info are populated from the UI. I want to use a trigger to auto populate the ClientID field (not seeded, not null) in SQL server. I have tested some codes (see below) but they don't seem work. any suggestions?</p>
<pre><code>CREATE TRIGGER [dbo].[UpdateClientID]
ON [dbo].[Client]
AFTER INSERT
AS
BEGIN
DECLARE @Max INT;
DECLARE @Increment INT;
SET @Max = 0;
SET @Increment = 1;
SELECT *
INTO #temp
FROM inserted
SELECT @Max = MAX(ClientID)
FROM Client
WHILE (SELECT Count(*) FROM #temp WHERE ClientID IS NULL) > 0
BEGIN
UPDATE #temp
SET ClientID = @Max + @Increment
SET @Increment = @Increment + 1
END
UPDATE c
SET ClientID = t.ClientID
FROM Client c
INNER JOIN #temp t on c.UnqiueID = t.UniqueID
END
</code></pre> | 1 |
Error in finding path in the device | <p>I just drag the Data.csv file to the application folder in the Navigator panel, I am trying to set the correct path of the file into the app. <BR><BR>The code below I used for the simulator and works perfect, but to run in the device I changed to the second block of code, then I got this errors:
<BR><BR>Data[399:157757] CFURLCopyResourcePropertyForKey failed because it was passed an URL which has no scheme<BR>
Error Domain=NSCocoaErrorDomain Code=256 "The file “Documents” couldn’t be opened." <BR>UserInfo={NSURL=/var/mobile/Containers/Data/Application/C7756542-6922-4C6F-A98E-C6F407B2063E/Documents}</p>
<pre><code>//code to show the path in the simulator:
guard let remoteURL = NSURL(string: "/Users/mbp/Library/Developer/CoreSimulator/Devices/7F25FC7C-F2B2-464E-85B4-A2B96DB83F17/data/Containers/Bundle/Application/F285940D-7776-4EE2-83A1-D54DD3411E0E/Data.app/Data.csv") else {
return
}
</code></pre>
<p>Block to run the app in the device:</p>
<pre><code> func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let sourcePath = NSBundle.mainBundle().pathForResource(“Data”, ofType: "csv")
print(sourcePath)
let filename = "Data.csv"
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let destinationPath = documentsPath + "/" + filename
do {
try NSFileManager().copyItemAtPath(sourcePath!, toPath: destinationPath)
} catch _ {
}
Try to load the file
let fetchRequest: NSFetchRequest = NSFetchRequest(entityName: "DataEntity")
fetchRequest.fetchLimit = 1
do {
let result = try managedObjectContext.executeFetchRequest(fetchRequest)
if result.count == 0 {
preloadData()
}
} catch let error as NSError {
print("Error: \(error.domain)")
}
func preloadData () {
guard let remoteURL = NSURL(string:NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]) else {
return
}
}
</code></pre> | 1 |
How to pass long string in HttpClient.PostAsync request | <p>Trying to send a rather long string to a REST web api (youtrack). I get the following exception:</p>
<p>Invalid URI: The Uri string is too long.</p>
<p>My code:</p>
<pre><code>var encodedMessage = HttpUtility.UrlEncode(message);
var requestUri = string.Format("{0}{1}issue/{2}/execute?comment={3}", url, YoutrackRestUrl, issue.Id, encodedMessage);
var response = await httpClient.PostAsync(requestUri, null).ConfigureAwait(false);
</code></pre>
<p>So I took my chances with a <code>FormUrlEncodedContent</code></p>
<pre><code>var requestUri = string.Format("{0}{1}issue/{2}/execute", url, YoutrackRestUrl, issue.Id);
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("comment", message));
var content = new FormUrlEncodedContent(postData);
var response = await httpClient.PostAsync(requestUri, content).ConfigureAwait(false);
</code></pre>
<p>Which results in the exact same issue.</p>
<p>The string (comment) I am sending, is the changed file set of a commit into SVN. Which can be really long, so I don't really have a way to get around that. Is there a way to post content without the string length restriction?</p>
<p>Read the following topics, but didn't find an answer there:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/15176538/net-httpclient-how-to-post-string-value">.NET HttpClient. How to POST string value?</a></li>
<li><a href="https://stackoverflow.com/questions/18971510/how-do-i-set-up-httpcontent-for-my-httpclient-postasync-second-parameter">How do I set up HttpContent for my HttpClient PostAsync second parameter?</a></li>
<li><a href="https://psycodedeveloper.wordpress.com/2014/06/30/how-to-call-httpclient-postasync-with-a-query-string/" rel="nofollow noreferrer">https://psycodedeveloper.wordpress.com/2014/06/30/how-to-call-httpclient-postasync-with-a-query-string/</a></li>
<li><a href="http://forums.asp.net/t/2057125.aspx?Invalid+URI+The+Uri+string+is+too+long+HttpClient" rel="nofollow noreferrer">http://forums.asp.net/t/2057125.aspx?Invalid+URI+The+Uri+string+is+too+long+HttpClient</a></li>
</ul> | 1 |
How can I put all the URL parameters in array of objects using jQuery? | <p>I have a giving string/url like this
<code>https://example.com/loadcontent?var1=100&var2=:somevar&var3=:morevariables</code></p>
<p>I need to loop thought each parameter in the url. If the value starts with <code>:</code> this indicated that it is a variable an I will need to change that value dynamically by looking at the corresponding meta attribute that matches that variable. </p>
<p>Here is my code in which loops over an array and sets the value of the parameters.</p>
<pre><code> var baseURL = getBaseURL(url);
var params = getParams(url);
var newParams = $.each(params, function(index, param){
if( param.value.substring(0, 1) == ':'){
var myVar = param.value.substring(1);
param.value = $('meta[name=" + myVar + "']).attr('value');
}
});
var finalURL = baseURL + '?' + jQuery.param( newParams );
function getParams(url){
// This function should return an array of objects. Each object should have 2 properties "value" and "name". The "name" property should be the name of the parameter (ie. var1, var2, var3 .....) and the "value" attribute should contains the value of the parameter (ie. 100, :somevar, :morevariables)
}
function getBaseURL(url){
var cutoff = url.indexOf('?');
if( cutoff > -1){
return url.substring(0, cutoff - 1);
}
return url;
}
</code></pre>
<p>I need help converting the parameters of a giving URL to array of object. How can I do this in jQuery?</p> | 1 |
Permission denied for running cron job | <p>I have codeigniter cron jobs in controller in /data1/src/test1.
I am running one of the methods in controller present in above code. so i run the cron as follows</p>
<pre><code>30 08 * * * /usr/bin/php /data2/src/test/index.php controller method1 > /tmp/test.log 2>&1.
</code></pre>
<p>Test folder is codeigniter framework and controller1.php is present in controllers folder.and method1 is function inside this controller class.</p>
<p>But when this cron runs.I get error in log file as permission denied.
Please guide me for scheduling cron in codeigniter</p> | 1 |
Bootstrap and horizontal radio buttons | <p>I'm trying to display radio buttons horizontally using <code>Bootstrap-CSS</code> and <code>Flask-WTForms</code>. As far as I understand, I need to use the Bootstrap class <code>class_="radio-inline"</code> to accomplish that. I've tried it and all I get is this:</p>
<p><a href="https://i.stack.imgur.com/LGwiD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LGwiD.png" alt="enter image description here"></a></p>
<p>where radio buttons are, discouragingly, organized vertically.</p>
<p><strong>Flask WTForm code:</strong></p>
<pre><code>from flask.ext.wtf import Form
import csv
import os
import buildHome as bh
from wtforms import TextField, RadioField, TextAreaField, SubmitField, validators, BooleanField
class ContactForm(Form):
firstName = TextField("First name", [validators.Required("Please enter your first name.")])
lastName = TextField("Last name", [validators.Required("Please enter your last name.")])
#name = TextField("Name", [validators.Required("Please enter your name.")])
email = TextField("Email", [validators.Required("Please enter your email address."), validators.Email("Please enter your email address.")])
node_1 = BooleanField("Joan Johnson (Buckridge Inc)")
direction_1 = RadioField('', choices=[('Choice1','Choice1'),('Choice2','Choice2'),('Choice3','Choice3')])
freq_1 = RadioField('', choices=[(1,'Daily'),(7,'Weekly'),(30,'Monthly'),(183,'Yearly'),(365,'More')])
submit = SubmitField("Send")
</code></pre>
<p><strong>Html template for Flask to create the html code</strong></p>
<pre><code>{% extends "layout.html" %}
{% block content %}
<form action="{{ url_for('home') }}" method=post>
{{ form.hidden_tag() }}
<h3>Part I</h3>
<div class="well span6">
<div>
{{ form.firstName.label }} {{ form.firstName }}
</div>
<div>
{{ form.lastName.label }} {{ form.lastName }}
</div>
<div>
{{ form.email.label }} {{ form.email }}
</div>
</div>
<h3>Part II</h3>
<div <form class="form-horizontal" role="form">
<div class="well span6">
{{ form.node_1 (class_="checkbox style-2 pull-left") }} {{ form.node_1.label(class_="col-sm-3 control-label") }}
{{ form.direction_1.label }} {{ form.direction_1 (class_="radio-inline") }}
{{ form.freq_1.label }} {{ form.freq_1 (class_="radio-inline") }}
</div>
{{ form.submit }}{% endblock %}
</code></pre>
<p><strong>Html script, produced by the Flask WTForm script above</strong></p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<title>TITLE</title>
<link rel="stylesheet" href="/static/css/bootstrap.css">
</head>
<body>
<header>
<div class="container">
<h1 class="logo">LOGO</h1>
<nav>
<ul class="menu">
<li><a href="/">Home</a></li>
</ul>
</nav>
</div>
</header>
<div class="container">
<form action="/" method=post>
<div style="display:none;"><input id="csrf_token" name="csrf_token" type="hidden" value="1454454094##65db3f398f17785503e4bf13dfe76ad4879eb792"></div>
<h3>
Part I</h3>
<div class="well span6">
<div>
<label for="firstName">First name</label> <input id="firstName" name="firstName" type="text" value="">
</div>
<div>
<label for="lastName">Last name</label> <input id="lastName" name="lastName" type="text" value="">
</div>
<div>
<label for="email">Email</label> <input id="email" name="email" type="text" value="">
</div>
</div>
<h3>Part II</h3>
<div <form class="form-horizontal" role="form">
<div class="well span6">
<input class="checkbox style-2 pull-left" id="node_1" name="node_1" type="checkbox" value="y"> <label class="col-sm-3 control-label" for="node_1">Joan Johnson (Buckridge Inc)</label>
<label for="direction_1"></label> <ul class="radio-inline" id="direction_1"><li><input id="direction_1-0" name="direction_1" type="radio" value="Choice1"> <label for="direction_1-0">Choice1</label></li><li><input id="direction_1-1" name="direction_1" type="radio" value="Choice2"> <label for="direction_1-1">Choice2</label></li><li><input id="direction_1-2" name="direction_1" type="radio" value="Choice3"> <label for="direction_1-2">Choice3</label></li></ul>
<label for="freq_1"></label> <ul class="radio-inline" id="freq_1"><li><input id="freq_1-0" name="freq_1" type="radio" value="1"> <label for="freq_1-0">Daily</label></li><li><input id="freq_1-1" name="freq_1" type="radio" value="7"> <label for="freq_1-1">Weekly</label></li><li><input id="freq_1-2" name="freq_1" type="radio" value="30"> <label for="freq_1-2">Monthly</label></li><li><input id="freq_1-3" name="freq_1" type="radio" value="183"> <label for="freq_1-3">Yearly</label></li><li><input id="freq_1-4" name="freq_1" type="radio" value="365"> <label for="freq_1-4">More</label></li></ul>
</div>
<input id="submit" name="submit" type="submit" value="Send">
</div>
</body>
</html>
</body>
</html>
</code></pre>
<p>I'm probably missing something rather obvious, but can't get my finger on it. Also, it's my first time using Bootstrap or any CSS styling for that matter. So that might be it</p>
<p>In short, What am I doing wrong?</p> | 1 |
log file to json file conversion | <p>I have some log files.i want to convert content of these files to <code>json</code> format using python.required json format is </p>
<pre><code>{
"content": {
"text" : // raw text to be split
},
"metadata";: {
...meta data fields, eg. hostname, logpath,
other fields passed from client...
}
}
</code></pre>
<p>i tried <code>json</code> dump in <code>python 2.7</code> but unexpected errors are coming..any suggestion will be great..
thanks..</p>
<p>error I got : </p>
<pre><code>Traceback (most recent call last):
File "LogToJson.py", line 12,
in <module> f.write(json.dumps(json.loads(f1), indent=1))
File "/usr/lib/python2.7/json/__init__.py", line 338,
in loads return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366,
in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
</code></pre>
<p>sample data:</p>
<pre><code>Jan 27 10:46:57 sabya-ThinkPad-T420 NetworkManager[1462]:
<info> address 9.124.29.61
Jan 27 10:46:57 sabya-ThinkPad-T420 NetworkManager[1462]:
<info> prefix 24 (255.255.255.0)
Jan 27 10:46:57 sabya-ThinkPad-T420 NetworkManager[1462]:
<info> gateway 9.124.29.1
</code></pre> | 1 |
Implement type casting from one class to another | <p>Assuming I have two classes which are not related by inheritance. e.g:</p>
<pre><code>class MyString
{
private:
std::string str;
};
class MyInt
{
private:
int num;
};
</code></pre>
<p>and I want to be able to convert one to another using regular casting e.g <code>MyInt a = (MyInt)mystring</code> (where <code>mystring</code> is of <code>class MyString</code>).</p>
<p>How does one accomplish such a thing?</p> | 1 |
How to break the loop using user input? | <p>I am trying something like this.Its counting down seconds from 5-1.</p>
<pre><code> #include<iostream>
#include<stdlib.h>
#include<windows.h>
#include<iomanip>
using namespace std;
int main()
{
for(int i=5;i>0;i--)
{
cout<<"\n\n\n\n\n\n";
cout<<setw(35);
cout<<i;
Sleep(1000);
system("CLS");
}
system("PAUSE");
}
</code></pre>
<p>And i trying to figure out a way to break the loop using a user input(from keyboard) to break it while its running. I have no idea about how to do this.I have heard about multi-threading. I don't even know if multi-threading has any application in my situation or not .So any ideas on how to break it in middle while its executing the loop?</p> | 1 |
Error when sending Mail and attachment in Java | <p>I have a function to send mail with attachment in java. It works when i uploaded the attachment. However, the problem is that if i have to send a mail without attachment, it says error when i send a mail and i did not upload any attachment.</p>
<p>here is my code:</p>
<pre><code> Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
String html = text;
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(email));
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(html, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String filename = "C:/Users/gro/Desktop/"+attachment;
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
</code></pre>
<p>any idea how i can solve this?</p>
<p>i get this error:</p>
<p>org.apache.jasper.JasperException: java.lang.RuntimeException: javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.FileNotFoundException: C:\Users\gro\Desktop (Access is denied)</p> | 1 |
Using C# Restsharp, how can I replicate a form post? | <p>I am using a rest service to get back some json data. As a test harness, they gave me a url and if I go to the url in the browser, I have a form and i can put some json in a textarea and then submit the form and i get the json result back on the page reload. </p>
<p>I am now trying to replicate this programatically by using RestSharp in C# but i am running into an issue where the results from the call is the html of the page that i am going to (instead of the json result)</p>
<p>Here is my code:</p>
<pre><code>var client = new RestClient {BaseUrl = new Uri("http://myhost.com:22333") };
var request = new RestRequest { Method = Method.POST, Resource = "/site/api", RequestFormat = DataFormat.Json };
request.AddBody(new
{
fieldtype = "name", value = "joe"
});
request.AddHeader("accept", "application/json");
client.Authenticator = new NtlmAuthenticator();
var response = client.Execute(request);
var jsonDto = new JsonDeserializer().Deserialize<ResultObj>(response);
</code></pre>
<p>if i look at response.Content in the debugger (before any deserialization) i see an html string of the web page that i went to with the form to post (something like this)</p>
<pre><code><html>
<body>
<form method='POST'>
<table>
<tr>
<td>Enter the JSON:</td>
<td>
<textarea name="json_input" cols="80" rows="30">
</textarea>
</td>
</tr>
<tr><td colspan='2'><input type='Submit' value='submit'></td></tr>
</table>
</form>
</body>
</html>
</code></pre>
<p>Can someone advise what i am missing here as I am expecting to get the same json result back in response.Content that i see after submitting the form in the browser</p> | 1 |
c++ how do i get the current console conhost process | <p>i have searched on so many websites after <code>"how i get the conhost process"</code>, and nothing is really what i'm looking for.</p>
<p>i have searched on.</p>
<ul>
<li><a href="https://superuser.com/questions/624270/when-is-conhost-exe-actually-necessary"><code>superuser/stackoverflow</code> when-is-conhost-exe-actually-necessary</a></li>
<li><a href="https://stackoverflow.com/questions/185254/how-can-a-win32-process-get-the-pid-of-its-parent"><code>stackoverflow</code> how-can-a-win32-process-get-the-pid-of-its-parent</a></li>
<li><a href="https://stackoverflow.com/questions/18401572/c-how-to-fetch-parent-process-id"><code>stackoverflow</code> c-how-to-fetch-parent-process-id</a></li>
<li><a href="https://stackoverflow.com/questions/1591342/c-how-to-determine-if-a-windows-process-is-running"><code>stackoverflow</code> c-how-to-determine-if-a-windows-process-is-running</a></li>
<li><a href="https://stackoverflow.com/questions/3477097/get-full-running-process-list-visual-c"><code>stackoverflow</code> get-full-running-process-list-visual-c</a></li>
<li><a href="https://stackoverflow.com/questions/298257/ms-c-get-pid-of-current-process"><code>stackoverflow</code> ms-c-get-pid-of-current-process</a></li>
<li><a href="https://stackoverflow.com/questions/29774529/get-list-of-dlls-loaded-in-current-process-with-their-reference-counts"><code>stackoverflow</code> get-list-of-dlls-loaded-in-current-process-with-their-reference-counts</a></li>
<li><a href="http://www.codeproject.com/Articles/9893/Get-Parent-Process-PID" rel="nofollow noreferrer"><code>codeproject</code> Get-Parent-Process-PID</a></li>
<li><a href="http://www.cplusplus.com/forum/windows/45564/" rel="nofollow noreferrer"><code>cplusplus</code> Getting list of running processes</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms683198%28v=vs.85%29.aspx" rel="nofollow noreferrer"><code>msdn.microsoft</code> GetModuleFileNameEx</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms683197%28v=vs.85%29.aspx" rel="nofollow noreferrer"><code>msdn.microsoft</code> GetModuleFileName</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/ms683180%28VS.85%29.aspx" rel="nofollow noreferrer"><code>msdn.microsoft</code> GetCurrentProcessId</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms683215%28v=vs.85%29.aspx" rel="nofollow noreferrer"><code>msdn.microsoft</code> GetProcessId</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms683199%28v=vs.85%29.aspx" rel="nofollow noreferrer"><code>msdn.microsoft</code> GetModuleHandle</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms683175%28v=vs.85%29.aspx" rel="nofollow noreferrer"><code>msdn.microsoft</code> GetConsoleWindow</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/ms686832%28VS.85%29.aspx" rel="nofollow noreferrer"><code>msdn.microsoft</code> Tool Help</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/ms682489%28v=vs.85%29.aspx" rel="nofollow noreferrer"><code>msdn.microsoft</code> CreateToolhelp32Snapshot</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/ms684221%28v=vs.85%29.aspx" rel="nofollow noreferrer"><code>msdn.microsoft</code> NextModule32</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/ms679295%28VS.85%29.aspx" rel="nofollow noreferrer"><code>msdn.microsoft</code> DebugActiveProcess</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms682621%28v=vs.85%29.aspx" rel="nofollow noreferrer"><code>msdn.microsoft</code> Enumerating All Modules For a Process</a></li>
</ul>
<p>and i can't find anything about <code>"how to get the conhost process"</code>.</p>
<p>i have some code that works for the current <code>"cmd.exe / program.exe"</code> and that gives me the <code>"PID, NAME, PATH, READ/WRITE ADDRESS"</code>.</p>
<p>i can get the <code>parent</code> process but that is not <code>conhost.exe</code>.</p>
<p>code <code>"need to link library 'psapi' first"</code>:</p>
<pre><code>#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <psapi.h>
#include <iostream>
#include <tlhelp32.h>
int PrintModules(DWORD processID) {
HMODULE hMods[1024];
HANDLE hProcess;
DWORD cbNeeded;
unsigned int i;
printf( "\nProcess ID: %u\n", processID);
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
if(NULL == hProcess) return 1;
if(EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) {
for(i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) {
TCHAR szModName[MAX_PATH];
if(GetModuleFileNameEx(hProcess, hMods[i], szModName,sizeof(szModName) / sizeof(TCHAR))) {
_tprintf( TEXT(" %s (0x%08X)\n"), szModName, hMods[i]);
}
}
}
CloseHandle(hProcess);
return 0;
}
int main(void) {
DWORD cpid = GetCurrentProcessId();
PrintModules(cpid);
int ppid = -1;
HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe = { 0 };
pe.dwSize = sizeof(PROCESSENTRY32);
if(Process32First(h, &pe)) {
do {
if(pe.th32ProcessID == cpid) {
printf("PID: %i; PPID: %i\n", cpid, pe.th32ParentProcessID);
ppid = pe.th32ParentProcessID;
}
} while(Process32Next(h, &pe));
}
PrintModules(ppid);
CloseHandle(h);
std::cin.get();
return 0;
}
</code></pre>
<p>and i can't figure out a way to get the current <code>conhost</code> process.</p>
<p>when you open a <code>program</code> that uses the console, a <code>conhost.exe</code> process is created.
and my question is how do i get that <code>conhost.exe</code> process...</p>
<p>Thanks! :)</p> | 1 |
Golang UnmarshalTypeError missing Offset | <p>I'm totally newbie in Golang and solving problem with parsing JSON. Everything is working, except error handling.</p>
<pre><code>if err := json.Unmarshal(file, &configData); err != nil {
if ute, ok := err.(*json.UnmarshalTypeError); ok {
fmt.Printf("UnmarshalTypeError %v - %v - %v", ute.Value, ute.Type, ute.Offset)
}
}
</code></pre>
<p>Here I get error <code>ute.Offset undefined (type *json.UnmarshalTypeError has no field or method Offset)</code> but in <a href="https://golang.org/pkg/encoding/json/#UnmarshalTypeError" rel="nofollow">Docs of JSON package</a> and also <a href="https://golang.org/src/encoding/json/decode.go?s=3363:3613#L89" rel="nofollow">code</a> they have this variable in <code>UnmarshalTypeError</code> struct.</p>
<p>What I'm doing wrong? Thank you</p> | 1 |
Could not load IBDesignable xib in the Interface Builder | <p>I have a <code>xib</code> (<code>childXib</code>) file linked to its custom <code>UIView</code> swift file through its Owner.</p>
<p>This is how I initialize my custom <code>UIView</code>:</p>
<pre><code>// init for IBDesignable
override init(frame: CGRect) {
super.init(frame: frame)
let view = loadViewFromNib()
view.frame = bounds
addSubview(view)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addSubview(loadViewFromNib())
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "CommentCellView", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
</code></pre>
<p>When I want to add this <code>xib</code> (<code>childXib</code>) in another <code>xib</code> (<code>parentXib</code>), I get the following errors:</p>
<blockquote>
<p>error: IB Designables: Failed to render instance of MyRootView: The agent threw an exception.</p>
</blockquote>
<p>Where <code>MyRootView</code> is the file linked to <code>parentXib</code></p>
<blockquote>
<p>error: IB Designables: Failed to update auto layout status: The agent raised a "NSInternalInconsistencyException" exception: Could not load NIB in bundle: 'NSBundle (loaded)' with name 'MyIBDesignableCustomViewFilename'</p>
</blockquote>
<p>Where <code>MyIBDesignableCustomViewFilename</code> is the file linked to <code>childXib</code>.</p>
<p>When I debug it by clicking on <code>Debug</code> in <code>Custom class</code> from the <code>Identity inspector</code>, it doesn't work from that line:</p>
<pre><code>let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
</code></pre>
<p>All the <code>xib</code> files are in <code>Copy Bundle Resources</code> in <code>Build Phases</code>.</p>
<p>Any idea what's wrong?</p> | 1 |
swift : show another view controller on swipe up in first view controller | <p>Hi I checked many questions regarding swiping in SO but have doubts .</p>
<p>In my app I have two pages
1. user view controller
2. question view controller</p>
<p>user page looks like this
<a href="https://i.stack.imgur.com/pQ0Gy.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/pQ0Gy.jpg" alt="userpage"></a></p>
<p>now what i want to implement is to show questions view controller while swiping up the users screen from bottom.</p>
<p>I am new to Ios, so help me in achieving this. </p>
<p><strong><em>edit:</em></strong></p>
<p>the problem is while swiping up only it should start showing the other view controller. if i swiped till middle of the screen with my finger still touching the screen, then it should show 2 view controllers.can I achieve this using push/pop like this</p>
<p><a href="https://i.stack.imgur.com/6PtTH.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/6PtTH.jpg" alt="enter image description here"></a></p> | 1 |
get exact time in javascript | <p>How to get exact currect time in javascript? For Example when you execute the code you whoud get (2016-02-11 03:11:22:33). </p>
<p><strong>Note:</strong> There is so many tutorial but none of them gives you the <strong>milliseconds</strong> of current time.</p> | 1 |
Powershell REG LOAD command not working | <p>Windows 7, in Powershell (running as admin), running the following command on an offline user:</p>
<pre><code>& REG LOAD HKLM\CHANGEUSER c:\users\testuser\ntuser.dat
Write-Host Loaded with result $?
</code></pre>
<p>Result: <strong>False</strong>. On inspection of the key using regedit, it has NOT been loaded. Note: HKLM\Changeuser is not precreated.</p>
<hr>
<p>If I use the same command from a command prompt (as admin), it is all fine:</p>
<pre><code>REG LOAD HKLM\CHANGEUSER c:\users\testuser\ntuser.dat
</code></pre>
<p>Result: <strong>The command completed successfully</strong>, and the file has been loaded into the registry.</p>
<p>Why is it not loading into the registry when using powershell? I have attempted with and without the call operator (&), but get the same result.</p> | 1 |
ora-02393 exceed limit on call cpu usage (Oracle) - how to workaround | <p>I have function which calcs the IRR (Internal Rate of Return) for specific contract ..</p>
<p>This function is called inside simple procedure and is applied to all contracts in defined table ..</p>
<p>problem is, that there is a roughly 200k rows which needs to be updated .. and the function calc_IRR() is not so effective (loop and sub-loop), which is necessary to calc the correct value ..</p>
<p>After an hour of run, query will exceed the CALL CPU USAGE limit (ora-02393) and the query ends.. but I need to re-run the query again ...</p>
<p>Here comes the procedure:</p>
<pre><code>CREATE OR REPLACE PROCEDURE proc_set_irr ( p_table_name IN VARCHAR2, p_cashflow_column IN VARCHAR2, p_dimension IN VARCHAR2, p_irr_column IN VARCHAR2 )
IS
v_data VARCHAR2(2000);
v_updt VARCHAR2(2000);
v_condition VARCHAR2(2000);
v_irr NUMBER;
c1 SYS_REFCURSOR;
BEGIN
-- fetch each dimension data separately
OPEN c1 FOR 'SELECT distinct '||p_dimension||' FROM '||p_table_name||' WHERE 1=1 AND '||p_irr_column||' IS NULL';
LOOP
FETCH c1 INTO v_data;
EXIT WHEN c1%NOTFOUND;
v_condition := p_dimension || ' = ' || v_data; -- build condition for IRR calculation
v_irr := f_calc_irr(p_table_name, p_cashflow_column, v_condition)*100; -- calc IRR for defined contract
v_updt := 'UPDATE '||p_table_name||' SET '||p_irr_column||' = :1 WHERE '||p_dimension||' = :2'; -- build UDPATE query for contract
EXECUTE IMMEDIATE v_updt USING v_irr, v_data; -- update contract with IRR
COMMIT;
END LOOP;
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
END proc_set_irr;
/
</code></pre>
<p>How to do it without manual input of user? I have it in PACKAGE so it's called automatically once a month ... </p> | 1 |
How to recover from pip freeze exception? | <p>I am installing python 2.7 packages on an ubuntu 14 system and have run into a problem wherein "pip freeze" produces output like this ...</p>
<pre><code>$ pip freeze
Exception:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
status = self.run(options, args)
File "/usr/lib/python2.7/dist-packages/pip/commands/freeze.py", line 74, in run
req = pip.FrozenRequirement.from_dist(dist, dependency_links, find_tags=find_tags)
File "/usr/lib/python2.7/dist-packages/pip/__init__.py", line 286, in from_dist
assert len(specs) == 1 and specs[0][0] == '=='
AssertionError
Storing debug log for failure in /home/ubuntu/.pip/pip.log
$ cat /home/ubuntu/.pip/pip.log
------------------------------------------------------------
/usr/bin/pip run on Tue Feb 9 21:00:36 2016
Exception:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
status = self.run(options, args)
File "/usr/lib/python2.7/dist-packages/pip/commands/freeze.py", line 74, in run
req = pip.FrozenRequirement.from_dist(dist, dependency_links, find_tags=find_tags)
File "/usr/lib/python2.7/dist-packages/pip/__init__.py", line 286, in from_dist
assert len(specs) == 1 and specs[0][0] == '=='
AssertionError
</code></pre>
<p>I am uncertain what caused this state of affairs.<br>
My suspicion is that a failure of the easy_install program might have caused something to get corrupted. </p>
<p>I have tried re-installing pip.<br>
This had no effect. </p>
<p>I suspect that I will have to do a complete uninstall and reinstall of all python packages via pip and python related ubuntu packages via apt-get. package by package.</p>
<p>This will be quite time consuming and I am uncertain if it will achieve the desired result.</p>
<p>Is there a better approach to this problem?</p>
<p>Here are the packages that I installed prior to running easy_install:</p>
<pre><code>sudo apt-get install -y libprotobuf-dev libleveldb-dev libsnappy-dev libopencv-dev libboost-all-dev libhdf5-serial-dev protobuf-compiler gfortran libjpeg62 libfreeimage-dev libatlas-base-dev git python-dev python-pip libgoogle-glog-dev libbz2-dev libxml2-dev libxslt-dev libffi-dev libssl-dev libgflags-dev liblmdb-dev python-yaml python-numpy
</code></pre>
<p>Here is the initial exception that I got from easy_install:</p>
<pre><code>$ sudo easy_install pillow
Searching for pillow
Reading https://pypi.python.org/simple/pillow/
Best match: Pillow 3.1.1
Downloading https://pypi.python.org/packages/source/P/Pillow/Pillow-3.1.1.zip#md5=3868f54fd164e65f95fbcb32f62940ae
Processing Pillow-3.1.1.zip
Writing /tmp/easy_install-Bvu_2f/Pillow-3.1.1/setup.cfg
Running Pillow-3.1.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-Bvu_2f/Pillow-3.1.1/egg-dist-tmp-lMm5Tk
warning: no previously-included files found matching '.editorconfig'
Building using 4 processes
_imaging.c: In function ‘getink’:
_imaging.c:474:9: warning: ‘r’ may be used uninitialized in this function [-Wmaybe-uninitialized]
int r, g, b, a;
^
libImaging/Resample.c:87:45: warning: always_inline function might not be inlinable [-Wattributes]
static float __attribute__((always_inline)) i2f(int v) {
^
Building using 4 processes
Building using 4 processes
Building using 4 processes
--------------------------------------------------------------------
PIL SETUP SUMMARY
--------------------------------------------------------------------
version Pillow 3.1.1
platform linux2 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2]
--------------------------------------------------------------------
*** TKINTER support not available
--- JPEG support available
*** OPENJPEG (JPEG2000) support not available
--- ZLIB (PNG/ZIP) support available
--- LIBTIFF support available
--- FREETYPE2 support available
*** LITTLECMS2 support not available
*** WEBP support not available
*** WEBPMUX support not available
--------------------------------------------------------------------
To add a missing option, make sure you have the required
library, and set the corresponding ROOT variable in the
setup.py script.
To check the build, run the selftest.py script.
Adding Pillow 3.1.1 to easy-install.pth file
Installing pildriver.py script to /usr/local/bin
Installing viewer.py script to /usr/local/bin
Installing gifmaker.py script to /usr/local/bin
Installing pilconvert.py script to /usr/local/bin
Installing pilfont.py script to /usr/local/bin
Installing pilfile.py script to /usr/local/bin
Installing createfontdatachunk.py script to /usr/local/bin
Installing explode.py script to /usr/local/bin
Installing pilprint.py script to /usr/local/bin
Installing player.py script to /usr/local/bin
Installing thresholder.py script to /usr/local/bin
Installing painter.py script to /usr/local/bin
Installing enhancer.py script to /usr/local/bin
Installed /usr/local/lib/python2.7/dist-packages/Pillow-3.1.1-py2.7-linux-x86_64.egg
Processing dependencies for pillow
Finished processing dependencies for pillow
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 330, in _handle_workers
debug('worker handler exiting')
TypeError: 'NoneType' object is not callable
Exception Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 357, in _handle_tasks
debug('task handler got sentinel')
TypeError: 'NoneType' object is not callable
TypeError: TypeError("'NoneType' object does not support item deletion",) in <Finalize object, dead> ignored
ubuntu@ip-10-234-31-217:~/nvidia_installers/cuda$
</code></pre>
<p>I was subsequently able to install pillow via pip.</p>
<p>I've noticed that there seem to be 2 different dist-packages in my path.<br>
That seems to be a little odd. </p>
<pre><code>>>> import sys
>>> import pprint
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(sys.path)
[ '',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages']
</code></pre>
<p>Here is the full procedure that I am following:<br>
<a href="https://github.com/BVLC/caffe/wiki/Install-Caffe-on-EC2-from-scratch-(Ubuntu,-CUDA-7,-cuDNN)#installing-caffe" rel="nofollow" title="Install Caffe on EC2 from scratch">Install Caffe on EC2 from scratch</a></p>
<p>I understand that the version of pip supported by apt-get is very old.<br>
I have tried updating pip.<br>
I get "Owned by OS" errors.<br>
I am uncertain about how to diverge from using apt-get here and the consequences of doing so. </p>
<pre><code>$ pip install -U pip
Downloading/unpacking pip from https://pypi.python.org/packages/py2.py3/p/pip/pip-8.0.2-py2.py3-none-any.whl#md5=2056f553d5b593d3a970296f229c1b79
Downloading pip-8.0.2-py2.py3-none-any.whl (1.2MB): 1.2MB downloaded
Installing collected packages: pip
Found existing installation: pip 1.5.4
Not uninstalling pip at /usr/lib/python2.7/dist-packages, owned by OS
Can't roll back pip; was not uninstalled
Cleaning up...
Exception:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
status = self.run(options, args)
File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 283, in run
requirement_set.install(install_options, global_options, root=options.root_path)
File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1436, in install
requirement.install(install_options, global_options, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/pip/req.py", line 672, in install
self.move_wheel_files(self.source_dir, root=root)
File "/usr/lib/python2.7/dist-packages/pip/req.py", line 902, in move_wheel_files
pycompile=self.pycompile,
File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 206, in move_wheel_files
clobber(source, lib_dir, True)
File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 193, in clobber
os.makedirs(destsubdir)
File "/usr/lib/python2.7/os.py", line 157, in makedirs
mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/pip-8.0.2.dist-info'
Storing debug log for failure in /home/ubuntu/.pip/pip.log
$ sudo pip install -U pip
Downloading/unpacking pip from https://pypi.python.org/packages/py2.py3/p/pip/pip-8.0.2-py2.py3-none-any.whl#md5=2056f553d5b593d3a970296f229c1b79
Downloading pip-8.0.2-py2.py3-none-any.whl (1.2MB): 1.2MB downloaded
Installing collected packages: pip
Found existing installation: pip 1.5.4
Not uninstalling pip at /usr/lib/python2.7/dist-packages, owned by OS
Successfully installed pip
Cleaning up...
$ pip --version
pip 1.5.4 from /usr/lib/python2.7/dist-packages (python 2.7)
ubuntu@ip-10-234-31-217:~$ pip freeze
Exception:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
status = self.run(options, args)
File "/usr/lib/python2.7/dist-packages/pip/commands/freeze.py", line 74, in run
req = pip.FrozenRequirement.from_dist(dist, dependency_links, find_tags=find_tags)
File "/usr/lib/python2.7/dist-packages/pip/__init__.py", line 286, in from_dist
assert len(specs) == 1 and specs[0][0] == '=='
AssertionError
Storing debug log for failure in /home/ubuntu/.pip/pip.log
</code></pre>
<p>Another method of upgrading pip also failed:</p>
<pre><code>$ sudo pip install --upgrade pip
The directory '/home/ubuntu/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/ubuntu/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:315: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning.
SNIMissingWarning
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:120: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
Requirement already up-to-date: pip in /usr/local/lib/python2.7/dist-packages
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:120: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
$ pip freeze
Exception:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
status = self.run(options, args)
File "/usr/lib/python2.7/dist-packages/pip/commands/freeze.py", line 74, in run
req = pip.FrozenRequirement.from_dist(dist, dependency_links, find_tags=find_tags)
File "/usr/lib/python2.7/dist-packages/pip/__init__.py", line 286, in from_dist
assert len(specs) == 1 and specs[0][0] == '=='
AssertionError
Storing debug log for failure in /home/ubuntu/.pip/pip.log
$ ls -lF /home/ubuntu/.cache/pip/http
ls: cannot access /home/ubuntu/.cache/pip/http: No such file or directory
$ ls -lF /home/ubuntu/.cache
total 0
-rw-r--r-- 1 ubuntu ubuntu 0 Feb 6 00:39 motd.legal-displayed
</code></pre> | 1 |
Understanding message "Cannot accept external Xdebug connection: Cannot evaluate expression 'isset($_SERVER['PHP_IDE_CONFIG'])'" | <p>I'm using the PHPstorm as my main PHP development enviroment and XDebug to debugging my applications.</p>
<p>My only problem is the message "Cannot accept external Xdebug connection: Cannot evaluate expression 'isset($_SERVER['PHP_IDE_CONFIG'])'" appearing from time to time.</p>
<p>I already saw some solutions to the problem <a href="https://stackoverflow.com/questions/29035705/phpstorm-is-not-receiving-xdebug-connections-phpstorm-event-log-cannot-evalu">here</a> and also in the JetBrains support (<a href="https://devnet.jetbrains.com/message/5462505" rel="nofollow noreferrer">here</a> and <a href="https://devnet.jetbrains.com/message/5478634" rel="nofollow noreferrer">here</a>), but my problem is a little bit different 'cause I CAN Debug normally, but the message continues to appear. </p>
<p>See the print of the event log below. Apparently, the message appears every 30 minutes.</p>
<p><a href="https://i.stack.imgur.com/xbL7X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xbL7X.png" alt="event log of phpstorm"></a></p>
<p>FYI, I'm debbuging a webservice, so, I configure the Xdebug to listen all HTTP requests, I click the "Start Listen PHP Debug Connections button" (green in the figure) and then launch the requests through Advannced Rest Client(Chrome).</p>
<p>As I said, I can debug without problems, so I just want to understand the message. Can it cause any problem? Am I doing something wrong? Can I disable this message? How?</p>
<p>I tried the solutions in the linked question, but the message still there.</p>
<p>This is my Xdebug configuration:</p>
<pre><code>[Zend]
zend_extension="/usr/lib/php5/20131226/xdebug.so"
xdebug.remote_enable=1
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=127.0.0.1
xdebug.remote_port=9000
xdebug.remote_autostart=1
xdebug.remote_connect_back=0
</code></pre> | 1 |
vscode regex sub match evaluate instead of concatenate? | <pre><code>Test 300
Test 301
Test 302
</code></pre>
<p>I can use regex find to loop through these:</p>
<pre><code>Test (3[0-9]*)
</code></pre>
<p>When I try replace with math it concatenates instead of evaluates?</p>
<pre><code>Test $1-100
</code></pre>
<p>So, it becomes:</p>
<pre><code>Test 300-100
</code></pre>
<p>Is it possible to evaluate instead of concatenate, so it becomes:</p>
<pre><code>Test 200
</code></pre>
<p>Thanks.</p> | 1 |
ODP.NET Managed ConnectionPool closes/opens every 3 minutes | <p>We are using the latest Official ODP.NET Managed (Published: 2015-10-14 | Version: 12.1.2400) from Oracle to a Oracle 12 database (non RAC) configuration and we are unable to keep database connections alive for more than typically < 3 minutes. </p>
<p>Our connection string specifies: </p>
<pre><code>MAX POOL SIZE=10;MIN POOL SIZE=5;INCR POOL SIZE=1;
</code></pre>
<p>and we have also tried</p>
<pre><code>CONNECTION LIFETIME=90000;MAX POOL SIZE=10;MIN POOL SIZE=5;INCR POOL SIZE=1;
</code></pre>
<p>When we use PerfMon on the server and watch the counters for HardConnects/HardDisconnects we se that the connection pool closes and reopen 5 connections every 3 minutes and this is not what we expected. </p>
<p>We have this behavior in both a webapp that uses EF6 for DataAccess and an app that has no ORM (just plain old SQL). </p>
<p>According to the <a href="http://docs.oracle.com/html/E10927_01/featConnecting.htm" rel="nofollow" title="Oracle Documentation">Oracle Documentation</a>: </p>
<blockquote>
<p>The connection pooling service closes connections when they are not used; connections are closed every 3 minutes. The Decr Pool Size attribute of the ConnectionString property provides connection pooling service for the maximum number of connections that can be closed every 3 minutes.</p>
</blockquote>
<p>To me - as long as the connection is within the lifetime limit there should be MIN POOL SIZE of valid connection for a much longer duration than 3 minutes in the ConnectionPool. </p>
<p>We have another app that use Devart's Oracle driver and this driver har pooled connections that stays alive for a long time. </p>
<p>Has anyone else seeen this "misbehavior" of the ConnectionPool in ODP.NET Managed Driver and found a solution?
Or could this be a bug in the ConnectionPool of ODP.NET Managed? </p>
<p>UPDATE 2016.01.27:</p>
<p>I have added a demo app on my github account to demonstrate the issue:</p>
<p><a href="https://github.com/jonnybee/OraConnTest" rel="nofollow">https://github.com/jonnybee/OraConnTest</a></p>
<p>This is just a small winforms app where you add the connection string and click the button to start a background worker that runs "SELECT 'OK' FROM DUAL" every 3 seconds.</p>
<p>My connection string contains: POOLING=True;MAX POOL SIZE=10;DECR POOL SIZE=1;CONNECTION LIFETIME=86400;INCR POOL SIZE=1;MIN POOL SIZE=5 + you must add the USER ID, PASSWORD and DATA SOURCE. </p>
<p>Every 3 minutes you will see that 5 existing connections are closed and 5 new connections (MIN POOL SIZE setting) is created. </p>
<p>Run this SQL to see the actual connections:
select sid, logon_time, prev_exec_start, wait_time_micro/1000
from v$session
where program like '%OraWinApp%'
order by logon_time desc </p>
<p>While the program and perfmon is running and you will see this behavior as the old connections gets closed and the new connections with new login_time is created. </p> | 1 |
Gorilla Mux routes not resolving | <p>So, I'm working on a simple RESTful API using Go and Gorilla Mux. I'm having issues with with my second route not working, it's returning a 404 error. I'm not sure what the problem is as I'm new to Go and Gorilla. I'm sure it's something really simple, but I can't seem to find it. I think it might be a problem with the fact that I'm using different custom packages. </p>
<p>This question is similar, <a href="https://stackoverflow.com/questions/28831190/routes-returning-404-for-mux-gorilla">Routes returning 404 for mux gorilla</a>, but the accepted solution didn't fix my problem </p>
<p>Here's what my code looks like:</p>
<p>Router.go:</p>
<pre><code>package router
import (
"github.com/gorilla/mux"
"net/http"
)
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(route.HandlerFunc)
}
return router
}
var routes = Routes{
Route{
"CandidateList",
"GET",
"/candidate",
CandidateList,
},
Route{
"Index",
"GET",
"/",
Index,
},
}
</code></pre>
<p>Handlers.go</p>
<pre><code>package router
import (
"fmt"
"net/http"
)
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Welcome!")
}
func CandidateList(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "CandidateList!")
}
</code></pre>
<p>Main.go</p>
<pre><code>package main
import (
"./router"
"log"
"net/http"
)
func main() {
rout := router.NewRouter()
log.Fatal(http.ListenAndServe(":8080", rout))
}
</code></pre>
<p>Going to just localhost:8080 returns Welcome! but going to localhost:8080/candidate returns a 404 Page Not Found error. I appreciate any input and help! Thanks!</p>
<p>This is an updated version of my Router.go file, there is still the same issue happening.</p>
<p>Router.go</p>
<pre><code>package router
import (
"github.com/gorilla/mux"
"net/http"
)
type Route struct {
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Handler(route.HandlerFunc).GetError()
}
return router
}
var routes = Routes{
Route{
"GET",
"/candidate",
CandidateList,
},
Route{
"GET",
"/",
Index,
},
}
</code></pre> | 1 |
How to create a partition function in javascript. using the following guidelines | <p>I've been trying to create a generic partition function that returns an array of arrays. the function should be made under the following guidelines:<br>
Arguments:</p>
<ol>
<li>An array</li>
<li>A function</li>
</ol>
<p>Objectives:</p>
<ol>
<li><p>Call <function> for each element in <array> passing it the arguments:</p>
<pre class="lang-none prettyprint-override"><code>element, key, <array>
</code></pre></li>
<li><p>Return an array that is made up of 2 sub arrays:</p>
<p> 0. An array that contains all the values for which <function> returned something truthy<br>
1. An array that contains all the values for which <function> returned something falsy</p></li>
</ol>
<p>Here is what I have so far. I get the return of two. I feel like maybe I just have to do the filter function on two separate occasions, but I'm not sure how to put it together. Thoughts and suggestions are highly appreciated.</p>
<pre><code>_.partition = function (collection, test){
var allValues = [];
var matches = [];
var misMatches = [];
_.filter(collection.value, function(value, key, collection){
if (test(value[key], key, collection) === "string"){
matches.push(value[key]);
}else{
misMatches.push(value[key]);
}
});
return allValues.push(matches, misMatches);
}
</code></pre> | 1 |
Toolbar going on top of Appbar - CoordinatorLayout | <p>I've been struggling with the <code>AppBarLayout</code>/<code>Toolbar</code>/<code>CoordinatorView</code>. Want the <code>Toolbar</code> <strong><em>to slide up on scroll,</em></strong> and return immediately on scroll down (like most reading apps, g+ is an example also). However, this is what I'm getting:</p>
<p><strong>Normal:</strong> </p>
<p><a href="https://i.stack.imgur.com/EjntP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/EjntP.png" alt="Normal"></a></p>
<p><strong>A little scroll:</strong></p>
<p><a href="https://i.stack.imgur.com/7lS64.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7lS64.png" alt="A little scroll"></a></p>
<p><strong>Full scroll:</strong></p>
<p><a href="https://i.stack.imgur.com/yE5VO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yE5VO.png" alt="Everything scrolled"></a></p>
<p><strong>This is my code:</strong></p>
<pre><code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="main.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="@+id/id_appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/id_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlwaysCollapsed"
android:title="Hello World"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
</android.support.design.widget.AppBarLayout>
<include layout="@layout/main__activitycontent"/>
</android.support.design.widget.CoordinatorLayout>
</code></pre>
<p><strong><code>main__activitycontent</code>:</strong></p>
<pre><code><android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="main.MainActivity"
tools:showIn="@layout/main__activity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/text_margin"
android:text="@string/large_text"/>
</android.support.v4.widget.NestedScrollView>
</code></pre>
<p>I've been reading a lot of blog posts, but none of their configs seems to work for me. The hide on scroll up/show on scroll down works fine, only the <code>Toolbar</code> is moving over the appbar. Checking the Android View Hierarchy I see that they the <code>Toolbar</code> is above the dark blue appbar, and they move up together.</p>
<p><strong>EDIT 1</strong></p>
<p>Removing the <code>fitsSytemWindows=true</code> from the <code>CoordinatorLayout</code> leads to the expected behavior, but the appbar becomes white, no matter the bg color for the <code>CoordinatorLayout</code>: </p>
<p><a href="https://i.stack.imgur.com/CIJuQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CIJuQ.png" alt="enter image description here"></a></p>
<p>My guess is that the behavior actually didn't change, what happend is that it doesn't cover the appbar anymore, so the toolbar doesn't go over it.</p>
<p><strong>EDIT 2</strong></p>
<pre><code><resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light"/>
</resources>
</code></pre>
<p><strong>EDIT 3</strong></p>
<pre><code>package main;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.ee.oef.refactor.R;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main__activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.main__toolbar);
setSupportActionBar(toolbar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main__menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
</code></pre> | 1 |
when object goes out of scope in c #? | <p>Method where scopes defined explicitly. </p>
<pre><code>static void Main(string[] args)
{
Class1 c1 = new Class1(1);
{
Class1 c2 = new Class1(2);
{
Class1 c3 = new Class1(3);
}
//this is not collecting object c3 which is out of scope here
GC.Collect();
}
//this is not collecting object c2 which is out of scope here
GC.Collect();
Console.ReadKey();
}
</code></pre>
<p>Class1 definition:</p>
<pre><code>class Class1
{
int x;
public Class1(int a)
{
x = a;
}
~Class1()
{
Console.WriteLine(x + "object destroy");
}
}
</code></pre>
<p>I write this code. But GC.Collect() method don't collect the object which goes out of scope.</p> | 1 |
How do I get a button to position on the bottom of a view controller in Xcode 7.2? | <p>I used to be able to do this: </p>
<pre><code>UIButton *bigBottomBtn=[[UIButton alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height-60, self.view.frame.size.width, 60)];
</code></pre>
<p>I also used to be able to just drag a button onto a storyboard and add a constraint that would hold it to the bottom of the parent.</p>
<p><a href="https://i.stack.imgur.com/cKRKp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cKRKp.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/gFSPw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gFSPw.png" alt="enter image description here"></a></p>
<p>What is going on with Xcode, Autolayout and Apple for that matter....is my Xcode not working properly? Have I missed a major memo? is Apple just going downhill fast?</p> | 1 |
Reversing a string in c++ | <p>I started doing the C++ challenges on coderbyte. The first one is: </p>
<blockquote>
<p>Using the C++ language, have the function FirstReverse(str) take the
str parameter being passed and return the string in reversed order. </p>
<p>Use the Parameter Testing feature in the box below to test your code
with different arguments.</p>
</blockquote>
<p>It gives u the follow starting code, which you then edit and add to to create the program:</p>
<pre><code>#include <iostream>
using namespace std;
string FirstReverse(string str) {
// code goes here
return str;
}
int main() {
// keep this function call here
cout << FirstReverse(gets(stdin));
return 0;
}
</code></pre>
<p>I have come up with the following: </p>
<pre><code>#include <iostream>
using namespace std;
string FirstReverse(string str) {
cout<<"Enter some text: ";
cin>>str;
string reverseString;
for(long i = str.size() - 1;i >= 0; --i){
reverseString += str[i];
}
return reverseString;
}
int main() {
// keep this function call here
cout << FirstReverse(gets(stdin))<<endl;
return 0;
}
</code></pre>
<p>It gives me the following error: "No matching function to call to gets"
Now, why does this happen and what can I do to fix it? Thank you for reading this and all help would be appreciated.</p> | 1 |
Reading a part of PDF file in c# | <p>I have many large size PDF files that I need to only read a part of them. I want to start reading the PDF file and write it to another file like a txt file, or any other type of files.
However, I want to make a limitation on the size of the file that I am writing in. When the size of txt file is about 15 MB, I should stop reading the PDF document and then I keep the created txt file for my purpose.
Does anyone can help me how can I do this in C#?</p>
<p>Thanks for your help in advance.</p>
<p>Here is the code that I use for reading the whole file; (image content is not important for me)</p>
<pre><code>using (StreamReader sr = new StreamReader(@"F:\1.pdf"))
{
using (StreamWriter sw = new StreamWriter(@"F:\test.txt"))
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
sw.WriteLine(line);
sw.Flush();
}
}
}
</code></pre> | 1 |
WScript.Run Command is not working for me | <p>I am attaching WSCript code below just to execute simple run command but it is showing error</p>
<pre><code>Set oShell = WScript.CreateObject ("WScript.Shell")
oShell.run "cmd /K CD C:\ & Dir"
</code></pre>
<blockquote>
<p>Error: oShell.run is not recognized as a internal or external command.</p>
</blockquote>
<p>Please help me knowing what wrong I did.</p> | 1 |
JsonConverter how to deserialize to generic object | <p>I'm sending this structure through webapi:</p>
<pre><code>[DataContract]
public class PacketData
{
public enum Opcodes
{
Hello = 0x00,
Close = 0x01,
Serial = 0x02,
GPIO = 0x04
}
[DataMember]
public object Data { get; private set; }
[DataMember]
public Opcodes Opcode { get; private set; }
public PacketData(Opcodes opcode, object data)
{
Data = data;
Opcode = opcode;
}
}
</code></pre>
<p>And my problem is that I set on server side when I sending it I assign to Data few class ex. CustomClass1, CustomClass2</p>
<p>Now on deserialize I get instead of object string which is:</p>
<pre><code>{\r\n \"Cmd\": 5,\r\n \"BaudRates\": [\r\n 2400,\r\n 4800,\r\n 9600,\r\n 19200,\r\n 38400,\r\n 57600,\r\n 115200\r\n ],\r\n \"SerialPorts\": null,\r\n \"IsOpen\": false,\r\n \"BaudRate\": 0,\r\n \"PortName\": null,\r\n \"WriteCMD\": null,\r\n \"WriteDATA\": null,\r\n \"Read\": null\r\n}
</code></pre>
<p>So Data is string instead of class or C# classic object type
And there is problem I don't know how to recognize from string if its CustomClass1 or CustomClass2.</p>
<p>Any ideas how to resolve this?</p>
<p>Thanks.</p>
<p>EDIT: Including deserialize and serialize</p>
<pre><code>[HttpGet("Send", Name = "Send")]
public IActionResult Send()
{
return Ok(WebAPI.Send(), HttpStatusCode.OK);
}
public IEnumerable<string> Send()
{
List<string> packets = new List<string>();
foreach (PacketData packet in StaticConfig.SendStack.ToArray())
packets.Add(JsonConvert.SerializeObject(packet));
return packets.ToArray();
}
</code></pre>
<p>And this is deserialize:</p>
<pre><code> string json = await client.GetStringAsync(new Uri("http://localhost:5000/api/Send"));
string[] jsonArray = JsonConvert.DeserializeObject<string[]>(json);
if (jsonArray.Length == 0)
Task.Delay(100).Wait();
List<PacketData> packets = new List<PacketData>();
foreach (string j in jsonArray)
packets.Add(JsonConvert.DeserializeObject<PacketData>(j));
foreach (PacketData packet in packets)
{
string p = packet.Data.ToString();
bool a = packet.Data is PacketSerialModel; // returns false
HandleReceivedData(this, new ReceivedDataArgs(packet));
}
</code></pre>
<p>EDIT 2:
So what do I want?</p>
<p>I would like to get back mentioned string into PacketData.Data then I can use something like this:</p>
<pre><code>if(packet.Data is CustomClass1)
{
}
else if(packet.Data is CustomClass2)
{
var b = packetData as CustomClass2;
//...
}
</code></pre>
<p>currently my packet.Data is string and I need to create on this object properties and set values to them based on json.</p>
<p>EDIT3:
using now </p>
<pre><code>JsonSerializerSettings()
{ TypeNameHandling = TypeNameHandling.Auto }
</code></pre>
<p>Works perfectly, but I have to replace in incoming json string project name
like in following string:</p>
<pre><code>["{\"Data\":{\"$type\":\"Shared.PacketSerialModel, ASP_MVC\",\"Cmd\":5,\"BaudRates\":[2400,4800,9600,19200,38400,57600,115200],\"SerialPorts\":null,\"IsOpen\":false,\"BaudRate\":0,\"PortName\":null,\"WriteCMD\":null,\"WriteDATA\":null,\"Read\":null},\"Opcode\":2}"]
</code></pre>
<p>I have to replace ASP_MVC to second project name, any workaround than replace?</p> | 1 |
canvas toDataURL() returns transparent image | <p>I am attempting to use a chrome extension to take a screenshot of the current page, and then draw some shapes on it. After I have done that to the image, I turn the whole thing into a canvas that way it is all together, like the divs I have drawn on it are now baked into the 'image', and they are one in the same. After doing this, I want to turn the canvas back into a png image I can use to push to a service I have, but when I go to use the <code>canvas.toDataURL()</code> in order to do so, the image source that it creates is completely transparent. If I do it as a jpeg, it is completely black. </p>
<p>I read something about the canvas being 'dirtied' because I have drawn an image to it, and that this won't work in Chrome, but that doesn't make sense to me as I have gotten it to work before, but I am unable to use my previous method. Below is the code snippet that isn't working. I am just making a canvas element, and then I am drawing an image before that.</p>
<pre><code>var passes = rectangles.length;
var run = 0;
var context = hiDefCanvas.getContext('2d');
while (run < passes) {
var rect = rectangles[run];
// Set the stroke and fill color
context.strokeStyle = 'rgba(0,255,130,0.7)';
context.fillStyle = 'rgba(0,0,255,0.1)';
context.rect(rect.left, rect.top, rect.width, rect.height);
context.setLineDash([2,1]);
context.lineWidth = 2;
run++;
} // end of the while loop
screencapImage.className = 'hide';
context.fill();
context.stroke();
console.log(hiDefCanvas.toDataURL());
</code></pre>
<p>And the image data that it returns is: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACWAAAAVGCAYAAAAaGIAxAAAgAElEQ…ECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAQBVKBUe32pNYAAAAAElFTkSuQmCC which is a blank, transparent image.</p>
<p>Is there something special I need to do with Chrome? Is there something that I am missing? Thanks, I appreciate the time and help.</p> | 1 |
How to create Progress Bar like Image in Android | <p>How to create below Image type of Progress ring in my Android app. I Want to show it 10 second before my whole app is loading on device. and also I want to rotate it. like window device rotate. Any Help be appreciated. I am new to Andorid.</p>
<p>Image :</p>
<p><a href="https://i.stack.imgur.com/fRawL.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fRawL.gif" alt="enter image description here"></a></p> | 1 |
How to delete a key with lodash _.map | <p>I have a lodash map function that sometimes has an empty value in the important property of a given key, and in this case I'd like to remove that key from the result entirely. How do I do that?</p>
<p>Tried just <code>if (_.isEmpty(key.thing)) { delete key }</code> but this didn't work - it actually broke the app.</p> | 1 |
Hide Swift "Will never be executed" warning | <p>I've got some code that is generating warnings like so:</p>
<blockquote>
<p><em>code path</em>.swift:9:13: warning: will never be executed</p>
<pre><code> fatalError()
^
</code></pre>
<p><em>code path</em>.swift:9:13: note: a call to a noreturn function</p>
<pre><code> fatalError()
^
</code></pre>
</blockquote>
<p>The compiler output doesn't give any <code>-W</code> arguments I can use to silence these in my source file. How can I stop these warnings?</p>
<p>Please note this is testing code and everything is working as designed - <strong>removing the lines complained about is not a solution</strong></p> | 1 |
Constant timeouts in Cassandra after adding second node | <p>I'm trying to migrate a moderately large swath of data (~41 million rows) from an SQL database to Cassandra. I've previously done a trial-run using half the dataset, and everything worked exactly as expected.</p>
<p>The problem is, now that I'm trying the complete migration Cassandra is throwing constant timeout errors. For instance:</p>
<pre><code>[INFO] [talledLocalContainer] com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: /127.0.0.1:10112 (com.datastax.driver.core.exceptions.DriverException: Timed out waiting for server response))
[INFO] [talledLocalContainer] at com.datastax.driver.core.exceptions.NoHostAvailableException.copy(NoHostAvailableException.java:84)
[INFO] [talledLocalContainer] at com.datastax.driver.core.DefaultResultSetFuture.extractCauseFromExecutionException(DefaultResultSetFuture.java:289)
[INFO] [talledLocalContainer] at com.datastax.driver.core.DefaultResultSetFuture.getUninterruptibly(DefaultResultSetFuture.java:205)
[INFO] [talledLocalContainer] at com.datastax.driver.core.AbstractSession.execute(AbstractSession.java:52)
[INFO] [talledLocalContainer] at com.mycompany.tasks.CassandraMigrationTask.execute(CassandraMigrationTask.java:164)
[INFO] [talledLocalContainer] at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
[INFO] [talledLocalContainer] at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)
[INFO] [talledLocalContainer] Caused by: com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: /127.0.0.1:10112 (com.datastax.driver.core.exceptions.DriverException: Timed out waiting for server response))
[INFO] [talledLocalContainer] at com.datastax.driver.core.RequestHandler.sendRequest(RequestHandler.java:108)
[INFO] [talledLocalContainer] at com.datastax.driver.core.RequestHandler$1.run(RequestHandler.java:179)
[INFO] [talledLocalContainer] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
[INFO] [talledLocalContainer] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
[INFO] [talledLocalContainer] at java.lang.Thread.run(Thread.java:745)
</code></pre>
<p>I've tried increasing the timeout values in <code>cassandra.yaml</code>, and that increased the amount of time that the migration was able to run before dying to a timeout (roughly in proportion to the increase in the timeout). </p>
<p>Prior to changing the timeout settings, my stack-trace looked more like:</p>
<pre><code>[INFO] [talledLocalContainer] com.datastax.driver.core.exceptions.WriteTimeoutException: Cassandra timeout during write query at consistency ONE (1 replica were required but only 0 acknowledged the write)
[INFO] [talledLocalContainer] at com.datastax.driver.core.exceptions.WriteTimeoutException.copy(WriteTimeoutException.java:54)
[INFO] [talledLocalContainer] at com.datastax.driver.core.DefaultResultSetFuture.extractCauseFromExecutionException(DefaultResultSetFuture.java:289)
[INFO] [talledLocalContainer] at com.datastax.driver.core.DefaultResultSetFuture.getUninterruptibly(DefaultResultSetFuture.java:205)
[INFO] [talledLocalContainer] at com.datastax.driver.core.AbstractSession.execute(AbstractSession.java:52)
[INFO] [talledLocalContainer] at com.mycompany.tasks.CassandraMigrationTask.execute(CassandraMigrationTask.java:164)
[INFO] [talledLocalContainer] at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
[INFO] [talledLocalContainer] at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)
[INFO] [talledLocalContainer] Caused by: com.datastax.driver.core.exceptions.WriteTimeoutException: Cassandra timeout during write query at consistency ONE (1 replica were required but only 0 acknowledged the write)
[INFO] [talledLocalContainer] at com.datastax.driver.core.exceptions.WriteTimeoutException.copy(WriteTimeoutException.java:54)
[INFO] [talledLocalContainer] at com.datastax.driver.core.Responses$Error.asException(Responses.java:99)
[INFO] [talledLocalContainer] at com.datastax.driver.core.DefaultResultSetFuture.onSet(DefaultResultSetFuture.java:140)
[INFO] [talledLocalContainer] at com.datastax.driver.core.RequestHandler.setFinalResult(RequestHandler.java:249)
[INFO] [talledLocalContainer] at com.datastax.driver.core.RequestHandler.onSet(RequestHandler.java:433)
[INFO] [talledLocalContainer] at com.datastax.driver.core.Connection$Dispatcher.messageReceived(Connection.java:697)
[INFO] [talledLocalContainer] at com.datastax.shaded.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:70)
[INFO] [talledLocalContainer] at com.datastax.shaded.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564)
[INFO] [talledLocalContainer] at com.datastax.shaded.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791)
[INFO] [talledLocalContainer] at com.datastax.shaded.netty.channel.Channels.fireMessageReceived(Channels.java:296)
[INFO] [talledLocalContainer] at com.datastax.shaded.netty.handler.codec.oneone.OneToOneDecoder.handleUpstream(OneToOneDecoder.java:70)
</code></pre>
<p>My timeout settings are currently:</p>
<pre><code># How long the coordinator should wait for read operations to complete
read_request_timeout_in_ms: 30000
# How long the coordinator should wait for seq or index scans to complete
range_request_timeout_in_ms: 30000
# How long the coordinator should wait for writes to complete
write_request_timeout_in_ms: 30000
# How long the coordinator should wait for counter writes to complete
counter_write_request_timeout_in_ms: 30000
# How long a coordinator should continue to retry a CAS operation
# that contends with other proposals for the same row
cas_contention_timeout_in_ms: 1000
# How long the coordinator should wait for truncates to complete
# (This can be much longer, because unless auto_snapshot is disabled
# we need to flush first so we can snapshot before removing the data.)
truncate_request_timeout_in_ms: 60000
# The default timeout for other, miscellaneous operations
request_timeout_in_ms: 20000
</code></pre>
<p>...which gets me about 1.5m rows inserted before the timeout happens. The original timeout settings were:</p>
<pre><code># How long the coordinator should wait for read operations to complete
read_request_timeout_in_ms: 5000
# How long the coordinator should wait for seq or index scans to complete
range_request_timeout_in_ms: 10000
# How long the coordinator should wait for writes to complete
write_request_timeout_in_ms: 2000
# How long the coordinator should wait for counter writes to complete
counter_write_request_timeout_in_ms: 5000
# How long a coordinator should continue to retry a CAS operation
# that contends with other proposals for the same row
cas_contention_timeout_in_ms: 1000
# How long the coordinator should wait for truncates to complete
# (This can be much longer, because unless auto_snapshot is disabled
# we need to flush first so we can snapshot before removing the data.)
truncate_request_timeout_in_ms: 60000
# The default timeout for other, miscellaneous operations
request_timeout_in_ms: 10000
</code></pre>
<p>...which caused the timeouts to happen approximately every 300,000 rows. </p>
<p>The only significant change that's occurred between when I had my successful run and now is that I added a second node to the Cassandra deployment. So intuitively I'd think the issue would have something to do with the propagation of data from the first node to the second (as in, there's <code><some process></code> that scales linearly with the amount of data inserted and which isn't used when there's only a single node). But I'm not seeing any obvious options that might be useful for configuring/mitigating this. </p>
<p>If it's relevant, I'm using batch statements during the migration, typically with between 100 and 200 statements/rows per batch, at most. </p>
<p>My keyspace was originally set up <code>WITH REPLICATION =
{ 'class' : 'SimpleStrategy', 'replication_factor' : 2 }</code>, but I altered it to be <code>WITH REPLICATION =
{ 'class' : 'SimpleStrategy', 'replication_factor' : 1 }</code> to see if that would make any difference. It didn't. </p>
<p>I also tried explicitly setting <code>ConsistencyLevel.ANY</code> on all my insert statements (and also the enclosing batch statements). That also made no difference. </p>
<p>There doesn't seem to be anything interesting in Cassandra's log on either node, although the first node is certainly showing more 'ops' than the second:</p>
<p><strong>First node - 454317 ops</strong></p>
<pre><code>INFO [SlabPoolCleaner] 2016-01-25 19:46:08,806 ColumnFamilyStore.java:905 - Enqueuing flush of assetproperties_flat: 148265302 (14%) on-heap, 0 (0%) off-heap
INFO [MemtableFlushWriter:15] 2016-01-25 19:46:08,807 Memtable.java:347 - Writing Memtable-assetproperties_flat@350387072(20.557MiB serialized bytes, 454317 ops, 14%/0% of on/off-heap limit)
INFO [MemtableFlushWriter:15] 2016-01-25 19:46:09,393 Memtable.java:382 - Completed flushing /var/cassandra/data/itb/assetproperties_flat-e83359a0c34411e593abdda945619e28/itb-assetproperties_flat-tmp-ka-32-Data.db (5.249MiB) for commitlog position ReplayPosition(segmentId=1453767930194, position=15188257)
</code></pre>
<p><strong>Second node - 2020 ops</strong></p>
<pre><code>INFO [BatchlogTasks:1] 2016-01-25 19:46:33,961 ColumnFamilyStore.java:905 - Enqueuing flush of batchlog: 4923957 (0%) on-heap, 0 (0%) off-heap
INFO [MemtableFlushWriter:22] 2016-01-25 19:46:33,962 Memtable.java:347 - Writing Memtable-batchlog@796821497(4.453MiB serialized bytes, 2020 ops, 0%/0% of on/off-heap limit)
INFO [MemtableFlushWriter:22] 2016-01-25 19:46:33,963 Memtable.java:393 - Completed flushing /var/cassandra/data/system/batchlog-0290003c977e397cac3efdfdc01d626b/system-batchlog-tmp-ka-11-Data.db; nothing needed to be retained. Commitlog position was ReplayPosition(segmentId=1453767955411, position=18567563)
</code></pre>
<p>Has anyone encountered a similar issue, and if so, what was the fix? </p>
<p>Would it be advisable to just take the second node offline, run the migration with just the first node, and then run <code>nodetool repair</code> afterwards to get the second node back in sync? </p>
<p><strong>Edit</strong></p>
<p>Answers to questions from comments:</p>
<ol>
<li><p>I'm using the datastax Java driver, and have a server-side task (<a href="http://quartz-scheduler.org/api/2.2.0/" rel="noreferrer">Quartz job</a>) that uses the ORM layer (hibernate) to lookup the next chunk of data to migrate, write it into Cassandra, and then purge it from the SQL database. I'm getting a connection to Cassandra using the following code:</p>
<pre><code>public static Session getCassandraSession(String keyspace) {
Session session = clusterSessions.get(keyspace);
if (session != null && ! session.isClosed()) {
//can use the cached session
return session;
}
//create a new session for the specified keyspace
Cluster cassandraCluster = getCluster();
session = cassandraCluster.connect(keyspace);
//cache and return the session
clusterSessions.put(keyspace, session);
return session;
}
private static Cluster getCluster() {
if (cluster != null && ! cluster.isClosed()) {
//can use the cached cluster
return cluster;
}
//configure socket options
SocketOptions options = new SocketOptions();
options.setConnectTimeoutMillis(30000);
options.setReadTimeoutMillis(300000);
options.setTcpNoDelay(true);
//spin up a fresh connection
cluster = Cluster.builder().addContactPoint(Configuration.getCassandraHost()).withPort(Configuration.getCassandraPort())
.withCredentials(Configuration.getCassandraUser(), Configuration.getCassandraPass()).withSocketOptions(options).build();
//log the cluster details for confirmation
Metadata metadata = cluster.getMetadata();
LOG.debug("Connected to Cassandra cluster: " + metadata.getClusterName());
for ( Host host : metadata.getAllHosts() ) {
LOG.debug("Datacenter: " + host.getDatacenter() + "; Host: " + host.getAddress() + "; Rack: " + host.getRack());
}
return cluster;
}
</code></pre>
<p>The part with the <code>SocketOptions</code> is a recent addition, as the latest timeout error sounded like it was coming from the Java/client side rather than from within Cassandra itself.</p></li>
<li><p>Each batch inserts no more than 200 records. Typical values are closer to 100.</p></li>
<li><p>Both nodes have the same specs: </p>
<ul>
<li>Intel(R) Xeon(R) CPU E3-1230 V2 @ 3.30GHz</li>
<li>32GB RAM</li>
<li>256GB SSD (primary), 2TB HDD (backups), both in RAID-1 configurations</li>
</ul></li>
<li><p><strong>First node:</strong></p>
<pre><code>Pool Name Active Pending Completed Blocked All time blocked
CounterMutationStage 0 0 0 0 0
ReadStage 0 0 58155 0 0
RequestResponseStage 0 0 655104 0 0
MutationStage 0 0 259151 0 0
ReadRepairStage 0 0 0 0 0
GossipStage 0 0 58041 0 0
CacheCleanupExecutor 0 0 0 0 0
AntiEntropyStage 0 0 0 0 0
MigrationStage 0 0 0 0 0
Sampler 0 0 0 0 0
ValidationExecutor 0 0 0 0 0
CommitLogArchiver 0 0 0 0 0
MiscStage 0 0 0 0 0
MemtableFlushWriter 0 0 80 0 0
MemtableReclaimMemory 0 0 80 0 0
PendingRangeCalculator 0 0 3 0 0
MemtablePostFlush 0 0 418 0 0
CompactionExecutor 0 0 8979 0 0
InternalResponseStage 0 0 0 0 0
HintedHandoff 0 0 2 0 0
Native-Transport-Requests 1 0 1175338 0 0
Message type Dropped
RANGE_SLICE 0
READ_REPAIR 0
PAGED_RANGE 0
BINARY 0
READ 0
MUTATION 0
_TRACE 0
REQUEST_RESPONSE 0
COUNTER_MUTATION 0
</code></pre>
<p><strong>Second node:</strong></p>
<pre><code>Pool Name Active Pending Completed Blocked All time blocked
CounterMutationStage 0 0 0 0 0
ReadStage 0 0 55803 0 0
RequestResponseStage 0 0 1 0 0
MutationStage 0 0 733828 0 0
ReadRepairStage 0 0 0 0 0
GossipStage 0 0 56623 0 0
CacheCleanupExecutor 0 0 0 0 0
AntiEntropyStage 0 0 0 0 0
MigrationStage 0 0 0 0 0
Sampler 0 0 0 0 0
ValidationExecutor 0 0 0 0 0
CommitLogArchiver 0 0 0 0 0
MiscStage 0 0 0 0 0
MemtableFlushWriter 0 0 394 0 0
MemtableReclaimMemory 0 0 394 0 0
PendingRangeCalculator 0 0 2 0 0
MemtablePostFlush 0 0 428 0 0
CompactionExecutor 0 0 8883 0 0
InternalResponseStage 0 0 0 0 0
HintedHandoff 0 0 1 0 0
Native-Transport-Requests 0 0 70 0 0
Message type Dropped
RANGE_SLICE 0
READ_REPAIR 0
PAGED_RANGE 0
BINARY 0
READ 0
MUTATION 0
_TRACE 0
REQUEST_RESPONSE 0
COUNTER_MUTATION 0
</code></pre></li>
<li><p>The output of <code>nodetool ring</code> was very long. Here's a <code>nodetool status</code> instead:</p>
<pre><code>Datacenter: DC1
===============
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
-- Address Load Tokens Owns Host ID Rack
UN 204.11.xxx.1 754.66 MB 1024 ? 8cf373d8-0b3e-4fd3-9e63-fdcdd8ce8cd4 RAC1
UN 208.66.xxx.2 767.78 MB 1024 ? 42e1f336-84cb-4260-84df-92566961a220 RAC2
</code></pre></li>
<li><p>I increased all of Cassandra's timeout values by a factor of 10, and also set the Java driver's read timeout settings to match, and now I'm up to <s>8m</s> 29.4m inserts with no issues. In theory if the issue scales linearly with the timeout values I should be good up until around 15m inserts (which is at least good enough that I don't need to constantly babysit the migration process waiting for each new error).</p></li>
</ol> | 1 |
Swift 2.1 do-try-catch not catching error | <p>Here's my Swift 2.1 code snippet. The error that's occurring is shown in the comments at the point where the error appears.</p>
<p>The error shows up in the debugging panel, and the app crashes. The app never prints the line in the catch, nor does it gracefully return as expected.</p>
<pre><code>let audioFileURL = receivedAudio.filePathURL
guard let audioFile = try? AVAudioFile(forReading: audioFileURL) else {
print("file setup failed")
return
}
let audioFileFrameCount = AVAudioFrameCount(audioFile.length)
audioFileBuffer = AVAudioPCMBuffer(PCMFormat: audioFile.fileFormat, frameCapacity: audioFileFrameCount)
do {
// ERROR: AVAudioFile.mm:263: -[AVAudioFile readIntoBuffer:frameCount:error:]: error -50
// Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'error -50'
// -50 = Core Audio: bad param
try audioFile.readIntoBuffer(audioFileBuffer)
}
catch {
print("unable to load sound file into buffer")
return
}
</code></pre>
<p>From everything I've seen, my do/try/catch format should be correct.</p>
<p><code>audioFile.readIntoBuffer</code> returns <code>void</code> and has the keyword <code>throws</code>.</p>
<p>Yet, the catch is never executed.</p>
<p>What am I missing?</p>
<p><strong>UPDATE: <a href="https://developer.apple.com/library/prerelease/ios/documentation/AVFoundation/Reference/AVAudioFile_Class/index.html#//apple_ref/occ/instm/AVAudioFile/initForReading:error:" rel="nofollow noreferrer">From Apple's documentation on AVAudioFile</a></strong></p>
<p>For:</p>
<pre><code>func readIntoBuffer(_ buffer: AVAudioPCMBuffer) throws
</code></pre>
<p>Under <strong>Discussion:</strong></p>
<blockquote>
<p>HANDLING ERRORS IN SWIFT:</p>
<p>In Swift, this API is imported as an initializer and is marked with the throws keyword to indicate that it throws an error in cases of failure.</p>
<p>You call this method in a try expression and handle any errors in the catch clauses of a do statement, as described in Error Handling in The Swift Programming Language (Swift 2.1) and Error Handling in Using Swift with Cocoa and Objective-C (Swift 2.1).</p>
</blockquote>
<p><strong>From <a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html" rel="nofollow noreferrer">The Swift Programming Language (Swift 2.1): Error Handline</a></strong></p>
<blockquote>
<p>NOTE</p>
<p>Error handling in Swift resembles exception handling in other languages, with the use of the try, catch and throw keywords. Unlike exception handling in many languages—including Objective-C—error handling in Swift does not involve unwinding the call stack, a process that can be computationally expensive. As such, the performance characteristics of a throw statement are comparable to those of a return statement.</p>
</blockquote>
<p><strong>And, finally, from the same document:</strong></p>
<blockquote>
<p>Handling Errors Using Do-Catch</p>
<p>You use a do-catch statement to handle errors by running a block of code. If an error is thrown by the code in the do clause, it is matched against the catch clauses to determine which one of them can handle the error.</p>
</blockquote>
<p><strong>I don't have to write and throw my own errors/exceptions for them to be caught. I should be able to catch Swift's exceptions as well.</strong></p> | 1 |
Trouble connecting to SQL when publishing application to remote server | <p>The application loads, but when the application tries to make the connection to SQL it takes a while to load then returns an error. When testing the connection properties using a DataLink (.udl file) it is successful. The application also runs fine on my local machine. I have searched everywhere and the settings are good, the network admin verified the firewalls and everything is set up correct. What am I missing?</p>
<p>I notice it mentions Name Pipes in the error, however, shouldn't this make it TCP?</p>
<pre><code>SQLConnectionString.NetworkLibrary = "dbmssocn";
</code></pre>
<p>This is my method for the connection string:</p>
<pre><code>public string GetReachoutConnectionString()
{
SqlConnectionStringBuilder SQLConnectionString = new SqlConnectionStringBuilder();
SQLConnectionString.TypeSystemVersion = "Latest";
SQLConnectionString.NetworkLibrary = "dbmssocn";
SQLConnectionString.DataSource = "10.10.xxx.xx,1433";
SQLConnectionString.InitialCatalog = "cat";
SQLConnectionString.UserID = "xxx";
SQLConnectionString.Password = "xxx";
SQLConnectionString.MultipleActiveResultSets = true;
SQLConnectionString.ApplicationName = "Website";
return SQLConnectionString.ConnectionString;
}
</code></pre>
<p>This is the error I am getting: </p>
<blockquote>
<p>[Win32Exception (0x80004005): The
network path was not found]</p>
<p>[SqlException (0x80131904): A network-related or instance-specific
error occurred while establishing a connection to SQL Server. The
server was not found or was not accessible. Verify that the instance
name is correct and that SQL Server is configured to allow remote
connections. (provider: Named Pipes Provider, error: 40 - Could not
open a connection to SQL Server)]</p>
<p>System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity
identity, SqlConnectionString connectionOptions, SqlCredential
credential, Object providerInfo, String newPassword, SecureString
newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString
userConnectionOptions, SessionData reconnectSessionData,
DbConnectionPool pool, String accessToken, Boolean
applyTransientFaultHandling) +1394<br>
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions
options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo,
DbConnectionPool pool, DbConnection owningConnection,
DbConnectionOptions userOptions) +1120<br>
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool
pool, DbConnection owningObject, DbConnectionOptions options,
DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +70<br>
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection
owningObject, DbConnectionOptions userOptions, DbConnectionInternal
oldConnection) +964<br>
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection
owningObject, DbConnectionOptions userOptions, DbConnectionInternal
oldConnection) +114<br>
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean
allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions
userOptions, DbConnectionInternal& connection) +1631<br>
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection
owningObject, TaskCompletionSource<code>1 retry, DbConnectionOptions
userOptions, DbConnectionInternal& connection) +117<br>
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection
owningConnection, TaskCompletionSource</code>1 retry, DbConnectionOptions
userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&
connection) +267<br>
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection
outerConnection, DbConnectionFactory connectionFactory,
TaskCompletionSource<code>1 retry, DbConnectionOptions userOptions) +318<br>
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource</code>1
retry) +211<br>
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1
retry) +393 System.Data.SqlClient.SqlConnection.Open() +122<br>
System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset,
DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String
srcTable, IDbCommand command, CommandBehavior behavior) +177<br>
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32
startRecord, Int32 maxRecords, String srcTable, IDbCommand command,
CommandBehavior behavior) +182<br>
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String
srcTable) +123<br>
System.Web.UI.WebControls.SqlDataSourceView.ExecuteSelect(DataSourceSelectArguments
arguments) +2964<br>
System.Web.UI.WebControls.ListControl.OnDataBinding(EventArgs e) +369
System.Web.UI.WebControls.ListControl.PerformSelect() +43<br>
System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +139
System.Web.UI.WebControls.ListControl.OnPreRender(EventArgs e) +36<br>
System.Web.UI.Control.PreRenderRecursiveInternal() +107<br>
System.Web.UI.Control.PreRenderRecursiveInternal() +204<br>
System.Web.UI.Control.PreRenderRecursiveInternal() +204<br>
System.Web.UI.Control.PreRenderRecursiveInternal() +204<br>
System.Web.UI.Control.PreRenderRecursiveInternal() +204<br>
System.Web.UI.Control.PreRenderRecursiveInternal() +204<br>
System.Web.UI.d__249.MoveNext() +1400
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) +13847892<br>
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) +61<br>
System.Web.Util.WithinCancellableCallbackTaskAwaiter.GetResult() +32<br>
System.Web.UI.d__523.MoveNext() +9283</p>
</blockquote> | 1 |
how to hide app's icon correctly? | <p>similar questions have been asked earlier, but the requirement was to hide the app's icon from drawer completely, by removing these two lines-</p>
<pre><code> <intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</code></pre>
<p>However, my case is a bit complicated. i want to hide my app in the drawer and launch it from other apps. if i remove those two lines, i wont be able to launch my app. for example launching a module from xposed framework</p> | 1 |
Telegram-bot (telepot api): Is it possible to send an image directly from URL without saving it | <p>Im writing a telegram bot using the python <a href="https://github.com/nickoala/telepot" rel="nofollow noreferrer">telepot api</a>. I'm now stuck at the point where I want to send a picture which directly comes from an URL without storing it locally. <a href="https://github.com/nickoala/telepot#send-files" rel="nofollow noreferrer">Telepot</a> provides the following instruction to send a photo:</p>
<pre><code>>>> f = open('zzzzzzzz.jpg', 'rb') # some file on local disk
>>> response = bot.sendPhoto(chat_id, f)
</code></pre>
<p>Now im using</p>
<pre><code>f = urllib2.urlopen('http://i.imgur.com/B1fzGoh.jpg')
bot.sendPhoto(chat_id, f)
</code></pre>
<p>The problem here is that <code>urllib2.urlopen('url')</code> provide me file-like object like:</p>
<p><code><addinfourl at 140379102313792 whose fp = <socket._fileobject object at 0x7fac8e86d750>></code> </p>
<p>and not like <code>open('myFile.jpg', 'rb')</code> a file object like: </p>
<p><code><open file 'app-root/runtime/repo/myImage.jpg', mode 'rb' at 0x7fac8f322540></code></p>
<p>If I send the file-like object in sendPhoto() I get the following error:
Traceback (most recent call last):</p>
<pre><code>[Wed Feb 10 06:21:09 2016] [error] File "/var/lib/openshift/56b8e2787628e1484a00013e/python/virtenv/lib/python2.7/site-packages/telepot/__init__.py", line 340, in handle
[Wed Feb 10 06:21:09 2016] [error] callback(update['message'])
[Wed Feb 10 06:21:09 2016] [error] File "/var/lib/openshift/56b8e2787628e1484a00013e/app-root/runtime/repo/moviequiz_main.py", line 35, in handle
[Wed Feb 10 06:21:09 2016] [error] response = bot.sendPhoto(chat_id, gif)
[Wed Feb 10 06:21:09 2016] [error] File "/var/lib/openshift/56b8e2787628e1484a00013e/python/virtenv/lib/python2.7/site-packages/telepot/__init__.py", line 230, in sendPhoto
[Wed Feb 10 06:21:09 2016] [error] return self._sendFile(photo, 'photo', p)
[Wed Feb 10 06:21:09 2016] [error] File "/var/lib/openshift/56b8e2787628e1484a00013e/python/virtenv/lib/python2.7/site-packages/telepot/__init__.py", line 226, in _sendFile
[Wed Feb 10 06:21:09 2016] [error] return self._parse(r)
[Wed Feb 10 06:21:09 2016] [error] File "/var/lib/openshift/56b8e2787628e1484a00013e/python/virtenv/lib/python2.7/site-packages/telepot/__init__.py", line 172, in _parse
[Wed Feb 10 06:21:09 2016] [error] raise BadHTTPResponse(response.status_code, response.text)
[Wed Feb 10 06:21:09 2016] [error] BadHTTPResponse: (414, u'<html>\\r\\n<head><title>414 Request-URI Too Large</title></head>\\r\\n<body bgcolor="white">\\r\\n<center><h1>414 Request-URI Too Large</h1></center>\\r\\n<hr><center>nginx/1.9.1</center>\\r\\n</body>\\r\\n</html>\\r\\n')
</code></pre>
<p>There is a solution for a <a href="https://stackoverflow.com/a/32896809/5907838">different telegram-bot project provided here</a> where they send the <code>urllib2.urlopen('url').read()</code> back to telegram but in my case this generates the same error as without .read() . </p>
<p>How could I get the file from the url as file object (best would be without saving it locally)?
Or how do I get the "file object" out of the "file-like object" provided by urlopen()?</p>
<p>Thanks for any help :)</p> | 1 |
php error ( Call to a member function query() on resource ) | <pre><code><?php
$dbhost='localhost:3306';
$dbuser='root';
$dbpass='';
$con=mysql_connect($dbhost,$dbuser,$dbpass);
if(!$con) {
die("Couldnotconnect:".mysql_error());
}
mysql_select_db('shop');
$sql="SELECTCD_ID,Title,Artist,Year,Company,Price,Quantity,TypeFROMcd_data";
$result=$con->query($sql); //somethingiswronghere
$numRows=$result->num_rows; //somethingiswronghere
if($result->num_rows) { //somethingiswronghere
//outputdataofeachrow
//somethingiswronghere
while($row=$result->fetch_assoc($sql)) {
echo"id:".$row["CD_ID"]."Name:".$row["Title"]."".$row["Artist"].$row["Year"].$row["Company"].$row["Price"]."Euro".$row["Quantity"].$row["Type"];
}
}
else {
echo"0results";
}
mysql_close($con);
?>
</code></pre> | 1 |
WebRTC Between two pages in the same machine | <p>I'm trying to implement a mechanism to send textual data (JSON for instance) in from page to page, using javascript at the <strong>same</strong> machine. <br>
I found some code and wrapped it but it only works at the same page. <br>
At the moment I don't want to use a WwebRTC framework, only adapter.js.</p>
<pre><code>//Must include adapter.js before
var WebRTCManager = (function () {
'use strict';
//Ctor
function WebRTCManagerFn() {
console.log('WebRTCManagerFn ctor reached');
this._events = {};
this._localConnection = null
this._remoteConnection = null;
this._sendChannel = null;
this._receiveChannel = null;
}
WebRTCManagerFn.prototype.addEventListener = function (name, handler) {
if (this._events.hasOwnProperty(name))
this._events[name].push(handler);
else
this._events[name] = [handler];
};
WebRTCManagerFn.prototype._fireEvent = function (name, event) {
if (!this._events.hasOwnProperty(name))
return;
if (!event)
event = {};
var listeners = this._events[name], l = listeners.length;
for (var i = 0; i < l; i++) {
listeners[i].call(null, event);
}
};
WebRTCManagerFn.prototype.createConnection = function () {
var servers = null;
var pcConstraint = null;
var dataConstraint = null;
console.log('Using SCTP based data channels');
// SCTP is supported from Chrome 31 and is supported in FF.
// No need to pass DTLS constraint as it is on by default in Chrome 31.
// For SCTP, reliable and ordered is true by default.
// Add localConnection to global scope to make it visible
// from the browser console.
window.localConnection = this._localConnection =
new RTCPeerConnection(servers, pcConstraint);
console.log('Created local peer connection object localConnection');
this._sendChannel = this._localConnection.createDataChannel('sendDataChannel',
dataConstraint);
console.log('Created send data channel');
this._localConnection.onicecandidate = this._localIceCallback.bind(this);
this._sendChannel.onopen = this._onSendChannelStateChange.bind(this);
this._sendChannel.onclose = this._onSendChannelStateChange.bind(this);
// Add remoteConnection to global scope to make it visible
// from the browser console.
window.remoteConnection = this._remoteConnection =
new RTCPeerConnection(servers, pcConstraint);
console.log('Created remote peer connection object remoteConnection');
this._remoteConnection.onicecandidate = this._remoteIceCallback.bind(this);
this._remoteConnection.ondatachannel = this._receiveChannelCallback.bind(this);
this._localConnection.createOffer(this._gotOfferFromLocalConnection.bind(this), this._onCreateSessionDescriptionError.bind(this));
}
WebRTCManagerFn.prototype._onCreateSessionDescriptionError = function (error) {
console.log('Failed to create session description: ' + error.toString());
}
WebRTCManagerFn.prototype.sendMessage = function (msgText) {
var msg = new Message(msgText);
// Send the msg object as a JSON-formatted string.
var data = JSON.stringify(msg);
this._sendChannel.send(data);
console.log('Sent Data: ' + data);
}
WebRTCManagerFn.prototype.closeDataChannels = function () {
console.log('Closing data channels');
this._sendChannel.close();
console.log('Closed data channel with label: ' + this._sendChannel.label);
this._receiveChannel.close();
console.log('Closed data channel with label: ' + this._receiveChannel.label);
this._localConnection.close();
this._remoteConnection.close();
this._localConnection = null;
this._remoteConnection = null;
console.log('Closed peer connections');
}
WebRTCManagerFn.prototype._gotOfferFromLocalConnection = function (desc) {
console.log('reached _gotOfferFromLocalConnection');
if (this && this._localConnection != 'undefined' && this._remoteConnection != 'undefined') {
this._localConnection.setLocalDescription(desc);
console.log('Offer from localConnection \n' + desc.sdp);
this._remoteConnection.setRemoteDescription(desc);
this._remoteConnection.createAnswer(this._gotAnswerFromRemoteConnection.bind(this),
this._onCreateSessionDescriptionError.bind(this));
}
}
WebRTCManagerFn.prototype._gotAnswerFromRemoteConnection = function (desc) {
console.log('reached _gotAnswerFromRemoteConnection');
if (this && this._localConnection != 'undefined' && this._remoteConnection != 'undefined') {
this._remoteConnection.setLocalDescription(desc);
console.log('Answer from remoteConnection \n' + desc.sdp);
this._localConnection.setRemoteDescription(desc);
}
}
WebRTCManagerFn.prototype._localIceCallback = function (event) {
console.log('local ice callback');
if (event.candidate) {
this._remoteConnection.addIceCandidate(event.candidate,
this._onAddIceCandidateSuccess.bind(this), this._onAddIceCandidateError.bind(this));
console.log('Local ICE candidate: \n' + event.candidate.candidate);
}
}
WebRTCManagerFn.prototype._remoteIceCallback = function (event) {
console.log('remote ice callback');
if (event.candidate) {
this._localConnection.addIceCandidate(event.candidate,
this._onAddIceCandidateSuccess.bind(this), this._onAddIceCandidateError.bind(this));
console.log('Remote ICE candidate: \n ' + event.candidate.candidate);
}
}
WebRTCManagerFn.prototype._onAddIceCandidateSuccess = function (evt) {
debugger;
console.log('AddIceCandidate success. evt: '+ evt);
}
WebRTCManagerFn.prototype._onAddIceCandidateError = function (error) {
console.log('Failed to add Ice Candidate: ' + error.toString());
}
WebRTCManagerFn.prototype._receiveChannelCallback = function (event) {
console.log('Receive Channel Callback');
this._receiveChannel = event.channel;
this._receiveChannel.onmessage = this._onReceiveMessageCallback.bind(this);
this._receiveChannel.onopen = this._onReceiveChannelStateChange.bind(this);
this._receiveChannel.onclose = this._onReceiveChannelStateChange.bind(this);
}
WebRTCManagerFn.prototype._onReceiveMessageCallback = function (event) {
console.log('Received Message: ' + event.data);
console.log('Received Message this is: ' + this);
var msgObj = JSON.parse(event.data);
this._fireEvent("messageRecieved", {
details: {
msg: msgObj
}
});
}
WebRTCManagerFn.prototype._onSendChannelStateChange = function () {
console.log('_onSendChannelStateChange');
var readyState = this._sendChannel.readyState;
console.log('Send channel state is: ' + readyState);
}
WebRTCManagerFn.prototype._onReceiveChannelStateChange = function () {
var readyState = this._receiveChannel.readyState;
console.log('Receive channel state is: ' + readyState);
}
return WebRTCManagerFn;
})();
</code></pre>
<p>My question is how to <strong>pass data between two pages on the same machine</strong> using WebRTC?</p> | 1 |
OpenCV GPU Farneback Optical Flow badly works in multi-threading | <p>My application uses the Opencv gpu class <code>gpu::FarnebackOpticalFlow</code> to compute the optical flow between a pair of consecutive frames of an input video. In order to speed-up the process, I exploited the TBB support of OpenCV to run the method in multi-threading. However, the multi-threading performance does not behave like the single-threaded one. Just to give you an idea of the different behaviour, here are two snapshots, respectively of the single threaded and the multi threaded implementation.</p>
<p><a href="https://i.stack.imgur.com/q1udO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/q1udO.png" alt="single threaded optical flow"></a>
<a href="https://i.stack.imgur.com/dsNM6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dsNM6.png" alt="multi threaded optical flow"></a></p>
<p>The multi-threaded implementation assumes to split the image in 8 different stripes (the number of cores on my pc), and the gpu method for the Farneback implementation of the optical flow is applied on each of them. Here are the corresponding code lines for both methods:</p>
<p><strong>Single-threaded implementation</strong></p>
<pre><code>/* main.cpp */
//prevImg and img are the input Mat images extracted from the input video
...
GpuMat gpuImg8U(img);
GpuMat gpuPrevImg8U(prevImg);
GpuMat u_flow, v_flow;
gpu::FarnebackOpticalFlow farneback_flow;
farneback_flow.numLevels = maxLayer;
farneback_flow.pyrScale = 0.5;
farneback_flow.winSize = windows_size;
farneback_flow.numIters = of_iterations;
farneback_flow(gpuPrevImg8U,gpuImg8U,u_flow,v_flow);
getFlowField(Mat(u_flow),Mat(v_flow),optical_flow);
...
}
void getFlowField(const Mat& u, const Mat& v, Mat& flowField){
for (int i = 0; i < flowField.rows; ++i){
const float* ptr_u = u.ptr<float>(i);
const float* ptr_v = v.ptr<float>(i);
Point2f* row = flowField.ptr<Point2f>(i);
for (int j = 0; j < flowField.cols; ++j){
row[j].y = ptr_v[j];
row[j].x = ptr_u[j];
}
}
}
</code></pre>
<p><strong>Multi-threaded implementation</strong></p>
<pre><code>/* parallel.h */
class ParallelOpticalFlow : public cv::ParallelLoopBody {
private:
int coreNum;
cv::gpu::GpuMat img, img2;
cv::gpu::FarnebackOpticalFlow& farneback_flow;
const cv::gpu::GpuMat u_flow, v_flow;
cv::Mat& optical_flow;
public:
ParallelOpticalFlow(int cores, cv::gpu::FarnebackOpticalFlow& flowHandler, cv::gpu::GpuMat img_, cv::gpu::GpuMat img2_, const cv::gpu::GpuMat u, const cv::gpu::GpuMat v, cv::Mat& of)
: coreNum(cores), farneback_flow(flowHandler), img(img_), img2(img2_), u_flow(u), v_flow(v), optical_flow(of){}
virtual void operator()(const cv::Range& range) const;
};
/* parallel.cpp*/
void ParallelOpticalFlow::operator()(const cv::Range& range) const {
for (int k = range.start ; k < range.end ; k ++){
cv::gpu::GpuMat img_rect(img,cv::Rect(0,img.rows/coreNum*k,img.cols,img.rows/coreNum));
cv::gpu::GpuMat img2_rect(img2,cv::Rect(0,img2.rows/coreNum*k,img2.cols,img2.rows/coreNum));
cv::gpu::GpuMat u_rect(u_flow,cv::Rect(0,u_flow.rows/coreNum*k,u_flow.cols,u_flow.rows/coreNum));
cv::gpu::GpuMat v_rect(v_flow,cv::Rect(0,v_flow.rows/coreNum*k,v_flow.cols,v_flow.rows/coreNum));
cv::Mat of_rect(optical_flow,cv::Rect(0,optical_flow.rows/coreNum*k,optical_flow.cols,optical_flow.rows/coreNum));
farneback_flow(img_rect,img2_rect,u_rect,v_rect);
getFlowField(Mat(u_rect),Mat(v_rect),of_rect);
}
}
/* main.cpp */
parallel_for_(Range(0,cores_num),ParallelOpticalFlow(cores_num,farneback_flow,gpuPrevImg8U,gpuImg8U,u_flow,v_flow,optical_flow));
</code></pre>
<p>The codes look like equivalent in the two cases. Can anyone explain me why there are these different behaviours? Or if there are some mistakes in my code?
Thanks in advance for your answers</p> | 1 |
How to get components of a JPanel which inside another JPanel in java | <p>I have a JPanel(first JPanel) and it fill with another JPanel(second JPanel).</p>
<p>I add this second JPanel to first JPanel programmatically. Like below,</p>
<pre><code>firstJPanel.removeAll();
JPanel secondJPanel = new JPanel(gridLayout);
secondJPanel.setBorder(new TitledBorder("Testing"));
secondJPanel.setName("secondJPanel");
firstJPanel.add(secondJPanel);
firstJPanel.revalidate();
</code></pre>
<p>The second JPanel has some components like JTextFields , JCheckBoxes, etc . I try to get these components . But I could get only the second JPanel.</p>
<p>Here is my code sample,</p>
<pre><code>Component[] components = firstJPanel.getComponents();
for(int i=0;i<components.length;i++){
System.out.println("Componenet name - " + components[i].getName());
}
</code></pre>
<p>Have any iedas to get the components inside the second JPanel.</p>
<p>Best Regards.</p> | 1 |
Python 2.7 pyodbc or pymssql vs R RODBC | <p>I'm trying to migrate R code to Python 2.7 in order to compare both. The first problem I get is when I try to do an odbc connection. R is much faster than python, but since I'm a newbie in Python I'm not sure if I'm using the right package.</p>
<p>In R I write:</p>
<pre><code>ptm <- proc.time()
require(RODBC)
dbXX <- odbcDriverConnect('driver={SQL Server};
server=s001111;database=XX;trusted_connection=true')
rech<-sqlQuery(dbXX, "select top 10000* from XX.dbo.table ", as.is=T)
proc.time() - ptm
</code></pre>
<p>and I get: </p>
<pre><code>> proc.time() - ptm
user system elapsed
2.47 0.11 2.87
</code></pre>
<p>I have downloaded Anaconda for python 2.7 windows 7 64.
So in Spyder I write:</p>
<pre><code>import pyodbc
import pandas
from pandas.io.sql import read_frame
sql = 'select top 10000 * from XX.dbo.table'
cnn = pyodbc.connect('DRIVER={SQL Server};SERVER=s001111;DATABASE=XX;Trusted_Connection=yes')
start = time.time()
data=pd.read_sql(sql,cnn)
end = time.time()
print(end - start)
</code></pre>
<p>This takes 6.35 secs</p>
<p>I've also tried with pymssql:</p>
<pre><code>import pymssql
conn = pymssql.connect(server='s001111', database='XX')
start = time.time()
data=pd.read_sql(sql,conn)
end = time.time()
print(end - start)
</code></pre>
<p>This takes 38.3 secs!</p>
<p>The real query needs to read a table which dimension is 220.000 rows by 353 columns and apply a filter (with where).</p>
<p>I only need to <strong>extract</strong> data from the db.</p>
<p>Is there a way to do it faster in Python 2.7?</p>
<p>I've found <a href="https://stackoverflow.com/questions/24766178/manage-pyodbc-memory-usage">pyodbc-memory usage relation caused by SQL Server</a> but I guess that if it were an SQL problem would be doing the same in R, wouldn't it?</p>
<p>I've also found this: <a href="https://www.continuum.io/blog/developer/faster-more-memory-efficient-sql-queries-iopro" rel="nofollow noreferrer">IOPro</a> but it's not free!</p>
<p>At this point I was wondering if the problem was the ODBC connection or pandas itself, so I tried:</p>
<pre><code>cur = conn.cursor();
start = time.time()
cur.execute(sql);
tabla=cur.fetchall()
end = time.time()
print(end - start)
</code></pre>
<p>But it took 29.29 secs.</p>
<p><strong>So, still: how is it possible that R is much faster than Python to retrieve data from an SQL Microsoft DB?</strong></p> | 1 |
Stored Procedure not executing in SQL SERVER? | <p>I'm trying to write a somewhat simple stored procedure. I first want to verify if there is anything in the table; if there is to TRUNCATE it, if there isn't to populate it with some data. What happens is, it gets execute without any error, but nothing happens to the table. It is as it was before executing it.........empty.</p>
<pre><code>ALTER PROCEDURE [dbo].[LoadReportDataCI]
AS
If (Select Count(*) from tbl_TempTableReport)>0
BEGIN
Truncate table tbl_TempTableReport
END
Begin
INSERT INTO tbl_TempTableReport (userID, VendorID, VendorName, UnitCost, UnitCount, CostValue)
SELECT
'1234',
VendorID,
VendorName,
InvValue,
BegInvOnHand,
BegCurrentValue
From vVendorsAndInvONHand
END
</code></pre>
<p>If I highlight starting at INSERT until the END, the data gets populated in the table, but otherwise it doesn't work. Shed some light anyone?</p> | 1 |
Error: org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectForm cannot be cast to org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage | <p>I am trying to extract image from the pdf using pdfbox. I have taken help from this <a href="https://stackoverflow.com/questions/8705163/extract-images-from-pdf-using-pdfbox">post</a> . It worked for some of the pdfs but for others/most it did not. For example, I am not able to extract the figures in this <a href="http://tinyurl.com/zcuahp5" rel="nofollow">file</a> </p>
<p>After doing some research I found that PDResources.getImages is deprecated. So, I am using PDResources.getXObjects(). With this, I am not able to extract any image from the PDF and instead get this message at the console:</p>
<pre><code>org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectForm cannot be cast to org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage
</code></pre>
<p>Now I am stuck and unable to find the solution. Please assist if anyone can.</p>
<p>//////UPDATE AS REPLY ON COMMENTS///</p>
<p>I am using pdfbox-1.8.10</p>
<p>Here is the code:</p>
<pre><code>public void getimg ()throws Exception {
try {
String sourceDir = "C:/Users/admin/Desktop/pdfbox/mypdfbox/pdfbox/inputs/Yavaa.pdf";
String destinationDir = "C:/Users/admin/Desktop/pdfbox/mypdfbox/pdfbox/outputs/";
File oldFile = new File(sourceDir);
if (oldFile.exists()){
PDDocument document = PDDocument.load(sourceDir);
List<PDPage> list = document.getDocumentCatalog().getAllPages();
String fileName = oldFile.getName().replace(".pdf", "_cover");
int totalImages = 1;
for (PDPage page : list) {
PDResources pdResources = page.getResources();
Map pageImages = pdResources.getXObjects();
if (pageImages != null){
Iterator imageIter = pageImages.keySet().iterator();
while (imageIter.hasNext()){
String key = (String) imageIter.next();
Object obj = pageImages.get(key);
if(obj instanceof PDXObjectImage) {
PDXObjectImage pdxObjectImage = (PDXObjectImage) obj;
pdxObjectImage.write2file(destinationDir + fileName+ "_" + totalImages);
totalImages++;
}
}
}
}
} else {
System.err.println("File not exist");
}
}
catch (Exception e){
System.err.println(e.getMessage());
}
}
</code></pre>
<p>//// PARTIAL SOLUTION/////</p>
<p>I have solved the problem of the error message. I have updated the correct code in the post as well. However, the problem remains the same. I am still not able to extract the images from few of the files. Like the one, I have mentioned in this post. Any solution in that regards. </p> | 1 |
Django - Save an uploaded image | <p>I have a form where I am supposed to upload an image, but I can't get the image to save. Everything else in the form works properly except the image.</p>
<p>I'm sure there are some issues with my <code>addGame</code> method, but I've tried it dozens of different ways with no luck.</p>
<p>I've gone through the <a href="https://docs.djangoproject.com/en/1.5/topics/http/file-uploads/" rel="nofollow noreferrer">documentation</a>, but it appears I'm still doing something wrong, as the image never gets saved.</p>
<p>(Just as a side note: I'm using Pillow for cropping the image, and I'm not sure if I'm doing that properly either, but I just added that in recently, and since the image doesn't save I have no way of knowing whether that is implemented correctly. I'm leaving the cropping part commented out while I try to get the upload to work.)</p>
<p><code>forms.py</code></p>
<pre><code>class GameForm(forms.ModelForm):
image = forms.ImageField()
code = forms.Textarea()
deleteGame = forms.BooleanField(required=False, widget=forms.HiddenInput())
class Meta:
model = Game
fields = ('title', 'image', 'description', 'requirements', 'code', 'deleteGame')
</code></pre>
<p><code>views.py</code>:</p>
<pre><code>@login_required
def add_game(request):
user = request.user
if request.method == 'POST':
form = GameForm(request.POST, request.FILES)
if form.is_valid():
form = form.save(commit=False)
image = request.FILES['image']
box = (200, 200, 200, 200)
cropped = image.crop(box)
form.image = cropped
form.user = request.user
form.save()
return HttpResponseRedirect('/userprofile')
else:
form = GameForm()
args = {}
args.update(csrf(request))
args['user'] = user
args['form'] = form
return render_to_response('addgame.html', args)
</code></pre>
<p><code>models.py</code></p>
<pre><code>class Game(models.Model):
user = models.ForeignKey(User, blank=True)
title = models.CharField(max_length=256)
image = models.ImageField(upload_to='games', blank=True)
description = models.CharField(max_length=256)
requirements = models.CharField(max_length=256)
code = models.TextField()
deleteGame = models.BooleanField(default=False)
def __unicode__(self):
return self.title
</code></pre>
<p>My media settings look like this:</p>
<pre><code>MEDIA_ROOT = 'media/'
MEDIA_URL = '/media/'
</code></pre>
<p>File Structure:</p>
<p><a href="https://i.stack.imgur.com/GPkix.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GPkix.png" alt=""></a></p>
<p>If I add an image via the admin portal, it saves properly, but I get an error like this in my log: </p>
<blockquote>
<p>Not Found: /media/games/Screen_Shot_2015-12-29_at_1.03.05_AM.png</p>
</blockquote> | 1 |
PowerShell wait application to launch | <p>I have the following script to launch an application: </p>
<pre><code>add-type -AssemblyName microsoft.VisualBasic
add-type -AssemblyName System.Windows.Forms
$args = "arguments"
$proc = Start-Process -PassThru "path" -ArgumentList $args
start-sleep -Seconds 5
[Microsoft.VisualBasic.Interaction]::AppActivate($proc.Id)
[System.Windows.Forms.SendKeys]::SendWait("~")
</code></pre>
<p>I use this script to launch several windows forms applications that need user interaction to start (i.e. push a start button). So far I've been sleeping the script 5 seconds to allow the application to launch. I tried to run this script in a variety of computers with different processing capabilities, but did not work in all computers, some launch the application slower than others, when the app took more than 5 seconds to launch the app the script fails, because the AppActivate could not find the PID.
I don't want to try different sleeping times for each computer, because I have to run this script in more than 100 computers at boot time.</p>
<p>I would like to know if there is a way to wait for the application to launch in a event driven way.</p>
<p>UPDATE:</p>
<p>The WaitForInputIdle does not work in all applications I tried to start. It returns immediately (successfully because it's returning true) and the AppActive method throws an exception.</p> | 1 |
ASP.NET add item to array | <p>I have this array defined:</p>
<pre><code>string[] emailAddress = {};
</code></pre>
<p>What I am trying to do is add items to this array like so:</p>
<pre><code>emailAddress[] = de.Properties["mail"][0].ToString();
</code></pre>
<p>and I get a cannot convert string to array error. How do I add an item to an array?</p> | 1 |
How to create custom Button with using AppCompat library? | <p>Is it possible to extend Button class without loosing AppCompat features like coloring/tinting/shadows?</p>
<p>For now, if I create custom class which extends Button and use it in layout it becomes white background/black foreground.</p> | 1 |
Why am I getting a segmentation fault only sometimes? | <p>I've got a hashtable here, and this program attempts to find anagrams by searching through linked-lists of words whose hash values are computed as the sum of their uppercase ascii values.</p>
<p>I cannot see how this segfault is happening, much less understand what <code>gdb</code> is telling me. It's obvious it's happening in <code>anagramlookup()</code> but I cannot see how.</p>
<p>Here is the <code>gdb</code> output:</p>
<pre><code>Program received signal SIGSEGV, Segmentation fault.
__strspn_sse2 ()
at ../sysdeps/x86_64/multiarch/../strspn.S:53
53 ../sysdeps/x86_64/multiarch/../strspn.S: No such file or directory.
(gdb) backtrace
#0 __strspn_sse2 ()
at ../sysdeps/x86_64/multiarch/../strspn.S:53
#1 0x0000000000400a0a in anagramlookup (
word=0x7fffffffe7c0 "you") at thirdfailure.c:66
#2 0x0000000000400c17 in main () at thirdfailure.c:121
(gdb) frame 2
#2 0x0000000000400c17 in main () at thirdfailure.c:121
121 anagramlookup(search);
(gdb) print search
$1 = "you\000\000\177\000\000\221I\336\367\377\177\000\000\000\000\000\000\000\000\000\000\020\232\377\367\377\177\000\000\001", '\000' <repeats 15 times>, "\001\000\000\000\377\177\000\000\310\341\377\367\377\177", '\000' <repeats 37 times>
</code></pre>
<p>The segfault doesn't happen all the time. If the word to lookup is "post", everything works fine. But when it is for example, "you", that's when I get a segfault. "youu" does not give me a segfault. How would I go about fixing things?</p>
<p>and here is my code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct Hash *hashTable = NULL;
struct Node{
char val[100];
struct Node *next;
};
struct Hash{
int size;
struct Node *head;
};
struct Node* newnode(char* word){
struct Node *ptr = (struct Node*)malloc(sizeof(struct Node));
strcpy(ptr->val, word);
ptr->next = NULL;
return ptr;
}
void insertHash(char* word){
int index = hashmaker(word);
struct Node *ptr = newnode(word);
if(!hashTable[index].head){
hashTable[index].head = ptr;
hashTable[index].size = 1;
return;
}
else{
ptr->next = (hashTable[index].head);
hashTable[index].head = ptr;
hashTable[index].size++;
return;
}
}
void anagramlookup(char* word){
int index = hashmaker(word);
struct Node *ptr = hashTable[index].head;
if(ptr == NULL){
printf("we dont have any");
}
else{
while((ptr!= NULL)){
if(strlen(word)==strspn(word,ptr->val) &&
strlen(word)==strspn(ptr->val,word) &&
strlen(word)==strlen(ptr->val)){
if(strcmp(word,ptr->val) != 0){
printf("\n%s", ptr->val );
}
}
ptr = ptr->next;
}
}
}
int hashmaker(char* word){
int toreturn = 0, i, len;
len = strlen(word);
for(i = 0; i < len; i++){
toreturn += toupper(word[i]);
}
return toreturn;
}
int main(){
char search[100];
hashTable = (struct Hash *) malloc(sizeof(struct Hash));
FILE* dict = fopen("words2", "r");
if(dict == NULL) {
printf("dict is null");
exit(1);
}
// Read each line of the file, and print it to screen
char wordo[128];
while(fgets(wordo, sizeof(wordo), dict) != NULL) {
printf("%s", wordo);
wordo[strlen(wordo) - 1] = '\0';
insertHash(wordo);
}
printf("now enter your search: ");
fgets(search, sizeof(wordo), stdin);
search[strlen(search) - 1] = '\0';
anagramlookup(search);
return 0;
}
</code></pre> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.