title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
Parsing json directly using input stream
<p>I am doing a api call and in response i am getting json. So for that I want to parse it directly through input stream so that there would not be need of storing it in memory. For this I am trying to use JSONReader but that i am unable use for api's less than 11. So i dont know how to proceed with. I want it to be done from 2.0 version onwards. Even parsing through JsonReader is not working. I was thing of having GSON parser but i am not getting how to implement the same with Inputstream.</p> <p>EDIT: My code for the same:</p> <pre><code>HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); Log.e("123", "Status code ----------- "+statusCode); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); // for showing it on textview i am storing in in builder BufferedReader bReader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = bReader.readLine()) != null) { builder.append(line); } //////////// JsonReader reader = new JsonReader(new InputStreamReader(content)); reader.setLenient(true); readGson(reader); } else { Log.e("TAG", "Failed to download file"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } private void readGson(JsonReader reader) { // TODO Auto-generated method stub Log.e("TAG", "inidde readgson"+reader); try { Log.e("TAG", "inside try"); reader.beginObject(); Log.e("123", "inside try "); while(reader.hasNext()){ Log.e("TAG", "reader values"+reader); String name = reader.nextName(); if (name.equals("max_id")) { long max_id = reader.nextLong(); Log.e("TAG", "sdbfhsajfgsdjbgksdfjv------------------"+max_id); } else { Log.e("TAG", "c skfnvklsfvn skip value"); reader.skipValue(); } } reader.endObject(); } catch (IOException e) { // TODO Auto-generated catch block Log.e("TAG", "inside catch"); e.printStackTrace(); } } </code></pre> <p>output:</p> <pre><code> 01-28 10:20:53.519: E/TAG(420): Status code ----------- 200 01-28 10:20:53.679: E/TAG(420): inidde readgsonJsonReader at line 1 column 1 01-28 10:20:53.679: E/TAG(420): inside try 01-28 10:20:53.679: E/TAG(420): inside catch 01-28 10:20:53.679: W/System.err(420): java.io.EOFException: End of input at line 1 column 1 01-28 10:20:53.689: W/System.err(420): at com.google.gson.stream.JsonReader.nextNonWhitespace(JsonReader.java:954) 01-28 10:20:53.689: W/System.err(420): at com.google.gson.stream.JsonReader.consumeNonExecutePrefix(JsonReader.java:405) 01-28 10:20:53.689: W/System.err(420): at com.google.gson.stream.JsonReader.peek(JsonReader.java:364) 01-28 10:20:53.689: W/System.err(420): at com.google.gson.stream.JsonReader.expect(JsonReader.java:337) 01-28 10:20:53.689: W/System.err(420): at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322) 01-28 10:20:53.689: W/System.err(420): at com.example.httpconnectiondemo.MainActivity.readGson(MainActivity.java:136) 01-28 10:20:53.699: W/System.err(420): at com.example.httpconnectiondemo.MainActivity.readTwitterFeed(MainActivity.java:116) 01-28 10:20:53.699: W/System.err(420): at com.example.httpconnectiondemo.MainActivity.onCreate(MainActivity.java:64) 01-28 10:20:53.699: W/System.err(420): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 01-28 10:20:53.699: W/System.err(420): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 01-28 10:20:53.699: W/System.err(420): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 01-28 10:20:53.699: W/System.err(420): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 01-28 10:20:53.699: W/System.err(420): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 01-28 10:20:53.699: W/System.err(420): at android.os.Handler.dispatchMessage(Handler.java:99) 01-28 10:20:53.699: W/System.err(420): at android.os.Looper.loop(Looper.java:123) 01-28 10:20:53.699: W/System.err(420): at android.app.ActivityThread.main(ActivityThread.java:3683) 01-28 10:20:53.710: W/System.err(420): at java.lang.reflect.Method.invokeNative(Native Method) 01-28 10:20:53.710: W/System.err(420): at java.lang.reflect.Method.invoke(Method.java:507) 01-28 10:20:53.710: W/System.err(420): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 01-28 10:20:53.710: W/System.err(420): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 01-28 10:20:53.710: W/System.err(420): at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>Thanks in advance.</p>
0
2,466
Gradle: Project "x" not found in root project "myProject"
<p>Having upgraded to Android Studio from Eclipse I wanted to update my TouchDB library which is now <a href="https://github.com/couchbase/couchbase-lite-android" rel="nofollow">Coubasebase-lite-android</a>. I removed TouchDB from my project, git cloned couchbase-lite-android added to my project in Android Studio via File -> Import Module.</p> <p>Everything looks good in the IDE and all the references look good. But when I try and compile it I receive the error in Android Studio: <code>Gradle: Project "x" not found in root project "myProject"</code> "x" being each module(?) inside couchbaselite...i.e CBLite, CBLiteEktrop etc</p> <p>I really don't know where to start with this one?</p> <p>Here's my project tree:</p> <pre><code>myProject ---myProject ---CouchbaseLiteProject ------CBLite ------CBLiteEktorp ------Gradle ------.Gradle ------gradlew ------CouchbaseLiteProject ---------build ---------libs ---------src </code></pre> <p>here's the contents of <code>gradlew</code> from CouchBaseLiteProject:</p> <pre><code>#!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # For Cygwin, ensure paths are in UNIX format before anything is touched. if $cygwin ; then [ -n "$JAVA_HOME" ] &amp;&amp; JAVA_HOME=`cygpath --unix "$JAVA_HOME"` fi # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-&gt; \(.*\)$'` if expr "$link" : '/.*' &gt; /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" &gt;&amp;- APP_HOME="`pwd -P`" cd "$SAVED" &gt;&amp;- CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java &gt;/dev/null 2&gt;&amp;1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\" \"-Xmx1024m\" \"-Xms256m\" \"-XX:MaxPermSize=1024m\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2&gt;/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] &amp;&amp; [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" </code></pre> <p>` There is no gradlew file under myProject as it was originally a Eclipse project</p> <p><strong>update</strong> following on from buzeeg's advice and not being able to export my project from Eclipse to generate the gradle files I decided to create a new project in Android Studio and manually copy my original project files into it, so Android Studio would create the gradle files for me. </p> <p>After importing couchbase-lite-android as a module and trying to build the project I get exactly the same errors as I originally encountered. <code>Gradle: Project "x" not found in root project "myProject"</code> "x" relating to all the sub modules (?) under the CouchbaseLiteProject tree...</p>
0
2,850
Docker: How to fix "Job for docker.service failed because the control process exited with error code"
<p>I'm trying to use docker in Manjaro (my kernel version is 4.19) and it is not working.</p> <p>After running <code>sudo pamac install docker</code> I run <code>sudo systemctl start docker.service</code> and receive this message:</p> <pre><code>Job for docker.service failed because the control process exited with error code. See "systemctl status docker.service" and "journalctl -xe" for details. </code></pre> <p>So <code>sudo systemctl status docker.service</code> returns:</p> <pre><code>● docker.service - Docker Application Container Engine Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled) Active: failed (Result: exit-code) since Mon 2019-04-29 12:28:44 -03; 39s ago Docs: https://docs.docker.com Process: 17769 ExecStart=/usr/bin/dockerd -H fd:// (code=exited, status=1/FAILURE) Main PID: 17769 (code=exited, status=1/FAILURE) abr 29 12:28:44 tamer-pc systemd[1]: docker.service: Service RestartSec=100ms expired, scheduling restart. abr 29 12:28:44 tamer-pc systemd[1]: docker.service: Scheduled restart job, restart counter is at 3. abr 29 12:28:44 tamer-pc systemd[1]: Stopped Docker Application Container Engine. abr 29 12:28:44 tamer-pc systemd[1]: docker.service: Start request repeated too quickly. abr 29 12:28:44 tamer-pc systemd[1]: docker.service: Failed with result 'exit-code'. abr 29 12:28:44 tamer-pc systemd[1]: Failed to start Docker Application Container Engine. </code></pre> <p>and <code>journalctl -xe</code> returns:</p> <pre><code>-- Defined-By: systemd -- Support: https://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- The unit docker.service has entered the 'failed' state with result 'exit-code'. abr 29 12:28:44 tamer-pc systemd[1]: Failed to start Docker Application Container Engine. -- Subject: A unidade docker.service falhou -- Defined-By: systemd -- Support: https://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- A unidade docker.service falhou. -- -- O resultado é failed. abr 29 12:28:44 tamer-pc systemd[1]: docker.socket: Failed with result 'service-start-limit-hit'. -- Subject: Unit failed -- Defined-By: systemd -- Support: https://lists.freedesktop.org/mailman/listinfo/systemd-devel -- -- The unit docker.socket has entered the 'failed' state with result 'service-start-limit-hit'. abr 29 12:29:02 tamer-pc dbus-daemon[650]: [system] Activating via systemd: service name='org.freedesktop.resolve1' unit='&gt; abr 29 12:29:02 tamer-pc dbus-daemon[650]: [system] Activation via systemd failed for unit 'dbus-org.freedesktop.resolve1.&gt; abr 29 12:29:24 tamer-pc sudo[17879]: tamer : TTY=pts/0 ; PWD=/etc/docker ; USER=root ; COMMAND=/usr/bin/systemctl stat&gt; abr 29 12:29:24 tamer-pc sudo[17879]: pam_unix(sudo:session): session opened for user root by (uid=0) abr 29 12:29:24 tamer-pc sudo[17879]: pam_unix(sudo:session): session closed for user root lines 1703-1725/1725 (END) </code></pre> <p>I'm looking for resolution for two days but whatever I read seems not to be exactly the same as my problem.</p>
0
1,047
"img" must be terminated by the matching end-tag
<p>When parsing some an XSL XML file using docx4j, I keep receiving this error: </p> <blockquote> <p>'The element type "img" must be terminated by the matching end-tag <code>"&lt;/img&gt;"</code>. Exception Error in Docx4JException'</p> </blockquote> <p>I have tried all sorts of combinations to solve the issue but nothing seems to work apart from putting some text in between the <code>img</code> tags. I don't want the text to display. Is there anything else that can be done?</p> <p>This is the piece of xsl that is causing the error: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:prettyprint="http://xml.apache.org/xslt" xmlns:xalan="http://xml.apache.org/xalan" version="1.0"&gt; &lt;xsl:output method="html" /&gt; &lt;!-- Main entry template --&gt; &lt;xsl:template match="Email"&gt; &lt;html&gt; &lt;body&gt; &lt;img width="100" height="100" src="http://thumbs.dreamstime.com/x/sun-logo-6350903.jpg" border="0" class="MyImage" /&gt; &lt;div style="font-family:Verdana, Arial; font-size:9.5pt; font-weight:normal"&gt; &lt;xsl:variable name="PTPTotalAmt" select="Issue_PTPTotalAmount_C" /&gt; &lt;xsl:variable name="LetterDate" select="LetterDate" /&gt; &lt;xsl:variable name="LtrDate" select="substring($LetterDate, 1, 11)" /&gt; &lt;br&gt; &lt;xsl:text /&gt; &lt;/br&gt; &lt;xsl:value-of select="Contact_Title_R" /&gt; &lt;xsl:text /&gt; &lt;xsl:value-of select="Contact_LastName_X" /&gt; &lt;br&gt; &lt;xsl:text /&gt; &lt;/br&gt; &lt;xsl:value-of select="Contact_DispAddrLine1_X" /&gt; &lt;br&gt; &lt;xsl:text /&gt; &lt;/br&gt; &lt;xsl:value-of select="Contact_DispAddrLine3_X" /&gt; &lt;br&gt; &lt;xsl:text /&gt; &lt;/br&gt; &lt;xsl:value-of select="Contact_DispAddrLine4_X" /&gt; &lt;br&gt; &lt;xsl:text /&gt; &lt;/br&gt; &lt;xsl:value-of select="Contact_DispAddrLine5_X" /&gt; &lt;br&gt; &lt;xsl:text /&gt; &lt;/br&gt; &lt;xsl:value-of select="Contact_DispAddrPostCode_X" /&gt; &lt;br&gt; &lt;xsl:text /&gt; &lt;/br&gt; &lt;xsl:text /&gt; &lt;xsl:text /&gt; &lt;xsl:value-of select="$LtrDate" /&gt; &lt;/div&gt; &lt;br&gt; &lt;xsl:text /&gt; &lt;/br&gt; &lt;br&gt; &lt;xsl:text /&gt; &lt;/br&gt; &lt;br&gt; &lt;xsl:text /&gt; &lt;/br&gt; &lt;br&gt; &lt;xsl:text /&gt; &lt;/br&gt; &lt;div style="font-family:Verdana, Arial; font-size:8.5pt; font-weight:normal"&gt; &lt;br&gt; &lt;xsl:text&gt;Address Here&lt;/xsl:text&gt; &lt;/br&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre>
0
1,996
Springboot could not extract ResultSet
<p>Currently I am getting a problem with fetching mysql data for my springboot project:</p> <p>There was an unexpected error (type=Internal Server Error, status=500). could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet</p> <p><strong>TestEntity.java</strong></p> <pre><code>@Entity public class TestEntity implements Serializable { @Id private int id; private String p1; private String p2; private String p3; public TestEntity() { } public TestEntity(int id, String p1, String p2, String p3){ this.id = id; this.p1 = p1; this.p2 = p2; this.p3 = p3; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getP1() { return p1; } public void setP1(String p1) { this.p1 = p1; } public String getP2() { return p2; } public void setP2(String p2) { this.p2 = p2; } public String getP3() { return p3; } public void setP3(String p3) { this.p3 = p3; } } </code></pre> <p><strong>TestService.java</strong></p> <pre><code>@Service public class TestService { @Autowired private TestRepository testRepository; public ArrayList&lt;TestEntity&gt; getAllTestEntities(){ ArrayList&lt;TestEntity&gt; list = new ArrayList(); testRepository.findAll().forEach(list::add); return list; } public Optional getTestEntity(int id){ return testRepository.findById(id); } public void addTestEntity(TestEntity t){ testRepository.save(t); } public void removeTestEntity(int index){ testRepository.deleteById(index); } } </code></pre> <p><strong>TestRepository.java</strong></p> <pre><code>@Repository("mysql") public interface TestRepository extends CrudRepository&lt;TestEntity,Integer&gt; { } </code></pre> <p><strong>TestController.java</strong></p> <pre><code>@RestController public class TestController { @Autowired private TestService testService; @RequestMapping("/test/AllUnits") public ArrayList&lt;TestEntity&gt; getAllTestUnits(){ return testService.getAllTestEntities(); } @RequestMapping("/test/{id}") public Optional getAllTestUnit(@PathVariable int id){ return testService.getTestEntity(id); } @RequestMapping(method=RequestMethod.POST,value = "/test" ) public void addTestUnit(@RequestBody TestEntity t){ testService.addTestEntity(t); } @RequestMapping(method=RequestMethod.DELETE,value = "/test/{id}" ) public void deleteTestUnit(@RequestBody Integer id){ testService.removeTestEntity(id); } @RequestMapping("/test/welcome") public String welcome(){ return "welcome to springboot"; } } </code></pre> <p><strong>Edit</strong>: <strong>application.properties</strong></p> <pre><code>cloud.aws.region.auto=true cloud.aws.region.static=us-east-2 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://alyxdev.czcdgqfkwsnr.us-east-2.rds.amazonaws.com:3306/CryptoCurrency spring.datasource.username=******* spring.datasource.password=******* </code></pre> <p>I am able to get the /test/welcome mapping working so I believe my implementation of the service and controller is correct. So I am wondering if I made a mistake for accessing my database in my repository or should I use a JpaRepository instead of a CrudRepository and use an explicit query?</p> <p><strong>Edit Stack Trace</strong>: org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'CryptoCurrency.test_entity' doesn't exist</p>
0
1,549
How do you dynamically create an AWS IAM policy document with a variable number of resource blocks using terraform?
<p>In my current terraform configuration I am using a static JSON file and importing into terraform using the file function to create an AWS IAM policy.</p> <p>Terraform code:</p> <pre><code>resource "aws_iam_policy" "example" { policy = "${file("policy.json")}" } </code></pre> <p>AWS IAM Policy definition in JSON file (policy.json):</p> <pre><code>{ "Version": "2012-10-17", "Id": "key-consolepolicy-2", "Statement": [ { "Sid": "Enable IAM User Permissions", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::111122223333:root" }, "Action": "kms:*", "Resource": "*" }, { "Sid": "Allow use of the key", "Effect": "Allow", "Principal": { "AWS": [ "arn:aws:iam::777788889999:root" ] }, "Action": [ "kms:Decrypt" ], "Resource": "*" }, { "Sid": "Allow use of the key", "Effect": "Allow", "Principal": { "AWS": [ "arn:aws:iam::444455556666:root" ] }, "Action": [ "kms:Decrypt" ], "Resource": "*" } ] } </code></pre> <p>My goal is to use a list of account numbers stored in a terraform variable and use that to dynamically build the aws_iam_policy resource in terraform. My first idea was to try and use the terraform jsonencode function. However, it looks like there might be a way to implement this using the new terraform dynamic expressions foreach loop.</p> <p>The sticking point seems to be appending a variable number of resource blocks in the IAM policy. </p> <p>Pseudo code below:</p> <pre><code>var account_number_list = ["123","456","789"] policy = {"Statement":[]} for each account_number in account_number_list: policy["Statement"].append(policy block with account_number var reference) </code></pre> <p>Any help is appreciated.</p> <p>Best, Andrew</p>
0
1,038
Angular 7 - Reload / refresh data different components
<p>How to refresh data in different component 1 when changes made in component 2. These two components are not under same parentnode.</p> <p><strong>customer.service.ts</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>export class UserManagementService extends RestService { private BASE_URL_UM: string = '/portal/admin'; private headers = new HttpHeaders({ 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' }); constructor(protected injector: Injector, protected httpClient: HttpClient) { super(injector); } getEapGroupList(): Observable &lt; EapGroupInterface &gt; { return this.get &lt; GroupInterface &gt; (this.getFullUrl(`${this.BASE_URL_UM}/groups`), { headers: this.headers }); } updateGroup(body: CreateGroupPayload): Observable &lt; CreateGroupPayload &gt; { return this.put &lt; GroupPayload &gt; (this.getFullUrl(`${this.BASE_URL_UM}/group`), body, { headers: this.headers }); } }</code></pre> </div> </div> </p> <p><strong>Component1.ts</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>export class UserGroupComponent implements OnInit { constructor(private userManagementService: UserManagementService) {} ngOnInit() { this.loadGroup(); } loadGroup() { this.userManagementService.getEapGroupList() .subscribe(response =&gt; { this.groups = response; }) } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;mat-list-item *ngFor="let group of groups?.groupList" role="listitem"&gt; &lt;div matLine [routerLink]="['/portal/user-management/group', group.groupCode, 'overview']" [routerLinkActive]="['is-active']"&gt; {{group.groupName}} &lt;/div&gt; &lt;/mat-list-item&gt; &lt;mat-sidenav-content&gt; &lt;router-outlet&gt;&lt;/router-outlet&gt; &lt;/mat-sidenav-content&gt;</code></pre> </div> </div> </p> <p><strong>component2.ts</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>setPayload() { const formValue = this.newGroupForm.value return { 'id': '5c47b24918a17c0001aa7df4', 'groupName': formValue.groupName, } } onUpdateGroup() { this.userManagementService.updateGroup(this.setPayload()) .subscribe(() =&gt; { console.log('success); }) }</code></pre> </div> </div> </p> <p>When I update onUpdateGroup() api in <strong>component1</strong>, loadGroup() should refresh in <strong>component2</strong></p>
0
1,129
Add embedded image in emails in AWS SES service
<p>I am trying to write a Java app which can send emails to specify emails. In the email i also want to attach some pic.</p> <p>Please find my code below :-</p> <pre><code>public class AmazonSESSample { static final String FROM = "abc@gmail.com"; static final String TO = "def@gmail.com"; static final String BODY = "This email was sent through Amazon SES by using the AWS SDK for Java. hello"; static final String SUBJECT = "Amazon SES test (AWS SDK for Java)"; public static void main(String[] args) throws IOException { Destination destination = new Destination().withToAddresses(new String[] { TO }); Content subject = new Content().withData(SUBJECT); Message msg = new Message().withSubject(subject); // Include a body in both text and HTML formats //Content textContent = new Content().withData("Hello - I hope you're having a good day."); Content htmlContent = new Content().withData("&lt;h2&gt;Hi User,&lt;/h2&gt;\n" + " &lt;h3&gt;Please find the ABC Association login details below&lt;/h3&gt;\n" + " &lt;img src=\"logo.png\" alt=\"Mountain View\"&gt;\n" + " Click &lt;a href=\"http://google.com"&gt;here&lt;/a&gt; to go to the association portal.\n" + " &lt;h4&gt;Association ID - 12345&lt;/h4&gt;\n" + " &lt;h4&gt;Admin UID - suny342&lt;/h4&gt;\n" + " &lt;h4&gt;Password - poass234&lt;/h4&gt;\n" + " Regards,\n" + " &lt;br&gt;Qme Admin&lt;/br&gt;"); Body body = new Body().withHtml(htmlContent); msg.setBody(body); SendEmailRequest request = new SendEmailRequest().withSource(FROM).withDestination(destination) .withMessage(msg); try { System.out.println("Attempting to send an email through Amazon SES by using the AWS SDK for Java..."); AWSCredentials credentials = null; credentials = new BasicAWSCredentials("ABC", "CDF"); try { // credentialsProvider. } catch (Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file. " + "Please make sure that your credentials file is at the correct " + "location (/Users/iftekharahmedkhan/.aws/credentials), and is in valid format.", e); } AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)).withRegion("us-west-2").build(); client.sendEmail(request); System.out.println("Email sent!"); } catch (Exception ex) { System.out.println("The email was not sent."); System.out.println("Error message: " + ex.getMessage()); } } } </code></pre> <p>The image is placed in the resource directory but it is not being embeded in the email. Can anyone please help.</p>
0
1,223
Running multiple async queries with ADODB - callbacks not always firing
<p>I have an Excel workbook that fires three queries to a database to populate three tables on hidden sheets, and then runs three 'refresh' scripts to pull this data through to three visible presentation sheets (one per query). Running this synchronously is quite slow: The total time to refresh is the sum of the time of each of the three queries, plus the sum of the time for each 'refresh' script to run.</p> <p>I'm aware that VBA isn't multi-threaded, but I thought it would be possible to speed things up a bit by firing the queries off asynchronously (thus allowing some clean-up work to be done whilst they were executing), and then doing the population / refresh work for each sheet as the data comes back.</p> <p>I rewrote my script as follows (note that I've had to remove the connection strings, query strings etc and make the variables generic):</p> <pre><code>Private WithEvents cnA As ADODB.Connection Private WithEvents cnB As ADODB.Connection Private WithEvents cnC As ADODB.Connection Private Sub StartingPoint() 'For brevity, only listing set-up of cnA here. You can assume identical 'set-up for cnB and cnC Set cnA = New ADODB.Connection Dim connectionString As String: connectionString = "&lt;my conn string&gt;" cnA.connectionString = connectionString Debug.Print "Firing cnA query: " &amp; Now cnA.Open cnA.Execute "&lt;select query&gt;", adAsyncExecute 'takes roughly 5 seconds to execute Debug.Print "Firing cnB query: " &amp; Now cnB.Open cnB.Execute "&lt;select query&gt;", adAsyncExecute 'takes roughly 10 seconds to execute Debug.Print "Firing cnC query: " &amp; Now cnC.Open cnC.Execute "&lt;select query&gt;", adAsyncExecute 'takes roughly 20 seconds to execute Debug.Print "Clearing workbook tables: " &amp; Now ClearAllTables TablesCleared = True Debug.Print "Tables cleared: " &amp; Now End Sub Private Sub cnA_ExecuteComplete(ByVal RecordsAffected As Long, ...) Debug.Print "cnA records received: " &amp; Now 'Code to handle the recordset, refresh the relevant presentation sheet here, 'takes roughly &lt; 1 seconds to complete Debug.Print "Sheet1 tables received: " &amp; Now End Sub Private Sub cnB_ExecuteComplete(ByVal RecordsAffected As Long, ...) Debug.Print "cnB records received: " &amp; Now 'Code to handle the recordset, refresh the relevant presentation sheet here, 'takes roughly 2-3 seconds to complete Debug.Print "Sheet2 tables received: " &amp; Now End Sub Private Sub cnC_ExecuteComplete(ByVal RecordsAffected As Long, ...) Debug.Print "cnC records received: " &amp; Now 'Code to handle the recordset, refresh the relevant presentation sheet here, 'takes roughly 5-7 seconds to complete Debug.Print "Sheet3 tables received: " &amp; Now End Sub </code></pre> <p>Typical expected debugger output:</p> <pre><code>Firing cnA query: 21/02/2014 10:34:22 Firing cnB query: 21/02/2014 10:34:22 Firing cnC query: 21/02/2014 10:34:22 Clearing tables: 21/02/2014 10:34:22 Tables cleared: 21/02/2014 10:34:22 cnB records received: 21/02/2014 10:34:26 Sheet2 tables refreshed: 21/02/2014 10:34:27 cnA records received: 21/02/2014 10:34:28 Sheet1 tables refreshed: 21/02/2014 10:34:28 cnC records received: 21/02/2014 10:34:34 Sheet3 tables refreshed: 21/02/2014 10:34:40 </code></pre> <p>The three queries can come back in different orders depending on which finishes first, of course, so sometimes the typical output is ordered differently - this is expected.</p> <p>Sometimes however, one or two of the <code>cnX_ExecuteComplete</code> callbacks don't fire at all. After some time debugging, I'm fairly certain the reason for this is that if a recordset returns whilst one of the callbacks is currently executing, the call does not occur. For example:</p> <ul> <li>query A, B and C all fire at time 0</li> <li>query A completes first at time 3, <code>cnA_ExecuteComplete</code> fires</li> <li>query B completes second at time 5</li> <li><code>cnA_ExecuteComplete</code> is still running, so <code>cnB_ExecuteComplete</code> never fires</li> <li><code>cnA_ExecuteComplete</code> completes at time 8</li> <li>query C completes at time 10, <code>cnC_ExecuteComplete</code> fires</li> <li>query C completes at time 15</li> </ul> <p>Am I right in my theory that this is the issue? If so, is it possible to work around this, or get the call to 'wait' until current code has executed rather than just disappearing?</p> <p>One solution would be to do something extremely quick during the <code>cnX_ExecuteComplete</code> callbacks (eg, a one-liner <code>Set sheet1RS = pRecordset</code> and a check to see if they're all done yet before running the refresh scripts synchronously) so the chance of them overlapping is about zero, but want to know if there's a better solution first.</p>
0
1,532
ClassPathResource cannot access my spring properties file (using Spring web MVC)
<p>The actual location of the file is in "D:\eclipse\projects\issu\src\main\webapp\WEB-INF\spring\spring.properties"</p> <p>I tried:</p> <pre><code>Resource resource = new ClassPathResource("/src/main/webapp/WEB-INF/spring/spring.properties"); Resource resource = new ClassPathResource("/WEB-INF/spring/spring.properties"); Resource resource = new ClassPathResource("classpath:/WEB-INF/spring/spring.properties"); </code></pre> <p>I also have added "/src/main/webapp" folder to my build path.</p> <p>ClassPathResource cannot find it. Any ideas? thanks! :)</p> <p><strong>my web.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"&gt; &lt;display-name&gt;ISSU&lt;/display-name&gt; &lt;servlet&gt; &lt;servlet-name&gt;spring&lt;/servlet-name&gt; &lt;servlet-class&gt; org.springframework.web.servlet.DispatcherServlet &lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/spring/spring-servlet.xml&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;spring&lt;/servlet-name&gt; &lt;url-pattern&gt;*.html&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;/web-app&gt; </code></pre> <p><strong>my spring-servlet.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"&gt; &lt;context:component-scan base-package="com.myapps.issu" /&gt; &lt;mvc:annotation-driven /&gt; &lt;mvc:resources mapping="/resources/**" location="/resources/" /&gt; &lt;tx:annotation-driven /&gt; &lt;bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt; &lt;property name="location" value="/WEB-INF/spring/spring.properties" /&gt; &lt;/bean&gt; &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt; &lt;property name="driverClassName" value="${jdbc.driverClassName}" /&gt; &lt;property name="url" value="${jdbc.databaseurl}" /&gt; &lt;property name="username" value="${jdbc.username}" /&gt; &lt;property name="password" value="${jdbc.password}" /&gt; &lt;/bean&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="configLocation" value="${hibernate.config}" /&gt; &lt;property name="packagesToScan" value="com.myapps.issu" /&gt; &lt;/bean&gt; &lt;bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt; &lt;property name="sessionFactory" ref="sessionFactory" /&gt; &lt;/bean&gt; &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"&gt; &lt;property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" /&gt; &lt;/bean&gt; &lt;bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"&gt; &lt;property name="definitions" value="/WEB-INF/tiles.xml" /&gt; &lt;/bean&gt; &lt;bean id="issuDao" class="com.myapps.issu.dao.IssuDaoImpl"&gt; &lt;property name="sessionFactory" ref="sessionFactory" /&gt; &lt;/bean&gt; &lt;bean id="issuService" class="com.myapps.issu.services.IssuServiceImpl"&gt; &lt;property name="issuDao" ref="issuDao" /&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre>
0
2,151
Stratified sampling with Random Forests in R
<p>I read the following in the documentation of <code>randomForest</code>:</p> <blockquote> <p>strata: A (factor) variable that is used for stratified sampling.</p> <p>sampsize: Size(s) of sample to draw. For classification, if sampsize is a vector of the length the number of strata, then sampling is stratified by strata, and the elements of sampsize indicate the numbers to be drawn from the strata.</p> </blockquote> <p>For reference, the interface to the function is given by:</p> <pre><code> randomForest(x, y=NULL, xtest=NULL, ytest=NULL, ntree=500, mtry=if (!is.null(y) &amp;&amp; !is.factor(y)) max(floor(ncol(x)/3), 1) else floor(sqrt(ncol(x))), replace=TRUE, classwt=NULL, cutoff, strata, sampsize = if (replace) nrow(x) else ceiling(.632*nrow(x)), nodesize = if (!is.null(y) &amp;&amp; !is.factor(y)) 5 else 1, maxnodes = NULL, importance=FALSE, localImp=FALSE, nPerm=1, proximity, oob.prox=proximity, norm.votes=TRUE, do.trace=FALSE, keep.forest=!is.null(y) &amp;&amp; is.null(xtest), corr.bias=FALSE, keep.inbag=FALSE, ...) </code></pre> <p>My question is: How exactly would one use <code>strata</code> and <code>sampsize</code>? Here is a minimal working example where I would like to test these parameters:</p> <pre><code>library(randomForest) iris = read.table("http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data", sep = ",", header = FALSE) names(iris) = c("sepal.length", "sepal.width", "petal.length", "petal.width", "iris.type") model = randomForest(iris.type ~ sepal.length + sepal.width, data = iris) &gt; model 500 samples 6 predictors 2 classes: 'Y0', 'Y1' No pre-processing Resampling: Bootstrap (7 reps) Summary of sample sizes: 477, 477, 477, 477, 477, 477, ... Resampling results across tuning parameters: mtry ROC Sens Spec ROC SD Sens SD Spec SD 2 0.763 1 0 0.156 0 0 4 0.782 1 0 0.231 0 0 6 0.847 1 0 0.173 0 0 ROC was used to select the optimal model using the largest value. The final value used for the model was mtry = 6. </code></pre> <p>I come to these parameters since I would like RF to use bootstrap samples that respect the proportion of positives to negatives in my data.</p> <p><a href="https://stackoverflow.com/questions/8704681/random-forest-with-classes-that-are-very-unbalanced">This other thread</a>, started a discussion on the topic, but it was settled without clarifying how one would use these parameters.</p>
0
1,131
how to drag and drop files from a directory in java
<p>I want to implement dragging and dropping of files from a directory such as someones hard drive but can't figure out how to do it. I've read the java api but it talks of color pickers and dragging and dropping between lists but how to drag files from a computers file system and drop into my application. I tried writing the transferhandler class and a mouse event for when the drag starts but nothing seems to work. Now I'm back to just having my JFileChooser set so drag has been enabled but how to drop? </p> <p>Any info or point in the right direction greatly appreciated.</p> <pre><code> import javax.swing.*; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import javax.swing.filechooser.FileFilter; public class FileChooserDemo extends JPanel implements ActionListener { JLabel selectedFileLabel; JList selectedFilesList; JLabel returnCodeLabel; public FileChooserDemo() { super(); createContent(); } void initFrameContent() { JPanel closePanel = new JPanel(); add(closePanel, BorderLayout.SOUTH); } private void createContent() { setLayout(new BorderLayout()); JPanel NorthPanel = new JPanel(); JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("File"); JMenuItem quit = new JMenuItem("Quit"); menuBar.add(menu); menu.add(quit); NorthPanel.add(menu,BorderLayout.NORTH); JPanel buttonPanel = new JPanel(new GridLayout(7,1 )); JButton openButton = new JButton("Open..."); openButton.setActionCommand("OPEN"); openButton.addActionListener(this); buttonPanel.add(openButton); JButton saveButton = new JButton("Save..."); saveButton.setActionCommand("SAVE"); saveButton.addActionListener(this); buttonPanel.add(saveButton); JButton delete = new JButton("Delete"); delete.addActionListener(this); delete.setActionCommand("DELETE"); buttonPanel.add(delete); add(buttonPanel, BorderLayout.WEST); // create a panel to display the selected file(s) and the return code JPanel displayPanel = new JPanel(new BorderLayout()); selectedFileLabel = new JLabel("-"); selectedFileLabel.setBorder(BorderFactory.createTitledBorder ("Selected File/Directory ")); displayPanel.add(selectedFileLabel, BorderLayout.NORTH); selectedFilesList = new JList(); JScrollPane sp = new JScrollPane(selectedFilesList); sp.setBorder(BorderFactory.createTitledBorder("Selected Files ")); MouseListener listener = new MouseAdapter() { public void mousePressed(MouseEvent me) { JComponent comp = (JComponent) me.getSource(); TransferHandler handler = comp.getTransferHandler(); handler.exportAsDrag(comp, me, TransferHandler.MOVE); } }; selectedFilesList.addMouseListener(listener); displayPanel.add(sp); returnCodeLabel = new JLabel(""); returnCodeLabel.setBorder(BorderFactory.createTitledBorder("Return Code")); displayPanel.add(returnCodeLabel, BorderLayout.SOUTH); add(displayPanel); } public void actionPerformed(ActionEvent e) { int option = 0; File selectedFile = null; File[] selectedFiles = new File[0]; if (e.getActionCommand().equals("CLOSE")) { System.exit(0); } else if (e.getActionCommand().equals("OPEN")) { JFileChooser chooser = new JFileChooser(); chooser.setDragEnabled(true); chooser.setMultiSelectionEnabled(true); option = chooser.showOpenDialog(this); selectedFiles = chooser.getSelectedFiles(); } else if (e.getActionCommand().equals("SAVE")) { JFileChooser chooser = new JFileChooser(); option = chooser.showSaveDialog(this); selectedFiles = chooser.getSelectedFiles(); } // display the selection and return code if (selectedFile != null) selectedFileLabel.setText(selectedFile.toString()); else selectedFileLabel.setText("null"); DefaultListModel listModel = new DefaultListModel(); for (int i =0; i &lt; selectedFiles.length; i++) listModel.addElement(selectedFiles[i]); selectedFilesList.setModel(listModel); returnCodeLabel.setText(Integer.toString(option)); } public static void main(String[] args) { SwingUtilities.invokeLater (new Runnable() { public void run() { FileChooserDemo app = new FileChooserDemo(); app.initFrameContent(); JFrame frame = new JFrame("LoquetUP"); frame.getContentPane().add(app); frame.setDefaultCloseOperation(3); frame.setSize(600,400); frame.setResizable(false); frame.setLocationRelativeTo(null); //frame.pack(); frame.setVisible(true); } }); } } </code></pre>
0
1,720
Butterknife is unable to bind inside my Adapter Class
<p>I have an Adapter that draws the layouts for my Navigation Drawer. My navigation drawer contains two inner xml files: One being the <code>Header</code> and the other being the <code>Row</code>. I draw these out in a single adapter, but when I'm trying to <code>setText()</code> on my header, I get failure to bind. Here is my adapter class:</p> <pre><code>public class DrawerAdapter extends RecyclerView.Adapter&lt;DrawerAdapter.ViewHolder&gt; { private static final int HEADER_TYPE = 0; private static final int ROW_TYPE = 1; private static Context context; private static DatabaseHelper databaseHelper; private List&lt;String&gt; rows; private List&lt;Integer&gt; icons; private String driverName; public DrawerAdapter(Context context, List&lt;String&gt; rows, List&lt;Integer&gt; icons, String driverName, DatabaseHelper databaseHelper) { this.icons = icons; this.rows = rows; this.context = context; this.driverName = driverName; this.databaseHelper = databaseHelper; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == HEADER_TYPE) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.drawer_header, parent, false); return new ViewHolder(view, viewType); } else if (viewType == ROW_TYPE) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.drawer_row, parent, false); return new ViewHolder(view, viewType); } return null; } @Override public void onBindViewHolder(ViewHolder holder, int position) { if (holder.viewType == ROW_TYPE) { String rowText = rows.get(position - 1); int imageView = icons.get(position - 1); holder.textView.setText(rowText); holder.imageView.setImageResource(imageView); } else if (holder.viewType == HEADER_TYPE) { holder.driverNameText.setText(driverName); } } @Override public int getItemCount() { return rows.size() + 1; } @Override public int getItemViewType(int position) { if (position == 0) return HEADER_TYPE; return ROW_TYPE; } public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { protected int viewType; @Bind(R.id.drawer_row_icon) ImageView imageView; @Bind(R.id.drawer_row_text) TextView textView; @Bind(R.id.drawer_row_id) FrameLayout listRow; @Bind(R.id.driverName) TextView driverNameText; public ViewHolder(View itemView, int viewType) { super(itemView); this.viewType = viewType; if (viewType == ROW_TYPE) { ButterKnife.bind(this, itemView); imageView.setOnClickListener(this); textView.setOnClickListener(this); listRow.setOnClickListener(this); } else { ButterKnife.bind(this, itemView); } } } </code></pre> <p>As you can see in my <code>onCreateViewHolder</code> method, I'm checking for both <code>viewType</code>'s so I know which layout to draw. This in turn will create a new object for the <code>ViewHolder</code> class in which I "TRY" to bind the elements inside my xml depending on the <code>viewType</code>. Am I missing something, or doing something wrongly?</p>
0
1,187
Problems with unixODBC and FreeTDS config
<p>I have been working on this for way too long and can't seem to figure it out. I am sure I have something wrong in my freetds.conf, odbc.ini or odbcinst.ini. I can connect to my mssql 2008 server using tsql, but still can't with isql or of course through php.</p> <p>I am on CentOS 5.6.</p> <p>Can anyone offer some assistance?</p> <p>Thanks! Shawn</p> <p>This is in my sqltrace.log:</p> <pre><code> [ODBC][12249][1347850711.939084][__handles.c][459] Exit:[SQL_SUCCESS] Environment = 0x1b5fc6c0 [ODBC][12249][1347850711.939149][SQLAllocHandle.c][375] Entry: Handle Type = 2 Input Handle = 0x1b5fc6c0 [ODBC][12249][1347850711.939187][SQLAllocHandle.c][493] Exit:[SQL_SUCCESS] Output Handle = 0x1b5fcff0 [ODBC][12249][1347850711.939231][SQLConnect.c][3654] Entry: Connection = 0x1b5fcff0 Server Name = [MSSQL_DSN][length = 9 (SQL_NTS)] User Name = [InetIndyArtsRemote][length = 18 (SQL_NTS)] Authentication = [**********][length = 10 (SQL_NTS)] UNICODE Using encoding ASCII 'ISO8859-1' and UNICODE 'UCS-2LE' DIAG [01000] [FreeTDS][SQL Server]Unexpected EOF from the server DIAG [01000] [FreeTDS][SQL Server]Adaptive Server connection failed DIAG [S1000] [FreeTDS][SQL Server]Unable to connect to data source [ODBC][12249][1347850711.949640][SQLConnect.c][4021] Exit:[SQL_ERROR] [ODBC][12249][1347850711.949694][SQLFreeHandle.c][286] Entry: Handle Type = 2 Input Handle = 0x1b5fcff0 [ODBC][12249][1347850711.949735][SQLFreeHandle.c][337] Exit:[SQL_SUCCESS] [ODBC][12249][1347850711.949773][SQLFreeHandle.c][219] Entry: Handle Type = 1 Input Handle = 0x1b5fc6c0 </code></pre> <p>freetds.conf:</p> <pre><code> # $Id: freetds.conf,v 1.12 2007/12/25 06:02:36 jklowden Exp $ # # This file is installed by FreeTDS if no file by the same # name is found in the installation directory. # # For information about the layout of this file and its settings, # see the freetds.conf manpage "man freetds.conf". # Global settings are overridden by those in a database # server specific section [global] # TDS protocol version tds version = 8.0 # Whether to write a TDSDUMP file for diagnostic purposes # (setting this to /tmp is insecure on a multi-user system) dump file = /tmp/freetds.log debug flags = 0xffff dump file append = yes # Command and connection timeouts ; timeout = 10 ; connect timeout = 10 # If you get out-of-memory errors, it may mean that your client # is trying to allocate a huge buffer for a TEXT field. # Try setting 'text size' to a more reasonable limit text size = 64512 [IndyArtsDB] host = xxx.xx.xxx.xx port = 1433 tds version = 8.0 client charset = UTF-8 </code></pre> <p>ODBC.INI</p> <pre><code>[MSSQL_DSN] Driver=FreeTDS Description=IndyArts DB on Rackspace Trace=No Server=xxx.xx.xxx.xx Port=1433 Database=DBName </code></pre> <p>ODCBINST.INI</p> <pre><code>[ODBC] DEBUG=1 TraceFile=/home/ftp/sqltrace.log Trace=Yes [FreeTDS] Description=MSSQL Driver Driver=/usr/local/lib/libtdsodbc.so UsageCount=1 </code></pre>
0
1,550
jQuery Validation plugin: submitHandler not preventing default on submit when making ajax call to servlet - return false not working
<p>I have a simple form that uses jquery and a servlet. The jquery makes an ajax call to the servlet, the servlet makes some server side calculations, then displays the results on the same page via jQuery. I don't want the form to do a default submit (and go to the servlet) because I want to stay on the same page and display results dynamically. It works exactly how I want it to as is:</p> <p>HTML:</p> <pre><code>&lt;form name="form1" action="FormHandler1" method="POST" class="stats-form"&gt; &lt;input class="stats-input" id="number0" type="text" name="number0"&gt; &lt;input id="number1" type="text" name="number1"&gt; &lt;input id="number2" type="text" name="number2"&gt; &lt;input id="number3" type="text" name="number3"&gt; &lt;input type="submit" value="Calculate" class="calculate-stats" name="stats-submit"&gt; &lt;/form&gt; </code></pre> <p>jQuery:</p> <pre><code>form.submit (function(event) { $.ajax({ type: form.attr("method"), // use method specified in form attributes url: form.attr("action"), // use action specified in form attributes (servlet) data: form.serialize(), // encodes set of form elements as string for submission success: function(data) { // get response form servlet and display on page via jquery } }); event.preventDefault(); // stop form from redirecting to java servlet page }); </code></pre> <p>Now, I wanted to add form validation, since the servlet expects decimal numbers to do it's calculations. The user should only be allowed to enter numbers, no other characters. To do this I adopted the popular <a href="http://jqueryvalidation.org/" rel="nofollow">jQuery Validation</a> plugin. </p> <p>The validation works as expected, but to make my ajax call to the servlet I have to use the submitHandler jQuery Validation provides, instead of the jQuery submit method shown above. When I use the validation submitHandler, the default action of the form on submit is executed, going to the servlet page instead of staying on the same page to display my results dynamically in jQuery. I have to pass the formHandler a form, instead of an event like before, which allowed me to prevent the default action. The only option is to return false, but it doesn't work. I've been trying to figure this out for the past two days, and have pretty much exhausted my google-fu. Here is the new code giving me grief:</p> <pre><code>form.validate({ rules: { number0: ruleSet, number1: ruleSet, number2: ruleSet, number3: ruleSet, }, submitHandler: function (form) { $.ajax({ type: "POST", url: form.attr("action"), data: form.serialize(), success: function () { // get response from servlet and display on page via jQuery } }); return false; // required to block normal submit ajax used } }); </code></pre> <p>Any help would be appreciated, I'd like to use this neat jQuery form validation, but I may just write my own jQuery validation from scratch so that I can use the form submit method that I already have working.</p>
0
1,155
C# MemoryStream - Timeouts are not supported on this stream
<p>I'm trying to create a csv file dynamially and output the stream to the browser.</p> <p>Here is my api end point:</p> <pre><code> [System.Web.Http.HttpGet] [System.Web.Http.Route("export-to-csv")] public FileStreamResult ExportDeposits([FromUri(Name = "")]DepositSearchParamsVM depositSearchParamsVM) { if (depositSearchParamsVM == null) { depositSearchParamsVM = new DepositSearchParamsVM(); } var records = _DepositsService.SearchDeposits(depositSearchParamsVM); var result = _DepositsService.WriteCsvToMemory(records); var memoryStream = new MemoryStream(result); return new FileStreamResult(memoryStream, "text/csv") { FileDownloadName = "export.csv" }; } </code></pre> <p>Here is my service method:</p> <pre><code>public byte[] WriteCsvToMemory(IEnumerable&lt;DepositSummaryVM&gt; records) { using (var stream = new MemoryStream()) using (var reader = new StreamReader(stream)) using (var writer = new StreamWriter(stream)) using (var csv = new CsvWriter(writer)) { csv.WriteRecords(records); writer.Flush(); stream.Position = 0; var text = reader.ReadToEnd(); return stream.ToArray(); </code></pre> <p>}</p> <pre><code> } </code></pre> <p>Here is the error message:</p> <blockquote> <p>{ "message": "An error has occurred.", "exceptionMessage": "Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.",<br> "exceptionType": "Newtonsoft.Json.JsonSerializationException",<br> "stackTrace": " at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract&amp; memberContract, Object&amp; memberValue)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Owin.HttpMessageHandlerAdapter.d__13.MoveNext()", "innerException": { "message": "An error has occurred.", "exceptionMessage": "Timeouts are not supported on this stream.", "exceptionType": "System.InvalidOperationException", "stackTrace": " at System.IO.Stream.get_ReadTimeout()\r\n at GetReadTimeout(Object )\r\n at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)" } }</p> </blockquote>
0
1,662
The entity or complex type ... cannot be constructed in a LINQ to Entities query
<p>Why does one method work but not the other, when it seems they are both doing the same thing, i.e. constructing an entity. My question then, is there a way to construct the entity in a L2E query instead of having to use just Linq or indeed both?</p> <p>This works fine...</p> <pre><code>var queryToList = (from ac in ctx.AuthorisationChecks where wedNumbers.Contains(ac.WedNo) orderby ac.WedNo, ac.ExpAuthDate, ac.ActAuthDate select new AuthorisationCheck { Blah = ac.Blah }).ToList(); model.AuthorisationChecks = queryToList.Select(x =&gt; new AuthorisationCheck { Blah = x.Blah }).ToList(); </code></pre> <p>However, if i change...</p> <pre><code>var queryToList </code></pre> <p>to</p> <pre><code>model.AuthorisationChecks queryToList // Of type List&lt;AuthorisationCheck&gt; </code></pre> <p>i get the error in the Title...</p> <pre><code>The entity or complex type 'Model.AuthorisationCheck' cannot be constructed in a LINQ to Entities query. </code></pre> <p><strong>EDIT:</strong> In the model it is simply, nothing fancy here.</p> <pre><code>public List&lt;AuthorisationCheck&gt; AuthorisationChecks { get; set; } </code></pre> <p><strong>EDIT2:</strong> Tidied this up a little to be (which works fine)...</p> <pre><code>model.AuthorisationChecks = (from ac in ctx.AuthorisationChecks where wedNumbers.Contains(ac.WedNo) orderby ac.WedNo, ac.ExpAuthDate, ac.ActAuthDate select ac).ToList() .Select(x =&gt; new AuthorisationCheck { Blah = x.Blah }).ToList(); </code></pre> <p><strong>EDIT2: My Solution</strong> I wasn't happy with the anonymous type method and so went ahead and created a simple model containing only the properties I required to be used in the viewmodel.</p> <p>Changed the type of model.AuthorisationChecks</p> <p>from </p> <pre><code>List&lt;AuthorisationCheck&gt; // List of Entities </code></pre> <p>to</p> <pre><code>List&lt;AuthorisationCheckModel&gt; // List of models </code></pre> <p>which allows the following code to work, and without profiling it seems a lot quicker than using an anonymous type (and of course I don't cast to a list twice!).</p> <pre><code>model.AuthorisationChecks = (from ac in ctx.AuthorisationChecks where wedNumbers.Contains(ac.WedNo) orderby ac.WedNo, ac.ExpAuthDate, ac.ActAuthDate select new AuthorisationCheckModel { Blah = x.Blah }).ToList(); </code></pre> <p>P.S. I was once warned by a coworker (who used to work for Microsoft) that it isn't a good idea to directly use Entities in this manner, maybe this was one of the reasons he was thinking of, I've also noticed some odd behavior using Entities directly in other cases (mainly corruptions).</p>
0
1,379
ClassNotFoundException: Didn't find class "com.google.android.gms.ads.AdView"
<p>I did a lot of research and this seems to be a common error for many users but for very different reasons. None of which I found worked for me.</p> <p>I'm getting</p> <pre><code>java.lang.RuntimeException: Unable to start activity ComponentInfo{ [...]/[...].activities.StartActivity}: android.view.InflateException: Binary XML file line #173: Error inflating class [...].BannerAd [...] Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class com.google.android.gms.ads.AdView [...] Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.ads.AdView" on path: DexPathList[[zip file "/data/app/[...]-1.apk"],nativeLibraryDirectories=[/data/app-lib/[...]-1, /vendor/lib, /system/lib]] </code></pre> <p>I'm having the newest versions of ADT and SDK packages installed. I copied google-play-services_lib to my workspace and imported it as a Android project. I added it as a library to my app project. I checked everything under "Order and Export".</p> <p>I'm having a banner_ad.xml:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal|top" android:orientation="vertical" &gt; &lt;com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto" android:id="@+id/adView" android:layout_width="match_parent" android:layout_height="wrap_content" ads:adSize="BANNER" ads:adUnitId="[...]" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>And a BannerAd.java which I am using:</p> <pre><code>package [...]; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.LinearLayout; import [...].R; import [...].general.Settings; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; public class BannerAd extends LinearLayout { public BannerAd(Context context, AttributeSet attrs) { super(context, attrs); if (!Settings.PRO) { LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mInflater.inflate(R.layout.banner_ad, this, true); AdView adView = (AdView) this.findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); adView.loadAd(adRequest); } } } </code></pre> <p>Could it have something to do with proguard? I have no idea, this is my proguard-project.txt file, however:</p> <pre><code># To enable ProGuard in your project, edit project.properties # to define the proguard.config property as described in that file. # # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in ${sdk.dir}/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the ProGuard # include property in project.properties. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} -keep class * extends java.util.ListResourceBundle { protected Object[][] getContents(); } -keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable { public static final *** NULL; } -keepnames @com.google.android.gms.common.annotation.KeepName class * -keepclassmembernames class * { @com.google.android.gms.common.annotation.KeepName *; } -keepnames class * implements android.os.Parcelable { public static final ** CREATOR; } </code></pre> <p>Any ideas what I could try to fix this?</p> <p>Edit: Sometimes, I also get such output in the console (but not every time I compile, only sometimes):</p> <pre><code>[2014-07-24 12:49:05 - [...]] Dx trouble processing: [2014-07-24 12:49:05 - [...]] Dx bad class file magic (cafebabe) or version (0033.0000) ...while parsing com/google/android/gms/internal/mb.class ...while processing com/google/android/gms/internal/mb.class [2014-07-24 12:49:05 - [...]] Dx trouble processing: [2014-07-24 12:49:05 - [...]] Dx bad class file magic (cafebabe) or version (0033.0000) ...while parsing com/google/android/gms/internal/mc.class ...while processing com/google/android/gms/internal/mc.class [2014-07-24 12:49:05 - [...]] Dx [...] [Lots of similar warnings here] [...] trouble processing: [2014-07-24 12:49:25 - [...]] Dx bad class file magic (cafebabe) or version (0033.0000) ...while parsing com/google/ads/mediation/customevent/CustomEventAdapter$a.class ...while processing com/google/ads/mediation/customevent/CustomEventAdapter$a.class [2014-07-24 12:49:25 - [...]] Dx trouble processing: [2014-07-24 12:49:25 - [...]] Dx bad class file magic (cafebabe) or version (0033.0000) ...while parsing com/google/ads/mediation/customevent/CustomEventServerParameters.class ...while processing com/google/ads/mediation/customevent/CustomEventServerParameters.class [2014-07-24 12:49:25 - [...]] Dx 2786 warnings </code></pre>
0
1,905
Which .NET collection is faster: enumerating foreach Dictionary<>.Values or List<>?
<p>Are one of these enumerations faster than the other or about the same? (example in C#)</p> <p>Case 1:</p> <pre><code>Dictionary&lt;string, object&gt; valuesDict; // valuesDict loaded with thousands of objects foreach (object value in valuesDict.Values) { /* process */ } </code></pre> <p>Case 2:</p> <pre><code>List&lt;object&gt; valuesList; // valuesList loaded with thousands of objects foreach (object value in valuesList) { /* process */ } </code></pre> <p>UPDATE:</p> <p>Background:</p> <p>The dictionary would be beneficial for keyed search elsewhere (as opposed to iterating through a list), but the benefit would be diminished if iterating through the dictionary is much slower than going through the list.</p> <p>UPDATE: Taking the advice of many, I've done my own testing.</p> <p>First, these are the results. Following is the program.</p> <p>Iterate whole collection Dict: 78 Keyd: 131 List: 76</p> <p>Keyed search collection Dict: 178 Keyd: 194 List: 142800</p> <pre><code>using System; using System.Linq; namespace IterateCollections { public class Data { public string Id; public string Text; } public class KeyedData : System.Collections.ObjectModel.KeyedCollection&lt;string, Data&gt; { protected override string GetKeyForItem(Data item) { return item.Id; } } class Program { static void Main(string[] args) { var dict = new System.Collections.Generic.Dictionary&lt;string, Data&gt;(); var list = new System.Collections.Generic.List&lt;Data&gt;(); var keyd = new KeyedData(); for (int i = 0; i &lt; 10000; i++) { string s = i.ToString(); var d = new Data { Id = s, Text = s }; dict.Add(d.Id, d); list.Add(d); keyd.Add(d); } var sw = new System.Diagnostics.Stopwatch(); sw.Start(); for (int r = 0; r &lt; 1000; r++) { foreach (Data d in dict.Values) { if (null == d) throw new ApplicationException(); } } sw.Stop(); var dictTime = sw.ElapsedMilliseconds; sw.Reset(); sw.Start(); for (int r = 0; r &lt; 1000; r++) { foreach (Data d in keyd) { if (null == d) throw new ApplicationException(); } } sw.Stop(); var keydTime = sw.ElapsedMilliseconds; sw.Reset(); sw.Start(); for (int r = 0; r &lt; 1000; r++) { foreach (Data d in list) { if (null == d) throw new ApplicationException(); } } sw.Stop(); var listTime = sw.ElapsedMilliseconds; Console.WriteLine("Iterate whole collection"); Console.WriteLine("Dict: " + dictTime); Console.WriteLine("Keyd: " + keydTime); Console.WriteLine("List: " + listTime); sw.Reset(); sw.Start(); for (int r = 0; r &lt; 1000; r++) { for (int i = 0; i &lt; 10000; i += 10) { string s = i.ToString(); Data d = dict[s]; if (null == d) throw new ApplicationException(); } } sw.Stop(); dictTime = sw.ElapsedMilliseconds; sw.Reset(); sw.Start(); for (int r = 0; r &lt; 1000; r++) { for (int i = 0; i &lt; 10000; i += 10) { string s = i.ToString(); Data d = keyd[s]; if (null == d) throw new ApplicationException(); } } sw.Stop(); keydTime = sw.ElapsedMilliseconds; sw.Reset(); sw.Start(); for (int r = 0; r &lt; 10; r++) { for (int i = 0; i &lt; 10000; i += 10) { string s = i.ToString(); Data d = list.FirstOrDefault(item =&gt; item.Id == s); if (null == d) throw new ApplicationException(); } } sw.Stop(); listTime = sw.ElapsedMilliseconds * 100; Console.WriteLine("Keyed search collection"); Console.WriteLine("Dict: " + dictTime); Console.WriteLine("Keyd: " + keydTime); Console.WriteLine("List: " + listTime); } } </code></pre> <p>}</p> <p>UPDATE:</p> <p>Comparison of Dictionary with KeyedCollection as suggested by @Blam.</p> <p>The fastest method is iterating over an Array of KeyedCollection Items.</p> <p>Note, however, that iterating over the dictionary values is faster than over the KeyedCollection without converting to an array.</p> <p>Note that iterating over the dictionary values is much, much faster than over the dictionary collection.</p> <pre><code> Iterate 1,000 times over collection of 10,000 items Dictionary Pair: 519 ms Dictionary Values: 95 ms Dict Val ToArray: 92 ms KeyedCollection: 141 ms KeyedC. ToArray: 17 ms </code></pre> <p>Timings are from a Windows console application (Release build). Here is the source code:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; namespace IterateCollections { public class GUIDkeyCollection : System.Collections.ObjectModel.KeyedCollection&lt;Guid, GUIDkey&gt; { // This parameterless constructor calls the base class constructor // that specifies a dictionary threshold of 0, so that the internal // dictionary is created as soon as an item is added to the // collection. // public GUIDkeyCollection() : base() { } // This is the only method that absolutely must be overridden, // because without it the KeyedCollection cannot extract the // keys from the items. // protected override Guid GetKeyForItem(GUIDkey item) { // In this example, the key is the part number. return item.Key; } public GUIDkey[] ToArray() { return Items.ToArray(); } //[Obsolete("Iterate using .ToArray()", true)] //public new IEnumerator GetEnumerator() //{ // throw new NotImplementedException("Iterate using .ToArray()"); //} } public class GUIDkey : Object { private Guid key; public Guid Key { get { return key; } } public override bool Equals(Object obj) { //Check for null and compare run-time types. if (obj == null || !(obj is GUIDkey)) return false; GUIDkey item = (GUIDkey)obj; return (Key == item.Key); } public override int GetHashCode() { return Key.GetHashCode(); } public GUIDkey(Guid guid) { key = guid; } } class Program { static void Main(string[] args) { const int itemCount = 10000; const int repetitions = 1000; const string resultFormat = "{0,18}: {1,5:D} ms"; Console.WriteLine("Iterate {0:N0} times over collection of {1:N0} items", repetitions, itemCount); var dict = new Dictionary&lt;Guid, GUIDkey&gt;(); var keyd = new GUIDkeyCollection(); for (int i = 0; i &lt; itemCount; i++) { var d = new GUIDkey(Guid.NewGuid()); dict.Add(d.Key, d); keyd.Add(d); } var sw = new System.Diagnostics.Stopwatch(); long time; sw.Reset(); sw.Start(); for (int r = 0; r &lt; repetitions; r++) { foreach (KeyValuePair&lt;Guid, GUIDkey&gt; w in dict) { if (null == w.Value) throw new ApplicationException(); } } sw.Stop(); time = sw.ElapsedMilliseconds; Console.WriteLine(resultFormat, "Dictionary Pair", time); sw.Reset(); sw.Start(); for (int r = 0; r &lt; repetitions; r++) { foreach (GUIDkey d in dict.Values) { if (null == d) throw new ApplicationException(); } } sw.Stop(); time = sw.ElapsedMilliseconds; Console.WriteLine(resultFormat, "Dictionary Values", time); sw.Reset(); sw.Start(); for (int r = 0; r &lt; repetitions; r++) { foreach (GUIDkey d in dict.Values.ToArray()) { if (null == d) throw new ApplicationException(); } } sw.Stop(); time = sw.ElapsedMilliseconds; Console.WriteLine(resultFormat, "Dict Val ToArray", time); sw.Reset(); sw.Start(); for (int r = 0; r &lt; repetitions; r++) { foreach (GUIDkey d in keyd) { if (null == d) throw new ApplicationException(); } } sw.Stop(); time = sw.ElapsedMilliseconds; Console.WriteLine(resultFormat, "KeyedCollection", time); sw.Reset(); sw.Start(); for (int r = 0; r &lt; repetitions; r++) { foreach (GUIDkey d in keyd.ToArray()) { if (null == d) throw new ApplicationException(); } } sw.Stop(); time = sw.ElapsedMilliseconds; Console.WriteLine(resultFormat, "KeyedC. ToArray", time); } } } </code></pre>
0
5,204
Spring Boot Microservice cant connect to Eureka Server
<p>I try to connect my service (auth-service) to the Eureka Server for the service registry. The Eureka server is running, but when I try to connect the auth-service nothing happens.</p> <p>I added the configurations to application.yaml and application.properties, but nothing helped.</p> <p>application.yaml from auth-service:</p> <pre><code>eureka: client: fetchRegistry: true registryFetchIntervalSeconds: 5 serviceUrl: defaultZone: http://localhost:8761/eureka instance: preferIpAddress: true </code></pre> <p>URL of Eureka server: <a href="http://localhost:8761/" rel="nofollow noreferrer">http://localhost:8761/</a></p> <p>DS Replicas: localhost</p> <p>Message when I start auth-service:</p> <pre><code>2019-05-24 16:58:11.457 INFO [auth-service,,,] 14704 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2019-05-24 16:58:13.293 INFO [auth-service,,,] 14704 --- [ main] o.s.cloud.commons.util.InetUtils : Cannot determine local hostname 2019-05-24 16:58:14.521 INFO [auth-service,,,] 14704 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2019-05-24 16:58:14.524 INFO [auth-service,,,] 14704 --- [ main] d.h.authservice.AuthServiceApplication : Started AuthServiceApplication in 11.448 seconds (JVM running for 12.63) </code></pre> <p>The Eureka Server is annotated with @EnableEurekaServer and the Client is annotated with @EnableDiscoveryClient</p> <p>auth-service pom:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;2.1.4.RELEASE&lt;/version&gt; &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;groupId&gt;de.hspf&lt;/groupId&gt; &lt;artifactId&gt;auth-service&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;auth-service&lt;/name&gt; &lt;description&gt;Demo project for Spring Boot&lt;/description&gt; &lt;properties&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;spring-cloud.version&gt;Greenwich.RELEASE&lt;/spring-cloud.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.postgresql&lt;/groupId&gt; &lt;artifactId&gt;postgresql&lt;/artifactId&gt; &lt;version&gt;42.2.5&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate.javax.persistence&lt;/groupId&gt; &lt;artifactId&gt;hibernate-jpa-2.0-api&lt;/artifactId&gt; &lt;version&gt;1.0.1.Final&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.security&lt;/groupId&gt; &lt;artifactId&gt;spring-security-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.sendgrid&lt;/groupId&gt; &lt;artifactId&gt;sendgrid-java&lt;/artifactId&gt; &lt;version&gt;4.1.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt; &lt;artifactId&gt;jjwt&lt;/artifactId&gt; &lt;version&gt;0.9.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.modelmapper&lt;/groupId&gt; &lt;artifactId&gt;modelmapper&lt;/artifactId&gt; &lt;version&gt;1.1.0&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.thymeleaf&lt;/groupId&gt; &lt;artifactId&gt;thymeleaf-spring3&lt;/artifactId&gt; &lt;version&gt;3.0.8.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.xmlunit&lt;/groupId&gt; &lt;artifactId&gt;xmlunit-core&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-sleuth-zipkin&lt;/artifactId&gt; &lt;version&gt;2.1.1.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-netflix-eureka-client&lt;/artifactId&gt; &lt;version&gt;2.0.1.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-starter&lt;/artifactId&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;dependencyManagement&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt; &lt;version&gt;Finchley.M9&lt;/version&gt; &lt;type&gt;pom&lt;/type&gt; &lt;scope&gt;import&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/dependencyManagement&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p></p> <p>Discovery Service pom</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.example&lt;/groupId&gt; &lt;artifactId&gt;discovery-server&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;name&gt;discovery-server&lt;/name&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;2.1.2.RELEASE&lt;/version&gt; &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;spring-cloud.version&gt;Greenwich.RELEASE&lt;/spring-cloud.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-server&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;dependencyManagement&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt; &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt; &lt;version&gt;Finchley.M9&lt;/version&gt; &lt;type&gt;pom&lt;/type&gt; &lt;scope&gt;import&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/dependencyManagement&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;repositories&gt; &lt;repository&gt; &lt;id&gt;spring-milestones&lt;/id&gt; &lt;name&gt;Spring Milestones&lt;/name&gt; &lt;url&gt;https://repo.spring.io/milestone&lt;/url&gt; &lt;snapshots&gt; &lt;enabled&gt;false&lt;/enabled&gt; &lt;/snapshots&gt; &lt;/repository&gt; &lt;/repositories&gt; </code></pre> <p></p>
0
4,721
How to set linker flags for OpenMP in CMake's try_compile function
<p>I would like to verify that the current compiler can build with openmp support. The application has do deploy across a wide variety of unix systems, some of which might have old versions of OpenMP, and I would like to test for important OpenMP functionality. So, I want to build a test source file that incorporates some of the OpenMP calls.</p> <p>Thus, I created a very simple test file, and attempted to use the try_compile function from CMake. Ufortunately, it doesn't seem to apply the -fopenmp linker flag correctly. Does anyone know how to either force the linker flag or to see if the linker flag is being applied anywhere?</p> <p>from CMakeLists.txt</p> <pre><code>try_compile( HAVE_OPENMP ${APBS_ROOT}/src/config ${APBS_ROOT}/src/config/omp_test.c CMAKE_FLAGS "-DCMAKE_C_FLAGS=-fopenmp -DCMAKE_EXE_LINKER_FLAGS=-fopenmp" OUTPUT_VARIABLE TRY_COMPILE_OUTPUT ) </code></pre> <p>from omp_test.c</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;omp.h&gt; int main() { int i; int threadID = 0; #pragma omp parallel for private(i, threadID) for(i = 0; i &lt; 16; i++ ) { threadID = omp_get_thread_num(); #pragma omp critical { printf("Thread %d reporting\n", threadID); } } return 0; } </code></pre> <p>The resulting output is</p> <pre><code>Change Dir: src/config/CMakeFiles/CMakeTmp Run Build Command:/usr/bin/make "cmTryCompileExec/fast" /usr/bin/make -f CMakeFiles/cmTryCompileExec.dir/build.make CMakeFiles/cmTryCompileExec.dir/build make[1]: Entering directory `src/config/CMakeFiles/CMakeTmp' /usr/bin/cmake -E cmake_progress_report /data/work/source/apbs/src/config/CMakeFiles/CMakeTmp/CMakeFiles 1 Building C object CMakeFiles/cmTryCompileExec.dir/omp_test.c.o /usr/bin/gcc -o CMakeFiles/cmTryCompileExec.dir/omp_test.c.o -c /data/work/source/apbs/src/config/omp_test.c Linking C executable cmTryCompileExec /usr/bin/cmake -E cmake_link_script CMakeFiles/cmTryCompileExec.dir/link.txt --verbose=1 /usr/bin/gcc CMakeFiles/cmTryCompileExec.dir/omp_test.c.o -o cmTryCompileExec -rdynamic CMakeFiles/cmTryCompileExec.dir/omp_test.c.o: In function `main': omp_test.c:(.text+0x19): undefined reference to `omp_get_thread_num' collect2: ld returned 1 exit status make[1]: *** [cmTryCompileExec] Error 1 make[1]: Leaving directory `src/config/CMakeFiles/CMakeTmp' make: *** [cmTryCompileExec/fast] Error 2 CMake Error at CMakeLists.txt:688 (message): Test OpenMP program would not build. OpenMP disabled </code></pre> <p>When I try to compile the test program on the command line, it works fine</p> <pre><code>src/config$ gcc -fopenmp omp_test.c -o omp_test &amp;&amp; ./omp_test Thread 1 reporting Thread 4 reporting Thread 7 reporting Thread 11 reporting Thread 9 reporting Thread 12 reporting Thread 6 reporting Thread 8 reporting Thread 15 reporting Thread 13 reporting Thread 10 reporting Thread 0 reporting Thread 3 reporting Thread 2 reporting Thread 5 reporting Thread 14 reporting </code></pre>
0
1,139
System.DirectoryServices.DirectoryServicesCOMException: An operations error occurred
<p>I have the same web app working in three others servers. Anyone have any idea why is not working in the 4th server? See the error and stacktrace:</p> <blockquote> <p><em>An operations error occurred.</em></p> <p><em>Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.</em></p> <p><em>Exception Details:<br> System.DirectoryServices.DirectoryServicesCOMException: An operations error occurred.</em></p> <p><em>Source Error:</em></p> <p><em>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</em></p> <p><em>Stack Trace:</em></p> <p><em>[DirectoryServicesCOMException (0x80072020): An operations error occurred. ] System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +454 System.DirectoryServices.DirectoryEntry.Bind() +36 System.DirectoryServices.DirectoryEntry.get_AdsObject() +31 System.DirectoryServices.PropertyValueCollection.PopulateList() +22<br> System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName) +96<br> System.DirectoryServices.PropertyCollection.get_Item(String propertyName) +142 System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer() +1134 System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit() +37 System.DirectoryServices.AccountManagement.PrincipalContext.Initialize() +124 System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx() +31 System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable'1 identityType, String identityValue, DateTime refDate) +14<br> System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(PrincipalContext context, Type principalType, String identityValue) +73<br> System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, String identityValue) +25<br> Infraero.TINE3.STTEnterprise.Web.Common.Seguranca.ServicoAutenticacao.EfetuarLogin(AcessoUsuario acessoUsuario, String senha) in D:\SVN\STT\trunk\4-0_CodigoFonte_Enterprise\4-4_SRC\Infraero.TINE3.STTEnterprise.Web\Common\Seguranca\ServicoAutenticacao.cs:34 Infraero.TINE3.STTEnterprise.Web.Controllers.LoginController.ValidarUsuarioAD(String matricula, String senha, AcessoUsuario acessoUsuario) in D:\SVN\STT\trunk\4-0_CodigoFonte_Enterprise\4-4_SRC\Infraero.TINE3.STTEnterprise.Web\Controllers\LoginController.cs:92 Infraero.TINE3.STTEnterprise.Web.Controllers.LoginController.ValidarUsuario(String matricula, String senha) in D:\SVN\STT\trunk\4-0_CodigoFonte_Enterprise\4-4_SRC\Infraero.TINE3.STTEnterprise.Web\Controllers\LoginController.cs:80 Infraero.TINE3.STTEnterprise.Web.Controllers.LoginController.Index(LoginViewModel loginViewModel) in D:\SVN\STT\trunk\4-0_CodigoFonte_Enterprise\4-4_SRC\Infraero.TINE3.STTEnterprise.Web\Controllers\LoginController.cs:54 lambda_method(Closure , ControllerBase , Object[] ) +108<br> System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17<br> System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary'2 parameters) +208<br> System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary'2 parameters) +27<br> System.Web.Mvc.&lt;>c__DisplayClass15.b__12() +55 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func'1 continuation) +263<br> System.Web.Mvc.&lt;>c__DisplayClass17.b__14() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList'1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191<br> System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343<br> System.Web.Mvc.Controller.ExecuteCore() +116<br> System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10<br> System.Web.Mvc.&lt;>c__DisplayClassb.b__5() +37<br> System.Web.Mvc.Async.&lt;>c__DisplayClass1.b__0() +21<br> System.Web.Mvc.Async.&lt;>c__DisplayClass8'1.b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult'1.End() +62 System.Web.Mvc.&lt;>c__DisplayClasse.b__d() +50<br> System.Web.Mvc.SecurityUtil.b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60<br> System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9<br> System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8963149 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +184</em></p> </blockquote> <p>EfetuarLogin Method:</p> <pre><code>public static bool EfetuarLogin(User user, string password) { bool isValid = false; if (user != null) { PrincipalContext context = new PrincipalContext(ContextType.Domain); using (context) { isValid = context.ValidateCredentials(user.Login, password); if (isValid) { UserPrincipal userAD = UserPrincipal.FindByIdentity(context, user.Login); MySession.CurrentUser = new MyUserSession() { Id = user.Id, ProfileId = user.ProfileId , Login = user.Login , Name = userAD.Name }; } } } return isValid; } </code></pre>
0
2,221
COBOL Program to read a flat file sequentially and write it to an output file, not able to read at all loop is going infinite
<p>I'm trying to write COBOL Program to read a flat file sequentially and write it to an output file, I'm able to read only one record at a time, not able to read next record what should I do?</p> <p>Here is my code:</p> <pre><code>PROCEDURE DIVISION. OPEN INPUT FILEX. PERFORM READ-PARA THRU END-PARA UNTIL END-OF-FILE = 'Y'. CLOSE FILEX. STOP RUN. READ-PARA. READ FILEX AT END MOVE 'Y' TO END-OF-FILE DISPLAY OFFCODE1 DISPLAY AGCODE1 DISPLAY POLNO1 DISPLAY EFFDATE1 DISPLAY EXPDATE DISPLAY REPCODE DISPLAY POLHOLDER1 DISPLAY LOCATION1 GO TO END-PARA. END-PARA. </code></pre> <p>i, ve tried using the scope terminator, still not able to loop 'm getting S001 ABEND here is my code :</p> <pre><code>IDENTIFICATION DIVISION. PROGRAM-ID. SIMPLE. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT FILEX ASSIGN TO SYSUT1 FILE STATUS IS FS. DATA DIVISION. FILE SECTION. FD FILEX. 01 FILEXREC. 02 OFFCODE1 PIC X(3). 02 FILLER PIC X. 02 AGCODE1 PIC X(3). 02 FILLER PIC X. 02 POLNO1 PIC X(6). 02 FILLER PIC X. 02 EFFDATE1 PIC X(8). 02 FILLER PIC X. 02 EXPDATE PIC X(8). 02 FILLER PIC X. 02 REPCODE PIC X(1) 02 FILLER PIC X. 02 POLHOLDER1 PIC X(8). 02 FILLER PIC X. 02 LOCATION1 PIC X(9). 02 FILLER PIC X(87). WORKING-STORAGE SECTION. 77 FS PIC 9(2). 01 WS-INDICATORS. 10 WS-EOF-IND PIC X(01) VALUE 'N'. 88 WS-END-OF-FILE VALUE 'Y'. PROCEDURE DIVISION. OPEN INPUT FILEX. PERFORM READ-PARA THRU END-PARA UNTIL WS-END-OF-FILE. CLOSE FILEX. STOP RUN. READ-PARA. READ FILEX AT END MOVE 'Y' TO WS-EOF-IND. DISPLAY OFFCODE1 DISPLAY AGCODE1 DISPLAY POLNO1 DISPLAY EFFDATE1 DISPLAY EXPDATE DISPLAY REPCODE DISPLAY POLHOLDER1 DISPLAY LOCATION1 IF WS-END-OF-FILE GO TO END-PARA. END-PARA. EXIT. </code></pre> <p>one more method i tried even in this works for only one record, again getting S001 ABEND while running the code. Here is the code:</p> <pre><code> IDENTIFICATION DIVISION. PROGRAM-ID. ASSIGNMENT. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT FILEX ASSIGN TO SYSUT1 DATA DIVISION. FILE SECTION. FD FILEX. LABEL RECORDS ARE STANDARD RECORD CONTAINS 140 CHARACTERS BLOCK CONTAINS 00 RECORDS. 01 FILEXREC. 02 OFFCODE1 PIC 9(3). 02 FILLER PIC X. 02 AGCODE1 PIC X(3). 02 FILLER PIC X. 02 POLNO1 PIC X(6). 02 FILLER PIC X. 02 EFFDATE1 PIC X(8). 02 FILLER PIC X. 02 EXPDATE1 PIC X(8). 02 FILLER PIC X. 02 REPCODE1 PIC X(1). 02 FILLER PIC X. 02 POLHOLDER1 PIC X(8). 02 FILLER PIC X. 02 LOCATION1 PIC X(9). 02 FILLER PIC X(26). WORKING-STORAGE SECTION. 01 WS-INDICATORS. 10 WS-EOF-IND PIC X(01) VALUE 'N'. 88 WS-END-OF-FILE VALUE 'Y'. 01 TEMP1. 02 OFFCODE2 PIC 9(3). 02 FILLER PIC X. 02 AGCODE2 PIC X(3). 02 FILLER PIC X. 02 POLNO2 PIC X(6). 02 FILLER PIC X. 02 EFFDATE2 PIC X(8). 02 FILLER PIC X. 02 EXPDATE2 PIC X(8). 02 FILLER PIC X. 02 REPCODE2 PIC X(1). 02 FILLER PIC X. 02 POLHOLDER2 PIC X(8). 02 FILLER PIC X. 02 LOCATION2 PIC X(9). 02 FILLER PIC X(26). PROCEDURE DIVISION. OPEN INPUT FILEX. PERFORM READ-PARA THRU END-PARA UNTIL WS-END-OF-FILE. CLOSE FILEX. STOP RUN. READ-PARA. READ FILEX INTO TEMP1 AT END MOVE 'Y' TO WS-EOF-IND. DISPLAY OFFCODE1 DISPLAY AGCODE1 DISPLAY POLNO1 DISPLAY EFFDATE1 DISPLAY EXPDATE1 DISPLAY REPCODE1 DISPLAY POLHOLDER1 DISPLAY LOCATION1 IF WS-END-OF-FILE GO TO END-PARA. END-PARA. EXIT. </code></pre>
0
5,610
Connecting to telnet server and send/recieve data
<p>So I am trying to connect to my telnet server, which works. It recives the first lot of data from the server which is us being asked to enter password to connect. But when I type in the password it does nothing and nothing that is recieved is printed to my console.</p> <p>An example of the output is as follows:</p> <pre><code>Connected to server. Please enter password: Response: MYPASSHERE __BLANK RESPONSE FROM SERVER__ Response: </code></pre> <p><img src="https://puu.sh/flM2h/260ca960cd.png" alt="enter image description here"></p> <p>I am currently using this code</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using System.Threading; namespace _7DaysServerManager { public class ServerSocket { private TcpClient client; private Thread readWriteThread; private NetworkStream networkStream; private string password; public ServerSocket(string ip, int port) { try { client = new TcpClient(ip, port); Console.WriteLine("Connected to server."); } catch (SocketException) { Console.WriteLine("Failed to connect to server"); return; } //Assign networkstream networkStream = client.GetStream(); //start socket read/write thread readWriteThread = new Thread(readWrite); readWriteThread.Start(); } private void readWrite() { string command, recieved; //Read first thing givent o us recieved = read(); Console.WriteLine(recieved); //Set up connection loop while (true) { Console.Write("Response: "); command = Console.ReadLine(); if (command == "exit") break; write(command); recieved = read(); Console.WriteLine(recieved); } Console.WriteLine("Disconnected from server"); networkStream.Close(); client.Close(); } public void write(string message) { networkStream.Write(Encoding.ASCII.GetBytes(message), 0, message.Length); networkStream.Flush(); } public string read() { byte[] data = new byte[1024]; string recieved = ""; int size = networkStream.Read(data, 0, data.Length); recieved = Encoding.ASCII.GetString(data, 0, size); return recieved; } } } </code></pre>
0
1,259
Using std::ostream as argument to a print function
<p>I have always used <code>cout</code> to print the statement but now I want learn printing by <code>passing the stream</code>, something like <code>void print(std::ostream&amp;) const;</code> my current print function looks like</p> <pre><code>template &lt;class T&gt; void Mystack&lt;T&gt;::print() { for (int i = 0; i &lt;= top; i++) { std::cout &lt;&lt; input[i] &lt;&lt; " "; } } </code></pre> <p>I have 2 questions:</p> <ol> <li>What is the benefit of switching from normal print function that I implemented above to the print function using <code>ostream</code>.</li> <li>How can I implement <code>ostream</code> in my function. I tried to understand <code>ostream</code> from internet source but could not understand. Please help. </li> </ol> <p>Below is the complete running code:</p> <pre><code>//*************STACK CODE***************// //VERY GOOD EXAMPLE TO UNDERSTAND RULE OF THREE FOR BEGINEERS http://www.drdobbs.com/c-made-easier-the-rule-of-three/184401400 //RULE OF THREE : Video : https://www.youtube.com/watch?v=F-7Rpt2D-zo //Thumb Rule : Whenever we have class which has members pointing to heap space we should implement Rule of three. //Concepts : Shallow Copy and Deep Copy #include &lt;iostream&gt; template &lt;class T&gt; class Mystack { private: T *input; int top; int capacity; public: Mystack(); ~Mystack(); void push(T const&amp; x); void pop(); T&amp; topElement() const; bool isEmpty() const; void print(); }; template &lt;class T&gt; Mystack&lt;T&gt;::Mystack() { top = -1; capacity = 5; input = new T[capacity]; } template &lt;class T&gt; Mystack&lt;T&gt;::~Mystack() //Since we are using destructor explictly we need to apply Rule of 3 { delete [] input; } template &lt;class T&gt; void Mystack&lt;T&gt;::push(T const&amp; x) //Passing x by Const Reference // Valus of x cannot be changed now in the function! { if (top + 1 == capacity) { T *vec = new T[capacity * 2]; for (int i = 0; i &lt;= top; i++) { vec[i] = input[i]; } delete []input; // Avoiding Memory Leak. input = vec; capacity *= capacity; } top++; std::cout &lt;&lt; x; std::cout &lt;&lt; &amp;x; input[top] = x; } template &lt;class T&gt; void Mystack&lt;T&gt;::pop() { if (isEmpty()) { throw std::out_of_range("Stack Underflow"); } else { std::cout &lt;&lt; "The popped element is" &lt;&lt; input[top--]; } } template &lt;class T&gt; bool Mystack&lt;T&gt;::isEmpty() const { if (top == -1) { std::cout &lt;&lt; "Is Empty" &lt;&lt; std::endl; return true; } else { std::cout &lt;&lt; "Not Empty" &lt;&lt; std::endl; return false; } } template &lt;class T&gt; T&amp; Mystack&lt;T&gt;::topElement() const { if (top == -1) { throw std::out_of_range("No Element to Display"); } else { std::cout &lt;&lt; "The top element is : " &lt;&lt; input[top]; return input[top]; } } template &lt;class T&gt; void Mystack&lt;T&gt;::print() { for (int i = 0; i &lt;= top; i++) { std::cout &lt;&lt; input[i] &lt;&lt; " "; } } int main() { Mystack&lt;int&gt; s1; Mystack&lt;float&gt; s2; Mystack&lt;char&gt; s3; int choice; int int_elem; float float_elem; char char_elem; std::cout &lt;&lt; "Enter the type of stack" &lt;&lt; std::endl; std::cout &lt;&lt; "1. int "; std::cout &lt;&lt; "2. float "; std::cout &lt;&lt; "3. Char"&lt;&lt; std::endl; std::cin &gt;&gt; choice; if (choice == 1) { int ch = 1; while (ch &gt; 0) { std::cout &lt;&lt; "\n1. Push "; std::cout &lt;&lt; "2. Top "; std::cout &lt;&lt; "3. IsEmpty "; std::cout &lt;&lt; "4. Pop "; std::cout &lt;&lt; "5. Exit "; std::cout &lt;&lt; "6. Print"&lt;&lt;std::endl; std::cout &lt;&lt; "Enter the choice" &lt;&lt; std::endl; std::cin &gt;&gt; ch; switch (ch) { case 1: std::cout &lt;&lt; "Enter the number to be pushed" &lt;&lt; std::endl; std::cin &gt;&gt; int_elem; s1.push(int_elem); break; case 2: std::cout &lt;&lt; "Get the TOP Element" &lt;&lt; std::endl; try { s1.topElement(); } catch (std::out_of_range &amp;oor) { std::cerr &lt;&lt; "Out of Range error:" &lt;&lt; oor.what() &lt;&lt; std::endl; } break; case 3: std::cout &lt;&lt; "Check Empty" &lt;&lt; std::endl; s1.isEmpty(); break; case 4: std::cout &lt;&lt; "POP the element" &lt;&lt; std::endl; try { s1.pop(); } catch (const std::out_of_range &amp;oor) { std::cerr &lt;&lt; "Out of Range error: " &lt;&lt; oor.what() &lt;&lt; '\n'; } break; case 5: exit(0); case 6: s1.print(); break; default: std::cout &lt;&lt; "Enter a valid input"; break; } } } else if (choice == 2) { int ch = 1; while (ch &gt; 0) { std::cout &lt;&lt; "\n1. PUSH" &lt;&lt; std::endl; std::cout &lt;&lt; "2. TOP" &lt;&lt; std::endl; std::cout &lt;&lt; "3. IsEmpty" &lt;&lt; std::endl; std::cout &lt;&lt; "4. POP" &lt;&lt; std::endl; std::cout &lt;&lt; "5. EXIT" &lt;&lt; std::endl; std::cout &lt;&lt; "6. Print" &lt;&lt; std::endl; std::cout &lt;&lt; "Enter the choice" &lt;&lt; std::endl; std::cin &gt;&gt; ch; switch (ch) { case 1: std::cout &lt;&lt; "Enter the number to be pushed" &lt;&lt; std::endl; std::cin &gt;&gt; float_elem; s2.push(float_elem); break; case 2: std::cout &lt;&lt; "Get the TOP Element" &lt;&lt; std::endl; try { s2.topElement(); } catch (std::out_of_range &amp;oor) { std::cerr &lt;&lt; "Out of Range error:" &lt;&lt; oor.what() &lt;&lt; std::endl; } break; case 3: std::cout &lt;&lt; "Check Empty" &lt;&lt; std::endl; s2.isEmpty(); break; case 4: std::cout &lt;&lt; "POP the element" &lt;&lt; std::endl; try { s2.pop(); } catch (const std::out_of_range &amp;oor) { std::cerr &lt;&lt; "Out of Range error: " &lt;&lt; oor.what() &lt;&lt; '\n'; } break; case 5: exit(0); case 6: s2.print(); break; default: std::cout &lt;&lt; "Enter a valid input"; break; } } } else if (choice == 3) { int ch = 1; while (ch &gt; 0) { std::cout &lt;&lt; "\n1. PUSH" &lt;&lt; std::endl; std::cout &lt;&lt; "2. TOP" &lt;&lt; std::endl; std::cout &lt;&lt; "3. IsEmpty" &lt;&lt; std::endl; std::cout &lt;&lt; "4. POP" &lt;&lt; std::endl; std::cout &lt;&lt; "5. EXIT" &lt;&lt; std::endl; std::cout &lt;&lt; "6. Print" &lt;&lt; std::endl; std::cout &lt;&lt; "Enter the choice" &lt;&lt; std::endl; std::cin &gt;&gt; ch; switch (ch) { case 1: std::cout &lt;&lt; "Enter the number to be pushed" &lt;&lt; std::endl; std::cin &gt;&gt; char_elem; s3.push(char_elem); break; case 2: std::cout &lt;&lt; "Get the TOP Element" &lt;&lt; std::endl; try { s3.topElement(); } catch (std::out_of_range &amp;oor) { std::cerr &lt;&lt; "Out of Range error:" &lt;&lt; oor.what() &lt;&lt; std::endl; } break; case 3: std::cout &lt;&lt; "Check Empty" &lt;&lt; std::endl; s3.isEmpty(); break; case 4: std::cout &lt;&lt; "POP the element" &lt;&lt; std::endl; try { s3.pop(); } catch (const std::out_of_range &amp;oor) { std::cerr &lt;&lt; "Out of Range error: " &lt;&lt; oor.what() &lt;&lt; '\n'; } break; case 5: exit(0); case 6: s3.print(); break; default: std::cout &lt;&lt; "Enter a valid input"; break; } } } else std::cout &lt;&lt; "Invalid Choice"; std::cin.get(); } </code></pre>
0
5,633
Codeigniter Pagination From Database limit, offset
<p>I started a web application in CI 3.0, everything working smooth, I got my pagination working, but there is a problem wich I cannot figure out...</p> <p>For example, I have the following URL: <strong>localhost/statistics/api_based</strong> When navigate, $query results are displayed, links are generated, OK. But, when I navigate to <strong>page 2</strong> for example, the URL will become: <strong>localhost/statistics/dll_based/index/2</strong> and <strong>page 3</strong> will become <strong>localhost/statistics/api_based/index/3</strong> , so therefore I am using segments. Now the problem is the query that is generated:</p> <pre><code>SELECT * FROM `shield_api` ORDER BY `id` ASC limit 20 offset 2 </code></pre> <p><strong>offset 2</strong> - is the page number 2, and it should be 20, if I am correct. I am displaying 20 results per page, so first page is correctly showing results from 1 - 20, but then page 2 will display results from 2 - 21, so you get my point, it`s not OK...</p> <p>Here is my controller:</p> <pre><code>function index($offset = 0) { // Enable SSL? maintain_ssl ( $this-&gt;config-&gt;item ( "ssl_enabled" ) ); // Redirect unauthenticated users to signin page if (! $this-&gt;authentication-&gt;is_signed_in ()) { redirect ( 'account/sign_in/?continue=' . urlencode ( base_url () . 'statistics/api_based' ) ); } if ($this-&gt;authentication-&gt;is_signed_in ()) { $data ['account'] = $this-&gt;account_model-&gt;get_by_id ( $this-&gt;session-&gt;userdata ( 'account_id' ) ); } $per_page = 20; $qry = "SELECT * FROM `shield_api` ORDER BY `id` ASC"; //$offset = ($this-&gt;uri-&gt;segment ( 4 ) != '' ? $this-&gt;uri-&gt;segment ( 4 ) : 0); $config ['total_rows'] = $this-&gt;db-&gt;query ( $qry )-&gt;num_rows (); $config ['per_page'] = $per_page; $config ['uri_segment'] = 4; $config ['base_url'] = base_url () . '/statistics/api_based/index'; $config ['use_page_numbers'] = TRUE; $config ['page_query_string'] = FALSE; $config ['full_tag_open'] = '&lt;ul class="pagination"&gt;'; $config ['full_tag_close'] = '&lt;/ul&gt;'; $config ['prev_link'] = '&amp;laquo;'; $config ['prev_tag_open'] = '&lt;li&gt;'; $config ['prev_tag_close'] = '&lt;/li&gt;'; $config ['next_link'] = '&amp;raquo;'; $config ['next_tag_open'] = '&lt;li&gt;'; $config ['next_tag_close'] = '&lt;/li&gt;'; $config ['cur_tag_open'] = '&lt;li class="active"&gt;&lt;a href="#"&gt;'; $config ['cur_tag_close'] = '&lt;/a&gt;&lt;/li&gt;'; $config ['num_tag_open'] = '&lt;li&gt;'; $config ['num_tag_close'] = '&lt;/li&gt;'; $config ["num_links"] = round ( $config ["total_rows"] / $config ["per_page"] ); $this-&gt;pagination-&gt;initialize ( $config ); $data ['pagination_links'] = $this-&gt;pagination-&gt;create_links (); //$data ['per_page'] = $this-&gt;uri-&gt;segment ( 4 ); $data ['offset'] = $offset; $qry .= " limit {$per_page} offset {$offset} "; if ($data ['pagination_links'] != '') { $data ['pagermessage'] = 'Showing ' . ((($this-&gt;pagination-&gt;cur_page - 1) * $this-&gt;pagination-&gt;per_page) + 1) . ' to ' . ($this-&gt;pagination-&gt;cur_page * $this-&gt;pagination-&gt;per_page) . ' results, of ' . $this-&gt;pagination-&gt;total_rows; } $data ['result'] = $this-&gt;db-&gt;query ( $qry )-&gt;result_array (); $this-&gt;load-&gt;view ( 'statistics/api_based', isset ( $data ) ? $data : NULL ); } </code></pre> <p>Can someone point me to my problem ? Any help is apreciated.</p>
0
1,609
MSB3411 Could not load Visual C++ component
<p>I have MS Visual Studio 2012 Ultimate and OS is Windows 7, and have nodeJs installed.I wanted to install socket.io using npm,but I get the following error.</p> <pre><code>C:\Users\NEW&gt;npm install socket.io npm http GET https://registry.npmjs.org/socket.io npm http 304 https://registry.npmjs.org/socket.io npm http GET https://registry.npmjs.org/socket.io-client/0.9.11 npm http GET https://registry.npmjs.org/policyfile/0.0.4 npm http GET https://registry.npmjs.org/base64id/0.1.0 npm http GET https://registry.npmjs.org/redis/0.7.3 npm http 304 https://registry.npmjs.org/socket.io-client/0.9.11 npm http 304 https://registry.npmjs.org/base64id/0.1.0 npm http 304 https://registry.npmjs.org/policyfile/0.0.4 npm http 304 https://registry.npmjs.org/redis/0.7.3 npm http GET https://registry.npmjs.org/uglify-js/1.2.5 npm http GET https://registry.npmjs.org/ws npm http GET https://registry.npmjs.org/xmlhttprequest/1.4.2 npm http GET https://registry.npmjs.org/active-x-obfuscator/0.0.1 npm http 304 https://registry.npmjs.org/ws npm http 304 https://registry.npmjs.org/xmlhttprequest/1.4.2 npm http 304 https://registry.npmjs.org/uglify-js/1.2.5 npm http 304 https://registry.npmjs.org/active-x-obfuscator/0.0.1 npm http GET https://registry.npmjs.org/zeparser/0.0.5 npm http GET https://registry.npmjs.org/tinycolor npm http GET https://registry.npmjs.org/commander npm http GET https://registry.npmjs.org/options npm http 304 https://registry.npmjs.org/zeparser/0.0.5 npm http 304 https://registry.npmjs.org/commander npm http 304 https://registry.npmjs.org/tinycolor npm http 304 https://registry.npmjs.org/options &gt; ws@0.4.25 install C:\Users\NEW\node_modules\socket.io\node_modules\socket.io-c lient\node_modules\ws &gt; (node-gyp rebuild 2&gt; builderror.log) || (exit 0) C:\Users\NEW\node_modules\socket.io\node_modules\socket.io-client\node_modules\w s&gt;node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_mo dules\node-gyp\bin\node-gyp.js" rebuild Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch. MSBUILD : error MSB3411: Could not load the Visual C++ component "VCBuild.exe". If the component is not installed, either 1) install the Microsoft Windows SDK for Windows Server 2008 and .NET Framework 3.5, or 2) install Microsoft Visual Studio 2008. [C:\Users\NEW\node_modules\socket.io\node_modules\socket.io-clie nt\node_modules\ws\build\binding.sln] MSBUILD : error MSB3411: Could not load the Visual C++ component "VCBuild.exe". If the component is not installed, either 1) install the Microsoft Windows SDK for Windows Server 2008 and .NET Framework 3.5, or 2) install Microsoft Visual Studio 2008. [C:\Users\NEW\node_modules\socket.io\node_modules\socket.io-clie nt\node_modules\ws\build\binding.sln] socket.io@0.9.13 node_modules\socket.io ├── base64id@0.1.0 ├── policyfile@0.0.4 ├── redis@0.7.3 └── socket.io-client@0.9.11 (xmlhttprequest@1.4.2, uglify-js@1.2.5, active-x-obf uscator@0.0.1, ws@0.4.25) </code></pre> <p>What might be the issue?How can I fix it? </p>
0
1,210
Flutter - Container width and height fit parent
<p>I have a <code>Card</code> widget which includes <code>Column</code> with several other Widgets. One of them is <code>Container</code>.</p> <pre><code>Widget _renderWidget() { return Column( children: &lt;Widget&gt;[ Visibility( visible: _isVisible, child: Container( width: 300, height: 200, decoration: BoxDecoration(border: Border.all(color: Colors.grey)), child: ListView.builder( itemCount: titles.length, itemBuilder: (context, index) { return Card( child: ListTile( leading: Icon(icons[index]), title: Text(titles[index]), ), ); }, )), ), ], ); } </code></pre> <p>Here, if I don't specify <code>width</code> and <code>height</code> I get error. But, is there a way to make them to fit parent element?</p> <p><strong>EDIT</strong></p> <p>Full code:</p> <pre><code>return ListView( children: &lt;Widget&gt;[ Center( child: Container( child: Card( margin: new EdgeInsets.all(20.0), child: new Container( margin: EdgeInsets.all(20.0), width: double.infinity, child: Column( children: &lt;Widget&gt;[ FormBuilder( key: _fbKey, autovalidate: true, child: Column( children: &lt;Widget&gt;[ FormBuilderDropdown( onChanged: (t) { setState(() { text = t.vrsta; }); }, validators: [FormBuilderValidators.required()], items: user.map((v) { return DropdownMenuItem( value: v, child: ListTile( leading: Image.asset( 'assets/img/car.png', width: 50, height: 50, ), title: Text("${v.vrsta}"), )); }).toList(), ), ], ), ), Container(child: _renderWidget()), text.isEmpty ? Container() : RaisedButton( child: Text("Submit"), onPressed: () { _fbKey.currentState.save(); if (_fbKey.currentState.validate()) { print(_fbKey.currentState.value.toString()); print(formData.startLocation); getAutocomplete(); } }, ) ], ), )), ), ), ], ); } </code></pre>
0
2,391
invokedynamic requires --min-sdk-version >= 26
<p>Today downloaded the studio 3.0 beta 2.0 version, after that tried to open an existing project in it and faced some difficulties, most of them I could solve with the help of Google and Stack Overflow, but this one I can not. </p> <pre><code>Error:Execution failed for task ':app:transformClassesWithDexBuilderForDebug'. &gt; com.android.build.api.transform.TransformException: org.gradle.tooling.BuildException: com.android.dx.cf.code.SimException: invalid opcode ba (invokedynamic requires --min-sdk-version &gt;= 26) </code></pre> <p>Also posting my app gradle </p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 26 buildToolsVersion "26.0.1" defaultConfig { applicationId "com.intersoft.snappy" minSdkVersion 19 targetSdkVersion 22 multiDexEnabled true versionCode 1 versionName "1.0" } buildTypeMatching 'dev', 'debug' buildTypeMatching 'qa', 'debug' buildTypeMatching 'rc', 'release' buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } sourceSets { main { assets.srcDirs = ['src/main/assets', 'src/main/assets/'] } } packagingOptions { exclude 'META-INF/DEPENDENCIES.txt' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/notice.txt' exclude 'META-INF/license.txt' exclude 'META-INF/dependencies.txt' exclude 'META-INF/LGPL2.1' } } repositories { mavenCentral() mavenLocal() jcenter() maven { url "https://plugins.gradle.org/m2/" } maven { url "https://s3.amazonaws.com/repo.commonsware.com" } maven { url "https://jitpack.io" } maven { url 'https://dl.bintray.com/ashokslsk/CheckableView' } maven { url "https://maven.google.com" } } android { useLibrary 'org.apache.http.legacy' } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'com.android.support:appcompat-v7:26.0.1' implementation 'com.github.mrengineer13:snackbar:1.2.0' implementation 'com.android.support:recyclerview-v7:26.0.1' implementation 'com.android.support:cardview-v7:26.0.1' implementation 'com.android.support:design:26.0.1' implementation 'com.android.support:percent:26.0.1' implementation 'dev.dworks.libs:volleyplus:+' implementation 'com.google.guava:guava:21.0' implementation 'com.facebook.fresco:fresco:1.0.1' implementation 'com.github.bumptech.glide:glide:3.7.0' implementation 'com.wdullaer:materialdatetimepicker:3.1.1' implementation 'com.squareup.picasso:picasso:2.5.2' implementation 'com.github.stfalcon:frescoimageviewer:0.4.0' implementation 'com.github.piotrek1543:CustomSpinner:0.1' implementation 'com.android.support:multidex:1.0.2' implementation 'com.github.satyan:sugar:1.4' implementation 'com.hedgehog.ratingbar:app:1.1.2' implementation project(':sandriosCamera') implementation('org.apache.httpcomponents:httpmime:4.2.6') { exclude module: 'httpclient' } implementation 'com.googlecode.json-simple:json-simple:1.1' } afterEvaluate { tasks.matching { it.name.startsWith('dex') }.each { dx -&gt; if (dx.additionalParameters == null) { dx.additionalParameters = ['--multi-dex'] } else { dx.additionalParameters += '--multi-dex' } } } subprojects { project.plugins.whenPluginAdded { plugin -&gt; if ("com.android.build.gradle.AppPlugin".equals(plugin.class.name)) { project.android.dexOptions.preDexLibraries = false } else if ("com.android.build.gradle.LibraryPlugin".equals(plugin.class.name)) { project.android.dexOptions.preDexLibraries = false } } } buildscript { repositories { mavenCentral() } dependencies { classpath 'com.jakewharton.hugo:hugo-plugin:1.2.1' } } apply plugin: 'com.jakewharton.hugo' </code></pre> <p>also my another module gradle</p> <pre><code>apply plugin: 'com.android.library' apply plugin: 'com.jfrog.bintray' apply plugin: 'com.github.dcendents.android-maven' buildscript { repositories { jcenter() jcenter() maven { url "https://maven.google.com" } } dependencies { classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7' classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1' } } group = 'com.sandrios.android' version = '1.0.8' ext { PUBLISH_GROUP_ID = 'com.sandrios.android' PUBLISH_ARTIFACT_ID = 'sandriosCamera' PUBLISH_VERSION = '1.0.8' PUBLISH_CODE = 9 } android { compileSdkVersion 26 buildToolsVersion "26.0.1" defaultConfig { minSdkVersion 19 targetSdkVersion 25 versionCode PUBLISH_CODE versionName PUBLISH_VERSION } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } lintOptions { abortOnError false } } task generateSourcesJar(type: Jar) { from android.sourceSets.main.java.srcDirs classifier 'sources' } task generateJavadocs(type: Javadoc) { failOnError false source = android.sourceSets.main.java.srcDirs classpath += project.files(android.getBootClasspath() .join(File.pathSeparator)) } task generateJavadocsJar(type: Jar) { from generateJavadocs.destinationDir classifier 'javadoc' } generateJavadocsJar.dependsOn generateJavadocs artifacts { archives generateSourcesJar archives generateJavadocsJar } install { repositories.mavenInstaller { pom.project { name PUBLISH_GROUP_ID description 'Simple integration of universal camera in android for easy image and video capture.' url 'https://github.com/sandrios/sandriosCamera' inceptionYear '2016' packaging 'aar' version PUBLISH_VERSION scm { connection 'https://github.com/sandrios/sandriosCamera.git' url 'https://github.com/sandrios/sandriosCamera' } developers { developer { name 'arpitgandhi9' } } } } } bintray { Properties properties = new Properties() properties.load(project.rootProject.file('local.properties').newDataInputStream()) user = properties.getProperty('bintray.user') key = properties.getProperty('bintray.apikey') configurations = ['archives'] pkg { repo = 'android' name = 'sandriosCamera' userOrg = 'sandriosstudios' desc = 'Android solution to simplify work with different camera apis.' licenses = ['MIT'] labels = ['android', 'camera', 'photo', 'video'] websiteUrl = 'https://github.com/sandrios/sandriosCamera' issueTrackerUrl = 'https://github.com/sandrios/sandriosCamera/issues' vcsUrl = 'https://github.com/sandrios/sandriosCamera.git' version { name = PUBLISH_VERSION vcsTag = PUBLISH_VERSION desc = 'Minor fixes.' released = new Date() } } } repositories { jcenter() } dependencies { implementation 'com.android.support:support-v4:26.0.0' implementation 'com.android.support:appcompat-v7:26.0.0' implementation 'com.android.support:recyclerview-v7:26.0.0' implementation 'com.github.bumptech.glide:glide:3.6.1' implementation 'com.yalantis:ucrop:2.2.0' implementation 'gun0912.ted:tedpermission:1.0.2' } </code></pre> <p>and also project level gradle</p> <pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.0.0-beta2' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() maven { url "https://maven.google.com" } } } </code></pre> <p>please help me to get rid of this error</p>
0
3,080
How Should VSCode Be Configured To Support A Lerna Monorepo?
<p>I have a <a href="https://github.com/lerna/lerna" rel="noreferrer">lerna</a> monorepo containing lots of packages.</p> <p>I'm trying to achieve the following:</p> <ol> <li>Ensure that VSCode provides the correct import suggestions (based on package names, not on relative paths) from one package to another.</li> <li>Ensure that I can 'Open Definition' of one of these imports and be taken to the src of that file.</li> </ol> <p>For 1. I mean that if I am navigating code within package-a and I start to type a function exported by package-b, I get a suggestion that will trigger the adding of an import: `import { example } from 'package-b'.</p> <p>For 2. I mean that if I alt/click on the name of a function exported by 'package-b' while navigating the file from a different package that has imported it, I am taken to '/packages/namespace/package/b/src/file-that-contains-function.js',</p> <p>My (lerna) monorepo is structured as standard, for example here is a 'components' package that is published as <code>@namespace/components</code>.</p> <pre><code>- packages - components - package.json - node_modules - src - index.js - components - Button - index.js - Button.js - es - index.js - components - Button - index.js - Button.js </code></pre> <p>Note that each component is represented by a directory so that it can contain other components if necessary. In this example, <code>packages/components/index</code> exports <code>Button</code> as a named export. Files are transpiled to the package's <code>/es/</code> directory.</p> <p>By default, VSCode provides autosuggestions for imports, but it is confused by this structure and, for if a different package in the monorepo needs to use <code>Button</code> for example, will autosuggest all of the following import paths:</p> <ul> <li><code>packages/components/src/index.js</code></li> <li><code>packages/components/src/Button/index.js</code></li> <li><code>packages/components/src/Button/Button.js</code></li> <li><code>packages/components/es/index.js</code></li> <li><code>packages/components/es/Button/index.js</code></li> <li><code>packages/components/es/Button/Button.js</code></li> </ul> <p>However none of these are the appropriate, because they will be rendered as relative paths from the importing file to the imported file. In this case, the following import is the correct import:</p> <pre><code>import { Button } from '@namespace/components' </code></pre> <p>Adding excludes to the project's <code>jsconfig.json</code> has no effect on the suggested paths, and doesn't even remove the suggestions at <code>/es/*</code>:</p> <pre><code>{ "compilerOptions": { "target": "es6", }, "exclude": [ "**/dist/*", "**/coverage/*", "**/lib/*", "**/public/*", "**/es/*" ] } </code></pre> <p>Explicitly adding paths using the "compilerOptions" also fails to set up the correct relationship between the files:</p> <pre><code>{ "compilerOptions": { "target": "es6", "baseUrl": ".", "paths": { "@namespace/components/*": [ "./packages/namespace-components/src/*.js" ] } }, } </code></pre> <p>At present Cmd/Clicking on an import from a different package fails to open anything (no definition is found).</p> <p><strong>How should I configure VSCode so that:</strong></p> <ol> <li><strong>VSCode autosuggests imports from other packages in the monorepo using the namespaced package as the import value.</strong></li> <li><strong>Using 'Open Definition' takes me to the src of that file.</strong></li> </ol> <p>As requested, I have a single babel config in the root:</p> <pre><code>const { extendBabelConfig } = require(`./packages/example/src`) const config = extendBabelConfig({ // Allow local .babelrc.js files to be loaded first as overrides babelrcRoots: [`packages/*`], }) module.exports = config </code></pre> <p>Which extends:</p> <pre><code>const presets = [ [ `@babel/preset-env`, { loose: true, modules: false, useBuiltIns: `entry`, shippedProposals: true, targets: { browsers: [`&gt;0.25%`, `not dead`], }, }, ], [ `@babel/preset-react`, { useBuiltIns: true, modules: false, pragma: `React.createElement`, }, ], ] const plugins = [ `@babel/plugin-transform-object-assign`, [ `babel-plugin-styled-components`, { displayName: true, }, ], [ `@babel/plugin-proposal-class-properties`, { loose: true, }, ], `@babel/plugin-syntax-dynamic-import`, [ `@babel/plugin-transform-runtime`, { helpers: true, regenerator: true, }, ], ] // By default we build without transpiling modules so that Webpack can perform // tree shaking. However Jest cannot handle ES6 imports becuase it runs on // babel, so we need to transpile imports when running with jest. if (process.env.UNDER_TEST === `1`) { // eslint-disable-next-line no-console console.log(`Running under test, so transpiling imports`) plugins.push(`@babel/plugin-transform-modules-commonjs`) } const config = { presets, plugins, } module.exports = config </code></pre>
0
1,954
How can I dynamically name an array in Javascript?
<p>I am using jQuery and JSON to pull data from a database. Each row of the database is a different product and each product has a number of properties associated with it.</p> <p>What I'm trying to do in js, is create a named array for each product containing all of the products properties. I know how to pull the data from JSON. I know how to construct the Array.</p> <p>What I don't know is how to create an array name dynamically. Can someone help me out?</p> <p>I am trying to name the array based on a field in the database. In the structure of my existing and working script, it's referenced as data.cssid. I'd like to use the value of data.cssid as the name of the array and then populate the array.</p> <pre><code>$.getJSON("products.php",function(data){ $.each(data.products, function(i,data){ var data.cssid = new Array(); data.cssid[0] = data.productid; ... etc }); }); </code></pre> <p>I know the code above is completely wrong, but it illustrates the idea. Where I declare "var data.cssid", I want to use the actual value of data.cssid as the name of the new array.</p> <p>EDIT:</p> <p>I've tried the methods mentioned here (except for eval). The code is below and is not really that different than my original post, except that I'm using a Object constructor.</p> <pre><code>$(document).ready(function(){ $.getJSON("productscript.php",function(data){ $.each(data.products, function(i,data){ var arrayName = data.cssid; obj[arrayName] = new Array(); obj[arrayName][0] = data.productid; obj[arrayName][1] = data.productname; obj[arrayName][2] = data.cssid; obj[arrayName][3] = data.benefits; alert(obj[arrayName]); //WORKS alert(obj.shoe); //WORKS WHEN arrayName = shoe, otherwise undefined }); }); }); </code></pre> <p>The alert for the non-specific obj[arrayName] works and shows the arrays in all their magnificence. But, when I try to access a specific array by name alert(obj.shoe), it works only when the arrayName = shoe. Next iteration it fails and it can't be accessed outside of this function.</p> <p>I hope this helps clarify the problem and how to solve it. I really appreciate all of the input and am trying everything you guys suggest.</p> <p>PROGRESS (THE SOLUTION):</p> <pre><code>$(document).ready(function(){ $.getJSON("productscript.php",function(data){ $.each(data.products, function(i,data){ var arrayName = data.cssid; window[arrayName] = new Array(); var arr = window[data.cssid]; arr[0] = data.productid; arr[1] = data.productname; arr[2] = data.cssid; arr[3] = data.benefits; alert(window[arrayName]); //WORKS alert(arrayName); //WORKS alert(shoe); //WORKS }); }); }); function showAlert() { alert(shoe); //WORKS when activated by button click } </code></pre> <p>Thanks to everybody for your input. </p>
0
1,030
Knockout.js mapping JSON object to Javascript Object
<p>I have a problem mapping a Json object recieved from the server into a predefined Javascript-object which contains all the necessary functions which are used in the bindings</p> <p>Javascript code is the following</p> <pre><code>function Person(FirstName, LastName, Friends) { var self = this; self.FirstName = ko.observable(FirstName); self.LastName = ko.observable(LastName); self.FullName = ko.computed(function () { return self.FirstName() + ' ' + self.LastName(); }) self.Friends = ko.observableArray(Friends); self.AddFriend = function () { self.Friends.push(new Person('new', 'friend')); }; self.DeleteFriend = function (friend) { self.Friends.remove(friend); }; } var viewModel = new Person(); $(document).ready(function () { $.ajax({ url: 'Home/GetPerson', dataType: 'json', type: 'GET', success: function (jsonResult) { viewModel = ko.mapping.fromJS(jsonResult); ko.applyBindings(viewModel); } }); }); </code></pre> <p>HTML:</p> <pre><code>&lt;p&gt;First name: &lt;input data-bind="value: FirstName" /&gt;&lt;/p&gt; &lt;p&gt;Last name: &lt;input data-bind="value: LastName" /&gt;&lt;/p&gt; &lt;p&gt;Full name: &lt;span data-bind="text: FullName" /&gt;&lt;/p&gt; &lt;p&gt;#Friends: &lt;span data-bind="text: Friends().length" /&gt;&lt;/p&gt; @*Allow maximum of 5 friends*@ &lt;p&gt;&lt;button data-bind="click: AddFriend, text:'add new friend', enable:Friends().length &lt; 5" /&gt;&lt;/p&gt; &lt;br&gt; @*define how friends should be rendered*@ &lt;table data-bind="foreach: Friends"&gt; &lt;tr&gt; &lt;td&gt;First name: &lt;input data-bind="value: FirstName" /&gt;&lt;/td&gt; &lt;td&gt;Last name: &lt;input data-bind="value: LastName" /&gt;&lt;/td&gt; &lt;td&gt;Full name: &lt;span data-bind="text: FullName" /&gt;&lt;/td&gt; &lt;td&gt;&lt;button data-bind="click: function(){ $parent.DeleteFriend($data) }, text:'delete'"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>My ServerSide MVC code for getting initial data looks like:</p> <pre><code> public ActionResult GetPerson() { Person person = new Person{FirstName = "My", LastName="Name", Friends = new List&lt;Person&gt; { new Person{FirstName = "Friend", LastName="Number1"}, new Person{FirstName = "Friend", LastName="Number2"} } }; return Json(person, JsonRequestBehavior.AllowGet); } </code></pre> <p>I am trying to use the mapping plugin to load the Json into my Javascript object so everything is available for the bindings (The add-function and the computed properties on the Friend objects).</p> <p>When I use the mapping plugin it does not seem to work. When using the plugin the AddFriend method is not available during the binding. Is it possible to populate the JavaScript Person object by using the mapping plugin or must everything be done manually?</p>
0
1,296
android: Data refresh in listview after deleting from database
<p>I have an application which retrieves data from DB and displays it in a list view. I have a custom adapter for the same. So when I press the "delete" button, a delete button for each row in the list is displayed. If I press that, the particular row gets deleted in the DB and the same should be reflected in the listview also. The problem is, its not reflecting this change, I should close the app and reopen or move into some other activity and get back to see the updated results.</p> <p>So my question is: where do I call the <code>notifyDataSetChanged()</code> method to get it updated instantly?</p> <p>Here is my customadapter view:</p> <pre><code>public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub MenuListItems menuListItems = menuList.get(position); if (convertView == null) { LayoutInflater inflater = (LayoutInflater) c .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.customlist, parent, false); } Button ck = (Button) convertView.findViewById(R.id.delbox); if(i){ ck.setVisibility(View.VISIBLE);} else{ ck.setVisibility(View.GONE); } ck.setTag(menuListItems.getSlno()); ck.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub final Integer Index = Integer.parseInt((String) v.getTag()); final DataHandler enter = new DataHandler(c); DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which){ case DialogInterface.BUTTON_POSITIVE: //Yes button clicked enter.open(); enter.delet(Index); enter.close(); notifyDataSetChanged(); dialog.dismiss(); break; case DialogInterface.BUTTON_NEGATIVE: //No button clicked dialog.dismiss(); break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(c); builder.setMessage("Are you sure you want to Delete?").setPositiveButton("Yes", dialogClickListener) .setNegativeButton("No", dialogClickListener).show(); } }); TextView id = (TextView) convertView.findViewById(R.id.tvhide); id.setText(menuListItems.getSlno()); TextView title = (TextView) convertView.findViewById(R.id.tvtitle); title.setText(menuListItems.getTitle()); TextView phone = (TextView) convertView.findViewById(R.id.tvpnumber); phone.setText(menuListItems.getPhone()); // ck.setChecked(menuList.) notifyDataSetChanged(); return convertView; } </code></pre>
0
1,568
Oracle VirtualBox terminated unexpectedly, with exit code -1073741819 (0xc0000005)
<p>My VirtualBox virtual machine suddenly doesn't work, instead producing an error. I don't know what is causing this error; I searched Google for a solution, but failed. I have already reinstalled it, uninstalled, rebooted and reinstalled, but to no avail.</p> <p>What can I do to solve this problem?</p> <h2>Logs:</h2> <pre><code>不能为虚拟电脑 sparkvm 打开一个新任务 The virtual machine 'sparkvm' has terminated unexpectedly during startup with exit code -1073741819(0xc0000005).More details may available in 'C:\......\VBoxStartup.log' ------------------- Environment: windows 7 ,oracle virtualbox VirtualBox-4.3.28-100309-Win VboxStartup.log: 66e8.7afc: Log file opened: 4.3.28r100309 g_hStartupLog=0000000000000054 g_uNtVerCombined=0x611db110 66e8.7afc: \SystemRoot\System32\ntdll.dll: 66e8.7afc: CreationTime: 2013-11-27T08:30:24.422775400Z 66e8.7afc: LastWriteTime: 2013-08-29T02:16:35.515578900Z 66e8.7afc: ChangeTime: 2013-12-08T07:42:09.731669000Z 66e8.7afc: FileAttributes: 0x20 66e8.7afc: Size: 0x1a6dc0 66e8.7afc: NT Headers: 0xe0 66e8.7afc: Timestamp: 0x521eaf24 66e8.7afc: Machine: 0x8664 - amd64 66e8.7afc: Timestamp: 0x521eaf24 66e8.7afc: Image Version: 6.1 66e8.7afc: SizeOfImage: 0x1a9000 (1740800) 66e8.7afc: Resource Dir: 0x151000 LB 0x560d8 66e8.7afc: ProductName: Microsoft® Windows® Operating System 66e8.7afc: ProductVersion: 6.1.7601.18247 66e8.7afc: FileVersion: 6.1.7601.18247 (win7sp1_gdr.130828-1532) 66e8.7afc: FileDescription: NT Layer DLL 66e8.7afc: \SystemRoot\System32\kernel32.dll: 66e8.7afc: CreationTime: 2013-10-08T11:03:54.187132100Z 66e8.7afc: LastWriteTime: 2013-08-02T02:13:34.533000000Z 66e8.7afc: ChangeTime: 2013-10-08T11:11:38.115147500Z 66e8.7afc: FileAttributes: 0x20 66e8.7afc: Size: 0x11b800 66e8.7afc: NT Headers: 0xe8 66e8.7afc: Timestamp: 0x51fb1676 66e8.7afc: Machine: 0x8664 - amd64 66e8.7afc: Timestamp: 0x51fb1676 66e8.7afc: Image Version: 6.1 66e8.7afc: SizeOfImage: 0x11f000 (1175552) 66e8.7afc: Resource Dir: 0x116000 LB 0x528 66e8.7afc: ProductName: Microsoft® Windows® Operating System 66e8.7afc: ProductVersion: 6.1.7601.18229 66e8.7afc: FileVersion: 6.1.7601.18229 (win7sp1_gdr.130801-1533) 66e8.7afc: FileDescription: Windows NT BASE API Client DLL 66e8.7afc: \SystemRoot\System32\KernelBase.dll: 66e8.7afc: CreationTime: 2013-10-08T11:03:54.405532500Z 66e8.7afc: LastWriteTime: 2013-08-02T02:13:34.580000000Z 66e8.7afc: ChangeTime: 2013-10-08T11:11:38.099547500Z 66e8.7afc: FileAttributes: 0x20 66e8.7afc: Size: 0x67a00 66e8.7afc: NT Headers: 0xe8 66e8.7afc: Timestamp: 0x51fb1677 66e8.7afc: Machine: 0x8664 - amd64 66e8.7afc: Timestamp: 0x51fb1677 66e8.7afc: Image Version: 6.1 66e8.7afc: SizeOfImage: 0x6b000 (438272) 66e8.7afc: Resource Dir: 0x69000 LB 0x530 66e8.7afc: ProductName: Microsoft® Windows® Operating System 66e8.7afc: ProductVersion: 6.1.7601.18229 66e8.7afc: FileVersion: 6.1.7601.18229 (win7sp1_gdr.130801-1533) 66e8.7afc: FileDescription: Windows NT BASE API Client DLL 66e8.7afc: \SystemRoot\System32\apisetschema.dll: 66e8.7afc: CreationTime: 2013-10-08T11:03:53.782108900Z 66e8.7afc: LastWriteTime: 2013-08-02T02:12:20.275000000Z 66e8.7afc: ChangeTime: 2013-10-08T11:11:37.459946300Z 66e8.7afc: FileAttributes: 0x20 66e8.7afc: Size: 0x1a00 66e8.7afc: NT Headers: 0xc0 66e8.7afc: Timestamp: 0x51fb15ca 66e8.7afc: Machine: 0x8664 - amd64 66e8.7afc: Timestamp: 0x51fb15ca 66e8.7afc: Image Version: 6.1 66e8.7afc: SizeOfImage: 0x50000 (327680) 66e8.7afc: Resource Dir: 0x30000 LB 0x3f8 66e8.7afc: ProductName: Microsoft® Windows® Operating System 66e8.7afc: ProductVersion: 6.1.7601.18229 66e8.7afc: FileVersion: 6.1.7601.18229 (win7sp1_gdr.130801-1533) 66e8.7afc: FileDescription: ApiSet Schema DLL 66e8.7afc: supR3HardenedWinFindAdversaries: 0x0 66e8.7afc: Calling main() 66e8.7afc: SUPR3HardenedMain: pszProgName=VirtualBox fFlags=0x2 66e8.7afc: SUPR3HardenedMain: Respawn #1 66e8.7afc: System32: \Device\HarddiskVolume2\Windows\System32 66e8.7afc: WinSxS: \Device\HarddiskVolume2\Windows\winsxs 66e8.7afc: KnownDllPath: C:\windows\system32 66e8.7afc: '\Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe' has no imports 66e8.7afc: supHardenedWinVerifyImageByHandle: -&gt; 0 (\Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe) 66e8.7afc: supR3HardNtEnableThreadCreation: 66e8.7afc: supR3HardNtDisableThreadCreation: pvLdrInitThunk=00000000774fc340 pvNtTerminateThread=00000000775217e0 66e8.7afc: supR3HardenedWinDoReSpawn(1): New child 5fcc.7914 [kernel32]. 66e8.7afc: supR3HardNtChildGatherData: PebBaseAddress=000007fffffda000 cbPeb=0x380 66e8.7afc: supR3HardNtPuChFindNtdll: uNtDllParentAddr=00000000774d0000 uNtDllChildAddr=00000000774d0000 66e8.7afc: supR3HardenedWinSetupChildInit: uLdrInitThunk=00000000774fc340 66e8.7afc: supR3HardenedWinSetupChildInit: Start child. 66e8.7afc: supR3HardNtChildWaitFor: Found expected request 0 (PurifyChildAndCloseHandles) after 10 ms. 66e8.7afc: supR3HardNtChildPurify: Startup delay kludge #1/0: 263 ms, 32 sleeps 66e8.7afc: supHardNtVpScanVirtualMemory: enmKind=CHILD_PURIFICATION 66e8.7afc: *0000000000000000-fffffffffffeffff 0x0001/0x0000 0x0000000 66e8.7afc: *0000000000010000-fffffffffffeffff 0x0004/0x0004 0x0020000 66e8.7afc: *0000000000030000-000000000002bfff 0x0002/0x0002 0x0040000 66e8.7afc: 0000000000034000-0000000000027fff 0x0001/0x0000 0x0000000 66e8.7afc: *0000000000040000-000000000003efff 0x0004/0x0004 0x0020000 66e8.7afc: 0000000000041000-0000000000031fff 0x0001/0x0000 0x0000000 66e8.7afc: *0000000000050000-000000000004efff 0x0040/0x0040 0x0020000 !! 66e8.7afc: supHardNtVpFreeOrReplacePrivateExecMemory: Freeing exec mem at 0000000000050000 (LB 0x1000, 0000000000050000 LB 0x1000) 66e8.7afc: supHardNtVpFreeOrReplacePrivateExecMemory: Free attempt #1 succeeded: 0x0 [0000000000050000/0000000000050000 LB 0/0x1000] 66e8.7afc: supHardNtVpFreeOrReplacePrivateExecMemory: QVM after free 0: [0000000000000000]/0000000000050000 LB 0x80000 s=0x10000 ap=0x0 rp=0x00000000000001 66e8.7afc: 0000000000051000-fffffffffffd1fff 0x0001/0x0000 0x0000000 66e8.7afc: *00000000000d0000-fffffffffffd3fff 0x0000/0x0004 0x0020000 66e8.7afc: 00000000001cc000-00000000001c8fff 0x0104/0x0004 0x0020000 66e8.7afc: 00000000001cf000-00000000001cdfff 0x0004/0x0004 0x0020000 66e8.7afc: 00000000001d0000-ffffffff88ecffff 0x0001/0x0000 0x0000000 66e8.7afc: *00000000774d0000-00000000774d0fff 0x0002/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\ntdll.dll 66e8.7afc: 00000000774d1000-00000000775d2fff 0x0020/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\ntdll.dll 66e8.7afc: 00000000775d3000-0000000077601fff 0x0002/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\ntdll.dll 66e8.7afc: 0000000077602000-0000000077609fff 0x0008/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\ntdll.dll 66e8.7afc: 000000007760a000-000000007760afff 0x0004/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\ntdll.dll 66e8.7afc: 000000007760b000-000000007760dfff 0x0008/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\ntdll.dll 66e8.7afc: 000000007760e000-0000000077678fff 0x0002/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\ntdll.dll 66e8.7afc: 0000000077679000-000000006fd11fff 0x0001/0x0000 0x0000000 66e8.7afc: *000000007efe0000-000000007dfdffff 0x0000/0x0002 0x0020000 66e8.7afc: *000000007ffe0000-000000007ffdefff 0x0002/0x0002 0x0020000 66e8.7afc: 000000007ffe1000-000000007ffd1fff 0x0000/0x0002 0x0020000 66e8.7afc: 000000007fff0000-ffffffffc0d9ffff 0x0001/0x0000 0x0000000 66e8.7afc: *000000013f240000-000000013f240fff 0x0002/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f241000-000000013f2c5fff 0x0020/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f2c6000-000000013f2c6fff 0x0080/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f2c7000-000000013f304fff 0x0002/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f305000-000000013f305fff 0x0004/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f306000-000000013f306fff 0x0008/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f307000-000000013f308fff 0x0004/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f309000-000000013f309fff 0x0008/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f30a000-000000013f30afff 0x0004/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f30b000-000000013f30efff 0x0008/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f30f000-000000013f347fff 0x0002/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f348000-fffff8037ee9ffff 0x0001/0x0000 0x0000000 66e8.7afc: *000007feff7f0000-000007feff7f0fff 0x0002/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\apisetschema.dll 66e8.7afc: 000007feff7f1000-000007fdff041fff 0x0001/0x0000 0x0000000 66e8.7afc: *000007fffffa0000-000007fffff6cfff 0x0002/0x0002 0x0040000 66e8.7afc: 000007fffffd3000-000007fffffcbfff 0x0001/0x0000 0x0000000 66e8.7afc: *000007fffffda000-000007fffffd8fff 0x0004/0x0004 0x0020000 66e8.7afc: 000007fffffdb000-000007fffffd7fff 0x0001/0x0000 0x0000000 66e8.7afc: *000007fffffde000-000007fffffdbfff 0x0004/0x0004 0x0020000 66e8.7afc: *000007fffffe0000-000007fffffcffff 0x0001/0x0002 0x0020000 66e8.7afc: apisetschema.dll: timestamp 0x51fb15ca (rc=VINF_SUCCESS) 66e8.7afc: VirtualBox.exe: timestamp 0x555369a5 (rc=VINF_SUCCESS) 66e8.7afc: '\Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe' has no imports 66e8.7afc: '\Device\HarddiskVolume2\Windows\System32\apisetschema.dll' has no imports 66e8.7afc: '\Device\HarddiskVolume2\Windows\System32\ntdll.dll' has no imports 66e8.7afc: supR3HardNtChildPurify: cFixes=1 g_fSupAdversaries=0x80000000 cPatchCount=0 66e8.7afc: supR3HardNtChildPurify: Startup delay kludge #1/1: 514 ms, 63 sleeps 66e8.7afc: supHardNtVpScanVirtualMemory: enmKind=CHILD_PURIFICATION 66e8.7afc: *0000000000000000-fffffffffffeffff 0x0001/0x0000 0x0000000 66e8.7afc: *0000000000010000-fffffffffffeffff 0x0004/0x0004 0x0020000 66e8.7afc: *0000000000030000-000000000002bfff 0x0002/0x0002 0x0040000 66e8.7afc: 0000000000034000-0000000000027fff 0x0001/0x0000 0x0000000 66e8.7afc: *0000000000040000-000000000003efff 0x0004/0x0004 0x0020000 66e8.7afc: 0000000000041000-fffffffffffb1fff 0x0001/0x0000 0x0000000 66e8.7afc: *00000000000d0000-fffffffffffd3fff 0x0000/0x0004 0x0020000 66e8.7afc: 00000000001cc000-00000000001c8fff 0x0104/0x0004 0x0020000 66e8.7afc: 00000000001cf000-00000000001cdfff 0x0004/0x0004 0x0020000 66e8.7afc: 00000000001d0000-ffffffff88ecffff 0x0001/0x0000 0x0000000 66e8.7afc: *00000000774d0000-00000000774d0fff 0x0002/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\ntdll.dll 66e8.7afc: 00000000774d1000-00000000775d2fff 0x0020/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\ntdll.dll 66e8.7afc: 00000000775d3000-0000000077601fff 0x0002/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\ntdll.dll 66e8.7afc: 0000000077602000-0000000077609fff 0x0008/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\ntdll.dll 66e8.7afc: 000000007760a000-000000007760afff 0x0004/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\ntdll.dll 66e8.7afc: 000000007760b000-000000007760bfff 0x0008/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\ntdll.dll 66e8.7afc: 000000007760c000-000000007760dfff 0x0004/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\ntdll.dll 66e8.7afc: 000000007760e000-0000000077678fff 0x0002/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\ntdll.dll 66e8.7afc: 0000000077679000-000000006fd11fff 0x0001/0x0000 0x0000000 66e8.7afc: *000000007efe0000-000000007dfdffff 0x0000/0x0002 0x0020000 66e8.7afc: *000000007ffe0000-000000007ffdefff 0x0002/0x0002 0x0020000 66e8.7afc: 000000007ffe1000-000000007ffd1fff 0x0000/0x0002 0x0020000 66e8.7afc: 000000007fff0000-ffffffffc0d9ffff 0x0001/0x0000 0x0000000 66e8.7afc: *000000013f240000-000000013f240fff 0x0002/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f241000-000000013f2c5fff 0x0020/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f2c6000-000000013f2c6fff 0x0040/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f2c7000-000000013f304fff 0x0002/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f305000-000000013f30efff 0x0004/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f30f000-000000013f347fff 0x0002/0x0080 0x1000000 \Device\HarddiskVolume6\Program Files\Oracle\VirtualBox\VirtualBox.exe 66e8.7afc: 000000013f348000-fffff8037ee9ffff 0x0001/0x0000 0x0000000 66e8.7afc: *000007feff7f0000-000007feff7f0fff 0x0002/0x0080 0x1000000 \Device\HarddiskVolume2\Windows\System32\apisetschema.dll 66e8.7afc: 000007feff7f1000-000007fdff041fff 0x0001/0x0000 0x0000000 66e8.7afc: *000007fffffa0000-000007fffff6cfff 0x0002/0x0002 0x0040000 66e8.7afc: 000007fffffd3000-000007fffffcbfff 0x0001/0x0000 0x0000000 66e8.7afc: *000007fffffda000-000007fffffd8fff 0x0004/0x0004 0x0020000 66e8.7afc: 000007fffffdb000-000007fffffd7fff 0x0001/0x0000 0x0000000 66e8.7afc: *000007fffffde000-000007fffffdbfff 0x0004/0x0004 0x0020000 66e8.7afc: *000007fffffe0000-000007fffffcffff 0x0001/0x0002 0x0020000 66e8.7afc: supR3HardNtChildPurify: Done after 1116 ms and 1 fixes (loop #1). 5fcc.7914: Log file opened: 4.3.28r100309 g_hStartupLog=0000000000000004 g_uNtVerCombined=0x611db110 5fcc.7914: supR3HardenedVmProcessInit: uNtDllAddr=00000000774d0000 5fcc.7914: ntdll.dll: timestamp 0x521eaf24 (rc=VINF_SUCCESS) 5fcc.7914: New simple heap: #1 00000000002d0000 LB 0x400000 (for 1740800 allocation) 5fcc.7914: System32: \Device\HarddiskVolume2\Windows\System32 5fcc.7914: WinSxS: \Device\HarddiskVolume2\Windows\winsxs 5fcc.7914: KnownDllPath: C:\windows\system32 5fcc.7914: supR3HardenedVmProcessInit: Opening vboxdrv stub... 66e8.7afc: supR3HardNtEnableThreadCreation: 5fcc.7914: supR3HardenedVmProcessInit: Restoring LdrInitializeThunk... 5fcc.7914: supR3HardenedVmProcessInit: Returning to LdrInitializeThunk... 5fcc.7914: Registered Dll notification callback with NTDLL. 5fcc.7914: supHardenedWinVerifyImageByHandle: -&gt; 22900 ( \Device\HarddiskVolume2\Windows\System32\kernel32.dll) 5fcc.7914: supR3HardenedWinVerifyCacheInsert: \Device\HarddiskVolume2\Windows\System32\kernel32.dll 5fcc.7914: supR3HardenedMonitor_LdrLoadDll: pName=C:\windows\system32\kernel32.dll (Input=kernel32.dll, rcNtResolve=0xc0150008) *pfFlags=0xffffffff pwszSearchPath=0000000000000000:&lt;flags&gt; [calling] 5fcc.7914: supR3HardenedScreenImage/NtCreateSection: cache hit (Unknown Status 22900 (0x5974)) on \Device\HarddiskVolume2\Windows\System32\kernel32.dll [lacks WinVerifyTrust] 5fcc.7914: supR3HardenedDllNotificationCallback: load 0000000076ef0000 LB 0x0011f000 C:\windows\system32\kernel32.dll [fFlags=0x0] 5fcc.7914: supR3HardenedScreenImage/LdrLoadDll: cache hit (Unknown Status 22900 (0x5974)) on \Device\HarddiskVolume2\Windows\System32\kernel32.dll [lacks WinVerifyTrust] 5fcc.7914: supR3HardenedDllNotificationCallback: load 000007fefdbb0000 LB 0x0006b000 C:\windows\system32\KERNELBASE.dll [fFlags=0x0] 5fcc.7914: supHardenedWinVerifyImageByHandle: -&gt; 22900 (\Device\HarddiskVolume2\Windows\System32\KernelBase.dll) 5fcc.7914: supR3HardenedWinVerifyCacheInsert: \Device\HarddiskVolume2\Windows\System32\KernelBase.dll 5fcc.7914: supR3HardenedMonitor_LdrLoadDll: returns rcNt=0x0 hMod=0000000076ef0000 'C:\windows\system32\kernel32.dll' 66e8.7afc: supR3HardNtChildWaitFor[1]: Quitting: ExitCode=0xc0000005 (rcNtWait=0x0, rcNt1=0x0, rcNt2=0x103, rcNt3=0x103, 10 ms, CloseEvents); </code></pre>
0
7,857
Using javascript to set value of hidden field then access value from serverside c# code
<p>I am using a nested html unordered list styled as a drop down. When the a tag within the inner lists list item is clicked it trigger some javascript which is supposed to set the value of a hidden field to the text for the link that was clicked.</p> <p>The javascript seems to work - I used an alert to read the value from the hidden field but then when I try to put that value in the querystring in my asp.net c# code behind - it pulls the initial value - not the javascript set value.</p> <p>I guess this is because the javascript is client side not server side but has anyone any idea how i can get this working</p> <p><strong>HTML</strong></p> <pre><code> &lt;div class="dropDown accomodation"&gt; &lt;label for="accomodationList"&gt;Type of accomodation&lt;/label&gt; &lt;ul class="quicklinks" id="accomodationList"&gt; &lt;li&gt;&lt;a href="#" title="Quicklinks" id="accomodationSelectList"&gt;All types &lt;!--[if IE 7]&gt;&lt;!--&gt;&lt;/a&gt;&lt;!--&lt;![endif]--&gt; &lt;!--[if lte IE 6]&gt;&lt;table&gt;&lt;tr&gt;&lt;td&gt;&lt;![endif]--&gt; &lt;ul id="sub" onclick="dropDownSelected(event,'accomodation');"&gt; &lt;li&gt;&lt;a href="#" id="val=-1$#$All types" &gt;All types&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" id="val=1$#$Villa" &gt;Villa&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" id="val=2$#$Studio" &gt;Studio&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" id="val=3$#$Apartment" &gt;Apartment&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="last" href="#" id="val=4$#$Rustic Properties" &gt;Rustic Properties&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;!--[if lte IE 6]&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/a&gt;&lt;![endif]--&gt; &lt;/li&gt;&lt;/ul&gt; &lt;/div&gt; &lt;input type="hidden" ID="accomodationAnswer" runat="server" /&gt; </code></pre> <p><strong>javascript</strong></p> <pre><code> if(isChildOf(document.getElementById(parentList),document.getElementById(targ.id)) == true) { document.getElementById(parentLi).innerHTML = tname; document.getElementById(hiddenFormFieldName).Value = targ.id; alert('selected id is ' + targ.id + ' value in hidden field is ' + document.getElementById(hiddenFormFieldName).Value); } </code></pre> <p><strong>C# code</strong></p> <pre><code>String qstr = "accom=" + getValFromLiId(accomodationAnswer.Value) + "&amp;sleeps=" + getValFromLiId(sleepsAnswer.Value) + "&amp;nights=" + getValFromLiId(nightsAnswer.Value) + "&amp;region=" + getValFromLiId(regionAnswer.Value) + "&amp;price=" + Utilities.removeCurrencyFormatting(priceAnswer.Value); </code></pre>
0
1,192
How to Disable future dates in Android date picker
<p>How to Disable future dates in Android date picker</p> <p>Java Code :</p> <pre><code>mExpireDate.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // To show current date in the datepicker final Calendar mcurrentDate = Calendar.getInstance(); int mYear = mcurrentDate.get(Calendar.YEAR); int mMonth = mcurrentDate.get(Calendar.MONTH); int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH); DatePickerDialog mDatePicker = new DatePickerDialog( EventRegisterActivity.this, new OnDateSetListener() { public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) { mcurrentDate.set(Calendar.YEAR, selectedyear); mcurrentDate.set(Calendar.MONTH, selectedmonth); mcurrentDate.set(Calendar.DAY_OF_MONTH, selectedday); SimpleDateFormat sdf = new SimpleDateFormat( getResources().getString( R.string.date_card_formate), Locale.US); mExpireDate.setText(sdf.format(mcurrentDate .getTime())); } }, mYear, mMonth, mDay); mDatePicker.setTitle(getResources().getString( R.string.alert_date_select)); mDatePicker.show(); } }); </code></pre> <p>How to do it?</p>
0
1,105
Open downloaded file on Android N using FileProvider
<p>I've got to fix our App for Android N due to the FileProvider changes. I've basically read all about this topic for the last ours, but no solution found did work out for me.</p> <p>Here's our prior code which starts downloads from our app, stores them in the <code>Download</code> folder and calls an <code>ACTION_VIEW</code> intent as soons as the <code>DownloadManager</code> tells he's finished downloading:</p> <pre><code>BroadcastReceiver onComplete = new BroadcastReceiver() { public void onReceive(Context ctxt, Intent intent) { Log.d(TAG, "Download commplete"); // Check for our download long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); if (mDownloadReference == referenceId) { DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(mDownloadReference); Cursor c = mDownloadManager.query(query); if (c.moveToFirst()) { int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS); if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) { String localUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); String fileExtension = MimeTypeMap.getFileExtensionFromUrl(localUri); String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension); if (mimeType != null) { Intent openFileIntent = new Intent(Intent.ACTION_VIEW); openFileIntent.setDataAndTypeAndNormalize(Uri.parse(localUri), mimeType); openFileIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); try { mAcme.startActivity(openFileIntent); } catch (ActivityNotFoundException e) { // Ignore if no activity was found. } } } } } } }; </code></pre> <p>This works on Android M, but breaks on N due to the popular <code>FileUriExposedException</code>. I've now tried to fix this by using the <code>FileProvider</code>, but I cannot get it to work. It's breaking when I try to get the content URI:</p> <p><code>Failed to find configured root that contains /file:/storage/emulated/0/Download/test.pdf</code></p> <p>The <code>localUri</code> returned from the <code>DownloadManager</code> for the file is:</p> <p><code>file:///storage/emulated/0/Download/test.pdf</code></p> <p>The <code>Environment.getExternalStorageDirectory()</code> returns <code>/storage/emulated/0</code> and this is the code for the conversion:</p> <pre><code>File file = new File(localUri); Log.d(TAG, localUri + " - " + Environment.getExternalStorageDirectory()); Uri contentUri = FileProvider.getUriForFile(ctxt, "my.file.provider", file); </code></pre> <p>From <code>AndroidManifest.xml</code></p> <pre><code> &lt;provider android:name="android.support.v4.content.FileProvider" android:authorities="my.file.provider" android:exported="false" android:grantUriPermissions="true"&gt; &lt;meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"/&gt; &lt;/provider&gt; </code></pre> <p>The <code>file_paths.xml</code>:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;paths xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;external-path name="external_path" path="." /&gt; &lt;/paths&gt; </code></pre> <p>And I've tried all values I could find in that xml file. :(</p>
0
1,594
Python: simple list merging based on intersections
<p>Consider there are some lists of integers as:</p> <pre><code>#-------------------------------------- 0 [0,1,3] 1 [1,0,3,4,5,10,...] 2 [2,8] 3 [3,1,0,...] ... n [] #-------------------------------------- </code></pre> <p>The question is to merge lists having at least one common element. So the results only for the given part will be as follows:</p> <pre><code>#-------------------------------------- 0 [0,1,3,4,5,10,...] 2 [2,8] #-------------------------------------- </code></pre> <p><strong>What is the most efficient way to do this on large data (elements are just numbers)?</strong> Is <code>tree</code> structure something to think about? I do the job now by converting lists to <code>sets</code> and iterating for intersections, but it is slow! Furthermore I have a feeling that is so-elementary! In addition, the implementation lacks something (unknown) because some lists remain unmerged sometime! Having said that, if you were proposing self-implementation please be generous and provide a simple sample code [apparently <strong>Python</strong> is my favoriate :)] or pesudo-code.<br> <strong>Update 1:</strong> Here is the code I was using:</p> <pre><code>#-------------------------------------- lsts = [[0,1,3], [1,0,3,4,5,10,11], [2,8], [3,1,0,16]]; #-------------------------------------- </code></pre> <p>The function is (<strong>buggy!!</strong>):</p> <pre><code>#-------------------------------------- def merge(lsts): sts = [set(l) for l in lsts] i = 0 while i &lt; len(sts): j = i+1 while j &lt; len(sts): if len(sts[i].intersection(sts[j])) &gt; 0: sts[i] = sts[i].union(sts[j]) sts.pop(j) else: j += 1 #---corrected i += 1 lst = [list(s) for s in sts] return lst #-------------------------------------- </code></pre> <p>The result is:</p> <pre><code>#-------------------------------------- &gt;&gt;&gt; merge(lsts) &gt;&gt;&gt; [0, 1, 3, 4, 5, 10, 11, 16], [8, 2]] #-------------------------------------- </code></pre> <p><strong>Update 2:</strong> To my experience the code given by <strong>Niklas Baumstark</strong> below showed to be a bit faster for the simple cases. Not tested the method given by "Hooked" yet, since it is completely different approach (by the way it seems interesting). The testing procedure for all of these could be really hard or impossible to be ensured of the results. The real data set I will use is so large and complex, so it is impossible to trace any error just by repeating. That is I need to be 100% satisfied of the reliability of the method before pushing it in its place within a large code as a module. Simply for now <strong>Niklas</strong>'s method is faster and the answer for simple sets is correct of course.<br> <strong>However how can I be sure that it works well for real large data set?</strong> Since I will not be able to trace the errors visually!</p> <p><strong>Update 3:</strong> Note that reliability of the method is much more important than speed for this problem. I will be hopefully able to translate the Python code to Fortran for the maximum performance finally.</p> <p><strong>Update 4:</strong><br> There are many interesting points in this post and generously given answers, constructive comments. I would recommend reading all thoroughly. Please accept my appreciation for the development of the question, amazing answers and constructive comments and discussion.</p>
0
1,104
Prevent redirect to /Account/Login in asp.net core 2.2
<p>I am trying to prevent the app to redirect to <code>/Account/Login</code> in asp.net core 2.2 when the user isn't logged in.</p> <p>Even though i write <code>LoginPath = new PathString(&quot;/api/contests&quot;);</code> any unauthorized requests are still redirected to <code>/Account/Login</code></p> <p>This is my Startup.cs:</p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Reflection; using AutoMapper; using Contest.Models; using Contest.Tokens; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Swashbuckle.AspNetCore.Swagger; namespace Contest { public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAutoMapper(); // In production, the React files will be served from this directory services.AddSpaStaticFiles(configuration =&gt; { configuration.RootPath = &quot;clientapp/build&quot;; }); // ===== Add our DbContext ======== string connection = Configuration.GetConnectionString(&quot;DBLocalConnection&quot;); string migrationAssemblyName = typeof(Startup).GetTypeInfo().Assembly.GetName().Name; services.AddDbContext&lt;ContestContext&gt;(options =&gt; options.UseSqlServer(connection, sql =&gt; sql.MigrationsAssembly(migrationAssemblyName))); // ===== Add Identity ======== services.AddIdentity&lt;User, IdentityRole&gt;(o =&gt; { o.User.RequireUniqueEmail = true; o.Tokens.EmailConfirmationTokenProvider = &quot;EMAILCONF&quot;; // I want to be able to resend an `Email` confirmation email // o.SignIn.RequireConfirmedEmail = true; }).AddRoles&lt;IdentityRole&gt;() .AddEntityFrameworkStores&lt;ContestContext&gt;() .AddTokenProvider&lt;EmailConfirmationTokenProvider&lt;User&gt;&gt;(&quot;EMAILCONF&quot;) .AddDefaultTokenProviders(); services.Configure&lt;DataProtectionTokenProviderOptions&gt;(o =&gt; o.TokenLifespan = TimeSpan.FromHours(3) ); services.Configure&lt;EmailConfirmationTokenProviderOptions&gt;(o =&gt; o.TokenLifespan = TimeSpan.FromDays(2) ); // ===== Add Authentication ======== services.AddAuthentication(o =&gt; o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options =&gt; { options.Cookie.Name = &quot;auth_cookie&quot;; options.Cookie.SameSite = SameSiteMode.None; options.LoginPath = new PathString(&quot;/api/contests&quot;); options.AccessDeniedPath = new PathString(&quot;/api/contests&quot;); options.Events = new CookieAuthenticationEvents { OnRedirectToLogin = context =&gt; { context.Response.StatusCode = StatusCodes.Status401Unauthorized; return Task.CompletedTask; }, }; }); // ===== Add Authorization ======== services.AddAuthorization(o =&gt; { }); services.AddCors(); // ===== Add MVC ======== services.AddMvc(config =&gt; { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); }) .AddJsonOptions(options =&gt; options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // ===== Add Swagger ======== services.AddSwaggerGen(c =&gt; { c.SwaggerDoc(&quot;v1&quot;, new Info { Title = &quot;Core API&quot;, Description = &quot;Documentation&quot;, }); var xmlPath = $&quot;{System.AppDomain.CurrentDomain.BaseDirectory}Contest.xml&quot;; c.IncludeXmlComments(xmlPath); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(&quot;/Error&quot;); app.UseHsts(); } app.UseHttpsRedirection(); app.UseSpaStaticFiles(new StaticFileOptions() { }); app.UseCors(policy =&gt; { policy.AllowAnyHeader(); policy.AllowAnyMethod(); policy.AllowAnyOrigin(); policy.AllowCredentials(); }); app.UseAuthentication(); app.UseMvc(); if (env.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(c =&gt; { c.SwaggerEndpoint(&quot;/swagger/v1/swagger.json&quot;, &quot;Core API&quot;); }); } app.UseSpa(spa =&gt; { spa.Options.SourcePath = &quot;clientapp&quot;; if (env.IsDevelopment()) { // spa.UseReactDevelopmentServer(npmScript: &quot;start&quot;); spa.UseProxyToSpaDevelopmentServer(&quot;http://localhost:3000&quot;); } }); } } } </code></pre> <p>I managed to bypass this by creating a controller to handle this route:</p> <pre class="lang-cs prettyprint-override"><code>[Route(&quot;/&quot;)] [ApiController] public class UnauthorizedController : ControllerBase { public UnauthorizedController() { } [HttpGet(&quot;/Account/Login&quot;)] [AllowAnonymous] public IActionResult Login() { HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized; return new ObjectResult(new { StatusCode = StatusCodes.Status401Unauthorized, Message = &quot;Unauthorized&quot;, }); } } </code></pre> <p>What is wrong with my setup? Thanks</p>
0
3,603
ESLint error - ESLint couldn't find the config "react-app"
<p>Me with my team, start a new React Project using the create-react-app bootstrap command. We add the eslint section on the project but we stuck with annoying error that we never found it before now. When we launch the command </p> <pre><code> yarn run lint </code></pre> <p>Here the error: <a href="https://i.stack.imgur.com/m4M0U.png" rel="noreferrer"><img src="https://i.stack.imgur.com/m4M0U.png" alt="enter image description here"></a></p> <p>Here the package.json:</p> <pre><code>{ "name": "name of the app", "version": "0.1.0", "private": true, "dependencies": { "jwt-decode": "^2.2.0", "react": "^16.12.0", "react-dom": "^16.12.0", "react-intl": "^3.12.0", "react-router": "^5.1.2", "react-router-dom": "^5.1.2", "react-scripts": "3.3.0", "redux": "^4.0.5", "redux-saga": "^1.1.3", "reselect": "^4.0.0", "styled-components": "^5.0.1" }, "scripts": { "analyze": "react-app-rewired build", "build": "react-scripts build", "cypress": "./node_modules/.bin/cypress open", "eject": "react-scripts eject", "lint:write": "eslint --debug src/ --fix", "lint": "eslint --debug src/", "prettier": "prettier --write src/*.tsx src/*.ts src/**/*.tsx src/**/*.ts src/**/**/*.tsx src/**/**/*.ts src/**/**/**/*.tsx src/**/**/**/*.ts src/**/**/**/**/*.tsx src/**/**/**/**/*.ts", "start": "react-scripts start", "storybook": "start-storybook -p 6006 -c .storybook", "test": "react-scripts test", "upgrade:check": "npm-check", "upgrade:interactive": "npm-check --update" }, "eslintConfig": { "extends": "react-app" }, "lint-staged": { "*.(ts|tsx)": [ "yarn run prettier" ] }, "browserslist": { "production": [ "&gt;0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "@cypress/webpack-preprocessor": "^4.1.2", "@storybook/addon-actions": "^5.3.12", "@storybook/addon-info": "^5.3.12", "@storybook/addon-knobs": "^5.3.12", "@storybook/addon-links": "^5.3.12", "@storybook/addons": "^5.3.12", "@storybook/preset-create-react-app": "^1.5.2", "@storybook/react": "^5.3.12", "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "@types/jest": "^24.0.0", "@types/jwt-decode": "^2.2.1", "@types/node": "^12.0.0", "@types/react": "^16.9.0", "@types/react-dom": "^16.9.0", "@types/react-redux": "^7.1.7", "@types/react-router": "^5.1.4", "@types/react-router-dom": "^5.1.3", "@types/storybook__addon-knobs": "^5.2.1", "@types/styled-components": "^4.4.2", "cypress": "^4.0.1", "eslint": "^6.8.0", "husky": "^4.2.1", "lint-staged": "^10.0.7", "npm-check": "^5.9.0", "prettier": "^1.19.1", "react-app-rewire-webpack-bundle-analyzer": "^1.1.0", "react-app-rewired": "^2.1.5", "react-docgen-typescript-webpack-plugin": "^1.1.0", "redux-devtools-extension": "^2.13.8", "storybook-addon-jsx": "^7.1.14", "ts-loader": "^6.2.1", "typescript": "~3.7.2", "webpack": "^4.41.6", "webpack-bundle-analyzer": "^3.6.0" } } </code></pre> <p>We also tried to add create a .eslintrc file and add </p> <pre><code>{ "extends": "react-app" } </code></pre> <p>But nothing change.</p>
0
1,679
How is geom_point removing rows containing missing values?
<p>I'm unsure why none of my data points show up on the map.</p> <pre><code> Store_ID visits CRIND_CC ISCC EBITDAR top_bottom Latitude Longitude (int) (int) (int) (int) (dbl) (chr) (fctr) (fctr) 1 92 348 14819 39013 76449.15 top 41.731373 -93.58184 2 2035 289 15584 35961 72454.42 top 41.589428 -93.80785 3 50 266 14117 27262 49775.02 top 41.559017 -93.77287 4 156 266 7797 25095 28645.95 top 41.6143 -93.834404 5 66 234 8314 18718 46325.12 top 41.6002 -93.779236 6 207 18 2159 17999 20097.99 bottom 41.636208 -93.531876 7 59 23 10547 28806 52168.07 bottom 41.56153 -93.88083 8 101 23 1469 11611 7325.45 bottom 41.20982 -93.84298 9 130 26 2670 13561 14348.98 bottom 41.614517 -93.65789 10 130 26 2670 13561 14348.98 bottom 41.6145172 -93.65789 11 24 27 17916 41721 69991.10 bottom 41.597134 -93.49263 &gt; dput(droplevels(top_bottom)) structure(list(Store_ID = c(92L, 2035L, 50L, 156L, 66L, 207L, 59L, 101L, 130L, 130L, 24L), visits = c(348L, 289L, 266L, 266L, 234L, 18L, 23L, 23L, 26L, 26L, 27L), CRIND_CC = c(14819L, 15584L, 14117L, 7797L, 8314L, 2159L, 10547L, 1469L, 2670L, 2670L, 17916L ), ISCC = c(39013L, 35961L, 27262L, 25095L, 18718L, 17999L, 28806L, 11611L, 13561L, 13561L, 41721L), EBITDAR = c(76449.15, 72454.42, 49775.02, 28645.95, 46325.12, 20097.99, 52168.07, 7325.45, 14348.98, 14348.98, 69991.1), top_bottom = c("top", "top", "top", "top", "top", "bottom", "bottom", "bottom", "bottom", "bottom", "bottom" ), Latitude = structure(c(11L, 4L, 2L, 7L, 6L, 10L, 3L, 1L, 8L, 9L, 5L), .Label = c("41.20982", "41.559017", "41.56153", "41.589428", "41.597134", "41.6002", "41.6143", "41.614517", "41.6145172", "41.636208", "41.731373"), class = "factor"), Longitude = structure(c(3L, 7L, 5L, 8L, 6L, 2L, 10L, 9L, 4L, 4L, 1L), .Label = c("-93.49263", "-93.531876", "-93.58184", "-93.65789", "-93.77287", "-93.779236", "-93.80785", "-93.834404", "-93.84298", "-93.88083"), class = "factor")), row.names = c(NA, -11L), .Names = c("Store_ID", "visits", "CRIND_CC", "ISCC", "EBITDAR", "top_bottom", "Latitude", "Longitude"), class = c("tbl_df", "tbl", "data.frame")) </code></pre> <p>Creating the plot:</p> <pre><code>map &lt;- qmap('Des Moines') + geom_point(data = top_bottom, aes(x = as.numeric(Longitude), y = as.numeric(Latitude)), colour = top_bottom, size = 3) </code></pre> <p>I get the warning message:</p> <pre><code>Removed 11 rows containing missing values (geom_point). </code></pre> <p>However, this works without the use of <code>ggmap()</code>:</p> <pre><code>ggplot(top_bottom) + geom_point(aes(x = as.numeric(Longitude), y = as.numeric(Latitude)), colour = top_bottom, size = 3) </code></pre> <p><a href="https://i.stack.imgur.com/AxuX4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AxuX4.png" alt="enter image description here"></a></p> <p>How do I get the points to overlay on ggmap??</p>
0
1,585
Segmentation fault in libcurl, multithreaded
<p>So I've got a bunch of worker threads doing simple curl class, each worker thread has his own curl easy handle. They are doing only HEAD lookups on random web sites. Also locking functions are present to enable multi threaded SSL as documented <a href="http://www.openssl.org/docs/crypto/threads.html" rel="noreferrer">here</a>. Everything is working except on 2 web pages ilsole24ore.com ( seen in example down ), and ninemsn.com.au/ , they sometimes produce seg fault as shown in trace output shown here</p> <pre><code> #0 *__GI___libc_res_nquery (statp=0xb4d12df4, name=0x849e9bd "ilsole24ore.com", class=1, type=1, answer=0xb4d0ca10 "", anslen=1024, answerp=0xb4d0d234, answerp2=0x0, nanswerp2=0x0, resplen2=0x0) at res_query.c:182 #1 0x00434e8b in __libc_res_nquerydomain (statp=0xb4d12df4, name=0xb4d0ca10 "", domain=0x0, class=1, type=1, answer=0xb4d0ca10 "", anslen=1024, answerp=0xb4d0d234, answerp2=0x0, nanswerp2=0x0, resplen2=0x0) at res_query.c:576 #2 0x004352b5 in *__GI___libc_res_nsearch (statp=0xb4d12df4, name=0x849e9bd "ilsole24ore.com", class=1, type=1, answer=0xb4d0ca10 "", anslen=1024, answerp=0xb4d0d234, answerp2=0x0, nanswerp2=0x0, resplen2=0x0) at res_query.c:377 #3 0x009c0bd6 in *__GI__nss_dns_gethostbyname3_r (name=0x849e9bd "ilsole24ore.com", af=2, result=0xb4d0d5fc, buffer=0xb4d0d300 "\177", buflen=512, errnop=0xb4d12b30, h_errnop=0xb4d0d614, ttlp=0x0, canonp=0x0) at nss_dns/dns-host.c:197 #4 0x009c0f2b in _nss_dns_gethostbyname2_r (name=0x849e9bd "ilsole24ore.com", af=2, result=0xb4d0d5fc, buffer=0xb4d0d300 "\177", buflen=512, errnop=0xb4d12b30, h_errnop=0xb4d0d614) at nss_dns/dns-host.c:251 #5 0x0079eacd in __gethostbyname2_r (name=0x849e9bd "ilsole24ore.com", af=2, resbuf=0xb4d0d5fc, buffer=0xb4d0d300 "\177", buflen=512, result=0xb4d0d618, h_errnop=0xb4d0d614) at ../nss/getXXbyYY_r.c:253 #6 0x00760010 in gaih_inet (name=&lt;value optimized out&gt;, service=&lt;value optimized out&gt;, req=0xb4d0f83c, pai=0xb4d0d764, naddrs=0xb4d0d754) at ../sysdeps/posix/getaddrinfo.c:531 #7 0x00761a65 in *__GI_getaddrinfo (name=0x849e9bd "ilsole24ore.com", service=0x0, hints=0xb4d0f83c, pai=0xb4d0f860) at ../sysdeps/posix/getaddrinfo.c:2160 #8 0x00917f9a in ?? () from /usr/lib/libkrb5support.so.0 #9 0x003b2f45 in krb5_sname_to_principal () from /usr/lib/libkrb5.so.3 #10 0x0028a278 in ?? () from /usr/lib/libgssapi_krb5.so.2 #11 0x0027eff2 in ?? () from /usr/lib/libgssapi_krb5.so.2 #12 0x0027fb00 in gss_init_sec_context () from /usr/lib/libgssapi_krb5.so.2 #13 0x00d8770e in ?? () from /usr/lib/libcurl.so.4 #14 0x00d62c27 in ?? () from /usr/lib/libcurl.so.4 #15 0x00d7e25b in ?? () from /usr/lib/libcurl.so.4 #16 0x00d7e597 in ?? () from /usr/lib/libcurl.so.4 #17 0x00d7f133 in curl_easy_perform () from /usr/lib/libcurl.so.4 </code></pre> <p>My function looks something like this</p> <pre><code>int do_http_check(taskinfo *info,standardResult *data) { standardResultInit(data); char errorBuffer[CURL_ERROR_SIZE]; CURL *curl; CURLcode result; curl = curl_easy_init(); if(curl) { //required options first curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer); curl_easy_setopt(curl, CURLOPT_URL, info-&gt;address.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &amp;data-&gt;body); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, writer); curl_easy_setopt(curl, CURLOPT_WRITEHEADER, &amp;data-&gt;head); curl_easy_setopt(curl, CURLOPT_DNS_USE_GLOBAL_CACHE,0); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30 ); curl_easy_setopt(curl, CURLOPT_NOSIGNAL,1); curl_easy_setopt(curl, CURLOPT_NOBODY,1); curl_easy_setopt(curl, CURLOPT_TIMEOUT ,240); //optional options if(info-&gt;options.follow) { curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_MAXREDIRS, info-&gt;options.redirects); } result = curl_easy_perform(curl); if (result == CURLE_OK) { data-&gt;success = true; curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE,&amp;data-&gt;httpMsg); curl_easy_getinfo(curl,CURLINFO_REDIRECT_COUNT,&amp;data-&gt;numRedirects); data-&gt;msg = "OK"; } else { ... handle error } return 1; } </code></pre> <p>Now, when i call function without any threads, just calling it from main it never breaks, so I was thinking its connected to threads, or maybe how data return structure is being returned, but from what I saw in trace it looks like fault is generated in easy_perform() call, and its confusing me. So if someone has any idea where should i look next it would be most helpful, thanks. </p>
0
2,407
Rails assign session variable
<p>Hi I'm hacking around Rails the last 8 months so don't truly understand a number of things. I've seen and used helper methods that set the current_user etc. and am now trying to replicate something similar. </p> <p>I'm trying to set a global value in the application controller for the current company the user is in. I know I'm doing it wrong but I can't quite figure out how to solve it or even if I'm approaching it correctly. I want it so that when the user clicks on a company, the global variable is set to the id of the company they are in. Then in any other sub-model, if I want info on the company, I use the global variable to retrieve the company object with that id.</p> <p>The code that's causing the problem is in my navbar in <strong>application.html.erb</strong></p> <pre><code>&lt;li&gt;&lt;%= link_to "Company", company_path, :method =&gt; :get %&gt;&lt;/li&gt; </code></pre> <p>This works when I'm using the companies controller etc. But when I try use any other controller I'm getting the error</p> <blockquote> <p>ActionController::UrlGenerationError in Employees#index</p> </blockquote> <pre><code>No route matches {:action=&gt;"show", :controller=&gt;"companies"} missing required keys: [:id] </code></pre> <p>which as I understand it means it can't render the url because no company id parameter is being passed?</p> <p>I was trying to hack a helper method I used in another project (for getting the current_user) but have realised that it uses the session to extract the user.id to return a user object. Here's my attempt at the helper method in <strong>application_controller.rb</strong></p> <pre><code>def current_company @company = Company.find_by_id(params[:id]) end </code></pre> <p>I'm not able to get the current company from the session so my method above is useless unless the company id is being passed as a parameter.</p> <p>I've thought about passing the company id on every sub-model method but </p> <ol> <li>I'm not 100% sure how to do this</li> <li>It doesn't sound very efficient</li> </ol> <p>So my question is am I approaching this correctly? What's the optimal way to do it? Can I create a helper method that stores a global company id variable that gets set once a user accesses a company and can then be retrieved by other models? </p> <p>I probably haven't explained it too well so let me know if you need clarification or more info. Thanks for looking. </p> <blockquote> <p><strong><em>Edit 1</em></strong></p> </blockquote> <p>Made the changes suggested by Ruby Racer and now I have:</p> <blockquote> <p><strong>application.html.erb</strong></p> </blockquote> <pre><code> &lt;%unless current_page?(root_path)||current_page?(companies_path)||current_company.nil? %&gt; &lt;li&gt;&lt;%= link_to "Company", company_path, :method =&gt; :get %&gt;&lt;/li&gt; </code></pre> <p>This is not displaying the link in the navbar, I presume because current_company is nil (the other two unless statements were fine before I added current_company.nil?</p> <p>I'm setting the current_company in </p> <blockquote> <p><strong>companies_controller.rb</strong></p> </blockquote> <pre><code>before_action :set_company, only: [:show, :edit, :update, :destroy, :company_home] def company_home current_company = @company respond_with(@company) end </code></pre> <blockquote> <p><strong>application_controller.rb</strong></p> </blockquote> <pre><code>def current_company=(company) session[:current_company] = company.id puts "The current_company has been assigned" puts params.inspect end def current_company @company = Company.find_by_id(session[:current_company]) puts "The current_company helper has been called" puts @company puts params.inspect end </code></pre> <p>Am I doing something wrong? </p> <blockquote> <p><strong><em>Edit 2</em></strong></p> </blockquote> <p>I have no idea why this isn't working. After the above edits, it appears as though the <code>session[:company_id]</code> is not being assigned so the <code>current_company</code> helper method is returning nil. I've tried printing the session paramaters <code>puts session.inspect</code> and can't find any company_id information. Anyone any idea why it isn't assigning the value? </p> <blockquote> <p><strong>Edit 3</strong></p> </blockquote> <p>Can't for the life of me figure out what's going wrong. I've tried multiple things including moving the <code>current_company = @company</code> into the <code>set_company</code> method in <strong><code>companies_controller.rb</code></strong> which now looks like this:</p> <pre><code>def company_home puts "Test the current company" puts "#{@company.id} #{@company.name}" puts params.inspect end private def set_company @company = Company.find_by_id(params[:id]) if @company.nil?||current_user.organisation_id != @company.organisation.id flash[:alert] = "Stop poking around you nosey parker" redirect_to root_path else current_company = @company end end </code></pre> <p>The <code>company_home</code> method is being given a company object (I can see this in the console output below) but the <code>current_company</code> assignment is just not happening. Here's the <strong>console output</strong> for reference</p> <pre><code>Started GET "/company_home/1" for 80.55.210.105 at 2014-12-19 10:26:49 +0000 Processing by CompaniesController#company_home as HTML Parameters: {"authenticity_token"=&gt;"gfdhjfgjhoFFHGHGFHJGhjkdgkhjgdjhHGLKJGJHpDQs6yNjONwSyTrdgjhgdjgjf=", "id"=&gt;"1"} User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = 6 ORDER BY "users"."id" ASC LIMIT 1 Company Load (0.3ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" = 1 LIMIT 1 Organisation Load (0.3ms) SELECT "organisations".* FROM "organisations" WHERE "organisations"."id" = $1 LIMIT 1 [["id", 6]] Test the current company 1 Cine {"_method"=&gt;"get", "authenticity_token"=&gt;"gfdhjfgjhoFFHGHGFHJGhjkdgkhjgdjhHGLKJGJHpDQs6yNjONwSyTrdgjhgdjgjf=", "controller"=&gt;"companies", "action"=&gt;"company_home", "id"=&gt;"1"} Rendered companies/company_home.html.erb within layouts/application (0.1ms) Company Load (0.6ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" IS NULL LIMIT 1 The current_company helper has been called {"_method"=&gt;"get", "authenticity_token"=&gt;"gfdhjfgjhoFFHGHGFHJGhjkdgkhjgdjhHGLKJGJHpDQs6yNjONwSyTrdgjhgdjgjf=", "controller"=&gt;"companies", "action"=&gt;"company_home", "id"=&gt;"1"} CACHE (0.0ms) SELECT "organisations".* FROM "organisations" WHERE "organisations"."id" = $1 LIMIT 1 [["id", 6]] Completed 200 OK in 280ms (Views: 274.0ms | ActiveRecord: 1.7ms) </code></pre> <p>As per above, under the line <code>The current_company helper has been called</code>, there's a blank line where <code>puts @company</code> should be outputting something. This means the current_company method is returning nothing.</p> <p>Also, in the <code>company_home</code> method in the companies_controller, if I change <code>puts "#{@company.id} #{@company.name}"</code> to <code>puts "#{current_company.id} #{current_company.name}"</code> an error gets thrown.</p> <p>Has anyone any idea why the <code>def current_company=(company)</code> isn't assigning a session parameter? Thanks</p> <blockquote> <p><strong>Final Edit</strong></p> </blockquote> <p>I've no idea why, but it appears the problem related to this:</p> <pre><code>def current_company=(company) session[:current_company] = company.id puts "The current_company has been assigned" puts params.inspect end </code></pre> <p>It looks as though this never gets called. I don't understand why as I've never used something like this before.</p> <p>I'll put my fix in an answer.</p>
0
3,821
Why eslint consider JSX or some react @types undefined, since upgrade typescript-eslint/parser to version 4.0.0
<p>The context is pretty big project built with ReactJs, based on eslint rules, with this eslint configuration</p> <pre><code>const DONT_WARN_CI = process.env.NODE_ENV === 'production' ? 0 : 1 module.exports = { extends: [ 'eslint:recommended', 'plugin:jsx-a11y/recommended', 'plugin:react/recommended', 'prettier', 'prettier/@typescript-eslint' ], plugins: [ 'react', 'html', 'json', 'prettier', 'import', 'jsx-a11y', 'jest', '@typescript-eslint', 'cypress' ], settings: { 'html/indent': '0', es6: true, react: { version: '16.5' }, propWrapperFunctions: ['forbidExtraProps'], 'import/resolver': { node: { extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'] }, alias: { extensions: ['.js', '.jsx', '.json'] } } }, env: { browser: true, node: true, es6: true, jest: true, 'cypress/globals': true }, globals: { React: true, google: true, mount: true, mountWithRouter: true, shallow: true, shallowWithRouter: true, context: true, expect: true, jsdom: true }, parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 'es2020', ecmaFeatures: { globalReturn: true, jsx: true }, lib: ['ES2020'] }, rules: { 'arrow-parens': ['error', 'as-needed'], 'comma-dangle': ['error', 'never'], eqeqeq: ['error', 'smart'], 'import/first': 0, 'import/named': 'error', 'import/no-deprecated': process.env.NODE_ENV === 'production' ? 0 : 1, 'import/no-unresolved': ['error', { commonjs: true }], 'jsx-a11y/alt-text': DONT_WARN_CI, 'jsx-a11y/anchor-has-content': DONT_WARN_CI, 'jsx-a11y/anchor-is-valid': DONT_WARN_CI, 'jsx-a11y/click-events-have-key-events': DONT_WARN_CI, 'jsx-a11y/heading-has-content': DONT_WARN_CI, 'jsx-a11y/iframe-has-title': DONT_WARN_CI, 'jsx-a11y/label-has-associated-control': [ 'error', { controlComponents: ['select'] } ], 'jsx-a11y/label-has-for': [ 'error', { required: { some: ['nesting', 'id'] } } ], 'jsx-a11y/media-has-caption': DONT_WARN_CI, 'jsx-a11y/mouse-events-have-key-events': DONT_WARN_CI, 'jsx-a11y/no-autofocus': DONT_WARN_CI, 'jsx-a11y/no-onchange': 0, 'jsx-a11y/no-noninteractive-element-interactions': DONT_WARN_CI, 'jsx-a11y/no-static-element-interactions': DONT_WARN_CI, 'jsx-a11y/no-noninteractive-tabindex': DONT_WARN_CI, 'jsx-a11y/tabindex-no-positive': DONT_WARN_CI, 'no-console': 'warn', 'no-debugger': 'warn', 'no-mixed-operators': 0, 'no-redeclare': 'off', 'no-restricted-globals': [ 'error', 'addEventListener', 'blur', 'close', 'closed', 'confirm', 'defaultStatus', 'defaultstatus', 'event', 'external', 'find', 'focus', 'frameElement', 'frames', 'history', 'innerHeight', 'innerWidth', 'length', 'localStorage', 'location', 'locationbar', 'menubar', 'moveBy', 'moveTo', 'name', 'onblur', 'onerror', 'onfocus', 'onload', 'onresize', 'onunload', 'open', 'opener', 'opera', 'outerHeight', 'outerWidth', 'pageXOffset', 'pageYOffset', 'parent', 'print', 'removeEventListener', 'resizeBy', 'resizeTo', 'screen', 'screenLeft', 'screenTop', 'screenX', 'screenY', 'scroll', 'scrollbars', 'scrollBy', 'scrollTo', 'scrollX', 'scrollY', 'self', 'status', 'statusbar', 'stop', 'toolbar', 'top' ], 'no-restricted-modules': ['error', 'chai'], 'no-unused-vars': [ 'error', { varsIgnorePattern: '^_', argsIgnorePattern: '^_' } ], 'no-var': 'error', 'one-var': ['error', { initialized: 'never' }], 'prefer-const': [ 'error', { destructuring: 'any' } ], 'prettier/prettier': 'error', 'react/jsx-curly-brace-presence': [ 'error', { children: 'ignore', props: 'never' } ], 'react/jsx-no-bind': [ 'error', { allowArrowFunctions: true } ], 'react/jsx-no-literals': 1, 'react/jsx-no-target-blank': DONT_WARN_CI, 'react/jsx-no-undef': ['error', { allowGlobals: true }], 'react/no-deprecated': DONT_WARN_CI, 'react/prop-types': 0, 'require-await': 'error', 'space-before-function-paren': 0 }, overrides: [ { files: ['**/*.ts', '**/*.tsx'], rules: { 'no-unused-vars': 'off', 'import/no-unresolved': 'off' } } ] } </code></pre> <p>Since the upgrade of the library <code>&quot;@typescript-eslint/parser&quot;: &quot;^4.0.0&quot;</code> from <code>&quot;@typescript-eslint/parser&quot;: &quot;^3.10.1&quot;</code> this following command ...</p> <pre><code>eslint --fix --ext .js,.jsx,.json,.ts,.tsx . &amp;&amp; stylelint --fix '**/*.scss' </code></pre> <p>... brings these following errors</p> <pre><code> 9:45 error 'ScrollBehavior' is not defined no-undef 224:12 error 'KeyboardEventInit' is not defined no-undef 53:5 error 'JSX' is not defined no-undef </code></pre> <p>I know I could fix them adding to the prop <code>globals</code> also the keys <code>JSX: true</code> or <code>KeyboardEventInit: true</code> but it is not the way I want to go. Any ideas of what is going on here? Where is the configuration error? Thanks a lot</p>
0
2,894
C++ Inner class not able to access Outer class's members
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/486099/can-inner-classes-access-private-variables">Can inner classes access private variables?</a><br> <a href="https://stackoverflow.com/questions/11405069/inner-class-accessing-outer-class">Inner class accessing outer class</a> </p> </blockquote> <p>I have some simple classes nested so they can interact with a variable without extra inputs, yet my compiler gives me an error. How would I allow for them to interact without using &amp;time as function input or having the variable &amp;time inside of the Vect class?</p> <p>I tried using the same logic where you can have data accessed that is just in the code, at the same place as function prototypes, but is instead wrapped in a class. This works fine for anything I've used except other classes. Can anyone explain why?</p> <p>I have marked the places that use the problematic time variable with comment lines like the one before the define.</p> <pre><code>/*********/ #define MAX_POLY 3 class Container { public: Container(void); ~Container(void); float time;/*********/ class Vect { float P[MAX_POLY],iT; public: Vect(void){iT = 0.0f;P = {0,0,0};} ~Vect(void); float GetPoly(int n){return P[n];} float Render(void) { float t = time - iT;/*********/ float temp[2] = {0,0}; for(int n=0;n&lt;MAX_POLY;n++) { temp[0] = P[n]; for(int m=0;m&lt;n;m++) temp[0] *= t; temp[1] += temp[0]; } return temp[1]; } void SetPoly(int n,float f) { float t = time-iT;/*********/ P[0] = P[2]*t*t + P[1]*t + P[0]; P[1] = 2*P[2]*t + P[1]; //P[2] = P[2]; P[n] = f; iT = time;/*********/ } }X; }; int main() { Container Shell; Shell.X.SetPoly(0,5); Shell.X.SetPoly(1,10); Shell.X.SetPoly(2,-1); for(int n=0;n&lt;10;n++) { Shell.time = (float)n; cout &lt;&lt; n &lt;&lt; " " &lt;&lt; Shell.X.Render() &lt;&lt; endl; } system("pause"); return 0; } </code></pre>
0
1,067
How to propagate errors through catchError() properly?
<p>I wrote a function that is <code>pipe</code>-able:</p> <pre class="lang-ts prettyprint-override"><code>HandleHttpBasicError&lt;T&gt;() { return ((source:Observable&lt;T&gt;) =&gt; { return source.pipe( catchError((err:any) =&gt; { let msg = ''; if(err &amp;&amp; err instanceof HttpErrorResponse) { if(err.status == 0) msg += &quot;The server didn't respond&quot;; } throw { err, msg } as CustomError }) ) }) } </code></pre> <p>I can use this function this way in my <code>HttpService</code>:</p> <pre class="lang-ts prettyprint-override"><code>checkExist(id:string) { return this.http.head&lt;void&gt;(environment.apiUrl + 'some_url/' + id) .pipe( HandleHttpBasicError(), catchError((err:CustomError) =&gt; { if(err.msg) throw err.msg; if(err.err.status == HttpStatusCodes.NOT_FOUND) throw(&quot;It doesn't exist.&quot;); throw(err); }) ) } </code></pre> <p>It's working great. When I subscribe to <code>checkExist()</code>, I get a good error message, because <code>HandleHttpBasicError</code> first catches an error and throws it to the service's <code>catchError()</code>, which throwes the error message because it was not <code>null</code>.</p> <p>This way, it allows me to have a global <code>catchError()</code> which handles error messages that will always be the same. In the future, I will do it in a <code>HttpHandler</code>, but that's not the point here.</p> <p>Is it ok to chain the errors with the <code>throw</code> keyword?</p> <p>I tried to return <code>Observable.throwError()</code>, but the browser said</p> <blockquote> <p>Observable.throwError is not a function</p> </blockquote> <p>My imports are <code>import {Observable, of, throwError} from 'rxjs';</code>.</p> <p>Isn't it better to do this:</p> <pre class="lang-ts prettyprint-override"><code>return ((source:Observable&lt;T&gt;) =&gt; { return source.pipe( catchError((err:any) =&gt; { msg = ''; ... return of({err, msg} as CustomError) /* instead of throw(err) -or- return Observable.throwError(err) (which doesn't work) */ }) ) }) </code></pre> <p>?</p>
0
1,282
Partial results using speech recognition
<p>I created a simple application inspired by <a href="http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/VoiceRecognition.html" rel="nofollow">this example</a> in order to test all the available options (ie extra). I read about the <a href="http://developer.android.com/reference/android/speech/RecognizerIntent.html#EXTRA_PARTIAL_RESULTS" rel="nofollow"><code>EXTRA_PARTIAL_RESULTS</code> extra</a> and if I enable this option I should receive from the server any partial results related to a speech recognition. However, when I add this extra to the <code>ACTION_RECOGNIZE_SPEECH</code> intent, the voice recognition does not work anymore: the list does not display any results.</p> <pre><code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_RECOGNITION_REQUEST_CODE) { switch(resultCode) { case RESULT_OK: Log.i(TAG, "RESULT_OK"); processResults(data); break; case RESULT_CANCELED: Log.i(TAG, "RESULT_CANCELED"); break; case RecognizerIntent.RESULT_AUDIO_ERROR: Log.i(TAG, "RESULT_AUDIO_ERROR"); break; case RecognizerIntent.RESULT_CLIENT_ERROR: Log.i(TAG, "RESULT_CLIENT_ERROR"); break; case RecognizerIntent.RESULT_NETWORK_ERROR: Log.i(TAG, "RESULT_NETWORK_ERROR"); break; case RecognizerIntent.RESULT_NO_MATCH: Log.i(TAG, "RESULT_NO_MATCH"); break; case RecognizerIntent.RESULT_SERVER_ERROR: Log.i(TAG, "RESULT_SERVER_ERROR"); break; default: Log.i(TAG, "RESULT_UNKNOWN"); break; } } Log.i(TAG, "Intent data: " + data); super.onActivityResult(requestCode, resultCode, data); } private void processResults(Intent data) { Log.i(TAG, "processResults()"); ArrayList&lt;String&gt; matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); // list of results ListView listOfResults = (ListView)(findViewById(R.id.list_of_results)); listOfResults.setAdapter(new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_list_item_1, matches)); // number of elements of above list TextView resultsCount = (TextView)(findViewById(R.id.results_count)); resultsCount.setText(getString(R.string.results_count_label) + ": " + matches.size()); } </code></pre> <p>When this option is enabled, the number of elements in the list of results is equal to 1 and this one result is an empty string. What is the reason for this behavior?</p> <p><strong>ADDED DETAILS</strong> I used the following code in order to enable <code>EXTRA_PARTIAL_RESULTS</code> option (on Android 2.3.5).</p> <pre><code>Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, ...); intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true); intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, ...); startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE); // where VOICE_RECOGNITION_REQUEST_CODE is a "global variable" </code></pre> <p>However, enabling this option, the <code>ArrayList&lt;String&gt; matches</code> in <code>processResults</code> method has only one empty element.</p>
0
1,341
Pandas: for loop through columns
<p>My data looks like: </p> <pre><code>SNP Name ss715583617 ss715592335 ss715591044 ss715598181 4 PI081762 T A A T 5 PI101404A T A A T 6 PI101404B T A A T 7 PI135624 T A A T 8 PI326581 T A A T 9 PI326582A T A A T 10 PI326582B T A A T 11 PI339732 T A A T 12 PI339735A T A A T 13 PI339735B T A A T 14 PI342618A T A A T </code></pre> <p>In reality I have a dataset of 50,000 columns of 479 rows. My objective is to go through each column with characters and convert the data to integers depending on which is the most abundant character.</p> <p>Right now I have the data input, and I have more or less written the function I would like to use to analyze each column separately. However, I can't quite understand how to use a forloop or use the apply function through all of the columns in the dataset. I would prefer not to hardcode the columns because I will have 40,000~50,000 columns to analyze. </p> <p>My code so far is:</p> <pre><code>import pandas as pd df = pd.read_csv("/home/dfreese/Desktop/testSNPtext", delimiter='\t') df.head() # check that the file format fits # ncol df df2 = df.iloc[4:-1] # Select the rows you want to analyze in a subset df print(df2) </code></pre> <p>My function: </p> <pre><code>def countAlleles(N): # N is just suppose to be the column, ideally once I've optimized the function # I need to analyze every column # Will hold the counts of each letter in the column letterCount = [] # This is a parallel array to know the order letterOrder = {'T','A','G','C','H','U'} # Boolean to use which one is the maximum TFlag = None AFlag = None GFlag = None CFlag = None HFlag = None UFlag = None # Loop through the column to determine which one is the maximum for i in range(len(N)): # How do I get index information of the column? if(N[i] == 'T'): # If the element in the column is T letterCount[0] = letterCount[0] + 1 elif(N[i] == 'A'): letterCount[1] = letterCount [1] + 1 elif (N[i] == 'G'): letterCount[2] = letterCount [2] + 1 elif (N[i] == 'C'): lettercount[3] = letterCount[3] + 1 elif(N[i] == 'H'): letterCount[4] = letterCount[4] + 1 else: letterCount[5] = letterCount[5] + 1 max = letterCount[0] # This will hold the value of maximum mIndex = 0 # This holds the index position with the max value # Determine which one is max for i in range(len(letterCount)): if (letterCount[i] &gt; max): max = letterCount[i] mIndex = i </code></pre> <p>So I designed the function to input the column, in hopes to be able to iterate through all the columns of the dataframe. My main question is: </p> <p>1) How would I pass each in each column as a parameter to the for loop through the elements of each column?</p> <p>My major source of confusion is how indexes are being used in pandas. I'm familiar with 2-dimensional array in C++ and Java and that is most of where my knowledge stems from.</p> <p>I'm attempting to use the apply function: </p> <pre><code>df2 = df2.apply(countAlleles('ss715583617'), axis=2) </code></pre> <p>but it doesn't seem that my application is correct.</p>
0
1,616
How to color sliderbar (sliderInput)?
<p>I tried to make different color for a few sliderInput bar in R shiny. It requires css etc. I looked online and can only find how to make one <code>sliderInput</code>. How can I make create several different color to different bars?</p> <p>Here are my testing code. It will show all bar in same style:</p> <pre><code> ui &lt;- fluidPage( tags$style(type = &quot;text/css&quot;, &quot; .irs-bar {width: 100%; height: 25px; background: black; border-top: 1px solid black; border-bottom: 1px solid black;} .irs-bar-edge {background: black; border: 1px solid black; height: 25px; border-radius: 0px; width: 20px;} .irs-line {border: 1px solid black; height: 25px; border-radius: 0px;} .irs-grid-text {font-family: 'arial'; color: white; bottom: 17px; z-index: 1;} .irs-grid-pol {display: none;} .irs-max {font-family: 'arial'; color: black;} .irs-min {font-family: 'arial'; color: black;} .irs-single {color:black; background:#6666ff;} .irs-slider {width: 30px; height: 30px; top: 22px;} .irs-bar1 {width: 50%; height: 25px; background: red; border-top: 1px solid black; border-bottom: 1px solid black;} .irs-bar-edge1 {background: black; border: 1px solid red; height: 25px; border-radius: 0px; width: 20px;} .irs-line1 {border: 1px solid red; height: 25px; border-radius: 0px;} .irs-grid-text1 {font-family: 'arial'; color: white; bottom: 17px; z-index: 1;} .irs-grid-pol1 {display: none;} .irs-max1 {font-family: 'arial'; color: red;} .irs-min1 {font-family: 'arial'; color: red;} .irs-single1 {color:black; background:#6666ff;} .irs-slider1 {width: 30px; height: 30px; top: 22px;} &quot;), uiOutput(&quot;testSlider&quot;) ) server &lt;- function(input, output, session){ output$testSlider &lt;- renderUI({ fluidRow( column(width=3, box( title = &quot;Preferences&quot;, width = NULL, status = &quot;primary&quot;, sliderInput(inputId=&quot;test&quot;, label=NULL, min=1, max=10, value=5, step = 1, width='100%'), sliderInput(inputId=&quot;test2&quot;, label=NULL, min=1, max=10, value=5, step = 1, width='50%') ) )) }) } shinyApp(ui = ui, server=server) </code></pre>
0
1,122
Module AppRegistry is not a registered callable module
<p>I'm starting with React Native development and I encountered an issue in the very beginning. When trying to run my app I get errors:</p> <blockquote> <p>Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)<br> Unhandled JS Exception: Invariant Violation: Native module cannot be null.<br> Unhandled JS Exception: Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)</p> </blockquote> <p>My App.js:</p> <pre><code>import React, { Component } from 'react'; import { SafeAreaView } from 'react-native'; import DefaultRouter from './src/navigation/DefaultRouter' export default class App extends Component { render() { return ( &lt;SafeAreaView&gt; &lt;DefaultRouter /&gt; &lt;/SafeAreaView&gt; ); } }; </code></pre> <p>index.js:</p> <pre><code>import { AppRegistry } from 'react-native'; import App from './App'; import {name as appName} from './app.json'; AppRegistry.registerComponent(appName, () =&gt; App); </code></pre> <p>DefaultRouter.js:</p> <pre><code>import { createSwitchNavigator, createAppContainer } from 'react-navigation'; import LoginScreen from '../screen/LoginScreen'; import DefaultTabBar from '../navigation/TabBar'; const DefaultRouter = createSwitchNavigator({ LOGIN_SCREEN: { screen: LoginScreen }, TAB_NAVIGATION: { screen: DefaultTabBar } }, { initialRouteName: 'LOGIN_SCREEN', headerMode: 'none' }) export default createAppContainer(DefaultRouter) </code></pre> <p>Other files are simple <code>Component</code> subclasses.</p> <p>The issue manifests regardless if I run the app from Visual Studio Code or from terminal with <code>react-native run-ios</code></p> <p>I looked through existing answers and I didn't find anything that could point me in the right direction:<br> <a href="https://stackoverflow.com/questions/34969858/react-native-module-appregistry-is-not-a-registered-callable-module">React-Native: Module AppRegistry is not a registered callable module</a><br> <a href="https://stackoverflow.com/questions/56397800/react-native-module-appregistry-is-not-a-registered-callable-module-calling-ru">React Native: Module AppRegistry is not a registered callable module (calling runApplication)</a><br> <a href="https://stackoverflow.com/questions/49128692/module-appregistry-is-not-a-registered-callable-module-calling-runapplication">module appregistry is not a registered callable module (calling runApplication)</a> <a href="https://stackoverflow.com/questions/55381142/module-appregistry-is-not-a-registered-callable-module-and-cant-find-variable-c">Module AppRegistry is not a registered callable module and Cant find variable: Constants</a><br> <a href="https://stackoverflow.com/questions/38133086/react-native-module-appregistry-is-not-a-registered-callable-module">React Native Module AppRegistry is not a registered callable module</a><br> <a href="https://stackoverflow.com/questions/48283521/module-appregistry-is-not-a-registered-callable-module-only-in-release-configura">Module AppRegistry is not a registered callable module only in Release configuration</a></p> <p>I'm stuck and I don't know where to go from here</p>
0
1,062
Home directory does not exist JBOSS
<p>I'm trying to run jboos as 7.1 and when I run the standalone.bat I get this error. I have configured everything as you can see here:</p> <pre><code>Calling "C:\jboss-as-7.1.1.Final\bin\standalone.conf.bat" =============================================================================== JBoss Bootstrap Environment JBOSS_HOME: C:\jboss-as-7.1.1.Final\ JAVA: C:\Program Files\Java\jdk1.7.0_45\bin\java JAVA_OPTS: -XX:+TieredCompilation -Dprogram.name=standalone.bat -Xms64M -Xmx51 2M -XX:MaxPermSize=256M -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.se rver.gcInterval=3600000 -Djava.net.preferIPv4Stack=true -Dorg.jboss.resolver.war ning=true -Djboss.modules.system.pkgs=org.jboss.byteman -Djboss.server.default.c onfig=standalone.xml =============================================================================== 13:21:17,915 Informaci¾n [org.jboss.modules] JBoss Modules version 1.1.1.GA java.lang.IllegalStateException: JBAS015849: Home directory does not exist: C:\j boss-as-7.1.1.Final" at org.jboss.as.server.ServerEnvironment.&lt;init&gt;(ServerEnvironment.java:3 28) at org.jboss.as.server.Main.determineEnvironment(Main.java:242) at org.jboss.as.server.Main.main(Main.java:83) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl. java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces sorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.jboss.modules.Module.run(Module.java:260) at org.jboss.modules.Main.main(Main.java:291) Presione una tecla para continuar . . . </code></pre> <p>The bin/standalone.conf.bat is this one:</p> <pre><code>rem ### -*- batch file -*- ###################################################### rem # ## rem # JBoss Bootstrap Script Configuration ## rem # ## rem ############################################################################# rem # $Id: run.conf.bat 88820 2009-05-13 15:25:44Z dimitris@jboss.org $ rem # rem # This batch file is executed by run.bat to initialize the environment rem # variables that run.bat uses. It is recommended to use this file to rem # configure these variables, rather than modifying run.bat itself. rem # rem Uncomment the following line to disable manipulation of JAVA_OPTS (JVM parameters) rem set PRESERVE_JAVA_OPTS=true if not "x%JAVA_OPTS%" == "x" ( echo "JAVA_OPTS already set in environment; overriding default settings with values: % JAVA_OPTS%" goto JAVA_OPTS_SET ) rem # rem # Specify the JBoss Profiler configuration file to load. rem # rem # Default is to not load a JBoss Profiler configuration file. rem # rem set "PROFILER=%JBOSS_HOME%\bin\jboss-profiler.properties" rem # rem # Specify the location of the Java home directory (it is recommended that rem # this always be set). If set, then "%JAVA_HOME%\bin\java" will be used as rem # the Java VM executable; otherwise, "%JAVA%" will be used (see below). rem # rem set "JAVA_HOME=C:\opt\jdk1.6.0_23" rem # rem # Specify the exact Java VM executable to use - only used if JAVA_HOME is rem # not set. Default is "java". rem # rem set "JAVA=C:\opt\jdk1.6.0_23\bin\java" rem # rem # Specify options to pass to the Java VM. Note, there are some additional rem # options that are always passed by run.bat. rem # rem # JVM memory allocation pool parameters - modify as appropriate. set "JAVA_OPTS=-Xms64M -Xmx512M -XX:MaxPermSize=256M" rem # Reduce the RMI GCs to once per hour for Sun JVMs. set "JAVA_OPTS=%JAVA_OPTS% -Dsun.rmi.dgc.client.gcInterval=3600000 - Dsun.rmi.dgc.server.gcInterval=3600000 -Djava.net.preferIPv4Stack=true" rem # Warn when resolving remote XML DTDs or schemas. set "JAVA_OPTS=%JAVA_OPTS% -Dorg.jboss.resolver.warning=true" rem # Make Byteman classes visible in all module loaders rem # This is necessary to inject Byteman rules into AS7 deployments set "JAVA_OPTS=%JAVA_OPTS% -Djboss.modules.system.pkgs=org.jboss.byteman" rem # Set the default configuration file to use if -c or --server-config are not used set "JAVA_OPTS=%JAVA_OPTS% -Djboss.server.default.config=standalone.xml" rem # Sample JPDA settings for remote socket debugging rem set "JAVA_OPTS=%JAVA_OPTS% -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n" rem # Sample JPDA settings for shared memory debugging rem set "JAVA_OPTS=%JAVA_OPTS% -Xrunjdwp:transport=dt_shmem,address=jboss,server=y,suspend=n" rem # Use JBoss Modules lockless mode rem set "JAVA_OPTS=%JAVA_OPTS% -Djboss.modules.lockless=true" :JAVA_OPTS_SET </code></pre> <p>Why?. Thanks so much. Regards</p>
0
1,848
Communications link failure due to: java.io.EOFException
<p>My webapp is running on Tomcat 5.5, I declared the datasource in web.xml:</p> <pre><code>&lt;resource-ref&gt; &lt;res-ref-name&gt;jdbc/OrdiniWebDS&lt;/res-ref-name&gt; &lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt; &lt;res-auth&gt;Container&lt;/res-auth&gt; &lt;res-sharing-scope&gt;Shareable&lt;/res-sharing-scope&gt; &lt;/resource-ref&gt; </code></pre> <p>In context.xml (tomcat conf):</p> <pre><code>&lt;Resource auth="Container" driverClassName="com.mysql.jdbc.Driver" maxActive="100" maxIdle="30" maxWait="10000" name="jdbc/OrdiniWebDS" password="[mypassword]" type="javax.sql.DataSource" url="jdbc:mysql://[myHost:port]/ordiniweb" username="[myusername]" /&gt; </code></pre> <p>The database is a MySql 5.0. Everything works well except that sometimes, after several hours of "unuse", at first access I got this Exception:</p> <pre><code>com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: ** BEGIN NESTED EXCEPTION ** java.io.EOFException STACKTRACE: java.io.EOFException at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1956) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2368) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2867) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1616) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1708) at com.mysql.jdbc.Connection.execSQL(Connection.java:3255) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1293) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1428) at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93) at com.blasetti.ordiniweb.dao.OrdiniDAO.caricaOrdine(OrdiniDAO.java:263) ... ** END NESTED EXCEPTION ** Last packet sent to the server was 0 ms ago. com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2579) com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2867) com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1616) com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1708) com.mysql.jdbc.Connection.execSQL(Connection.java:3255) com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1293) com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1428) org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93) com.blasetti.ordiniweb.dao.OrdiniDAO.caricaOrdine(OrdiniDAO.java:263) ... </code></pre> <p>I need to refresh and it works well again. Any idea? Thanks.</p>
0
1,079
How Can I Fix "TypeError: Cannot mix str and non-str arguments"?
<p>I'm writing some scraping codes and experiencing an error as above. My code is following.</p> <pre><code># -*- coding: utf-8 -*- import scrapy from myproject.items import Headline class NewsSpider(scrapy.Spider): name = 'IC' allowed_domains = ['kosoku.jp'] start_urls = ['http://kosoku.jp/ic.php'] def parse(self, response): """ extract target urls and combine them with the main domain """ for url in response.css('table a::attr("href")'): yield(scrapy.Request(response.urljoin(url), self.parse_topics)) def parse_topics(self, response): """ pick up necessary information """ item=Headline() item["name"]=response.css("h2#page-name ::text").re(r'.*(インターチェンジ)') item["road"]=response.css("div.ic-basic-info-left div:last-of-type ::text").re(r'.*道$') yield item </code></pre> <p>I can get the correct response when I do them individually on a shell script, but once it gets in a programme and run, it doesn't happen.</p> <pre><code> 2017-11-27 18:26:17 [scrapy.core.scraper] ERROR: Spider error processing &lt;GET http://kosoku.jp/ic.php&gt; (referer: None) Traceback (most recent call last): File "/Users/sonogi/envs/scrapy/lib/python3.5/site-packages/scrapy/utils/defer.py", line 102, in iter_errback yield next(it) File "/Users/sonogi/envs/scrapy/lib/python3.5/site-packages/scrapy/spidermiddlewares/offsite.py", line 29, in process_spider_output for x in result: File "/Users/sonogi/envs/scrapy/lib/python3.5/site-packages/scrapy/spidermiddlewares/referer.py", line 339, in &lt;genexpr&gt; return (_set_referer(r) for r in result or ()) File "/Users/sonogi/envs/scrapy/lib/python3.5/site-packages/scrapy/spidermiddlewares/urllength.py", line 37, in &lt;genexpr&gt; return (r for r in result or () if _filter(r)) File "/Users/sonogi/envs/scrapy/lib/python3.5/site-packages/scrapy/spidermiddlewares/depth.py", line 58, in &lt;genexpr&gt; return (r for r in result or () if _filter(r)) File "/Users/sonogi/scraping/myproject/myproject/spiders/IC.py", line 16, in parse yield(scrapy.Request(response.urljoin(url), self.parse_topics)) File "/Users/sonogi/envs/scrapy/lib/python3.5/site-packages/scrapy/http/response/text.py", line 82, in urljoin return urljoin(get_base_url(self), url) File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/parse.py", line 424, in urljoin base, url, _coerce_result = _coerce_args(base, url) File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/parse.py", line 120, in _coerce_args raise TypeError("Cannot mix str and non-str arguments") TypeError: Cannot mix str and non-str arguments 2017-11-27 18:26:17 [scrapy.core.engine] INFO: Closing spider (finished) </code></pre> <p>I'm so confused and appreciate anyone's help upfront!</p>
0
1,159
Javascript TypeError: xxx is not a function
<p>Friends I came to a bit of problem. Everything was working fine before. But I can't rectify why it starts giving me such error.<br> Here is my JavaScript Code:</p> <pre><code>function newSupplier() { $('div#AddSupplier div.msg').html('').hide(); $('div#AddSupplier div.loader').show(); registerSupplier($('div#AddSupplier table.frm :input').serialize()).done(function (a) { if (a.Msg) { $('div#AddSupplier div.msg').html(a.Msg).removeClass('success').addClass('error').fadeIn(); } else if (a.supid) { $('div#AddSupplier div.msg').html('Supplier &lt;span class="l2"&gt;' + a.supid + '&lt;/span&gt; Registered').removeClass('error').addClass('success').fadeIn(); $('div#AddSupplier table.frm :input').val(''); } }).always(function () { $('div#AddSupplier div.loader').hide(); }).fail(function () { $('div#AddSupplier div.msg').html(errMsgNet).removeClass('success').addClass('error').fadeIn(); }); } </code></pre> <p>And here is the code of <code>registerSupplier()</code> function:</p> <pre><code>function registerSupplier(dataToPost) { return $.ajax({ type: "POST", url: jsonpath + 'Json.ashx?method=RegisterSupplier', data: dataToPost }); } </code></pre> <p>And here is the complete JS file: <a href="http://preview.myignou.com/Docs/jScript.js">http://preview.myignou.com/Docs/jScript.js</a></p> <p>Related HTML </p> <pre><code>&lt;div id="ViewOrder"&gt; &lt;h2&gt;View Order Details&lt;/h2&gt; &lt;div class="tab-content"&gt; &lt;table class="frm"&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Enter Order Number&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="orderNumber" onkeyup="$('#ViewOrder&gt;div&gt;div').fadeOut();" /&gt;&lt;input type="button" class="but1 m-side" value="OK" onclick="LoadMaterialOrder();"/&gt;&lt;/td&gt; &lt;td&gt; &lt;div class="process"&gt;&amp;nbsp;&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;div&gt; &lt;div class="border shadow m-tb"&gt; &lt;h2 class="header"&gt;Order Details&lt;/h2&gt; &lt;div id="orderDetails" class="tab-content"&gt; &lt;table class="frm"&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Supplier&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;select id="newSupplier" name="supplier"&gt;&lt;/select&gt;&lt;/td&gt; &lt;td class="r-align"&gt;&lt;input type="button" value="Load Suppliers" onclick="loadSuppliers('#newSupplier')" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Order Date&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="orderDate" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Delivery Date&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="deliveryDate" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Cancel Date&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="cancelDate" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Payment Due Mark&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input id="payDue2" type="checkbox" name="isPayDue" /&gt;&lt;label for="payDue2"&gt;Yes&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Remember Mark&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input id="remark2" type="checkbox" name="isMarked" /&gt;&lt;label for="remark2"&gt;Yes&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;table class="footer-buttons"&gt; &lt;tr&gt; &lt;td&gt; &lt;div class="msg"&gt;&lt;/div&gt; &lt;div class="loader" style="display:none;"&gt;&lt;img alt="loader" src="CSS/Images/loader.gif" /&gt;&lt;/div&gt; &lt;/td&gt; &lt;td&gt;&lt;input type="button" class="but1 sub-but" value="Save Changes" onclick=""/&gt;&lt;input type="reset" value="Reset" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;br /&gt; &lt;div class="border shadow m-tb"&gt; &lt;h2 class="header"&gt;Payment Records&lt;/h2&gt; &lt;div id="paymentHistory" class="tab-content"&gt; &lt;table class="tab pay-his"&gt; &lt;tr class="th"&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;Trans#&lt;/td&gt; &lt;td&gt;Date&lt;/td&gt; &lt;td&gt;Comment&lt;/td&gt; &lt;td&gt;Type&lt;/td&gt; &lt;td&gt;Credit&lt;/td&gt; &lt;td&gt;Debit&lt;/td&gt; &lt;td&gt;Balance&lt;/td&gt; &lt;td&gt;Associated Agent&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="radio" name="paySelect" /&gt;&lt;/td&gt; &lt;td&gt;101-1&lt;/td&gt; &lt;td&gt;12-12-12&lt;/td&gt; &lt;td&gt;Abclk lask aa&lt;/td&gt; &lt;td&gt;Credit&lt;/td&gt; &lt;td&gt;500&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;500.00&lt;/td&gt; &lt;td&gt;Shashwat Tripathi&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="radio" name="paySelect" /&gt;&lt;/td&gt; &lt;td&gt;101-2&lt;/td&gt; &lt;td&gt;12-12-12&lt;/td&gt; &lt;td&gt;Shashwat Tripathi&lt;/td&gt; &lt;td&gt;Debit&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;500&lt;/td&gt; &lt;td&gt;500.00&lt;/td&gt; &lt;td&gt;Sudhir&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="radio" name="paySelect" /&gt;&lt;/td&gt; &lt;td&gt;101-3&lt;/td&gt; &lt;td&gt;12-12-12&lt;/td&gt; &lt;td&gt;Shashwat Tripathi&lt;/td&gt; &lt;td&gt;Credit&lt;/td&gt; &lt;td&gt;500&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;500.00&lt;/td&gt; &lt;td&gt;Sudhir Gaur&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;br /&gt; &lt;input type="button" class="but2" value="Edit" onclick="$('#ViewOrder #payEdit').slideDown(function () { $('html, body').animate({ scrollTop: $('#paymentHistory').offset().top-20 }, 500); });" /&gt;&lt;input type="button" class="but2 m-side" value="Delete" /&gt; &lt;div id="payEdit" class="border m-tb shadow" style="display:none;"&gt; &lt;h2 class="header"&gt;Edit Payment&lt;/h2&gt; &lt;div class="tab-content"&gt; &lt;table class="frm"&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Date&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="date" placeholder="dd-mm-yy"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Type&lt;/label&gt;&lt;/td&gt; &lt;td&gt; &lt;select name="type"&gt; &lt;option&gt;Credit&lt;/option&gt; &lt;option&gt;Debit&lt;/option&gt; &lt;option&gt;Expense&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Amount&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="amount" placeholder="धनराशी..." /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Comment&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;textarea name="comment" rows="4" cols="10"&gt;&lt;/textarea&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="button" class="but1" value="Save Changes" /&gt;&lt;input type="button" class="but2 m-side" onclick="$('#payEdit').slideUp();" value="Cancel" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;br /&gt; &lt;h2&gt;Register New Payment&lt;/h2&gt; &lt;hr /&gt; &lt;div id="newMatOrderPayment"&gt; &lt;table class="frm"&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Date&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="date" placeholder="dd-mm-yy" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Type&lt;/label&gt;&lt;/td&gt; &lt;td&gt; &lt;select name="type"&gt; &lt;option&gt;Credit&lt;/option&gt; &lt;option&gt;Debit&lt;/option&gt; &lt;option&gt;Expense&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Amount&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="amount" placeholder="धनराशी..." /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Comment&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;textarea name="comment" rows="4" cols="10"&gt;&lt;/textarea&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;table class="footer-buttons"&gt; &lt;tr&gt; &lt;td&gt; &lt;div class="msg"&gt;&lt;/div&gt; &lt;div class="loader" style="display:none;"&gt;&lt;img alt="loader" src="CSS/Images/loader.gif" /&gt;&lt;/div&gt; &lt;/td&gt; &lt;td&gt;&lt;input type="button" class="but1" value="Register Payment" onclick=""/&gt;&lt;input type="button" class="but2" onclick="$('#NewMatOrderPayment :text').val('');" value="Reset" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="AddSupplier"&gt; &lt;h2&gt;Register New Suppiler&lt;/h2&gt; &lt;div class="tab-content"&gt; &lt;table class="frm"&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Supplier ID&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="supId" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Contact Number&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="contact" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Address&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;textarea name="address" cols="10" rows="4"&gt;&lt;/textarea&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;Email address&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="email" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label&gt;City&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="city" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;table class="footer-buttons"&gt; &lt;tr&gt; &lt;td&gt; &lt;div class="msg"&gt;&lt;/div&gt; &lt;div class="loader" style="display:none;"&gt;&lt;img alt="loader" src="CSS/Images/loader.gif" /&gt;&lt;/div&gt; &lt;/td&gt; &lt;td&gt;&lt;input type="button" class="but1 sub-but" value="Register" onclick="newSupplier();"/&gt;&lt;input type="reset" value="रीसेट" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>If I am calling this function directly from FF and Firebug console then It is getting called.<br> <strong>But on button click I am getting error <code>TypeError: newSupplier is not a function</code></strong></p> <p>Please ask me If u need additional code.</p>
0
8,537
Failed to build Android app (refer to both ActionBarSherlock & ViewPagerTabs) with Ant
<p>I have one Android app which uses ActionBarSherlock &amp; ViewPagerTabs. I use Eclipse to write and build it, and it just works well until I try to build it with Ant. Here's what I did:</p> <ol> <li>go to ActionBarSherlock folder, run "android update <strong>lib-project</strong> --path ."</li> <li>go to ViewPagerTabs folder, run "android update <strong>lib-project</strong> --path ." too</li> <li>go to app folder, run "android update <strong>project</strong> --path ."</li> <li>run "and debug" under app folder, and I got following errors:</li> </ol> <p>:</p> <pre><code>[javac] C:\Android\TestApp\src\com\test\App\TestActivity.java:46: cannot find symbol [javac] symbol : method getSupportActionBar() [javac] location: class com.test.App.TestActivity [javac] final ActionBar ab = getSupportActionBar(); [javac] ^ </code></pre> <p>So question NO. 1: <strong>I have correct library references in app's project.properties, and ActionBarSherlock &amp; ViewPagerTabs could be built successfully, why do I still get these errors?</strong></p> <p>There's a workaround for this issue -- copy all classes.jar under library's bin folder into app's libs folder, and run "ant debug" again. But I need to delete these .jar files under app's libs folder after all .java files of app could be compiled.</p> <p>Running "ant debug" again after this, I will get following errors:</p> <pre><code>[dx] processing archive C:\Android\ActionBarSherlock\library\bin\classes.jar... [dx] ignored resource META-INF/MANIFEST.MF [dx] processing android/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoStubImpl.class... [dx] processing android/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoVersionImpl.class... [dx] processing android/support/v4/accessibilityservice/AccessibilityServiceInfoCompat.class... [dx] processing android/support/v4/accessibilityservice/AccessibilityServiceInfoCompatIcs.class... [dx] processing android/support/v4/app/ActionBar$LayoutParams.class... [dx] processing android/support/v4/app/ActionBar$OnMenuVisibilityListener.class... [dx] processing android/support/v4/app/ActionBar$OnNavigationListener.class... [dx] processing android/support/v4/app/ActionBar$Tab.class... [dx] processing android/support/v4/app/ActionBar$TabListener.class... [dx] processing android/support/v4/app/ActionBar.class... [dx] processing android/support/v4/app/ActivityCompatHoneycomb.class... [dx] [dx] UNEXPECTED TOP-LEVEL EXCEPTION: [dx] java.lang.IllegalArgumentException: already added: Landroid/support/v4/app/ActivityCompatHoneycomb; [dx] at com.android.dx.dex.file.ClassDefsSection.add(ClassDefsSection.java:123) [dx] at com.android.dx.dex.file.DexFile.add(DexFile.java:163) [dx] at com.android.dx.command.dexer.Main.processClass(Main.java:486) [dx] at com.android.dx.command.dexer.Main.processFileBytes(Main.java:455) [dx] at com.android.dx.command.dexer.Main.access$400(Main.java:67) [dx] at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:394) [dx] at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:245) [dx] at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:131) [dx] at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:109) [dx] at com.android.dx.command.dexer.Main.processOne(Main.java:418) [dx] at com.android.dx.command.dexer.Main.processAllFiles(Main.java:329) [dx] at com.android.dx.command.dexer.Main.run(Main.java:206) [dx] at com.android.dx.command.dexer.Main.main(Main.java:174) [dx] at com.android.dx.command.Main.main(Main.java:95) [dx] 1 error; aborting </code></pre> <p>My question NO.2 is: <strong>how can I fix this issue?</strong></p> <p>Thanks!</p>
0
1,357
send JSON to server via HTTP put request in android
<p>How to wrap given json to string and send it to server via Http put request in android?</p> <p>This is how my json look like. </p> <pre><code> { "version": "1.0.0", "datastreams": [ { "id": "example", "current_value": "333" }, { "id": "key", "current_value": "value" }, { "id": "datastream", "current_value": "1337" } ] } </code></pre> <p>above is my json array.</p> <p>below is how I wrote the code but, its not working</p> <pre><code> protected String doInBackground(Void... params) { String text = null; try { JSONObject child1 = new JSONObject(); try{ child1.put("id", "LED"); child1.put("current_value", "0"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } JSONArray jsonArray = new JSONArray(); jsonArray.put(child1); JSONObject datastreams = new JSONObject(); datastreams.put("datastreams", jsonArray); JSONObject version = new JSONObject(); version.put("version", "1.0.0"); version.put("version", datastreams); HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPut put = new HttpPut("url"); put.addHeader("X-Apikey",""); StringEntity se = new StringEntity( version.toString()); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); put.addHeader("Accept", "application/json"); put.addHeader("Content-type", "application/json"); put.setEntity(se); try{ HttpResponse response = httpClient.execute(put, localContext); HttpEntity entity = response.getEntity(); text = getASCIIContentFromEntity(entity); } catch (Exception e) { return e.getLocalizedMessage(); } }catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return text; } </code></pre> <p>please help on this </p>
0
1,339
How should I use ejs to render table vertically?
<p>I have an array like the following:</p> <pre><code>quotation: [{ "dimension" : 0, "currency": "RMB", "quantity": "100", "price": "3", "factory": "rx"}, { "dimension" : 0, "currency": "RMB", "quantity": "200", "price": "4", "factory": "rx"}, { "dimension" : 1, "currency": "RMB", "quantity": "100", "price": "3", "factory": "rx"}, { "dimension" : 1, "currency": "RMB", "quantity": "200", "price": "5", "factory": "rx"}, { "dimension" : 0, "currency": "RMB", "quantity": "100", "price": "1.2", "factory": "hsf"}, { "dimension" : 0, "currency": "RMB", "quantity": "200", "price": "2.4", "factory": "hsf"}, { "dimension" : 1, "currency": "RMB", "quantity": "100", "price": "3", "factory": "hsf"}, { "dimension" : 1, "currency": "RMB", "quantity": "200", "price": "4.5", "factory": "hsf"}] </code></pre> <p>How should I use ejs to turn into the following table?</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;th&gt;Dimension&lt;/th&gt;&lt;th&gt;Quantity&lt;/th&gt;&lt;th&gt;Factory: rx&lt;/th&gt;&lt;th&gt;Factory: hsf&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;0&lt;/td&gt;&lt;td&gt;100&lt;/td&gt;&lt;td&gt;3&lt;/td&gt;&lt;td&gt;1.2&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;0&lt;/td&gt;&lt;td&gt;200&lt;/td&gt;&lt;td&gt;4&lt;/td&gt;&lt;td&gt;2.4&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt;&lt;td&gt;100&lt;/td&gt;&lt;td&gt;3&lt;/td&gt;&lt;td&gt;3&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt;&lt;td&gt;200&lt;/td&gt;&lt;td&gt;5&lt;/td&gt;&lt;td&gt;4.5&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>I have to make sure that the price is from the correct factory. I think this problem is easy if html allows me to define table column by column. But html table only allows me to do it row-wise.</p> <p>Thank you very much for any help.</p>
0
1,549
'GridView1' fired event PageIndexChanging which wasn't handled
<p>I am using a gridview and I want to use paging. I have already set allow paging to true and page size to 5. I can see the numbers at the base of my gridview, but when i click on a number to move to respective page, it throws an error saying:</p> <p><code>The GridView 'GridView1' fired event PageIndexChanging which wasn't handled.</code></p> <p>Code:</p> <pre><code> &lt;asp:GridView ID="GridView1" runat="server" CellPadding="5" AutoGenerateColumns="False" AllowPaging="True" DataKeyNames="contact_id" onrowcancelingedit="GridView1_RowCancelingEdit" onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating" PageSize="5"&gt; &lt;Columns&gt; &lt;asp:TemplateField HeaderText="contact_id"&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="Label3" runat="server" Text='&lt;%# Eval("contact_id") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="name"&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="Label4" runat="server" Text='&lt;%# Eval("name") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="address"&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="Label5" runat="server" Text='&lt;%# Eval("address") %&gt;'&gt;&lt;/asp:Label&gt;&lt;br /&gt; &lt;asp:Label ID="Label6" runat="server" Text='&lt;%# Eval("city") %&gt;'&gt;&lt;/asp:Label&gt;&lt;br /&gt; &lt;asp:Label ID="Label7" runat="server" Text='&lt;%# Eval("state") %&gt;'&gt;&lt;/asp:Label&gt;&lt;br /&gt; &lt;asp:Label ID="Label8" runat="server" Text='&lt;%# Eval("pincode") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="email"&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="Label9" runat="server" Text='&lt;%# Eval("email") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="mobile"&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="Label10" runat="server" Text='&lt;%# Eval("mobile") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="context"&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="Label11" runat="server" Text='&lt;%# Eval("context") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="status"&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="Label12" runat="server" Text='&lt;%# Eval("status") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;EditItemTemplate&gt; &lt;asp:DropDownList ID="DropDownList1" runat="server"&gt; &lt;asp:ListItem&gt;PENDING&lt;/asp:ListItem&gt; &lt;asp:ListItem&gt;OK&lt;/asp:ListItem&gt; &lt;/asp:DropDownList&gt; &lt;/EditItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="Edit" ShowHeader="False"&gt; &lt;ItemTemplate&gt; &lt;asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"&gt;&lt;/asp:LinkButton&gt; &lt;/ItemTemplate&gt; &lt;EditItemTemplate&gt; &lt;asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"&gt;&lt;/asp:LinkButton&gt; &amp;nbsp;&lt;asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"&gt;&lt;/asp:LinkButton&gt; &lt;/EditItemTemplate&gt; &lt;ItemStyle CssClass="button" /&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;PagerStyle HorizontalAlign="Left" VerticalAlign="Middle" /&gt; &lt;/asp:GridView&gt; </code></pre>
0
2,139
Why my turn server doesn't work?
<p>I can connect in any situation when using <a href="https://appr.tc" rel="noreferrer">appr.tc</a> ice servers (google turn servers). but i can't connect with my own turn server. I did config my own turn server by <code>coturn project</code>. </p> <p>I'm using google's <code>libjingle_peerconnection</code> api to create an <code>Android Application</code> that can perform <code>video call</code>.</p> <p><strong>When i run turn server:</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;pre&gt; RFC 3489/5389/5766/5780/6062/6156 STUN/TURN Server Version Coturn-4.5.0.5 'dan Eider' 0: Max number of open files/sockets allowed for this process: 4096 0: Due to the open files/sockets limitation, max supported number of TURN Sessions possible is: 2000 (approximately) 0: ==== Show him the instruments, Practical Frost: ==== 0: TLS supported 0: DTLS supported 0: DTLS 1.2 is not supported 0: TURN/STUN ALPN is not supported 0: Third-party authorization (oAuth) supported 0: GCM (AEAD) supported 0: OpenSSL compile-time version: OpenSSL 1.0.1e-fips 11 Feb 2013 (0x1000105f) 0: 0: SQLite is not supported 0: Redis is not supported 0: PostgreSQL is not supported 0: MySQL supported 0: MongoDB is not supported 0: 0: Default Net Engine version: 3 (UDP thread per CPU core) ===================================================== 0: Config file found: /usr/local/etc/turnserver.conf 0: Config file found: /usr/local/etc/turnserver.conf 0: Domain name: 0: Default realm: myserver.com 0: CONFIGURATION ALERT: you specified long-term user accounts, (-u option) but you did not specify the long-term credentials option (-a or --lt-cred-mech option). I am turning --lt-cred-mech ON for you, but double-check your configuration. 0: WARNING: cannot find certificate file: turn_server_cert.pem (1) 0: WARNING: cannot start TLS and DTLS listeners because certificate file is not set properly 0: WARNING: cannot find private key file: turn_server_pkey.pem (1) 0: WARNING: cannot start TLS and DTLS listeners because private key file is not set properly 0: NO EXPLICIT LISTENER ADDRESS(ES) ARE CONFIGURED 0: ===========Discovering listener addresses: ========= 0: Listener address to use: 127.0.0.1 0: Listener address to use: 137.74.35.124 0: Listener address to use: ::1 0: ===================================================== 0: Total: 1 'real' addresses discovered 0: ===================================================== 0: NO EXPLICIT RELAY ADDRESS(ES) ARE CONFIGURED 0: ===========Discovering relay addresses: ============= 0: Relay address to use: 137.74.35.124 0: Relay address to use: ::1 0: ===================================================== 0: Total: 2 relay addresses discovered 0: ===================================================== 0: pid file created: /var/run/turnserver.pid 0: IO method (main listener thread): epoll (with changelist) 0: Wait for relay ports initialization... 0: relay 137.74.35.124 initialization... 0: relay 137.74.35.124 initialization done 0: relay ::1 initialization... 0: relay ::1 initialization done 0: Relay ports initialization done 0: IO method (general relay thread): epoll (with changelist) 0: turn server id=0 created 0: IO method (general relay thread): epoll (with changelist) 0: turn server id=1 created 0: IPv4. TCP listener opened on : 127.0.0.1:3478 0: IPv4. TCP listener opened on : 127.0.0.1:3479 0: IPv4. TCP listener opened on : 137.74.35.124:3478 0: IPv4. TCP listener opened on : 137.74.35.124:3479 0: IPv6. TCP listener opened on : ::1:3478 0: IPv6. TCP listener opened on : ::1:3479 0: IPv4. TCP listener opened on : 127.0.0.1:3478 0: IPv4. TCP listener opened on : 127.0.0.1:3479 0: IPv4. TCP listener opened on : 137.74.35.124:3478 0: IPv4. TCP listener opened on : 137.74.35.124:3479 0: IPv6. TCP listener opened on : ::1:3478 0: IPv6. TCP listener opened on : ::1:3479 0: IPv4. UDP listener opened on: 127.0.0.1:3478 0: IPv4. UDP listener opened on: 127.0.0.1:3479 0: IPv4. UDP listener opened on: 137.74.35.124:3478 0: IPv4. UDP listener opened on: 137.74.35.124:3479 0: IPv6. UDP listener opened on: ::1:3478 0: IPv6. UDP listener opened on: ::1:3479 0: Total General servers: 2 0: IO method (auth thread): epoll (with changelist) 0: IO method (auth thread): epoll (with changelist) 0: IO method (admin thread): epoll (with changelist) 0: IPv4. CLI listener opened on : 127.0.0.1:5766 &lt;/pre&gt; </code></pre> <p><strong>When i call from peer A to B :</strong></p> <p>IP of a peer is 192.68.7.3 !!! Why?</p> <pre class="lang-html prettyprint-override"><code>&lt;pre&gt; 58: IPv4. tcp or tls connected to: 5.112.222.14:1358 58: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;&gt;: incoming packet message processed, error 401: Unauthorized 58: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;&gt;: incoming packet message processed, error 401: Unauthorized 58: IPv4. Local relay addr: 137.74.35.124:51937 58: session 001000000000000001: new, realm=&lt;myserver.com&gt;, username=&lt;heydari&gt;, lifetime=600 58: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet ALLOCATE processed, success 58: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet ALLOCATE processed, success 69: session 001000000000000001: peer 192.168.7.3 lifetime updated: 300 69: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet CREATE_PERMISSION processed, success 69: session 001000000000000001: peer 192.168.7.3 lifetime updated: 300 69: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet CREATE_PERMISSION processed, success 69: session 001000000000000001: peer 109.110.172.36 lifetime updated: 300 69: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet CREATE_PERMISSION processed, success 69: session 001000000000000001: peer 109.110.172.36 lifetime updated: 300 69: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet CREATE_PERMISSION processed, success 186: session 001000000000000001: refreshed, realm=&lt;myserver.com&gt;, username=&lt;heydari&gt;, lifetime=0 186: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet REFRESH processed, success &lt;/pre&gt; </code></pre> <p><strong>When i call from peer B to peer A :</strong></p> <p>I don't see peers after realm lines !! why?</p> <pre class="lang-html prettyprint-override"><code>&lt;pre&gt; 188: handle_udp_packet: New UDP endpoint: local addr 137.74.35.124:3478, remote addr 5.112.222.14:1164 188: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;&gt;: incoming packet BINDING processed, success 188: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;&gt;: incoming packet message processed, error 401: Unauthorized 188: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;&gt;: incoming packet BINDING processed, success 188: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;&gt;: incoming packet message processed, error 401: Unauthorized 188: IPv4. Local relay addr: 137.74.35.124:57827 188: session 001000000000000001: new, realm=&lt;myserver.com&gt;, username=&lt;heydari&gt;, lifetime=600 188: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet ALLOCATE processed, success 188: IPv4. tcp or tls connected to: 5.112.222.14:1496 188: session 000000000000000001: realm &lt;myserver.com&gt; user &lt;&gt;: incoming packet message processed, error 401: Unauthorized 188: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet ALLOCATE processed, success 189: session 000000000000000001: realm &lt;myserver.com&gt; user &lt;&gt;: incoming packet message processed, error 401: Unauthorized 189: IPv4. Local relay addr: 137.74.35.124:52856 189: session 000000000000000001: new, realm=&lt;myserver.com&gt;, username=&lt;heydari&gt;, lifetime=600 189: session 000000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet ALLOCATE processed, success 189: session 000000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet ALLOCATE processed, success 198: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet BINDING processed, success 199: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet BINDING processed, success 209: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet BINDING processed, success 209: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet BINDING processed, success 219: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet BINDING processed, success 219: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet BINDING processed, success 229: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet BINDING processed, success 229: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet BINDING processed, success 239: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet BINDING processed, success 239: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet BINDING processed, success 249: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet BINDING processed, success 249: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet BINDING processed, success 260: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet BINDING processed, success 260: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet BINDING processed, success 267: session 001000000000000001: refreshed, realm=&lt;myserver.com&gt;, username=&lt;heydari&gt;, lifetime=0 267: session 001000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet REFRESH processed, success 267: session 000000000000000001: refreshed, realm=&lt;myserver.com&gt;, username=&lt;heydari&gt;, lifetime=0 267: session 000000000000000001: realm &lt;myserver.com&gt; user &lt;heydari&gt;: incoming packet REFRESH processed, success &lt;/pre&gt; </code></pre> <p>I Can't establish successfull connection peers. Where is the problem?</p> <p>When I use <a href="https://appr.tc" rel="noreferrer">appr.tc</a> turn servers I can call from and to each peers so i think my application is ok.</p>
0
3,534
problems after installing java 8
<p>Android Studio had a popup telling updates was available after i run the SDK manager and started the Android Studio again I got another popoup that toke me to Androids website where it told me that I should upgrade to Java JDK 8 and JRE 8 after I did i got over 235 errors when try to run the debug. I uninstalled version 8 and reinstalled 7u80 JDK and JRE now I'm down to 34 errors. When I type java -version I get 1.8.073 here are all 35 errors.</p> <pre><code> Error:java.lang.UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor version 52.0 Error:java.lang.UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor version 52.0 Error: at java.lang.ClassLoader.defineClass1(Native Method) Error: at java.lang.ClassLoader.defineClass1(Native Method) Error: at java.lang.ClassLoader.defineClass(ClassLoader.java:800) Error: at java.lang.ClassLoader.defineClass(ClassLoader.java:800) Error: at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) Error: at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) Error: at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) Error: at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) Error: at java.net.URLClassLoader.access$100(URLClassLoader.java:71) Error: at java.net.URLClassLoader.access$100(URLClassLoader.java:71) Error: at java.net.URLClassLoader$1.run(URLClassLoader.java:361) Error: at java.net.URLClassLoader$1.run(URLClassLoader.java:361) Error: at java.net.URLClassLoader$1.run(URLClassLoader.java:355) Error: at java.net.URLClassLoader$1.run(URLClassLoader.java:355) Error: at java.security.AccessController.doPrivileged(Native Method) Error: at java.security.AccessController.doPrivileged(Native Method) Error: at java.net.URLClassLoader.findClass(URLClassLoader.java:354) Error: at java.net.URLClassLoader.findClass(URLClassLoader.java:354) Error: at java.lang.ClassLoader.loadClass(ClassLoader.java:425) Error: at java.lang.ClassLoader.loadClass(ClassLoader.java:425) Error: at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) Error: at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) Error: at java.lang.ClassLoader.loadClass(ClassLoader.java:358) Error: at java.lang.ClassLoader.loadClass(ClassLoader.java:358) Error: at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482) Error: at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482) Error:Exception in thread "main" Error:Exception in thread "main" Error:Execution failed for task ':app:transformClassesWithDexForDebug'. &gt; com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_80\bin\java.exe'' finished with non-zero exit value 1 </code></pre> <p>Here is the Gradel.build</p> <pre><code>android { compileSdkVersion 23 buildToolsVersion '24.0.0 rc1' defaultConfig { applicationId "com.kim.printer" minSdkVersion 21 targetSdkVersion 23 } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } productFlavors { } } dependencies { compile 'com.google.android.gms:play-services-gcm:8.4.0' compile 'com.google.code.gson:gson:2.4' compile "com.android.support:support-v4:23.1.0" compile "com.android.support:support-v13:23.1.0" compile "com.android.support:cardview-v7:23.1.0" compile 'com.android.support:appcompat-v7:23.0.0' compile files('libs/StarIOPort3.1.jar') compile files('libs/StarIO_Extension.jar') } </code></pre> <p>Thanks for any help I have been working on this for 6 hours and I can get it to compile.</p>
0
1,441
Implementing a slider (SeekBar) in Android
<p>I want to implement a slider, which is basically two lines, one vertical and one horizontal, crossing where the screen is touched. I have managed to make one but I have to issues:</p> <ol> <li>The slider is not very smooth, there is a slight delay when I'm moving the finger</li> <li>If I place two sliders it is not multitouch, and I'd like to use both of them simultaneously</li> </ol> <p>Here is the code: </p> <pre><code>public class Slider extends View { private Controller controller = new Controller(); private boolean initialisedSlider; private int sliderWidth, sliderHeight; private Point pointStart; private Paint white; private int mode; final static int VERTICAL = 0, HORIZONTAL = 1, BOTH = 2; public Slider(Context context) { super(context); setFocusable(true); // TODO Auto-generated constructor stub } public Slider(Context context, AttributeSet attrs) { super(context, attrs); setFocusable(true); pointStart = new Point(); initialisedSlider = false; mode = Slider.BOTH; } @Override protected void onDraw(Canvas canvas) { if(!initialisedSlider) { initialisedSlider = true; sliderWidth = getMeasuredWidth(); sliderHeight = getMeasuredHeight(); pointStart.x = (int)(sliderWidth/2.0); pointStart.y = (int)(sliderHeight/2.0); controller = new Controller(pointStart, 3); white = new Paint(); white.setColor(0xFFFFFFFF); } canvas.drawLine(controller.getCoordX(),0, controller.getCoordX(),sliderHeight, white); canvas.drawLine(0, controller.getCoordY(), sliderWidth, controller.getCoordY(), white); } public boolean onTouchEvent(MotionEvent event) { int eventaction = event.getAction(); int X = (int)event.getX(); int Y = (int)event.getY(); switch (eventaction) { case MotionEvent.ACTION_DOWN: if(isInBounds(X,Y)) { updateController(X, Y); } break; case MotionEvent.ACTION_MOVE: if(isInBounds(X,Y)) { updateController(X, Y); } break; case MotionEvent.ACTION_UP: if(isInBounds(X,Y)) { updateController(X, Y); } break; } invalidate(); return true; } private boolean isInBounds(int x, int y) { return ((x&lt;=(sliderWidth)) &amp;&amp; (x&gt;=(0)) &amp;&amp; (y&lt;=(sliderHeight)) &amp;&amp; (y&gt;=(0))); } private void updateController(int x, int y) { switch(mode) { case Slider.HORIZONTAL: controller.setCoordX(x); break; case Slider.VERTICAL: controller.setCoordY(y); break; case Slider.BOTH: controller.setCoordX(x); controller.setCoordY(y); break; } } private class Controller { private int coordX, coordY; Controller() { } Controller(Point point, int width) { setCoordX(point.x); setCoordY(point.y); } public void setCoordX(int coordX) { this.coordX = coordX; } public int getCoordX() { return coordX; } public void setCoordY(int coordY) { this.coordY = coordY; } public int getCoordY() { return coordY; } } } </code></pre> <p>And the XML file: </p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" &gt; &lt;TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /&gt; &lt;com.android.lasttest.Slider android:id="@+id/slider" android:layout_width="100dp" android:layout_height="100dp" android:layout_gravity="center_horizontal" android:adjustViewBounds="true"/&gt; &lt;com.android.lasttest.Slider android:id="@+id/slider" android:layout_width="150dp" android:layout_height="150dp" android:layout_gravity="center_horizontal" android:adjustViewBounds="true"/&gt; &lt;com.android.lasttest.Slider android:id="@+id/slider" android:layout_width="200dp" android:layout_height="200dp" android:layout_gravity="center_horizontal" android:adjustViewBounds="true"/&gt; &lt;/LinearLayout&gt; </code></pre>
0
2,340
How to take values of only selected checkbox in Action class in Struts 2 and JSP
<p>I am displaying 24 checkboxes. I want to get all the values of checked checkboxes in action class and insert it as a new record inside database.Inserting will be done once I succeed in getting the values of checked checkboxes on button click.</p> <p>I referred <a href="https://stackoverflow.com/questions/6800008/how-to-retrieve-checkbox-values-in-struts-2-action-class">this</a> link in which I followed the answer answered by steven sir but with help of that I can display only boolean values but here I want text values of checkboxes selected.</p> <p>So below is my JSP page.</p> <pre class="lang-jsp prettyprint-override"><code>&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=ISO-8859-1&quot; pageEncoding=&quot;ISO-8859-1&quot;%&gt; &lt;%@taglib uri=&quot;/struts-tags&quot; prefix=&quot;s&quot; %&gt; &lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;s:form action=&quot;eventInsertAction&quot;&gt; &lt;!-- Main content --&gt; &lt;section class=&quot;content&quot;&gt; &lt;!-- Small boxes (Stat box) --&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;contetpanel&quot;&gt; &lt;div&gt; &lt;div class=&quot;crevtbl&quot;&gt; &lt;div class=&quot;crevtblRow&quot;&gt; &lt;div class=&quot;crevtblCell&quot;&gt;Event Name&lt;/div&gt; &lt;div class=&quot;crevtblCell1&quot;&gt;:&lt;/div&gt; &lt;div class=&quot;crevtblCell2&quot;&gt;&lt;input name=&quot;event.eventName&quot; class=&quot;formtextfield&quot; type=&quot;text&quot;&gt;&lt;s:fielderror fieldName=&quot;event.eventName&quot;/&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;crevtblRow&quot;&gt; &lt;div class=&quot;crevtblCell&quot;&gt;Company Name&lt;/div&gt; &lt;div class=&quot;crevtblCell1&quot;&gt;:&lt;/div&gt; &lt;div class=&quot;crevtblCell2&quot;&gt;&lt;input name=&quot;event.companyName&quot; class=&quot;formtextfield&quot; type=&quot;text&quot; &gt;&lt;s:fielderror fieldName=&quot;event.companyName&quot;/&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;crevtblRow&quot;&gt; &lt;div class=&quot;crevtblCell&quot;&gt;Contact Person Name&lt;/div&gt; &lt;div class=&quot;crevtblCell1&quot;&gt;:&lt;/div&gt; &lt;div class=&quot;crevtblCell2&quot;&gt;&lt;input name=&quot;event.contactPerson&quot; class=&quot;formtextfield&quot; type=&quot;text&quot; &gt;&lt;s:fielderror fieldName=&quot;event.contactPerson&quot;/&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;crevtblRow&quot;&gt; &lt;div class=&quot;crevtblCell&quot;&gt;Contact&lt;/div&gt; &lt;div class=&quot;crevtblCell1&quot;&gt;:&lt;/div&gt; &lt;div class=&quot;crevtblCell2&quot;&gt;&lt;input name=&quot;event.contactNumber&quot; class=&quot;formtextfield&quot; type=&quot;text&quot; &gt;&lt;s:fielderror fieldName=&quot;event.contactNumber&quot;/&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;crevtblRow&quot;&gt; &lt;div class=&quot;crevtblCell&quot;&gt;Email&lt;/div&gt; &lt;div class=&quot;crevtblCell1&quot;&gt;:&lt;/div&gt; &lt;div class=&quot;crevtblCell2&quot;&gt;&lt;input name=&quot;event.emailId&quot; class=&quot;formtextfield&quot; type=&quot;text&quot; &gt;&lt;s:fielderror fieldName=&quot;event.emailId&quot;/&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;crevtblRow&quot;&gt; &lt;div class=&quot;crevtblCell&quot;&gt;Event Venue&lt;/div&gt; &lt;div class=&quot;crevtblCell1&quot;&gt;:&lt;/div&gt; &lt;div class=&quot;crevtblCell2&quot;&gt;&lt;input name=&quot;event.eventVenue&quot; class=&quot;formtextfield&quot; type=&quot;text&quot; &gt;&lt;s:fielderror fieldName=&quot;event.eventVenue&quot;/&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;crevtblRow&quot;&gt; &lt;div class=&quot;crevtblCell&quot;&gt;Event Date&lt;/div&gt; &lt;div class=&quot;crevtblCell1&quot;&gt;:&lt;/div&gt; &lt;div class=&quot;crevtblCell2&quot;&gt;From : &lt;input name=&quot;event.fromDate&quot; class=&quot;formtextfield1&quot; type=&quot;text&quot; placeholder=&quot;YYYY/MM/DD&quot;&gt; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; To : &lt;input name=&quot;event.toDate&quot; class=&quot;formtextfield1&quot; type=&quot;text&quot; placeholder=&quot;YYYY/MM/DD&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;crevtblRow&quot;&gt; &lt;div class=&quot;crevtblCell&quot;&gt;Event Time&lt;/div&gt; &lt;div class=&quot;crevtblCell1&quot;&gt;:&lt;/div&gt; &lt;div class=&quot;crevtblCell2&quot;&gt;&lt;input name=&quot;event.eventTime&quot; class=&quot;formtextfield1&quot; type=&quot;text&quot; placeholder=&quot;HH:MM AM/PM&quot; &gt;&lt;s:fielderror fieldName=&quot;event.eventTime&quot;/&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;crevtblRow&quot;&gt; &lt;div class=&quot;crevtblCell&quot;&gt;License Required&lt;/div&gt; &lt;div class=&quot;crevtblCell1&quot;&gt;:&lt;/div&gt; &lt;div class=&quot;crevtblCell2&quot;&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Rangabhoomi&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Fire NOC&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Fire Engine&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Premises &amp;amp; NOC&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Performance&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;PWD&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Local Police&lt;/span&gt;&lt;br /&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Collector&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;PPL&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;IPRS&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Traffic&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Liquor License&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Ticket Selling License&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;BMC Parking&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Parking&lt;/span&gt;&lt;br /&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Port Trust&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Novex&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Foreign Artist&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;DCP Office&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Fire Marshal&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Sale Tax NOC&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Other&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Extra&lt;/span&gt; &lt;input name=&quot;event.licenserequired&quot; type=&quot;checkbox&quot; class=&quot;formcheckbox&quot; value=&quot;&quot;&gt;&lt;span class=&quot;formcheckbox_content&quot;&gt;Commission&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;crevtblRow&quot;&gt; &lt;div class=&quot;crevtblCell&quot;&gt;&lt;/div&gt; &lt;div class=&quot;crevtblCell1&quot;&gt;&lt;/div&gt; &lt;div class=&quot;crevtblCell2&quot;&gt;&lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Create Event&lt;/button&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;/s:form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Below is my setters and getters class</strong></p> <pre class="lang-java prettyprint-override"><code>package com.ca.pojo; public class Event { public Event() { // TODO Auto-generated constructor stub } private String eventName; private String companyName; private String contactPerson; private String contactNumber; private String emailId; private String eventVenue; private String fromDate; private String toDate; private String eventTime; private String licenserequired; public String getEventName() { return eventName; } public void setEventName(String eventName) { this.eventName = eventName; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getContactPerson() { return contactPerson; } public void setContactPerson(String contactPerson) { this.contactPerson = contactPerson; } public String getContactNumber() { return contactNumber; } public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public String getEventVenue() { return eventVenue; } public void setEventVenue(String eventVenue) { this.eventVenue = eventVenue; } public String getFromDate() { return fromDate; } public void setFromDate(String fromDate) { this.fromDate = fromDate; } public String getToDate() { return toDate; } public void setToDate(String toDate) { this.toDate = toDate; } public String getEventTime() { return eventTime; } public void setEventTime(String eventTime) { this.eventTime = eventTime; } public String getLicenserequired() { return licenserequired; } public void setLicenserequired(String licenserequired) { this.licenserequired = licenserequired; } } </code></pre> <p><strong>Below is my Action class</strong></p> <pre class="lang-java prettyprint-override"><code>package com.ca.actions; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.ca.database.Database; import com.ca.pojo.Event; import com.opensymphony.xwork2.ActionSupport; public class EventInsertAction extends ActionSupport { private String eventId; Event event; String name; public EventInsertAction() { // TODO Auto-generated constructor stub } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEventId() { return eventId; } public void setEventId(String eventId) { this.eventId = eventId; } public Event getEvent() { return event; } public void setEvent(Event event) { this.event = event; } @Override public String execute() throws Exception { System.out.println(&quot;Event&quot;+event.getLicenserequired()); // TODO Auto-generated method stub System.out.println(&quot;Hi Mahi&quot;+name); List&lt;Integer&gt; ints = new ArrayList&lt;Integer&gt;(); int i = 0; for (int i1 = 0; i1 &lt; 10000; i1++) { ints.add(i1); } // Collections.shuffle(ints); String Id = String.valueOf(ints.get(i++)); eventId = event.getEventName() + Id; System.out.println(eventId); try { Database database = new Database(); Connection con = database.Get_Connection(); System.out.println(&quot;Driver Loaded&quot;); PreparedStatement st = con .prepareStatement(&quot;insert into event(EVENT_ID,EVENT_NAME,COMPANY_NAME,CONTACT_PERSON,CONTACT_NO,EMAIL_ID,EVENT_VENUE,FROM_DATE,TO_DATE,EVENT_TIME)&quot; + &quot;values(?,?,?,?,?,?,?,?,?,?)&quot;); st.setString(1, eventId); st.setString(2, event.getEventName()); st.setString(3, event.getCompanyName()); st.setString(4, event.getContactPerson()); st.setString(5, event.getContactNumber()); st.setString(6, event.getEmailId()); st.setString(7, event.getEventVenue()); st.setString(8, event.getFromDate()); st.setString(9, event.getToDate()); st.setString(10, event.getEventTime()); st.executeUpdate(); System.out.println(&quot;success&quot;); con.close(); } catch (Exception e) { System.out.println(e); } return &quot;success&quot;; } @Override public void validate() { // TODO Auto-generated method stub super.validate(); if (event.getEventName().isEmpty()) { System.out.println(&quot;Event Name&quot;); addFieldError(&quot;event.eventName&quot;, &quot;Please Enter Event Name ..&quot;); } if (event.getCompanyName().isEmpty()) { addFieldError(&quot;event.companyName&quot;, &quot;Please Enter Company Name.. &quot;); } if (event.getContactNumber().isEmpty()) { addFieldError(&quot;event.contactNumber&quot;, &quot;Please Enter Contact Number..&quot;); } else { String expression = &quot;^\\+?[0-9\\-]+\\*?$&quot;; CharSequence inputStr = event.getContactNumber(); Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputStr); if (!matcher.matches()) addFieldError(&quot;event.contactNumber&quot;, &quot;Invalid Contact Number..&quot;); } if (event.getContactPerson().isEmpty()) { addFieldError(&quot;event.contactPerson&quot;, &quot;Please Enter Contact Person Name..&quot;); } if (event.getEmailId().isEmpty()) { addFieldError(&quot;event.emailId&quot;, &quot;Please Enter Email ID..&quot;); } else { String expression = &quot;^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$&quot;; CharSequence inputStr = event.getEmailId(); Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputStr); if (!matcher.matches()) addFieldError(&quot;event.emailId&quot;, &quot;Invalid Email Address..&quot;); } if (event.getEventVenue().isEmpty()) { addFieldError(&quot;event.eventVenue&quot;, &quot;Please Enter Event Venue..&quot;); } if (event.getFromDate().isEmpty()) { addFieldError(&quot;event.fromDate&quot;, &quot;Please Enter Date..&quot;); } if (event.getToDate().isEmpty()) { addFieldError(&quot;event.toDate&quot;, &quot;Please Enter To Date..&quot;); } if (event.getEventTime().isEmpty()) { addFieldError(&quot;event.eventTime&quot;, &quot;Please Enter Event Time..&quot;); } } } </code></pre>
0
10,382
jQuery post a serialized form then inserting into mysql via php?
<p>I'm trying to post a serialized form to a sumbit.php file, in turn, will then insert into a MySQL database; however, the last input which is hidden, is not getting inserted into the database, though the rest are.</p> <p>Here's some snippet examples of what I've got thus far which is not working: </p> <p><strong>HTML</strong></p> <pre><code> &lt;form method="post" action="" &gt; &lt;label for="name" class="overlay"&gt;&lt;span&gt;Name...&lt;/span&gt;&lt;/label&gt; &lt;input class="input-text" type="text" name="name" id="name" /&gt; &lt;label for="email" class="overlay"&gt;&lt;span&gt;Email...&lt;/span&gt;&lt;/label&gt; &lt;input type="text" class="input-text" name="email" id="email"/&gt; &lt;label for="website" class="overlay"&gt;&lt;span&gt;Website...&lt;/span&gt;&lt;/label&gt; &lt;input type="text" class="input-text" name="website" id="website"/&gt; &lt;label id="body-label" for="body" class="overlay"&gt;&lt;span&gt;Comment it up...&lt;/span&gt;&lt;/label&gt; &lt;textarea class="input-text" name="body" id="body" cols="20" rows="5"&gt;&lt;/textarea&gt; &lt;input type="hidden" name="parentid" id="parentid" value="0" /&gt; &lt;input type="submit" value="Comment" name="submit" id="comment-submit" /&gt; &lt;/span&gt; &lt;/form&gt; </code></pre> <p><strong>Javascript</strong> </p> <pre><code>$('form.').submit(function(event) { $.post('submit.php',$(this).serialize(),function(msg){ // form inputs consist of 5 values total: name, email, website, text, and a hidden input that has the value of an integer } }); </code></pre> <p><strong>PHP (submit.php)</strong></p> <pre><code>$arr = array(); mysql_query(" INSERT INTO comments(name,email,website,body,parentid) VALUES ( '".$arr['name']."', '".$arr['email']."', '".$arr['website']."', '".$arr['body']."', '".$arr['parentid']."' )"); </code></pre>
0
1,170
Tee does not show output or write to file
<p>I wrote a python script to monitor the statuses of some network resources, an infinite pinger if you will. It pings the same 3 nodes forever until it receives a keyboard interrupt. I tried using tee to redirect the output of the program to a file, but it does not work:</p> <pre><code>λ sudo ./pingster.py 15:43:33 node1 SUCESS | node2 SUCESS | node3 SUCESS 15:43:35 node1 SUCESS | node2 SUCESS | node3 SUCESS 15:43:36 node1 SUCESS | node2 SUCESS | node3 SUCESS 15:43:37 node1 SUCESS | node2 SUCESS | node3 SUCESS 15:43:38 node1 SUCESS | node2 SUCESS | node3 SUCESS ^CTraceback (most recent call last): File "./pingster.py", line 42, in &lt;module&gt; main() File "./pingster.py", line 39, in main sleep(1) KeyboardInterrupt λ sudo ./pingster.py | tee ping.log # wait a few seconds ^CTraceback (most recent call last): File "./pingster.py", line 42, in &lt;module&gt; main() File "./pingster.py", line 39, in main sleep(1) KeyboardInterrupt λ file ping.log ping.log: empty </code></pre> <p>I am using <a href="https://pypi.python.org/pypi/colorama" rel="noreferrer">colorama</a> for my output, I thought that perhaps could be causing the issue, but I tried printing something before I even imported colorama, and the file is still empty. What am I doing wrong here?</p> <p>Edit: Here is the python file I'm using</p> <pre><code>#!/home/nate/py-env/ping/bin/python from __future__ import print_function from datetime import datetime from collections import OrderedDict from time import sleep import ping import colorama def main(): d = { 'node1': '10.0.0.51', 'node2': '10.0.0.50', 'node3': '10.0.0.52', } addresses = OrderedDict(sorted(d.items(), key=lambda t: t[0])) colorama.init() while True: status = [] time = datetime.now().time().strftime('%H:%M:%S') print(time, end='\t') for location, ip_address in addresses.items(): loss, max_time, avg_time = ping.quiet_ping(ip_address, timeout=0.5) if loss &lt; 50: status.append('{0} SUCESS'.format(location)) else: status.append( '{}{} FAIL{}'.format( colorama.Fore.RED, location, colorama.Fore.RESET, ) ) print(' | '.join(status)) sleep(1) if __name__ == '__main__': main() </code></pre>
0
1,109
Spark SQL UNION - ORDER BY column not in SELECT
<p>I'm doing a UNION of two temp tables and trying to order by column but spark complains that the column I am ordering by cannot be resolved. Is this a bug or I'm missing something?</p> <pre class="lang-scala prettyprint-override"><code>lazy val spark: SparkSession = SparkSession.builder.master(&quot;local[*]&quot;).getOrCreate() import org.apache.spark.sql.types.StringType val oldOrders = Seq( Seq(&quot;old_order_id1&quot;, &quot;old_order_name1&quot;, &quot;true&quot;), Seq(&quot;old_order_id2&quot;, &quot;old_order_name2&quot;, &quot;true&quot;) ) val newOrders = Seq( Seq(&quot;new_order_id1&quot;, &quot;new_order_name1&quot;, &quot;false&quot;), Seq(&quot;new_order_id2&quot;, &quot;new_order_name2&quot;, &quot;false&quot;) ) val schema = new StructType() .add(&quot;id&quot;, StringType) .add(&quot;name&quot;, StringType) .add(&quot;is_old&quot;, StringType) val oldOrdersDF = spark.createDataFrame(spark.sparkContext.makeRDD(oldOrders.map(x =&gt; Row(x:_*))), schema) val newOrdersDF = spark.createDataFrame(spark.sparkContext.makeRDD(newOrders.map(x =&gt; Row(x:_*))), schema) oldOrdersDF.createOrReplaceTempView(&quot;old_orders&quot;) newOrdersDF.createOrReplaceTempView(&quot;new_orders&quot;) //ordering by column not in select works if I'm not doing UNION spark.sql( &quot;&quot;&quot; |SELECT oo.id, oo.name FROM old_orders oo |ORDER BY oo.is_old &quot;&quot;&quot;.stripMargin).show() //ordering by column not in select doesn't work as I'm doing a UNION spark.sql( &quot;&quot;&quot; |SELECT oo.id, oo.name FROM old_orders oo |UNION |SELECT no.id, no.name FROM new_orders no |ORDER BY oo.is_old &quot;&quot;&quot;.stripMargin).show() The output of the above code is: +-------------+---------------+ | id| name| +-------------+---------------+ |old_order_id1|old_order_name1| |old_order_id2|old_order_name2| +-------------+---------------+ cannot resolve '`oo.is_old`' given input columns: [id, name]; line 5 pos 9; 'Sort ['oo.is_old ASC NULLS FIRST], true +- Distinct +- Union :- Project [id#121, name#122] : +- SubqueryAlias oo : +- SubqueryAlias old_orders : +- LogicalRDD [id#121, name#122, is_old#123] +- Project [id#131, name#132] +- SubqueryAlias no +- SubqueryAlias new_orders +- LogicalRDD [id#131, name#132, is_old#133] org.apache.spark.sql.AnalysisException: cannot resolve '`oo.is_old`' given input columns: [id, name]; line 5 pos 9; 'Sort ['oo.is_old ASC NULLS FIRST], true +- Distinct +- Union :- Project [id#121, name#122] : +- SubqueryAlias oo : +- SubqueryAlias old_orders : +- LogicalRDD [id#121, name#122, is_old#123] +- Project [id#131, name#132] +- SubqueryAlias no +- SubqueryAlias new_orders +- LogicalRDD [id#131, name#132, is_old#133] </code></pre> <p>So ordering by a column that's not in the SELECT clause works if I'm not doing a UNION and it fails if I'm doing a UNION of two tables.</p>
0
1,623
log4j.xml Rolling Appender based on size
<p>Please find below my log4.xml configuration for rolling file appender</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"&gt; &lt;log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'&gt; &lt;appender name="instrumentationAppender" class="org.apache.log4j.RollingFileAppender"&gt; &lt;param name="file" value="C:\\Users\\Test\\Downloads\\Testlogs\\instrumentation.log"/&gt; &lt;param name="Append" value="true" /&gt; &lt;param name="Encoding" value="UTF-8" /&gt; &lt;param name="MaxFileSize" value="100KB"/&gt; &lt;param name="MaxBackupIndex" value="10"/&gt; &lt;layout class="org.apache.log4j.PatternLayout"&gt; &lt;param name="ConversionPattern" value="%d %-5p [%t] (%C:%L) - %m%n"/&gt; &lt;/layout&gt; &lt;filter class="org.apache.log4j.varia.LevelRangeFilter"&gt; &lt;param name="LevelMin" value="INFO" /&gt; &lt;param name="LevelMax" value="INFO" /&gt; &lt;param name="AcceptOnMatch" value="true" /&gt; &lt;/filter&gt; &lt;/appender&gt; &lt;appender name="debugAppender" class="org.apache.log4j.RollingFileAppender"&gt; &lt;param name="file" value="C:\\Users\\Test\\Downloads\\Testlogs\\Test.log"/&gt; &lt;param name="Append" value="true" /&gt; &lt;param name="Encoding" value="UTF-8" /&gt; &lt;param name="MaxFileSize" value="100KB"/&gt; &lt;param name="MaxBackupIndex" value="10"/&gt; &lt;layout class="org.apache.log4j.PatternLayout"&gt; &lt;param name="ConversionPattern" value="%d %-5p [%t] (%C:%L) - %m%n"/&gt; &lt;/layout&gt; &lt;param name="ImmediateFlush" value="true" /&gt; &lt;filter class="org.apache.log4j.varia.LevelRangeFilter"&gt; &lt;param name="LevelMin" value="DEBUG" /&gt; &lt;param name="LevelMax" value="DEBUG" /&gt; &lt;param name="AcceptOnMatch" value="true" /&gt; &lt;/filter&gt; &lt;/appender&gt; &lt;appender name="errorAppender" class="org.apache.log4j.RollingFileAppender"&gt; &lt;param name="file" value="C:\\Users\\Test\\Downloads\\Testlogs\\Test.log"/&gt; &lt;param name="Append" value="true" /&gt; &lt;param name="Encoding" value="UTF-8" /&gt; &lt;param name="MaxFileSize" value="100KB"/&gt; &lt;param name="MaxBackupIndex" value="10"/&gt; &lt;layout class="org.apache.log4j.PatternLayout"&gt; &lt;param name="ConversionPattern" value="%d %-5p [%t] (%C:%L) - %m%n"/&gt; &lt;/layout&gt; &lt;filter class="org.apache.log4j.varia.LevelRangeFilter"&gt; &lt;param name="LevelMin" value="ERROR" /&gt; &lt;param name="LevelMax" value="FATAL" /&gt; &lt;param name="AcceptOnMatch" value="true" /&gt; &lt;/filter&gt; &lt;/appender&gt; &lt;category name="com.practice.Test" additivity="false"&gt; &lt;priority value="DEBUG"/&gt; &lt;appender-ref ref="instrumentationAppender" /&gt; &lt;appender-ref ref="debugAppender" /&gt; &lt;appender-ref ref="errorAppender" /&gt; &lt;/category&gt; </code></pre> <p></p> <p>The issue is instrumentationAppender,debugAppender and errorAppender are refered by com.practice pakaage as defined in above category. In all the appenders maxFileSize is 100kb and configured for Test.log file. The issue Test.log file does not get rollover after 100kb of size. All logs just get appended to same Test.log file. How do configure RollingAppender based on size?</p> <p>Thanks in advance for the help.</p>
0
1,689
Removing Previous Button on First Step jQuery Steps
<p>I'm using jQuery Steps for my site signup wizard, works awesome with the exception that on the first step I'm getting the previous button, which really makes no sense since there is no previous content.</p> <p>I looked at the <code>onInit()</code> function in the API but there is no setting for <code>enablePreviousButton</code>, only <code>enableFinishButton</code> and <code>enableCancelButton</code>.</p> <p>Is there a way I can remove the Previous button on the first step?</p> <p>Requested code:</p> <pre><code>$("#register-form").steps({ headerTag: "h3", bodyTag: "fieldset", autoFocus: true, onInit: function (event, current) { alert(current); }, labels: { finish: 'Sign Up &lt;i class="fa fa-chevron-right"&gt;&lt;/i&gt;', next: 'Next &lt;i class="fa fa-chevron-right"&gt;&lt;/i&gt;', previous: '&lt;i class="fa fa-chevron-left"&gt;&lt;/i&gt; Previous' } }); </code></pre> <p>HTML:</p> <pre><code>&lt;h3&gt;&lt;?= $lang_wizard_account; ?&gt;&lt;/h3&gt; &lt;fieldset&gt; &lt;legend&gt;&lt;?= $lang_text_your_details; ?&gt;&lt;/legend&gt; &lt;div class="form-group"&gt; &lt;label class="control-label col-sm-3" for="username"&gt;&lt;b class="required"&gt;*&lt;/b&gt; &lt;?= $lang_entry_username; ?&gt;&lt;/label&gt; &lt;div class="col-sm-8"&gt; &lt;input type="text" name="username" value="&lt;?= $username; ?&gt;" class="form-control" placeholder="&lt;?= $lang_entry_username; ?&gt;" autofocus id="username" required&gt; &lt;?php if ($error_username) { ?&gt; &lt;span class="help-block error"&gt;&lt;?= $error_username; ?&gt;&lt;/span&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label class="control-label col-sm-3" for="firstname"&gt;&lt;b class="required"&gt;*&lt;/b&gt; &lt;?= $lang_entry_firstname; ?&gt;&lt;/label&gt; &lt;div class="col-sm-8"&gt; &lt;input type="text" name="firstname" value="&lt;?= $firstname; ?&gt;" class="form-control" placeholder="&lt;?= $lang_entry_firstname; ?&gt;" id="firstname" required&gt; &lt;?php if ($error_firstname) { ?&gt; &lt;span class="help-block error"&gt;&lt;?= $error_firstname; ?&gt;&lt;/span&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; .... &lt;/fieldset&gt; </code></pre>
0
1,116
Why is std::unordered_map slow, and can I use it more effectively to alleviate that?
<p>I’ve recently found out an odd thing. It seems that calculating Collatz sequence lengths with <a href="http://melpon.org/wandbox/permlink/xpx3rSzV6thjfz1q" rel="noreferrer">no caching at all</a> is over 2 times <em>faster</em> than <a href="http://melpon.org/wandbox/permlink/Omhqamehs2P6y7Or" rel="noreferrer">using <code>std::unordered_map</code> to cache all elements</a>.</p> <p>Note I did take hints from question <a href="https://stackoverflow.com/questions/11614106/is-gcc-stdunordered-map-implementation-slow-if-so-why">Is gcc std::unordered_map implementation slow? If so - why?</a> and I tried to used that knowledge to make <code>std::unordered_map</code> perform as well as I could (I used g++ 4.6, it did perform better than recent versions of g++, and I tried to specify a sound initial bucket count, I made it exactly equal to the maximum number of elements the map must hold).</p> <p>In comparision, <a href="http://melpon.org/wandbox/permlink/9YayIIQmPm8I1Hmm" rel="noreferrer">using <code>std::vector</code> to cache a few elements</a> was almost 17 times faster than no caching at all and almost 40 times faster than using <code>std::unordered_map</code>.</p> <p>Am I doing something wrong or is this container THAT slow and why? Can it be made performing faster? Or maybe hashmaps are inherently ineffective and should be avoided whenever possible in high-performance code?</p> <p>The problematic benchmark is:</p> <pre><code>#include &lt;iostream&gt; #include &lt;unordered_map&gt; #include &lt;cstdint&gt; #include &lt;ctime&gt; std::uint_fast16_t getCollatzLength(std::uint_fast64_t val) { static std::unordered_map &lt;std::uint_fast64_t, std::uint_fast16_t&gt; cache ({{1,1}}, 2168611); if(cache.count(val) == 0) { if(val%2 == 0) cache[val] = getCollatzLength(val/2) + 1; else cache[val] = getCollatzLength(3*val+1) + 1; } return cache[val]; } int main() { std::clock_t tStart = std::clock(); std::uint_fast16_t largest = 0; for(int i = 1; i &lt;= 999999; ++i) { auto cmax = getCollatzLength(i); if(cmax &gt; largest) largest = cmax; } std::cout &lt;&lt; largest &lt;&lt; '\n'; std::cout &lt;&lt; "Time taken: " &lt;&lt; (double)(std::clock() - tStart)/CLOCKS_PER_SEC &lt;&lt; '\n'; } </code></pre> <p>It outputs: <code>Time taken: 0.761717</code></p> <p>Whereas a benchmark with no caching at all:</p> <pre><code>#include &lt;iostream&gt; #include &lt;unordered_map&gt; #include &lt;cstdint&gt; #include &lt;ctime&gt; std::uint_fast16_t getCollatzLength(std::uint_fast64_t val) { std::uint_fast16_t length = 1; while(val != 1) { if(val%2 == 0) val /= 2; else val = 3*val + 1; ++length; } return length; } int main() { std::clock_t tStart = std::clock(); std::uint_fast16_t largest = 0; for(int i = 1; i &lt;= 999999; ++i) { auto cmax = getCollatzLength(i); if(cmax &gt; largest) largest = cmax; } std::cout &lt;&lt; largest &lt;&lt; '\n'; std::cout &lt;&lt; "Time taken: " &lt;&lt; (double)(std::clock() - tStart)/CLOCKS_PER_SEC &lt;&lt; '\n'; } </code></pre> <p>Outputs <code>Time taken: 0.324586</code></p>
0
1,390
Reading from a cryptostream to the end of the stream
<p>I'm having some trouble with the code below. I have a file in a temporary location which is in need of encryption, this function encrypts that data which is then stored at the "pathToSave" location.</p> <p>On inspection is does not seem to be handling the whole file properly - There are bits missing from my output and I suspect it has something to do with the while loop not running through the whole stream.</p> <p>As an aside, if I try and call CryptStrm.Close() after the while loop I receive an exception. This means that if I attempt to decrypt the file, I get a file already in use error! </p> <p>Tried all the usual and Ive looked on here at similar issues, any help would be great.</p> <p>Thanks</p> <pre><code>public void EncryptFile(String tempPath, String pathToSave) { try { FileStream InputFile = new FileStream(tempPath, FileMode.Open, FileAccess.Read); FileStream OutputFile = new FileStream(pathToSave, FileMode.Create, FileAccess.Write); RijndaelManaged RijCrypto = new RijndaelManaged(); //Key byte[] Key = new byte[32] { ... }; //Initialisation Vector byte[] IV = new byte[32] { ... }; RijCrypto.Padding = PaddingMode.None; RijCrypto.KeySize = 256; RijCrypto.BlockSize = 256; RijCrypto.Key = Key; RijCrypto.IV = IV; ICryptoTransform Encryptor = RijCrypto.CreateEncryptor(Key, IV); CryptoStream CryptStrm = new CryptoStream(OutputFile, Encryptor, CryptoStreamMode.Write); int data; while (-1 != (data = InputFile.ReadByte())) { CryptStrm.WriteByte((byte)data); } } catch (Exception EncEx) { throw new Exception("Encoding Error: " + EncEx.Message); } } </code></pre> <p>EDIT:</p> <p>I've made the assumption that my problem is with Encryption. My Decrypt might be the culprit </p> <pre><code> public String DecryptFile(String encryptedFilePath) { FileStream InputFile = new FileStream(encryptedFilePath, FileMode.Open, FileAccess.Read); RijndaelManaged RijCrypto = new RijndaelManaged(); //Key byte[] Key = new byte[32] { ... }; //Initialisation Vector byte[] IV = new byte[32] { ... }; RijCrypto.Padding = PaddingMode.None; RijCrypto.KeySize = 256; RijCrypto.BlockSize = 256; RijCrypto.Key = Key; RijCrypto.IV = IV; ICryptoTransform Decryptor = RijCrypto.CreateDecryptor(Key, IV); CryptoStream CryptStrm = new CryptoStream(InputFile, Decryptor, CryptoStreamMode.Read); String OutputFilePath = Path.GetTempPath() + "myfile.name"; StreamWriter OutputFile = new StreamWriter(OutputFilePath); OutputFile.Write(new StreamReader(CryptStrm).ReadToEnd()); CryptStrm.Close(); OutputFile.Close(); return OutputFilePath; } </code></pre>
0
1,238
How to force FormRequest return json in Laravel 5.1?
<p>I'm using <a href="http://laravel.com/docs/5.1/validation#form-request-validation">FormRequest</a> to validate from which is sent in an API call from my smartphone app. So, I want FormRequest alway return json when validation fail.</p> <p>I saw the following source code of Laravel framework, the default behaviour of FormRequest is return json if reqeust is Ajax or wantJson.</p> <pre><code>//Illuminate\Foundation\Http\FormRequest class /** * Get the proper failed validation response for the request. * * @param array $errors * @return \Symfony\Component\HttpFoundation\Response */ public function response(array $errors) { if ($this-&gt;ajax() || $this-&gt;wantsJson()) { return new JsonResponse($errors, 422); } return $this-&gt;redirector-&gt;to($this-&gt;getRedirectUrl()) -&gt;withInput($this-&gt;except($this-&gt;dontFlash)) -&gt;withErrors($errors, $this-&gt;errorBag); } </code></pre> <p>I knew that I can add <code>Accept= application/json</code> in request header. FormRequest will return json. But I want to provide an easier way to request my API by support json in default without setting any header. So, I tried to find some options to force FormRequest response json in <code>Illuminate\Foundation\Http\FormRequest</code> class. But I didn't find any options which are supported in default. </p> <h2>Solution 1 : Overwrite Request Abstract Class</h2> <p>I tried to overwrite my application request abstract class like followings:</p> <pre><code>&lt;?php namespace Laravel5Cg\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Http\JsonResponse; abstract class Request extends FormRequest { /** * Force response json type when validation fails * @var bool */ protected $forceJsonResponse = false; /** * Get the proper failed validation response for the request. * * @param array $errors * @return \Symfony\Component\HttpFoundation\Response */ public function response(array $errors) { if ($this-&gt;forceJsonResponse || $this-&gt;ajax() || $this-&gt;wantsJson()) { return new JsonResponse($errors, 422); } return $this-&gt;redirector-&gt;to($this-&gt;getRedirectUrl()) -&gt;withInput($this-&gt;except($this-&gt;dontFlash)) -&gt;withErrors($errors, $this-&gt;errorBag); } } </code></pre> <p>I added <code>protected $forceJsonResponse = false;</code> to setting if we need to force response json or not. And, in each FormRequest which is extends from Request abstract class. I set that option. </p> <p>Eg: I made an StoreBlogPostRequest and set <code>$forceJsoResponse=true</code> for this FormRequest and make it response json.</p> <pre><code>&lt;?php namespace Laravel5Cg\Http\Requests; use Laravel5Cg\Http\Requests\Request; class StoreBlogPostRequest extends Request { /** * Force response json type when validation fails * @var bool */ protected $forceJsonResponse = true; /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'title' =&gt; 'required|unique:posts|max:255', 'body' =&gt; 'required', ]; } } </code></pre> <h2>Solution 2: Add an Middleware and force change request header</h2> <p>I build a middleware like followings: <pre><code>namespace Laravel5Cg\Http\Middleware; use Closure; use Symfony\Component\HttpFoundation\HeaderBag; class AddJsonAcceptHeader { /** * Add Json HTTP_ACCEPT header for an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $request-&gt;server-&gt;set('HTTP_ACCEPT', 'application/json'); $request-&gt;headers = new HeaderBag($request-&gt;server-&gt;getHeaders()); return $next($request); } } </code></pre> <p>It 's work. But I wonder is this solutions good? And are there any Laravel Way to help me in this situation ? </p>
0
1,654
attempting to reference a deleted function
<p>I'm trying to learn about the fstream class and I'm having some trouble. I created a couple of txt files, one with a joke and the other with a punchline (joke.txt) and (punchline.txt) just for the sake of reading in and displaying content. I ask the user for the file name and if found it should open it up, clear the flags then read the content in. but I cant even test what it reads in because I'm currently getting errors regarding a deleted function but I don't know what that means</p> <p>error 1:</p> <pre><code>"IntelliSense: function "std::basic_ifstream&lt;_Elem, _Traits&gt;::basic_ifstream(const std::basic_ifstream&lt;_Elem, _Traits&gt;::_Myt &amp;) [with _Elem=char, _Traits=std::char_traits&lt;char&gt;]" (declared at line 818 of "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\fstream") cannot be referenced -- it is a deleted function </code></pre> <p>the second error is the exact same but for the 2nd function (displayLastLine())</p> <p>and error 3:</p> <pre><code>Error 1 error C2280: 'std::basic_ifstream&lt;char,std::char_traits&lt;char&gt;&gt;::basic_ifstream(const std::basic_ifstream&lt;char,std::char_traits&lt;char&gt;&gt; &amp;)' : attempting to reference a deleted function </code></pre> <p>and here's my code:</p> <pre><code>#include "stdafx.h" #include &lt;string&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; using namespace std; void displayAllLines(ifstream joke); void displayLastLine(ifstream punchline); int main() { string fileName1, fileName2; ifstream jokeFile, punchlineFile; // Desribe the assigned project to the User cout &lt;&lt; "This program will print a joke and its punch line.\n\n"; cout &lt;&lt; "Enter the name of the joke file (ex. joke.txt): "; cin &gt;&gt; fileName1; jokeFile.open(fileName1.data()); if (!jokeFile) { cout &lt;&lt; " The file " &lt;&lt; fileName1 &lt;&lt; " could not be opened." &lt;&lt; endl; } else { cout &lt;&lt; "Enter name of punch line file (ex. punchline.txt): "; cin &gt;&gt; fileName2; punchlineFile.open(fileName2.data()); if (!punchlineFile) { cout &lt;&lt; " The file " &lt;&lt; fileName2 &lt;&lt; " could not be opened." &lt;&lt; endl; jokeFile.close(); } else { cout &lt;&lt; endl &lt;&lt; endl; displayAllLines(jokeFile); displayLastLine(punchlineFile); cout &lt;&lt; endl; jokeFile.close(); punchlineFile.close(); } } // This prevents the Console Window from closing during debug mode cin.ignore(cin.rdbuf()-&gt;in_avail()); cout &lt;&lt; "\nPress only the 'Enter' key to exit program: "; cin.get(); return 0; } void displayAllLines(ifstream joke) { joke.clear(); joke.seekg(0L, ios::beg); string jokeString; getline(joke, jokeString); while (!joke.fail()) { cout &lt;&lt; jokeString &lt;&lt; endl; } } void displayLastLine(ifstream punchline) { punchline.clear(); punchline.seekg(0L, ios::end); string punchString; getline(punchline, punchString); while (!punchline.fail()) { cout &lt;&lt; punchString &lt;&lt; endl; } } </code></pre>
0
1,416
keras error on predict
<p>I am trying to use a keras neural network to recognize canvas images of drawn digits and output the digit. I have saved the neural network and use django to run the web interface. But whenever I run it, I get an internal server error and an error on the server side code. The error says <strong>Exception: Error when checking : expected dense_input_1 to have shape (None, 784) but got array with shape (784, 1)</strong>. My only main view is </p> <pre><code>from django.shortcuts import render from django.http import HttpResponse import StringIO from PIL import Image import numpy as np import re from keras.models import model_from_json def home(request): if request.method=="POST": vari=request.POST.get("imgBase64","") imgstr=re.search(r'base64,(.*)', vari).group(1) tempimg = StringIO.StringIO(imgstr.decode('base64')) im=Image.open(tempimg).convert("L") im.thumbnail((28,28), Image.ANTIALIAS) img_np= np.asarray(im) img_np=img_np.flatten() img_np.astype("float32") img_np=img_np/255 json_file = open('model.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # load weights into new model loaded_model.load_weights("model.h5") # evaluate loaded model on test data loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) output=loaded_model.predict(img_np) score=output.tolist() return HttpResponse(score) else: return render(request, "digit/index.html") </code></pre> <p>The links I have checked out are:</p> <ul> <li><a href="https://stackoverflow.com/questions/37901698/error-error-when-checking-model-input-expected-dense-input-6-to-have-shape-no">Here</a></li> <li><a href="https://github.com/fchollet/keras/issues/3109" rel="noreferrer"> Here </a></li> <li><a href="http://machinelearningmastery.com/handwritten-digit-recognition-using-convolutional-neural-networks-python-keras/" rel="noreferrer">and Here</a></li> </ul> <p><strong>Edit</strong> Complying with Rohan's suggestion, this is my stack trace</p> <pre><code>Internal Server Error: /home/ Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/vivek/keras/neural/digit/views.py", line 27, in home output=loaded_model.predict(img_np) File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 671, in predict return self.model.predict(x, batch_size=batch_size, verbose=verbose) File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1161, in predict check_batch_dim=False) File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 108, in standardize_input_data str(array.shape)) Exception: Error when checking : expected dense_input_1 to have shape (None, 784) but got array with shape (784, 1) </code></pre> <p>Also, I have my model that I used to train the network initially.</p> <pre><code>import numpy from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.utils import np_utils # fix random seed for reproducibility seed = 7 numpy.random.seed(seed) (X_train, y_train), (X_test, y_test) = mnist.load_data() for item in y_train.shape: print item num_pixels = X_train.shape[1] * X_train.shape[2] X_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32') X_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32') # normalize inputs from 0-255 to 0-1 X_train = X_train / 255 X_test = X_test / 255 print X_train.shape # one hot encode outputs y_train = np_utils.to_categorical(y_train) y_test = np_utils.to_categorical(y_test) num_classes = y_test.shape[1] # define baseline model def baseline_model(): # create model model = Sequential() model.add(Dense(num_pixels, input_dim=num_pixels, init='normal', activation='relu')) model.add(Dense(num_classes, init='normal', activation='softmax')) # Compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model # build the model model = baseline_model() # Fit the model model.fit(X_train, y_train, validation_data=(X_test, y_test), nb_epoch=20, batch_size=200, verbose=1) # Final evaluation of the model scores = model.evaluate(X_test, y_test, verbose=0) print("Baseline Error: %.2f%%" % (100-scores[1]*100)) # serialize model to JSON model_json = model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 model.save_weights("model.h5") print("Saved model to disk") </code></pre> <p><strong>Edit</strong> I tried reshaping the img to (1,784) and it also failed, giving the same error as the title of this question</p> <p>Thanks for the help, and leave comments on how I should add to the question.</p>
0
1,937
How to setup conditionals for BPMN2 Exclusive Gateway
<p>I'm using Camunda BPMN2 for the first time in my spring project and trying to get my head around a couple of things ...</p> <p>In my applicationContext, I have the following block to setup Camunda:</p> <pre><code> &lt;!-- Setup BPMN Process Engine --&gt; &lt;bean id="processEngineConfiguration" class="org.camunda.bpm.engine.spring.SpringProcessEngineConfiguration"&gt; &lt;property name="processEngineName" value="engine" /&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="transactionManager" ref="transactionManager" /&gt; &lt;property name="databaseSchemaUpdate" value="true" /&gt; &lt;property name="jobExecutorActivate" value="false" /&gt; &lt;property name="deploymentResources" value="classpath*:*.bpmn" /&gt; &lt;/bean&gt; &lt;bean id="processEngine" class="org.camunda.bpm.engine.spring.ProcessEngineFactoryBean"&gt; &lt;property name="processEngineConfiguration" ref="processEngineConfiguration" /&gt; &lt;/bean&gt; &lt;bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService" /&gt; &lt;bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService" /&gt; &lt;bean id="taskService" factory-bean="processEngine" factory-method="getTaskService" /&gt; &lt;bean id="historyService" factory-bean="processEngine" factory-method="getHistoryService" /&gt; &lt;bean id="managementService" factory-bean="processEngine" factory-method="getManagementService" /&gt; &lt;context:annotation-config /&gt; </code></pre> <p>I've setup two services:</p> <pre><code>@Component(value="service1") public class Service1 implements JavaDelegate { @Override public void execute(DelegateExecution execution) throws Exception { System.out.println("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;"); System.out.println("SERVICE1"); System.out.println("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;"); } } </code></pre> <p>and </p> <pre><code>@Component(value="service2") public class Service2 implements JavaDelegate { @Override public void execute(DelegateExecution execution) throws Exception { System.out.println("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;"); System.out.println("SERVICE2"); System.out.println("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;"); } } </code></pre> <p>In scenario 1 I have a parallel gateway that calls both Service1 and Service2 (I've built these diagrams using BPMN2 editor in eclipse):</p> <p><img src="https://i.stack.imgur.com/7707I.png" alt="scenario 1"></p> <p><img src="https://i.stack.imgur.com/gLiJB.png" alt="scenario 1 - service 1"></p> <p><img src="https://i.stack.imgur.com/eWYDP.png" alt="scenario 1 - service 2"></p> <p>Running this line of code:</p> <pre><code>runtimeService.startProcessInstanceByKey("ConnectorSwitch"); </code></pre> <p>Prints out </p> <pre><code>&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; SERVICE1 &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; SERVICE2 &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; </code></pre> <p>as expected.</p> <p>Now I'm trying to put in an Exclusive Gateway:</p> <p><img src="https://i.stack.imgur.com/fbVoF.png" alt="enter image description here"></p> <p>Running it gives me the following exception:</p> <pre><code>SEVERE: Error while closing command context org.camunda.bpm.engine.ProcessEngineException: Exclusive Gateway 'ExclusiveGateway_3' has outgoing sequence flow 'SequenceFlow_39' without condition which is not the default flow. | ..../ConnectorSwitch.bpmn | line 0 | column 0 Exclusive Gateway 'ExclusiveGateway_3' has outgoing sequence flow 'SequenceFlow_40' without condition which is not the default flow. | ..../ConnectorSwitch.bpmn | line 0 | column 0 at org.camunda.bpm.engine.impl.util.xml.Parse.throwExceptionForErrors(Parse.java:183) at org.camunda.bpm.engine.impl.bpmn.parser.BpmnParse.execute(BpmnParse.java:177) at org.camunda.bpm.engine.impl.bpmn.deployer.BpmnDeployer.deploy(BpmnDeployer.java:106) at org.camunda.bpm.engine.impl.persistence.deploy.DeploymentCache.deploy(DeploymentCache.java:50) at org.camunda.bpm.engine.impl.persistence.entity.DeploymentManager.insertDeployment(DeploymentManager.java:42) at org.camunda.bpm.engine.impl.cmd.DeployCmd.execute(DeployCmd.java:81) at org.camunda.bpm.engine.impl.cmd.DeployCmd.execute(DeployCmd.java:50) at org.camunda.bpm.engine.impl.interceptor.CommandExecutorImpl.execute(CommandExecutorImpl.java:24) at org.camunda.bpm.engine.impl.interceptor.CommandContextInterceptor.execute(CommandContextInterceptor.java:90) at org.camunda.bpm.engine.spring.SpringTransactionInterceptor$1.doInTransaction(SpringTransactionInterceptor.java:42) at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:130) ...... </code></pre> <p>The exception is pretty clear, I'm missing a condition on the Exclusive Gateway. So my question is, how do I assign a condition to the exclusive gateway, how do I call a method in a certain class and evaluate the true / false and if I want to call something else that is not a JavaDelegate for service1 / service2 (in other words, MyClass.doSomethingWithParams(someparam)), how would I go about that?</p> <p>Answers in XML is fine as well, would prefer to learn how to use BPMN2 in XML instead of relying on the BPMN2 visuals.</p>
0
2,814
Rock-paper-scissors game c++
<p>Rock-paper-scissors game c++ doesn't display the cout to tell who win the game, i dont know what wrong and why is the program doesn't show the cout. Please let me know whats wrong and how to fix it and why it happened and i think the cstdlib is doing nothing there.</p> <blockquote> <p>Objective: To score the rock-paper-scissors game. If the user enters invalid input, your program should say so, otherwise it will output one of the above results.</p> </blockquote> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; using namespace std; int main() { string pone; string ptwo; string r; string p; string s; cout &lt;&lt; "Rock, Paper, Scissors Game\n"; cout &lt;&lt; "\nPlayer One, please enter your move: ('p' for Paper, 'r' for Rock, 's' for Scissor)"; cin &gt;&gt; pone; cout &lt;&lt; "\nPlayer Two, please enter your move: ('p' for Paper, 'r' for Rock, 's' for Scissor)"; cin &gt;&gt; ptwo; if (pone == ptwo) { cout &lt;&lt;"\nThere is a tie"&lt;&lt;endl; } if ( pone == r &amp;&amp; ptwo == p) { cout &lt;&lt; "\nPaper wraps rock, Player 1 win"; } else if (pone == r &amp;&amp; ptwo == s) { cout &lt;&lt; "\nRock smashes scissors, player 1 win"; } if (pone == p &amp;&amp; ptwo == r) { cout &lt;&lt;"\nPaper wraps rock, player 1 win"; } else if ( pone == p &amp;&amp; ptwo == s) { cout &lt;&lt;"\nScissors cut paper, player 2 win"; } if ( pone == r &amp;&amp; ptwo == p) { cout &lt;&lt; "\nPaper wraps rock, Player 1 win"; } else if (pone == r &amp;&amp; ptwo == s) { cout &lt;&lt; "\nRock smashes scissors, player 1 win"; } if (pone == p &amp;&amp; ptwo == r) { cout &lt;&lt;"\nPaper wraps rock, player 1 win"; } else if ( pone == p &amp;&amp; ptwo == s) { cout &lt;&lt;"\nScissors cut paper, player 2 win"; } if ( ptwo == s &amp;&amp; pone == r) { cout &lt;&lt;"\nScissors cut paper, player 1 win"; } else if (ptwo == s &amp;&amp; pone == p) { cout &lt;&lt;"\nRock smashes scissors, player 2 win "; } return 0; } </code></pre>
0
1,054
SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)
<p>I am seeing this in several situations and it is intermittent in our web based application connecting to SQL 2008 R2 serve back end. Users are coming across a point 2 point connection and seeing this on and off. Thought it was bandwidth issues until I started seeing it on terminal servers that are on the same core switch as this SQL server. I have checked remote connection enabled, Port 1433 is set correctly in Configuration for TCP/IP and the only thing I see that could be a cause is the timeout setting is set to 100000 in the remote connections rather than unlimited. </p> <p>The error is </p> <blockquote> <p><code>System.Data.SqlClient.SqlException</code> (<code>0x80131904</code>): <em>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)</em> <code>---&gt;</code></p> <p><code>System.ComponentModel.Win32Exception</code> (<code>0x80004005</code>): <em>The network path was not found</em> <code>at</code></p> <pre class="lang-none prettyprint-override"><code>System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal&amp; connection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal&amp; connection) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&amp; connection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) at System.Data.SqlClient.SqlConnection.Open() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.&lt;&gt;c__DisplayClass1.b__0() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation) at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation) at System.Data.Entity.Core.EntityClient.EntityConnection.Open() ClientConnectionId:00000000-0000-0000-0000-000000000000 </code></pre> </blockquote>
0
1,429
How would I catch and deal with "undefined" from parsed json object
<p>I'm trying to populate a spreadsheet from a RESTful service and sometimes there's no such property so I get an "undefined" in my spreadsheet and the script stops and gives an error. I have no clue as to how to go about dealing with it, or skipping over the "undefined" part.</p> <p>Here's a sample query in json</p> <p>{</p> <pre><code>"rel": "self", "url": "https://www.sciencebase.gov/catalog/items?max=2&amp;s=Search&amp;q=project+ 2009+WLCI&amp;format=json&amp;fields=title%2Csummary%2Cspatial%2Cfacets", "total": 65, "nextlink": { "rel": "next", "url": "https://www.sciencebase.gov/catalog/items?max=2&amp;s= Search&amp;q=project+2009+WLCI&amp;format=json&amp;fields=title%2Csummary%2 Cspatial%2Cfacets&amp;offset=2" }, "items": [ { "link": { "rel": "self", "url": "https://www.sciencebase.gov/catalog/item/ 4f4e4ac3e4b07f02db67875f" }, "id": "4f4e4ac3e4b07f02db67875f", "title": "Decision-Making and Evaluation - Social and Economic Evaluation Supporting Adaptive Management for WLCI", "summary": "Provide information on the social and economic environment for the WLCI area and provide context for the biological and physical aspects of this project.", "spatial": { "representationalPoint": [ -108.585, 42.141 ] }, "facets": [ { "startDate": "2007-10-01 00:00:00", "projectStatus": "Active", "facetName": "Project", "_class": "ProjectFacet", "active": true, "className": "gov.sciencebase.catalog.item.facet.ProjectFacet", "endDate": null, "projectType": "Science", "_embeddedClassName": "gov.sciencebase.catalog.item.facet. ProjectFacet" } ] }, { "link": { "rel": "self", "url": "https://www.sciencebase.gov/catalog/item /4f4e4ac0e4b07f02db676d57" }, "id": "4f4e4ac0e4b07f02db676d57", "title": "Data and Information Management Products for the Wyoming Landscape Conservation Initiative" } ] </code></pre> <p>}</p> <p>Since the second item has only a title and nothing more after that I get "undefined" if I try to get a summary or facet etc. for items using a loop. I've thought of and tried using if statements like </p> <pre><code>if (parsedResponse.items[i].summary === "undefined") { Do something here; } </code></pre> <p>but this doesn't seem to work. Any suggestions I could try are appreciated. Thanks</p>
0
1,247
Reading httprequest content from spring exception handler
<p>I Am using Spring's <code>@ExceptionHandler</code> annotation to catch exceptions in my controllers.</p> <p>Some requests hold POST data as plain XML string written to the request body, I want to read that data in order to log the exception. The problem is that when i request the inputstream in the exception handler and try to read from it the stream returns -1 (empty).</p> <p>The exception handler signature is:</p> <pre><code>@ExceptionHandler(Throwable.class) public ModelAndView exception(HttpServletRequest request, HttpServletResponse response, HttpSession session, Throwable arff) </code></pre> <p>Any thoughts? Is there a way to access the request body?</p> <p>My controller: </p> <pre><code>@Controller @RequestMapping("/user/**") public class UserController { static final Logger LOG = LoggerFactory.getLogger(UserController.class); @Autowired IUserService userService; @RequestMapping("/user") public ModelAndView getCurrent() { return new ModelAndView("user","response", userService.getCurrent()); } @RequestMapping("/user/firstLogin") public ModelAndView firstLogin(HttpSession session) { userService.logUser(session.getId()); userService.setOriginalAuthority(); return new ModelAndView("user","response", userService.getCurrent()); } @RequestMapping("/user/login/failure") public ModelAndView loginFailed() { LOG.debug("loginFailed()"); Status status = new Status(-1,"Bad login"); return new ModelAndView("/user/login/failure", "response",status); } @RequestMapping("/user/login/unauthorized") public ModelAndView unauthorized() { LOG.debug("unauthorized()"); Status status = new Status(-1,"Unauthorized.Please login first."); return new ModelAndView("/user/login/unauthorized","response",status); } @RequestMapping("/user/logout/success") public ModelAndView logoutSuccess() { LOG.debug("logout()"); Status status = new Status(0,"Successful logout"); return new ModelAndView("/user/logout/success", "response",status); } @RequestMapping(value = "/user/{id}", method = RequestMethod.POST) public ModelAndView create(@RequestBody UserDTO userDTO, @PathVariable("id") Long id) { return new ModelAndView("user", "response", userService.create(userDTO, id)); } @RequestMapping(value = "/user/{id}", method = RequestMethod.GET) public ModelAndView getUserById(@PathVariable("id") Long id) { return new ModelAndView("user", "response", userService.getUserById(id)); } @RequestMapping(value = "/user/update/{id}", method = RequestMethod.POST) public ModelAndView update(@RequestBody UserDTO userDTO, @PathVariable("id") Long id) { return new ModelAndView("user", "response", userService.update(userDTO, id)); } @RequestMapping(value = "/user/all", method = RequestMethod.GET) public ModelAndView list() { return new ModelAndView("user", "response", userService.list()); } @RequestMapping(value = "/user/allowedAccounts", method = RequestMethod.GET) public ModelAndView getAllowedAccounts() { return new ModelAndView("user", "response", userService.getAllowedAccounts()); } @RequestMapping(value = "/user/changeAccount/{accountId}", method = RequestMethod.GET) public ModelAndView changeAccount(@PathVariable("accountId") Long accountId) { Status st = userService.changeAccount(accountId); if (st.code != -1) { return getCurrent(); } else { return new ModelAndView("user", "response", st); } } /* @RequestMapping(value = "/user/logout", method = RequestMethod.GET) public void perLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { userService.setOriginalAuthority(); response.sendRedirect("/marketplace/user/logout/spring"); } */ @ExceptionHandler(Throwable.class) public ModelAndView exception(HttpServletRequest request, HttpServletResponse response, HttpSession session, Throwable arff) { Status st = new Status(); try { Writer writer = new StringWriter(); byte[] buffer = new byte[1024]; //Reader reader2 = new BufferedReader(new InputStreamReader(request.getInputStream())); InputStream reader = request.getInputStream(); int n; while ((n = reader.read(buffer)) != -1) { writer.toString(); } String retval = writer.toString(); retval = ""; } catch (IOException e) { e.printStackTrace(); } return new ModelAndView("profile", "response", st); } } </code></pre> <p>Thank you</p>
0
1,707
How to use Firebase Realtime Database for Android Google Map app?
<p>I'm trying to work on Firebase <code>Realtime Dataase</code> access to my map's Markers which includes <code>dob</code>, <code>dod</code>, <code>name</code>, <code>latitude</code> , <code>longitude</code>, etc. And I want to use Full name as the title of marker, as well as dob and dod for the snippet of marker. </p> <p>My problem is don't kown how to get the value of <code>latitude</code> , <code>longitude</code> as the position of Marker and also <code>firstname</code> and <code>lastname</code> as the title ...</p> <p>Here is my <code>Realtime Dataase</code></p> <p><code>Profile</code></p> <pre><code>0 dob: "24/12/1940" dod: "02/07/2016" firstname:"Lincon" lastname:"Hall" latitude: -34.506081 longitude:150.88104 1 dob: "05/06/1949" dod: "08/08/2016" firstname:"Ben" lastname:"Roberts" latitude:-34.50609 longitude:150.8811 </code></pre> <p>The code of my map app:</p> <pre><code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, OnMarkerClickListener { private Marker myMarker; FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance(); DatabaseReference mProfileRef = firebaseDatabase.getReference(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override protected void onStart(){ super.onStart(); mProfileRef.child("Profile").addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { for (DataSnapshot child : dataSnapshot.child("0").getChildren()){ String dob = child.child("dob").getValue().toString(); String dod = child.child("dod").getValue().toString(); String latitude = child.child("latitude").getValue().toString(); String longitude = child.child("longitude").getValue().toString(); String firstname = child.child("firstname").getValue().toString(); String lastname = child.child("lastname").getValue().toString(); LatLng location = new LatLng(latitude,longitude); googleMap.addMarker(new MarkerOptions().position(location).title(firstname,lastname).snippet(dob,dod)); } } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override public void onMapReady(GoogleMap googleMap) { googleMap.setOnMarkerClickListener(this); LatLng wollongong = new LatLng(-34.404336, 150.881632); myMarker = googleMap.addMarker(new MarkerOptions() .position(wollongong) .title("Ben Roberts") .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)) .snippet("05/06/1949 - 08/08/2016") .anchor(0.0f,1.0f ) ); LatLng test2 = new LatLng(-34.404464, 150.881892); googleMap.addMarker(new MarkerOptions() .position(test2) .title("Graveyard") .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)) .snippet("This is a test graveyard too") .anchor(0.0f,1.0f ) ); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(wollongong, 18)); googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &amp;&amp; ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } googleMap.setMyLocationEnabled(true); } @Override public boolean onMarkerClick(Marker marker) { if (marker.equals(myMarker)) { Intent intent = new Intent(MapsActivity.this,Info_window.class); startActivity(intent); } else { Intent intent = new Intent(MapsActivity.this,Info_window.class); startActivity(intent); } return false; } </code></pre> <p>}</p> <p>Can anyone help me with that? Thanks a lot!</p> <p>The value of Dob and dod is null.</p> <p><a href="http://i.stack.imgur.com/bSMR4.jpg" rel="nofollow">map</a></p>
0
1,901
Getting "Caused by: java.lang.VerifyError:"
<p>I created an android application which is used as library in another android application. I used some third party jars in the android app which acts as a library. When I link this library in my android application and run it, I am getting the verify error when it tries to access the class present in the library. May I know what is the issue blocking here for me ? Any help greatly appreciated..</p> <p>I attached the log here and Parser1 is the class inside the library. I am getting the error in the line when i try to create the object for Parser1 class.</p> <pre><code>06-06 10:05:43.742: WARN/dalvikvm(224): VFY: unable to resolve static method 3084: Lorg/codehaus/jackson/JsonToken;.values ()[Lorg/codehaus/jackson/JsonToken; 06-06 10:05:43.742: DEBUG/dalvikvm(224): VFY: replacing opcode 0x71 at 0x0005 06-06 10:05:43.742: DEBUG/dalvikvm(224): Making a copy of Lcom/support/utils/Parser1;.$SWITCH_TABLE$org$codehaus$jackson$JsonToken code (522 bytes) 06-06 10:05:43.752: WARN/dalvikvm(224): VFY: unable to find class referenced in signature (Lorg/codehaus/jackson/JsonParser;) 06-06 10:05:43.752: INFO/dalvikvm(224): Could not find method org.codehaus.jackson.JsonParser.getCurrentToken, referenced from method com.support.utils.Parser1.addSectionContentData 06-06 10:05:43.761: WARN/dalvikvm(224): VFY: unable to resolve virtual method 3077: Lorg/codehaus/jackson/JsonParser;.getCurrentToken ()Lorg/codehaus/jackson/JsonToken; 06-06 10:05:43.761: DEBUG/dalvikvm(224): VFY: replacing opcode 0x74 at 0x0002 06-06 10:05:43.761: DEBUG/dalvikvm(224): Making a copy of Lcom/support/utils/Parser1;.addSectionContentData code (2421 bytes) 06-06 10:05:43.761: WARN/dalvikvm(224): VFY: unable to resolve exception class 685 (Lorg/codehaus/jackson/JsonParseException;) 06-06 10:05:43.771: WARN/dalvikvm(224): VFY: unable to resolve exception class 685 (Lorg/codehaus/jackson/JsonParseException;) 06-06 10:05:43.771: WARN/dalvikvm(224): VFY: unable to resolve exception class 685 (Lorg/codehaus/jackson/JsonParseException;) 06-06 10:05:43.771: WARN/dalvikvm(224): VFY: unable to find exception handler at addr 0x19b 06-06 10:05:43.771: WARN/dalvikvm(224): VFY: rejected Lcom/support/utils/Parser1;.addSectionContentData (Lorg/codehaus/jackson/JsonParser;Ljava/util/List;Lcom/support/ModelClasses/SectionContent;Lcom/support/ModelClasses/FeatureInfo;ZZLjava/lang/String;)Ljava/util/List; 06-06 10:05:43.781: WARN/dalvikvm(224): VFY: rejecting opcode 0x0d at 0x019b 06-06 10:05:43.781: WARN/dalvikvm(224): VFY: rejected Lcom/support/utils/Parser1;.addSectionContentData (Lorg/codehaus/jackson/JsonParser;Ljava/util/List;Lcom/support/ModelClasses/SectionContent;Lcom/support/ModelClasses/FeatureInfo;ZZLjava/lang/String;)Ljava/util/List; 06-06 10:05:43.781: WARN/dalvikvm(224): Verifier rejected class Lcom/support/utils/Parser1; 06-06 10:05:43.793: WARN/dalvikvm(224): threadid=15: thread exiting with uncaught exception (group=0x4001b188) 06-06 10:05:43.793: ERROR/AndroidRuntime(224): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception 06-06 10:05:43.812: ERROR/AndroidRuntime(224): java.lang.RuntimeException: An error occured while executing doInBackground() 06-06 10:05:43.812: ERROR/AndroidRuntime(224): at android.os.AsyncTask$3.done(AsyncTask.java:200) 06-06 10:05:43.812: ERROR/AndroidRuntime(224): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 06-06 10:05:43.812: ERROR/AndroidRuntime(224): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 06-06 10:05:43.812: ERROR/AndroidRuntime(224): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 06-06 10:05:43.812: ERROR/AndroidRuntime(224): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 06-06 10:05:43.812: ERROR/AndroidRuntime(224): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) 06-06 10:05:43.812: ERROR/AndroidRuntime(224): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) 06-06 10:05:43.812: ERROR/AndroidRuntime(224): at java.lang.Thread.run(Thread.java:1096) 06-06 10:05:43.812: ERROR/AndroidRuntime(224): Caused by: java.lang.VerifyError: com.support.utils.Parser1 06-06 10:05:43.812: ERROR/AndroidRuntime(224): at com.Sample.checkforversioning(Sample.java:652) 06-06 10:05:43.812: ERROR/AndroidRuntime(224): at com.Sample$checkVersionThread.doInBackground(Sample.java:682) 06-06 10:05:43.812: ERROR/AndroidRuntime(224): at com.Sample$checkVersionThread.doInBackground(Sample.java:1) 06-06 10:05:43.812: ERROR/AndroidRuntime(224): at android.os.AsyncTask$2.call(AsyncTask.java:185) 06-06 10:05:43.812: ERROR/AndroidRuntime(224): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 06-06 10:05:43.812: ERROR/AndroidRuntime(224): ... 4 more 06-06 10:05:43.832: INFO/Process(52): Sending signal. PID: 224 SIG: 3 </code></pre> <p>Thanks, Senthil.M</p>
0
1,810
select records from postgres where timestamp is in certain range
<p>I have arrival column of type timestamp in table reservations ( I'm using postgres ). How would I select all dates within this year for example?</p> <p>I know I could do something like this:</p> <pre><code>select * FROM reservations WHERE extract(year from arrival) = 2012; </code></pre> <p>But I've ran <strong>analyze</strong> and it looks like it require a sequence scan. Is there a better option?</p> <p><strong>P.S. 1 Hmm. both ways seem to require seq. scan. But the one by wildplasser produces results faster - why?</strong></p> <pre><code>cmm=# EXPLAIN ANALYZE select * FROM reservations WHERE extract(year from arrival) = 2010; QUERY PLAN --------------------------------------------------------------------------------------------------------------- Seq Scan on vrreservations (cost=0.00..165.78 rows=14 width=4960) (actual time=0.213..4.509 rows=49 loops=1) Filter: (date_part('year'::text, arrival) = 2010::double precision) Total runtime: 5.615 ms (3 rows) cmm=# EXPLAIN ANALYZE SELECT * from reservations WHERE arrival &gt; '2010-01-01 00:00:00' AND arrival &lt; '2011-01-01 00:00:00'; QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------- Seq Scan on reservations (cost=0.00..165.78 rows=51 width=4960) (actual time=0.126..2.491 rows=49 loops=1) Filter: ((arrival &gt; '2010-01-01 00:00:00'::timestamp without time zone) AND (arrival &lt; '2011-01-01 00:00:00'::timestamp without time zone)) Total runtime: 3.144 ms (3 rows) </code></pre> <p>** P.S. 2 - After I have created index on arrival column second way got even faster - since it looks like query uses index. Mkey - I guess I'll stik with this one. **</p> <pre><code> QUERY PLAN --------------------------------------------------------------------------------------------------------------------------------------------------------- Bitmap Heap Scan on reservations (cost=4.77..101.27 rows=51 width=4960) (actual time=0.359..0.791 rows=49 loops=1) Recheck Cond: ((arrival &gt; '2010-01-01 00:00:00'::timestamp without time zone) AND (arrival &lt; '2011-01-01 00:00:00'::timestamp without time zone)) -&gt; Bitmap Index Scan on arrival_idx (cost=0.00..4.76 rows=51 width=0) (actual time=0.177..0.177 rows=49 loops=1) Index Cond: ((arrival &gt; '2010-01-01 00:00:00'::timestamp without time zone) AND (arrival &lt; '2011-01-01 00:00:00'::timestamp without time zone)) Total runtime: 1.265 ms </code></pre>
0
1,144
Why doesn't my <script> tag work from php file? (jQuery involved here too)
<p>Here is what I am trying to accomplish. I have a form that uses jQuery to make an AJAX call to a PHP file. The PHP file interacts with a database, and then creates the page content to return as the AJAX response; i.e. this page content is written to a new window in the success function for the <code>$.ajax</code> call. As part of the page content returned by the PHP file, I have a straightforward HTML script tag that has a JavaScript file. Specifically:</p> <pre><code>&lt;script type="text/javascript" src="pageControl.js"&gt;&lt;/script&gt; </code></pre> <p>This is not echoed in the php (although I have tried that), it is just html. The pageControl.js is in the same directory as my php file that generates the content.</p> <p>No matter what I try, I can't seem to get the <code>pageControl.js</code> file included or working in the resulting new window created in response to success in the AJAX call. I end up with errors like "Object expected" or variable not defined, leading me to believe the file is not getting included. If I copy the JavaScript directly into the PHPfile, rather than using the script tag with src, I can get it working.</p> <p>Is there something I am missing here about scope resolution between calling file, php, and the jQuery AJAX? I am going to want to include javascript files this way in the future and would like to understand what I am doing wrong.</p> <hr> <p>Hello again:</p> <p>I have worked away at this issue, and still no luck. I am going to try and clarify what I am doing, and maybe that will bring something to mind. I am including some code as requested to help clarify things a bit.</p> <p>Here is the sequence:</p> <ol> <li>User selects some options, and clicks submit button on form.</li> <li><p>The form button click is handled by jQuery code that looks like this:</p> <pre><code>$(document).ready(function() { $("#runReport").click(function() { var report = $("#report").val(); var program = $("#program").val(); var session = $("#session").val(); var students = $("#students").val(); var dataString = 'report=' +report+ '&amp;program=' +program+ '&amp;session=' +session+ '&amp;students=' +students; $.ajax({ type: "POST", url: "process_report_request.php", cache: false, data: dataString, success: function(pageContent) { if (pageContent) { $("#result_msg").addClass("successMsg") .text("Report created."); var windowFeatures = "width=800,menubar=yes,scrollbars=1,resizable=1,status=yes"; // open a new report window var reportWindow = window.open("", "newReportWindow", windowFeatures); // add the report data itself returned from the AJAX call reportWindow.document.write(pageContent); reportWindow.document.close(); } else { $("#result_msg").addClass("failedMsg") .text("Report creation failed."); } } }); // end ajax call // return false from click function to prevent normal submit handling return false; }); // end click call }); // end ready call </code></pre></li> </ol> <p>This code performs an AJAX call to a PHP file (<code>process_report_request.php</code>) that creates the page content for the new window. This content is taken from a database and HTML. In the PHP file I want to include another javascript file in the head with javascript used in the new window. I am trying to include it as follows</p> <pre><code>&lt;script src="/folder1/folder2/folder3/pageControl.js" type="text/javascript"&gt;&lt;/script&gt; </code></pre> <p>Changed path folder names to protect the innocent :) </p> <p>The pageControl.js file is actually in the same folder as the jQuery code file and the php file, but I am trying the full path just to be safe. <strong>I am also able to access the js file using the URL in the browser, and I can successfully include it in a static html test page using the script src tag.</strong></p> <p>After the javascript file is included in the php file, I have a call to one of its functions as follows (echo from php):</p> <pre><code> echo '&lt;script type="text/javascript" language="javascript"&gt;writePageControls();&lt;/script&gt;'; </code></pre> <p>So, once the php file sends all the page content back to the AJAX call, then the new window is opened, and the returned content is written to it by the jQuery code above.</p> <p><em>The <code>writePageControls</code> line is where I get the error "Error: Object expected" when I run the page.</em> However, since the JavaScript works fine in both the static HTML page and when included "inline" in the PHP file, it is leading me to think this is a path issue of some kind.</p> <p>Again, no matter what I try, my calls to the functions in the pageControls.js file do not work. <strong><em>If I put the contents of the pageControl.js file in the php file between script tags and change nothing else, it works as expected.</em></strong></p> <p>Based on what some of you have already said, I am wondering if the path resolution to the newly opened window is not correct. But I don't understand why because I am using the full path. Also to confuse matters even more, my linked stylesheet works just fine from the PHP file.</p> <p>Apologies for how long this is, but if anyone has the time to look at this further, I would greatly appreciate it. I am stumped. <strong>I am a novice when it comes to a lot of this</strong>, so if there is just a better way to do this and avoid this problem, I am all ears (or eyes I suppose...)</p>
0
1,853
how to dynamically add swt widgets to a composite?
<p>I'm trying to add widgets like text boxes, buttons to a composite on click of a button. I've tried , but i could only add these widgets dynamically only up to the size of the composite. My jface dialog is such that, it has a scrolled composite in which it holds a composite. In the main composite i have 3 other composites where i have to achieve this functionality, so if i add dynamic widgets to a composite it might expand, but it should not overlap existing composites down to it, rather it should adjust other composites accordingly and also i should be able to dispose those widgets on a button click. Did any one try this dynamic addition and removal of widgets before, I'm new to swt, jface . So, could any one share their experience here, I'm posting the code i've tried.</p> <pre><code>import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; public class DynamicDialog extends Dialog { private Text text; private Text text_1; private Composite composite; /** * Create the dialog. * @param parentShell */ public DynamicDialog(Shell parentShell) { super(parentShell); } /** * Create contents of the dialog. * @param parent */ @Override protected Control createDialogArea(Composite parent) { Composite container = (Composite) super.createDialogArea(parent); container.setLayout(new FillLayout(SWT.HORIZONTAL)); ScrolledComposite scrolledComposite = new ScrolledComposite(container, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); scrolledComposite.setExpandHorizontal(true); scrolledComposite.setExpandVertical(true); composite = new Composite(scrolledComposite, SWT.NONE); composite.setLayout(new FormLayout()); scrolledComposite.setContent(composite); scrolledComposite.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); final Composite composite_1 = new Composite(composite, SWT.NONE); composite_1.setLayout(new GridLayout(4, false)); final FormData fd_composite_1 = new FormData(); fd_composite_1.top = new FormAttachment(0); fd_composite_1.left = new FormAttachment(0, 10); fd_composite_1.bottom = new FormAttachment(0, 85); fd_composite_1.right = new FormAttachment(0, 430); composite_1.setLayoutData(fd_composite_1); Label label = new Label(composite_1, SWT.NONE); label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); label.setText("1"); text_1 = new Text(composite_1, SWT.BORDER); text_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); text = new Text(composite_1, SWT.BORDER); text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Button btnDelete = new Button(composite_1, SWT.NONE); btnDelete.setText("delete"); final Composite composite_2 = new Composite(composite, SWT.NONE); composite_2.setLayout(new GridLayout(2, false)); final FormData fd_composite_2 = new FormData(); fd_composite_2.bottom = new FormAttachment(100, -91); fd_composite_2.top = new FormAttachment(0, 91); fd_composite_2.right = new FormAttachment(100, -10); fd_composite_2.left = new FormAttachment(100, -74); composite_2.setLayoutData(fd_composite_2); new Label(composite_2, SWT.NONE); Button btnAdd = new Button(composite_2, SWT.NONE); btnAdd.setText("ADD"); btnAdd.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Label label2 = new Label(composite_1, SWT.NONE); label2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); label2.setText("1"); Text text_12 = new Text(composite_1, SWT.BORDER); text_12.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Text text13 = new Text(composite_1, SWT.BORDER); text13.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Button btnDelete = new Button(composite_1, SWT.NONE); btnDelete.setText("delete"); //Point p0 = composite_1.getSize(); //composite_1.setSize(SWT.DEFAULT,SWT.DEFAULT); composite_1.layout(); //Point p = composite.getSize(); //composite.setSize(SWT.DEFAULT,SWT.DEFAULT); //composite.setSize(p); // composite.layout(); } }); return container; } /** * Create contents of the button bar. * @param parent */ @Override protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { return new Point(450, 300); } public static void main(String[] args){ Display display = new Display(); Shell shell = new Shell(display); shell.setLayout(new FillLayout()); DynamicDialog dd = new DynamicDialog(shell); dd.open(); } } </code></pre>
0
2,598
_M_ construct null not valid error when trying to implement multi threaded queue
<p>I am trying to implement a priority queue using using a simple linear approach as explained in <a href="https://rads.stackoverflow.com/amzn/click/com/B008CYT5TS" rel="nofollow noreferrer" rel="nofollow noreferrer">Art of Multiprocessor programming</a>. I'm new to c++ and have difficulty troubleshooting.</p> <p>I've implemented two template classes and am testing them using a simple test method. As I'm not able to pin point the error, I'm pasting all the three classes below for reference.</p> <p>I know that <code>_M_ construct null not valid</code> comes when trying to construct a string using <code>nullptr</code>, but am not sure where I'm doing that.</p> <p>The three classes created are given below:</p> <h1>bin.h</h1> <pre><code>#include &lt;mutex&gt; #include &lt;deque&gt; #include &lt;memory&gt; #include &lt;iostream&gt; using namespace std; namespace priority { template&lt;typename T&gt; class Bin { private: std::deque&lt;T&gt; v; std::mutex m; public: Bin() { } Bin(const Bin &amp;o) { } const Bin &amp;operator=(const Bin &amp;other) { return *this; } void put(T item) { std::lock_guard&lt;std::mutex&gt; lock(m); v.push_back(item); } T *get() { std::lock_guard&lt;std::mutex&gt; lock(m); if (v.size() == 0) { return nullptr; } else { T val = v.front(); T *ptr_val = &amp;(val); v.pop_front(); return ptr_val; } } bool isEmpty() { std::lock_guard&lt;std::mutex&gt; lock(m); return v.size() == 0; } }; } </code></pre> <h1>SimpleLinear.h</h1> <pre><code>#include &lt;mutex&gt; #include &lt;vector&gt; #include &lt;memory&gt; #include &quot;Bin.h&quot; namespace priority { template&lt;typename T&gt; class SimpleLinear { private: int range; std::vector&lt;Bin&lt;T&gt;&gt; pqueue; public: SimpleLinear(int range){ this-&gt;range = range; for (int i = 0; i &lt; range; i++) { pqueue.push_back(Bin&lt;T&gt;()); } } void add(T item, int key) { pqueue[key].put(item); } T removeMin() { for (int i = 0; i &lt; range; i++) { T *item = pqueue[i].get(); if (item != nullptr) { return *item; } } return nullptr; } }; } </code></pre> <h1>test.cpp</h1> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;thread&gt; #include &lt;algorithm&gt; #include &quot;SimpleLinear.h&quot; using namespace std; using namespace priority; void te(SimpleLinear&lt;string&gt; s, int thread_id) { s.add(&quot;sundar&quot;+to_string(thread_id), thread_id); s.add(&quot;akshaya&quot;+to_string(thread_id), 3); s.add(&quot;anirudh&quot;+to_string(thread_id), 1); s.add(&quot;aaditya&quot;+to_string(thread_id), 5); cout &lt;&lt; s.removeMin() &lt;&lt; endl; cout &lt;&lt; s.removeMin() &lt;&lt; endl; cout &lt;&lt; s.removeMin() &lt;&lt; endl; } int main(int argc, char const *argv[]) { SimpleLinear&lt;string&gt; s(100); std::vector&lt;std::thread&gt; v; for (int i = 0; i &lt; 100; i++) { // if (i % 2 == 0) v.push_back(thread(te, std::ref(s), i)); // else // v.push_back(thread(t, std::ref(s), i)); } for_each(v.begin(), v.end(), std::mem_fn(&amp;std::thread::join)); return 0; } </code></pre> <p>I'm getting the error:</p> <pre><code>terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid terminate called recursively terminate called recursively terminate called recursively Aborted (core dumped) </code></pre>
0
2,035
Downloading Xcode with wget or curl
<p>I am trying to download Xcode from the Apple Developer site using just wget or curl. I think I am successfully storing the cookie I need to download the .dmg file, but I am not completely sure.</p> <p>When I run this command:</p> <pre><code>wget \ --post-data="theAccountName=USERNAME&amp;theAccountPW=PASSWORD" \ --cookies=on \ --keep-session-cookies \ --save-cookies=cookies.txt \ -O - \ https://developer.apple.com/ios/download.action?path=/ios/ios_sdk_4.1__final/xcode_3.2.4_and_ios_sdk_4.1.dmg &gt; /dev/null </code></pre> <p>A file called <code>cookies.txt</code> is created and contains something like this:</p> <pre><code>developer.apple.com FALSE / FALSE 0 XXXXXXXXXXXXXXXX XXXXXXXXXXXX developer.apple.com FALSE / FALSE 0 developer.sessionToken </code></pre> <p>I'm not completely certain, but I think there should be more to it than that (specifically, an alphanumeric string after <code>sessionToken</code>).</p> <p>When I try to do the same thing with curl using this:</p> <pre><code>curl \ -d "theAccountName=USERNAME&amp;theAccountPW=PASSWORD" \ -c xcode-cookie \ -A "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1" \ https://developer.apple.com/ios/download.action?path=/ios/ios_sdk_4.1__final/xcode_3.2.4_and_ios_sdk_4.1.dmg </code></pre> <p>I get a file called <code>xcode-cookie</code> that contains the same information as the <code>cookies.txt</code> file wget gives me, except that the lines are reversed.</p> <p>I then tried to download the .dmg file.</p> <p>Using wget:</p> <pre><code>wget \ --cookies=on \ --load-cookies=cookies.txt \ --keep-session-cookies \ http://developer.apple.com/ios/download.action?path=/ios/ios_sdk_4.1__final/xcode_3.2.4_and_ios_sdk_4.1.dmg </code></pre> <p>This gives me a file called <code>login?appIdKey=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&amp;path=%2F%2Fios%2Fdownload.action?path=%2Fios%2Fios_sdk_4.1__final%2Fxcode_3.2.4_and_ios_sdk_4.1.dmg </code>, which is just an HTML page containing the login form for the developer site.</p> <p>Using curl:</p> <pre><code>curl \ -b xcode-cookie \ -c xcode-cookie \ -O -v \ -A "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1" \ https://developer.apple.com/ios/download.action?path=/ios/ios_sdk_4.1__final/xcode_3.2.4_and_ios_sdk_4.1.dmg </code></pre> <p>Which prints basically the same thing as wget (minus the HTML).</p> <p>I want to say it has to do with the sessionToken not being in the cookie, but like I said before I am not sure. I even tried exporting the cookies from my browser and following the instructions in the blog post I linked below and several other sites I found while searching for help.</p> <p>I must be doing something wrong, unless Apple has changed something since Oct. 10 <a href="http://greendesignhq.com/blog/2010/10/downloading-xcode-builds-with-wget-or-curl/" rel="noreferrer">because this guy seems to be to do something right</a>.</p> <p>Thanks in advance!</p>
0
1,202
React Material UI Multiple Collapse
<p>Currently my list all have collapses but they are linked to one state for "open" so if I open one list, all the other lists open. What is the best way to keep the collapses separate from each other without having a lot of states for each list.</p> <p>EDIT: The app is going through an infinite loop</p> <p><strong>App.tsx</strong></p> <pre><code>interface IState { error: any, intro: any, threads: any[], title: any, } export default class App extends React.Component&lt;{}, IState&gt; { constructor (props : any) { super (props); this.state = { error: "", intro: "Welcome to RedQuick", threads: [], title: "" }; this.getRedditPost = this.getRedditPost.bind(this) this.handleClick = this.handleClick.bind(this) } public getRedditPost = async (e : any) =&gt; { e.preventDefault(); const subreddit = e.target.elements.subreddit.value; const redditAPI = await fetch('https://www.reddit.com/r/'+ subreddit +'.json'); const data = await redditAPI.json(); console.log(data); if (data.kind) { this.setState({ error: undefined, intro: undefined, threads: data.data.children, title: data.data.children[0].data.subreddit.toUpperCase() }); } else { this.setState({ error: "Please enter a valid subreddit name", intro: undefined, threads: [], title: undefined }); } } public handleClick = (index : any) =&gt; { this.setState({ [index]: true }); } public render() { return ( &lt;div&gt; &lt;Header getRedditPost={this.getRedditPost} /&gt; &lt;p className="app__intro"&gt;{this.state.intro}&lt;/p&gt; { this.state.error === "" &amp;&amp; this.state.title.length &gt; 0 ? &lt;LinearProgress /&gt;: &lt;ThreadList error={this.state.error} handleClick={this.handleClick} threads={this.state.threads} title={this.state.title} /&gt; } &lt;/div&gt; ); } } </code></pre> <p><strong>Threadlist.tsx</strong></p> <pre><code>&lt;div className="threadlist__subreddit_threadlist"&gt; &lt;List&gt; { props.threads.map((thread : any, index : any) =&gt; &lt;div key={index} className="threadlist__subreddit_thread"&gt; &lt;Divider /&gt; &lt;ListItem button={true} onClick={props.handleClick(index)}/* component="a" href={thread.data.url}*/ &gt; &lt;ListItemText primary={thread.data.title} secondary={&lt;p&gt;&lt;b&gt;Author: &lt;/b&gt;{thread.data.author}&lt;/p&gt;} /&gt; {props[index] ? &lt;ExpandLess /&gt; : &lt;ExpandMore /&gt;} &lt;/ListItem&gt; &lt;Collapse in={props[index]} timeout="auto" unmountOnExit={true}&gt; &lt;p&gt;POOP&lt;/p&gt; &lt;/Collapse&gt; &lt;Divider /&gt; &lt;/div&gt; ) } &lt;/List&gt; &lt;/div&gt; </code></pre>
0
1,792
Visual C++ template syntax errors
<p>I have a header file...</p> <pre><code>#include &lt;SFML\Graphics.hpp&gt; #include &lt;SFML\Graphics\Drawable.hpp&gt; #include &lt;SFML\System.hpp&gt; #include &lt;iostream&gt; #ifndef _SPRITE_H_ #define _SPRITE_H_ namespace Engine { template &lt;class T&gt; class Sprite { sf::Vector2&lt;T&gt; * vector; sf::Sprite * sprite; public: Sprite(sf::Vector2&lt;T&gt; vect, sf::Sprite spr) { this-&gt;sprite = spr; this-&gt;vector = vect; } ~Sprite(); bool Draw(T x, T y, T rotate = 0); sf::Image GetImage() { return this-&gt;sprite-&gt;GetImage(); } }; }; #endif _SPRITE_H_ </code></pre> <p>And a source file...</p> <pre><code>#include &lt;SFML/Graphics.hpp&gt; #include &lt;SFML/Config.hpp&gt; #include "sprite.h" template &lt;typename T&gt; Sprite(sf::Vector2&lt;T&gt; vector, sf::Sprite sprite) { this-&gt;sprite = sprite; this-&gt;vector = vector; } template &lt;typename T&gt; bool Draw(T x, T y, T rotate) { return false; } </code></pre> <p>In VS 2010, when I compile VC++ I get the following errors:</p> <pre><code>Error 2 error C2143: syntax error : missing ';' before '&lt;' c:\users\owner\documents\visual studio 2010\projects\engine2\engine2\sprite.cpp 7 1 Engine2 Error 3 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\owner\documents\visual studio 2010\projects\engine2\engine2\sprite.cpp 7 1 Engine2 Error 4 error C2988: unrecognizable template declaration/definition c:\users\owner\documents\visual studio 2010\projects\engine2\engine2\sprite.cpp 7 1 Engine2 Error 5 error C2059: syntax error : '&lt;' c:\users\owner\documents\visual studio 2010\projects\engine2\engine2\sprite.cpp 7 1 Engine2 Error 6 error C2059: syntax error : ')' c:\users\owner\documents\visual studio 2010\projects\engine2\engine2\sprite.cpp 7 1 Engine2 Error 7 error C2143: syntax error : missing ';' before '{' c:\users\owner\documents\visual studio 2010\projects\engine2\engine2\sprite.cpp 15 1 Engine2 Error 8 error C2447: '{' : missing function header (old-style formal list?) c:\users\owner\documents\visual studio 2010\projects\engine2\engine2\sprite.cpp 15 1 Engine2 </code></pre> <p>I am a total noob to C++ (coming from C#), and have been having issues compiling this simple file as a means to at least learn the syntax before I continue on. As you can see, all I'm trying to do is reference a template from a header file to a source file, so that template reference effects all of my methods.</p> <p>What am I doing wrong? I've tried to understand these compiler messages, but I'm having trouble decrypting them.</p> <p><strong>Update</strong></p> <p>Followed suggestion: took care of almost everything, except for this:</p> <pre><code>Error 1 error C2995: 'Engine::Sprite&lt;T&gt;::Sprite(sf::Vector2&lt;T&gt;,sf::Sprite)' : function template has already been defined c:\users\owner\documents\visual studio 2010\projects\engine2\engine2\sprite.cpp 12 1 Engine2 </code></pre>
0
1,257
JSF h:selectOneMenu trouble: java.lang.IllegalArgumentException Cannot convert "string" of type class java.lang.String to interface java.util.List
<p>I have some JSF-trouble using h:selectOneMenu with a list from my backend bean: My xhtml file looks like this:</p> <pre><code> &lt;f:view&gt; &lt;h:form id="serverOptions"&gt; &lt;h:selectOneMenu id="preset" value="#{overview.pdfPresets}" &gt; &lt;f:selectItems value="#{overview.pdfPresets}" /&gt; &lt;/h:selectOneMenu&gt; &lt;h:commandButton action="submit" value="Submit" /&gt; &lt;/h:form&gt; &lt;/f:view&gt; </code></pre> <p>where the corresponding managing bean looks like this:</p> <pre><code>private List&lt;String&gt; pdfPresets; private String pdfPreset; /** * Returns a list of pdfPresets * @return a List&lt;String&gt; of pdf preset names */ public final List&lt;String&gt; getPdfPresets() { return pdfPresets; } /** * Sets the name of the selected pdfPreset * (trying to overload setPdfPresets here) * @param presetName * @see setPdfPreset */ public final void setPdfPresets(String presetName) { // write preset name somehwere else this.presetName = presetName; } /** * Sets the pdfPresets * @param list */ public final void setPdfPresets(List&lt;String&gt; list) { pdfPresets = list; } </code></pre> <p>The problem occurs on submitting the form in my browser, the full error stack looks like this:</p> <pre><code>EVERE: An exception occurred javax.faces.component.UpdateModelException: java.lang.IllegalArgumentException: Cannot convert screen_druckbogen of type class java.lang.String to interface java.util.List at javax.faces.component.UIInput.updateModel(UIInput.java:398) at javax.faces.component.UIInput.processUpdates(UIInput.java:299) at javax.faces.component.UIForm.processUpdates(UIForm.java:187) at javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1258) at javax.faces.component.UIViewRoot._processUpdatesDefault(UIViewRoot.java:1317) at javax.faces.component.UIViewRoot.access$600(UIViewRoot.java:75) at javax.faces.component.UIViewRoot$UpdateModelPhaseProcessor.process(UIViewRoot.java:1419) at javax.faces.component.UIViewRoot._process(UIViewRoot.java:1278) at javax.faces.component.UIViewRoot.processUpdates(UIViewRoot.java:761) at org.apache.myfaces.lifecycle.UpdateModelValuesExecutor.execute(UpdateModelValuesExecutor.java:34) at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:171) at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:189) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:390) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:440) at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230) at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:326) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542) at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:943) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404) at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410) at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582) Caused by: java.lang.IllegalArgumentException: Cannot convert screen_druckbogen of type class java.lang.String to interface java.util.List at com.sun.el.lang.ELSupport.coerceToType(ELSupport.java:397) at com.sun.el.parser.AstValue.setValue(AstValue.java:164) at com.sun.el.ValueExpressionImpl.setValue(ValueExpressionImpl.java:273) at org.apache.myfaces.view.facelets.el.TagValueExpression.setValue(TagValueExpression.java:117) at javax.faces.component.UIInput.updateModel(UIInput.java:380) ... 29 more </code></pre>
0
1,658
VBA Excel - Compile Error Object Required
<p><strong>Disclosure: I'm fairly inexperienced at coding of most sorts but have a reasonable understanding of the logic behind it and quite often just need a little push with getting syntax's right etc.</strong></p> <p><strong>I posted the same code earlier but with a different problem and have no discovered this issue so I thought it best to create a new question for it</strong></p> <p><strong>Objective:</strong> What I'm trying to do is create a spreadsheet where across the top row is a list of consecutive dates. In the first few columns is data for bills etc. What I want my macro to do is look at the amount of a bill, the start and end dates and the frequency of the bill (weekly/monthly etc) and then populate the cells in that same row in the columns of the dates where the bill is due. I've spent the last day coming up with this code and I was pretty happy with it until I went to run it. I've already got rid of a few bugs where I was using a variable.Value which apparently doesn't exist and I had messed up the syntax for Cells(row, column).</p> <p>The problem that I'm coming up against now is Compile Error: Object Required on this line: </p> <pre><code>Set dateAddress = Range("J1:AAI1").Find(currentDate, LookIn:=xlValues).Address 'find the current date within the range of dates in row 1 </code></pre> <p>What that line is supposed to be doing is searching across all the dates in the first row for that 'currentDate' and then storing that as dateAddress so that I can then use the dateAddress.Column in the next line of code along with the currentRow, to find the right cell that is to be populated with the bill amount.</p> <p>Am I being clear enough? My code is below.</p> <p>My Code: </p> <pre><code>Private Sub CommandButton1_Click() Dim currentDate As Date Dim currentRow As Integer Dim repeatuntilDate As Date Dim repeatuntilRow As Integer Dim dateAddress As Date currentRow = 3 'First row of entries repeatuntilRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row 'Last row of entries While currentRow &lt; repeatuntilRow 'Loop from first row until last row of entries currentDate = Cells(currentRow, "G").Value 'Set Start Date repeatuntilDate = Cells(currentRow, "H").Value 'Set End Date While currentDate &lt;= repeatuntilDate 'Loop from Start Date until End Date Set dateAddress = Range("J1:AAI1").Find(currentDate, LookIn:=xlValues).Address 'find the current date within the range of dates in row 1 Cells("dateAddress.Column,currentRow").Value = Cells("D,currentRow").Value 'Populate cell with amount 'Increment the currentDate by the chosen frequency If Cells(currentRow, "E").Value = "Weekly" Then currentDate = DateAdd("ww", 1, currentDate) ElseIf Cells(currentRow, "E").Value = "Fortnightly" Then currentDate = DateAdd("ww", 2, currentDate) ElseIf Cells(currentRow, "E").Value = "Monthly" Then currentDate = DateAdd("m", 1, currentDate) ElseIf Cells(currentRow, "E").Value = "Quarterly" Then currentDate = DateAdd("q", 1, currentDatee) ElseIf Cells(currentRow, "E").Value = "6 Monthly" Then currentDate = DateAdd("m", 6, currentDate) ElseIf Cells(currentRow, "E").Value = "Annually" Then currentDate = DateAdd("y", 1, currentDate) ' ElseIf Cells(currentRow,"E").Value = "Once off" Then ' Exit While End If Wend currentRow = currentRow + 1 'Once row is complete, increment to next row down Wend End Sub </code></pre>
0
1,108
Disable all dialog boxes in Excel while running VB script?
<p>I have some code in VB that saves all XLSM files as XLSX. I already have the code that will do that for me, but dialog boxes show up for every action. This was fine for a few dozen files. However, I'm going to use this on hundreds of XLSM files at once, and I can't just sit at my computer all day clicking dialog boxes over and over. </p> <p>The code I've tried is pretty much:</p> <pre><code>Application.DisplayAlerts = False </code></pre> <p>While this doesn't cause an error, it also doesn't work. </p> <p>The boxes give a warning about enabling macros, and also warn that saving as XLSX strips the file of all macros. Considering the type of warnings, I suspect that they've restricted turning off those dialog boxes due to the security risk. </p> <p>Since I'm running this code in Excel's VB editor, is there perhaps an option that will allow me to disable dialog boxes for debugging?</p> <p>I've also tried:</p> <pre><code>Application.DisplayAlerts = False Application.EnableEvents = False ' applied code Application.DisableAlerts = True Application.EnableEvents = True </code></pre> <p>Neither of those worked. </p> <p><strong>Edit:</strong></p> <p>Here's what the code above looks like in my current code:</p> <pre><code>Public Sub example() Application.DisplayAlerts = False Application.EnableEvents = False For Each element In sArray XLSMToXLSX(element) Next element Application.DisplayAlerts = False Application.EnableEvents = False End Sub Sub XLSMToXLSX(ByVal file As String) Do While WorkFile &lt;&gt; "" If Right(WorkFile, 4) &lt;&gt; "xlsx" Then Workbooks.Open Filename:=myPath &amp; WorkFile Application.DisplayAlerts = False Application.EnableEvents = False ActiveWorkbook.SaveAs Filename:= _ modifiedFileName, FileFormat:= _ xlOpenXMLWorkbook, CreateBackup:=False Application.DisplayAlerts = True Application.EnableEvents = True ActiveWorkbook.Close End If WorkFile = Dir() Loop End Sub </code></pre> <p>I also surrounded the <code>For</code> loop, as opposed to the <code>ActiveWorkbook.SaveAs</code> line:</p> <pre><code>Public Sub example() For Each element In sArray XLSMToXLSX(element) Next element End Sub </code></pre> <p>Finally, I shifted the <code>Application.DisplayAlerts</code> above the <code>Workbooks.Open</code> line:</p> <pre><code>Sub XLSMToXLSX(ByVal file As String) Do While WorkFile &lt;&gt; "" If Right(WorkFile, 4) &lt;&gt; "xlsx" Then Workbooks.Open Filename:=myPath &amp; WorkFile Application.DisplayAlerts = False Application.EnableEvents = False ActiveWorkbook.SaveAs Filename:= _ modifiedFileName, FileFormat:= _ xlOpenXMLWorkbook, CreateBackup:=False Application.DisplayAlerts = True Application.EnableEvents = True ActiveWorkbook.Close End If WorkFile = Dir() Loop End Sub </code></pre> <p>None of those work as well.</p> <p><strong>Edit:</strong></p> <p>I'm using Excel for Mac 2011, if that helps. </p>
0
1,191
Matplotlib backend missing modules with underscore
<p>I've been using matplotlib for some time without problems. It's been a while since i needed the interactive plot functions (for which Tkaag was used). Since then i updated matplotlib a few times.</p> <p>I tried to use it today, but it spawned an error.</p> <pre><code>/usr/local/lib/python2.7/dist-packages/matplotlib/backends/tkagg.py in &lt;module&gt;() ----&gt; 1 import _tkagg 2 import Tkinter as Tk 3 4 def blit(photoimage, aggimage, bbox=None, colormode=1): 5 tk = photoimage.tk ImportError: No module named _tkagg </code></pre> <p>I tried a different backend, added the </p> <pre><code>backend : GTKAgg </code></pre> <p>to matplotlibrc. Just to get the same error for a different module.</p> <pre><code>ImportError: No module named _backend_gdk </code></pre> <p>When I browsed for backends in /usr/local/lib/python2.7/dist-packages/matplotlib/backends/ i've noticed that all the required modules with underscore are missing.</p> <pre><code>alan@linux /usr/local/lib/python2.7/dist-packages/matplotlib/backends $ ls backend_agg.py backend_macosx.py backend_template.pyc backend_agg.pyc backend_macosx.pyc backend_tkagg.py _backend_agg.so backend_mixed.py backend_tkagg.pyc backend_cairo.py backend_mixed.pyc backend_wxagg.py backend_cairo.pyc backend_pdf.py backend_wxagg.pyc backend_cocoaagg.py backend_pdf.pyc backend_wx.py backend_cocoaagg.pyc backend_ps.py backend_wx.pyc backend_emf.py backend_ps.pyc __init__.py backend_emf.pyc backend_qt4agg.py __init__.pyc backend_fltkagg.py backend_qt4agg.pyc Matplotlib.nib backend_fltkagg.pyc backend_qt4.py qt4_compat.py backend_gdk.py backend_qt4.pyc qt4_compat.pyc backend_gdk.pyc backend_qtagg.py qt4_editor backend_gtkagg.py backend_qtagg.pyc tkagg.py backend_gtkagg.pyc backend_qt.py tkagg.pyc backend_gtkcairo.py backend_qt.pyc windowing.py backend_gtkcairo.pyc backend_svg.py windowing.pyc backend_gtk.py backend_svg.pyc backend_gtk.pyc backend_template.py </code></pre> <p>My current matplotlib version:</p> <pre><code>matplotlib - 1.1.1 - active development (/usr/local/lib/python2.7/dist-packages) </code></pre> <p>I've tried uninstalled and reinstalling matplotlib with:</p> <pre><code>pip uninstall matplotlib pip install matplotlib </code></pre> <p>and all went well.</p> <p>Tips on setting on getting interactive plotting running again?</p> <pre><code> BUILDING MATPLOTLIB matplotlib: 1.1.1 python: 2.7.3rc2 (default, Apr 22 2012, 22:35:38) [GCC 4.6.3] platform: linux2 REQUIRED DEPENDENCIES numpy: 1.6.2 freetype2: 14.1.8 OPTIONAL BACKEND DEPENDENCIES libpng: 1.2.49 Tkinter: no * Using default library and include directories for * Tcl and Tk because a Tk window failed to open. * You may need to define DISPLAY for Tk to work so * that setup can determine where your libraries are * located. Tkinter present, but header files are not * found. You may need to install development * packages. pkg-config: looking for pygtk-2.0 gtk+-2.0 * Package pygtk-2.0 was not found in the pkg-config * search path. Perhaps you should add the directory * containing `pygtk-2.0.pc' to the PKG_CONFIG_PATH * environment variable No package 'pygtk-2.0' found * Package gtk+-2.0 was not found in the pkg-config * search path. Perhaps you should add the directory * containing `gtk+-2.0.pc' to the PKG_CONFIG_PATH * environment variable No package 'gtk+-2.0' found * You may need to install 'dev' package(s) to * provide header files. Gtk+: no * Could not find Gtk+ headers in any of * '/usr/local/include', '/usr/include', '.' Mac OS X native: no Qt: no Qt4: Qt: 4.8.1, PyQt4: 4.9.1 PySide: no Cairo: 1.8.8 OPTIONAL DATE/TIMEZONE DEPENDENCIES datetime: present, version unknown dateutil: matplotlib will provide pytz: matplotlib will provide adding pytz OPTIONAL USETEX DEPENDENCIES dvipng: 1.14 ghostscript: 9.05 latex: 3.1415926 pdftops: 0.18.4 </code></pre>
0
2,598
How to refresh Material-Table (Material-ui) component in ReactJS when data changes
<p>I am using material-table in my ReactJS project, and I checked it documentation and I don't have a clue how to refresh the table when the data is continuously changing (like every 500ms or so). I appreciate any information. </p> <p>The below code is of the data table that I am trying to use. After creating the data table as below, I want to update the values of the elements in rows from incoming UDP messages in a periodical manner. I will be receiving new values in a UDP message in 500 ms periods and I have to update the values.</p> <pre><code>import React from 'react'; import { forwardRef } from 'react'; import MaterialTable from 'material-table'; import AddBox from '@material-ui/icons/AddBox'; import ArrowDownward from '@material-ui/icons/ArrowDownward'; import Check from '@material-ui/icons/Check'; import ChevronLeft from '@material-ui/icons/ChevronLeft'; import ChevronRight from '@material-ui/icons/ChevronRight'; import Clear from '@material-ui/icons/Clear'; import DeleteOutline from '@material-ui/icons/DeleteOutline'; import Edit from '@material-ui/icons/Edit'; import FilterList from '@material-ui/icons/FilterList'; import FirstPage from '@material-ui/icons/FirstPage'; import LastPage from '@material-ui/icons/LastPage'; import Remove from '@material-ui/icons/Remove'; import SaveAlt from '@material-ui/icons/SaveAlt'; import Search from '@material-ui/icons/Search'; import ViewColumn from '@material-ui/icons/ViewColumn'; const tableIcons = { Add: forwardRef((props, ref) =&gt; &lt;AddBox {...props} ref={ref} /&gt;), Check: forwardRef((props, ref) =&gt; &lt;Check {...props} ref={ref} /&gt;), Clear: forwardRef((props, ref) =&gt; &lt;Clear {...props} ref={ref} /&gt;), Delete: forwardRef((props, ref) =&gt; &lt;DeleteOutline {...props} ref={ref} /&gt;), DetailPanel: forwardRef((props, ref) =&gt; &lt;ChevronRight {...props} ref={ref} /&gt;), Edit: forwardRef((props, ref) =&gt; &lt;Edit {...props} ref={ref} /&gt;), Export: forwardRef((props, ref) =&gt; &lt;SaveAlt {...props} ref={ref} /&gt;), Filter: forwardRef((props, ref) =&gt; &lt;FilterList {...props} ref={ref} /&gt;), FirstPage: forwardRef((props, ref) =&gt; &lt;FirstPage {...props} ref={ref} /&gt;), LastPage: forwardRef((props, ref) =&gt; &lt;LastPage {...props} ref={ref} /&gt;), NextPage: forwardRef((props, ref) =&gt; &lt;ChevronRight {...props} ref={ref} /&gt;), PreviousPage: forwardRef((props, ref) =&gt; &lt;ChevronLeft {...props} ref={ref} /&gt;), ResetSearch: forwardRef((props, ref) =&gt; &lt;Clear {...props} ref={ref} /&gt;), Search: forwardRef((props, ref) =&gt; &lt;Search {...props} ref={ref} /&gt;), SortArrow: forwardRef((props, ref) =&gt; &lt;ArrowDownward {...props} ref={ref} /&gt;), ThirdStateCheck: forwardRef((props, ref) =&gt; &lt;Remove {...props} ref={ref} /&gt;), ViewColumn: forwardRef((props, ref) =&gt; &lt;ViewColumn {...props} ref={ref} /&gt;) }; export default function ElementsTable() { const [state, setState] = React.useState({ columns: [ { title: 'Element Name', field: 'elmName' }, { title: 'Value', field: 'elmVal' }, { title: 'Direction', field: 'msgDirection', lookup: { 1: 'INCOMING', 2: 'OUTGOING' } }, { title: 'Value Type', field: 'valType', lookup: { 1: 'Engineering', 2: 'Raw' }, }, ], data: [ { elmName: 'Elem1', elmVal: 'STATUS_ON', msgDirection: 1, valType: 1 }, { elmName: 'Elem2', elmVal: 'STATUS_OFF', msgDirection: 2, valType: 2 }, { elmName: 'Elem2', elmVal: 'STATUS_ON', msgDirection: 1, valType: 1 }, ], }); return ( &lt;MaterialTable title="Element List" icons={tableIcons} columns={state.columns} data={state.data} editable={{ onRowAdd: newData =&gt; new Promise(resolve =&gt; { setTimeout(() =&gt; { resolve(); setState(prevState =&gt; { const data = [...prevState.data]; data.push(newData); return { ...prevState, data }; }); }, 600); }), onRowUpdate: (newData, oldData) =&gt; new Promise(resolve =&gt; { setTimeout(() =&gt; { resolve(); if (oldData) { setState(prevState =&gt; { const data = [...prevState.data]; data[data.indexOf(oldData)] = newData; return { ...prevState, data }; }); } }, 600); }), onRowDelete: oldData =&gt; new Promise(resolve =&gt; { setTimeout(() =&gt; { resolve(); setState(prevState =&gt; { const data = [...prevState.data]; data.splice(data.indexOf(oldData), 1); return { ...prevState, data }; }); }, 600); }), }} /&gt; ); } </code></pre>
0
2,197
javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
<p>I have the following connector configuration in <code>server.xml</code>:</p> <pre><code>&lt;Connector SSLEnabled="true" clientAuth="true" keystoreFile="${user.home}/kstore.jks" keystorePass="1234567" maxThreads="150" port="8443" protocol="org.apache.coyote.http11.Http11Protocol" scheme="https" secure="true" trustStoreFile="${user.home}/truststore" trustStorePass="1234567" sslProtocol="TLS" sslEnabledProtocols="TLSv1.2,TLSv1.1,TLSv1,SSLv3" ciphers="SSL_RSA_WITH_RC4_128_MD5,SSL_RSA_WITH_RC4_128_SHA,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_DSS_WITH_AES_128_CBC_SHA,SSL_RSA_WITH_3DES_EDE_CBC_SHA,SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_DSS_WITH_AES_256_CBC_SHA" /&gt; </code></pre> <p>On client side, I have set the System properties as follow:</p> <pre><code>System.setProperty("javax.net.ssl.trustStore", "C:\\truststore"); System.setProperty("javax.net.ssl.trustStorePassword", "1234567"); System.setProperty("javax.net.ssl.keyStore", "C:\\kstore.jks"); System.setProperty("javax.net.ssl.keyStorePassword", "1234567"); System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,TLSv1,SSLv3"); </code></pre> <p>But when I hit the HTTPS URL with the client I get the following handshake exception: </p> <pre><code>keyStore is : C:\kstore.jks keyStore type is : jks keyStore provider is : init keystore init keymanager of type SunX509 trustStore is: C:\truststore trustStore type is : jks trustStore provider is : init truststore adding as trusted cert: Subject: CN=CA, OU=AA, O=AA Issuer: CN=CA Algorithm: RSA; Serial number: 0x1 Valid from Mon Sep 07 15:43:29 IST 2015 until Tue Sep 06 15:43:29 IST 2016 adding as trusted cert: Subject: CN=Server, OU=AA, O=AA Issuer: CN=CA Algorithm: RSA; Serial number: 0x1 Valid from Mon Sep 07 15:41:25 IST 2015 until Tue Sep 06 15:41:25 IST 2016 adding as trusted cert: Subject: CN=CAroot, OU=AA, O=AA Issuer: CN=CA Algorithm: RSA; Serial number: 0x1 Valid from Mon Sep 07 15:42:33 IST 2015 until Tue Sep 06 15:42:33 IST 2016 trigger seeding of SecureRandom done seeding SecureRandom Ignoring unavailable cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA Ignoring unavailable cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA Ignoring unavailable cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256 Ignoring unavailable cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 Ignoring unavailable cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 Ignoring unavailable cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA Ignoring unavailable cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA256 Allow unsafe renegotiation: false Allow legacy hello messages: true Is initial handshake: true Is secure renegotiation: false main, setSoTimeout(0) called Ignoring disabled protocol: SSLv3 %% No cached client session *** ClientHello, TLSv1.2 RandomCookie: GMT: 1424914489 bytes = { 135, 3, 105, 154, 35, 164, 247, 246, 152, 195, 40, 99, 91, 75, 72, 93, 101, 43, 206, 224, 67, 22, 8, 132, 59, 187, 48, 100 } Session ID: {} Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_EMPTY_RENEGOTIATION_INFO_SCSV] Compression Methods: { 0 } Extension elliptic_curves, curve names: {secp256r1, sect163k1, sect163r2, secp192r1, secp224r1, sect233k1, sect233r1, sect283k1, sect283r1, secp384r1, sect409k1, sect409r1, secp521r1, sect571k1, sect571r1, secp160k1, secp160r1, secp160r2, sect163r1, secp192k1, sect193r1, sect193r2, secp224k1, sect239k1, secp256k1} Extension ec_point_formats, formats: [uncompressed] Extension signature_algorithms, signature_algorithms: SHA512withECDSA, SHA512withRSA, SHA384withECDSA, SHA384withRSA, SHA256withECDSA, SHA256withRSA, SHA224withECDSA, SHA224withRSA, SHA1withECDSA, SHA1withRSA, SHA1withDSA, MD5withRSA *** [write] MD5 and SHA1 hashes: len = 179 0000: 01 00 00 AF 03 03 55 EE 78 39 87 03 69 9A 23 A4 ......U.x9..i.#. 0010: F7 F6 98 C3 28 63 5B 4B 48 5D 65 2B CE E0 43 16 ....(c[KH]e+..C. 0020: 08 84 3B BB 30 64 00 00 2A C0 09 C0 13 00 2F C0 ..;.0d..*...../. 0030: 04 C0 0E 00 33 00 32 C0 08 C0 12 00 0A C0 03 C0 ....3.2......... 0040: 0D 00 16 00 13 C0 07 C0 11 00 05 C0 02 C0 0C 00 ................ 0050: 04 00 FF 01 00 00 5C 00 0A 00 34 00 32 00 17 00 ......\...4.2... 0060: 01 00 03 00 13 00 15 00 06 00 07 00 09 00 0A 00 ................ 0070: 18 00 0B 00 0C 00 19 00 0D 00 0E 00 0F 00 10 00 ................ 0080: 11 00 02 00 12 00 04 00 05 00 14 00 08 00 16 00 ................ 0090: 0B 00 02 01 00 00 0D 00 1A 00 18 06 03 06 01 05 ................ 00A0: 03 05 01 04 03 04 01 03 03 03 01 02 03 02 01 02 ................ 00B0: 02 01 01 ... main, WRITE: TLSv1.2 Handshake, length = 179 main, READ: TLSv1.2 Alert, length = 2 main, RECV TLSv1 ALERT: fatal, handshake_failure main, called closeSocket() main, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure Exception in thread "main" org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://10.137.235.128:8443/multipart-http/inboundAdapter.htm":Received fatal alert: handshake_failure; nested exception is javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:580) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:530) at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:448) at org.springframework.integration.samples.multipart.MultipartRestGetClient.callForMultipartPush(MultipartRestGetClient.java:216) at org.springframework.integration.samples.multipart.MultipartRestGetClient.callClient(MultipartRestGetClient.java:121) at org.springframework.integration.samples.multipart.MultipartRestGetClient.main(MultipartRestGetClient.java:103) Caused by: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) at sun.security.ssl.Alerts.getSSLException(Alerts.java:154) at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1979) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1086) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1332) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1359) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1343) at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153) at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:81) at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:569) ... 5 more </code></pre> <p>I have added the cipher suites supported as suggested in similar cases in different forums, but I still get this error.</p>
0
3,540
Typescript build getting errors from node_modules folder
<p>I am running a typescript build and getting errors in node_modules. Why isn't it ignoring this folder? I have it in the exclude section of my tsconfig.json. The really strange thing is that I have another project that I have done a file comparison with and it does not throw these errors even though gulpfile.js, tsconfig.json and the node_modules folders are identical. What else can I check?</p> <p>Errors:</p> <pre><code>c:/Dev/streak-maker/node_modules/angular2/src/core/change_detection/parser/locals.d.ts(3,14): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/core/change_detection/parser/locals.d.ts(4,42): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/core/debug/debug_node.d.ts(14,13): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/core/debug/debug_node.d.ts(24,17): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/core/debug/debug_node.d.ts(25,17): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/core/di/provider.d.ts(436,103): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/core/di/provider.d.ts(436,135): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/core/render/api.d.ts(13,13): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/core/render/api.d.ts(14,84): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/facade/collection.d.ts(1,25): error TS2304: Cannot find name 'MapConstructor'. c:/Dev/streak-maker/node_modules/angular2/src/facade/collection.d.ts(2,25): error TS2304: Cannot find name 'SetConstructor'. c:/Dev/streak-maker/node_modules/angular2/src/facade/collection.d.ts(4,27): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/facade/collection.d.ts(4,39): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/facade/collection.d.ts(7,9): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/facade/collection.d.ts(8,30): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/facade/collection.d.ts(11,43): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/facade/collection.d.ts(12,27): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/facade/collection.d.ts(14,23): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/facade/collection.d.ts(15,25): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/facade/collection.d.ts(95,41): error TS2304: Cannot find name 'Set'. c:/Dev/streak-maker/node_modules/angular2/src/facade/collection.d.ts(96,22): error TS2304: Cannot find name 'Set'. c:/Dev/streak-maker/node_modules/angular2/src/facade/collection.d.ts(97,25): error TS2304: Cannot find name 'Set'. c:/Dev/streak-maker/node_modules/angular2/src/facade/lang.d.ts(13,17): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/facade/lang.d.ts(14,17): error TS2304: Cannot find name 'Set'. c:/Dev/streak-maker/node_modules/angular2/src/facade/lang.d.ts(78,59): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/facade/promise.d.ts(1,10): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/angular2/src/facade/promise.d.ts(3,14): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/angular2/src/facade/promise.d.ts(8,32): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/angular2/src/facade/promise.d.ts(9,38): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/angular2/src/facade/promise.d.ts(10,35): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/angular2/src/facade/promise.d.ts(10,93): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/angular2/src/facade/promise.d.ts(11,34): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/angular2/src/facade/promise.d.ts(12,32): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/angular2/src/facade/promise.d.ts(12,149): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/angular2/src/facade/promise.d.ts(13,43): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/angular2/src/http/headers.d.ts(43,59): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/http/url_search_params.d.ts(11,16): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/platform/browser/browser_adapter.d.ts(75,33): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/angular2/src/platform/dom/dom_adapter.d.ts(85,42): error TS2304: Cannot find name 'Map'. c:/Dev/streak-maker/node_modules/rxjs/CoreOperators.d.ts(22,67): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/rxjs/CoreOperators.d.ts(72,67): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/rxjs/CoreOperators.d.ts(77,31): error TS2304: Cannot find name 'PromiseConstructor'. c:/Dev/streak-maker/node_modules/rxjs/CoreOperators.d.ts(77,54): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/rxjs/Observable.d.ts(65,67): error TS2304: Cannot find name 'PromiseConstructor'. c:/Dev/streak-maker/node_modules/rxjs/Observable.d.ts(65,88): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/rxjs/Observable.d.ts(72,84): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/rxjs/Observable.d.ts(77,38): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/rxjs/Observable.d.ts(100,66): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/rxjs/Observable.d.ts(154,66): error TS2304: Cannot find name 'Promise'. c:/Dev/streak-maker/node_modules/rxjs/Observable.d.ts(159,31): error TS2304: Cannot find name 'PromiseConstructor'. c:/Dev/streak-maker/node_modules/rxjs/Observable.d.ts(159,54): error TS2304: Cannot find name 'Promise'. </code></pre> <p>tsconfig.js</p> <pre><code>{ "version": 3, "compilerOptions": { "target": "es5", "module": "system", "moduleResolution": "node", "sourceMap": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, "removeComments": false, "noImplicitAny": false }, "exclude": [ "node_modules", "jspm_packages" ] } </code></pre> <p>gulpfile.js (I am running the build-typescript task - I get the same errors when just typing tsc at the command line)</p> <pre><code>/// &lt;binding Build='default' /&gt; var del = require('del'), gulp = require("gulp"), ts = require('gulp-typescript'), watch = require('gulp-watch'); var webproj = "./src/StreakMaker.Web/"; var webroot = webproj + "wwwroot/"; var appsource = webproj + "App/"; var appout = webroot + "app/"; var jspmsource = "./jspm_packages/"; var jspmout = webroot + "jspm_packages/"; var paths = { webroot: webroot, src: appsource, app: appout, jspm: jspmsource, jspm_out: jspmout }; gulp.task('watch', ['watch-typescript', 'watch-html']); gulp.task('watch-typescript', function(){ gulp.watch(paths.src + '/**/*.ts', ['build-typescript']); }); gulp.task('clean-typescript', function () { del([paths.app + '/**/*.ts']); }); gulp.task('build-typescript', ['clean-typescript'], function () { var tsProject = ts.createProject('./tsconfig.json'); gulp.src(paths.src + '/**/*.ts') .pipe(ts(tsProject)) .pipe(gulp.dest(paths.app)); }); gulp.task('watch-html', function () { gulp.watch(paths.src + '/**/*.html', ['copy-html']); }); gulp.task('clean-html', function () { del([paths.app + '/**/*.html']); }); gulp.task('copy-html', ['clean-html'], function () { gulp.src(paths.src + '/**/*.html') .pipe(gulp.dest(paths.app)); }); gulp.task('copy-jspm', ['clean-jspm', 'copy-config'], function() { gulp.src(paths.jspm + "**/*.{js,css,map}") .pipe(gulp.dest(paths.jspm_out)); }); gulp.task('clean-jspm', function(){ del([paths.jspm_out + "**/*.*"]); }); gulp.task('copy-config', ['clean-config'], function(){ gulp.src("./config.js") .pipe(gulp.dest(paths.webroot)); }); gulp.task('clean-config', function(){ del(paths.webroot + 'config.js'); }); gulp.task('default', ['build-typescript', 'copy-html', 'copy-jspm']); </code></pre>
0
3,398
spl_autoload_register not working
<p>I have created 5 folders containing 5 classes (Ad_Class, Blocked_Class, Friend_Class, Image_Class, Profile_Class) in the main directory. I also created the respective classes within the mentioned folders with the exact name as the folders. i.e. if folder name is Ad_Class then the class within the folder is also the same as the folder name as in "class Ad_Class. </p> <p>In the index.php file I wrote the following code:</p> <pre><code>function Ad_Class($name) { include "Ad_Class/$name.php"; } function Blocked_Class($name) { include "Blocked_Class/$name.php"; } function Friend_Class($name) { include "Friend_Class/$name.php"; } function Image_Class($name) { include "Image_Class/$name.php"; } function Profile_Class($name) { include "Profile_Class/$name.php"; } spl_autoload_register("Ad_Class"); spl_autoload_register("Blocked_Class"); spl_autoload_register("Friend_Class"); spl_autoload_register("Image_Class"); spl_autoload_register("Profile_Class"); $a = new Ad_Class; $b = new Blocked_Class; $c = new Blocked_Class; $d = new Image_Class; $e = new Profile_Class; </code></pre> <p>After executing the above code I get the below warnings:</p> <pre><code>Warning: include(Ad_Class/Blocked_Class.php): failed to open stream: No such file or directory in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\development.php on line 4 Warning: include(): Failed opening 'Ad_Class/Blocked_Class.php' for inclusion (include_path='.;C:\Users\Robert\Documents\web development\xampp\php\PEAR') in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\development.php on line 4 Warning: include(Ad_Class/Image_Class.php): failed to open stream: No such file or directory in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\development.php on line 4 Warning: include(): Failed opening 'Ad_Class/Image_Class.php' for inclusion (include_path='.;C:\Users\Robert\Documents\web development\xampp\php\PEAR') in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\development.php on line 4 Warning: include(Blocked_Class/Image_Class.php): failed to open stream: No such file or directory in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\development.php on line 8 Warning: include(): Failed opening 'Blocked_Class/Image_Class.php' for inclusion (include_path='.;C:\Users\Robert\Documents\web development\xampp\php\PEAR') in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\development.php on line 8 Warning: include(Friend_Class/Image_Class.php): failed to open stream: No such file or directory in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\development.php on line 12 Warning: include(): Failed opening 'Friend_Class/Image_Class.php' for inclusion (include_path='.;C:\Users\Robert\Documents\web development\xampp\php\PEAR') in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\development.php on line 12 Warning: include(Ad_Class/Profile_Class.php): failed to open stream: No such file or directory in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\development.php on line 4 Warning: include(): Failed opening 'Ad_Class/Profile_Class.php' for inclusion (include_path='.;C:\Users\Robert\Documents\web development\xampp\php\PEAR') in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\development.php on line 4 Warning: include(Blocked_Class/Profile_Class.php): failed to open stream: No such file or directory in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\development.php on line 8 Warning: include(): Failed opening 'Blocked_Class/Profile_Class.php' for inclusion (include_path='.;C:\Users\Robert\Documents\web development\xampp\php\PEAR') in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\development.php on line 8 Warning: include(Friend_Class/Profile_Class.php): failed to open stream: No such file or directory in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\development.php on line 12 Warning: include(): Failed opening 'Friend_Class/Profile_Class.php' for inclusion (include_path='.;C:\Users\Robert\Documents\web development\xampp\php\PEAR') in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\development.php on line 12 Warning: include(Image_Class/Profile_Class.php): failed to open stream: No such file or directory in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\development.php on line 16 Warning: include(): Failed opening 'Image_Class/Profile_Class.php' for inclusion (include_path='.;C:\Users\Robert\Documents\web development\xampp\php\PEAR') in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\development.php on line 16 </code></pre> <p>Why is this happening? Can anyone explain?</p> <p>Update: I found the following code to work. If you have any suggestions please feel free to share!</p> <pre><code>function ad_class($class) { if(!class_exists($class) &amp;&amp; $class == "Ad_Class") { include "Ad_Class/$class" . ".php"; } elseif(!class_exists($class)) { return; } } function blocked_class($class) { if(!class_exists($class) &amp;&amp; $class == "Blocked_Class") { include "Blocked_Class/$class" . ".php"; } elseif(!class_exists($class)) { return; } } function friend_class($class) { if(!class_exists($class) &amp;&amp; $class == "Friend_Class") { include "Friend_Class/$class" . ".php"; } elseif(!class_exists($class)) { return; } } function image_class($class) { if(!class_exists($class) &amp;&amp; $class == "Image_Class") { include "Image_Class/$class" . ".php"; } elseif(!class_exists($class)) { return; } } function profile_class($class) { if(!class_exists($class) &amp;&amp; $class == "Profile_Class") { include "Profile_Class/$class" . ".php"; } elseif(!class_exists($class)) { return; } } spl_autoload_register("ad_class"); spl_autoload_register("blocked_class"); spl_autoload_register("friend_class"); spl_autoload_register("image_class"); spl_autoload_register("profile_class"); $a = new Ad_Class; $a-&gt;ad(); $b = new Blocked_Class; $b-&gt;block(); $c = new Friend_Class; $c-&gt;fr(); $d = new Image_Class; $d-&gt;image(); </code></pre> <p>It produces the following: Advertising Blocked Friend Image</p> <p>which is nothing more than displaying the class name of the instantiated object to see if the code worked correclty in loading classes.</p>
0
2,334
Adding ripple effect for View in onClick
<p>Hello I am trying to add a ripple effect onClick method for View, but this one no working. All my items having an ID, but I don't know how to call it</p> <p>Here is a code.</p> <pre><code> @Override public void onClick(View v) { int[] attrs = new int[]{R.attr.selectableItemBackground}; TypedArray typedArray = getActivity().obtainStyledAttributes(attrs); int backgroundResource = typedArray.getResourceId(0, 0); v.setBackgroundResource(backgroundResource); switch (v.getId()) { case ACTION_PLAY_ID: Log.d(MainActivity.TAG, getString(R.string.detail_action_play)); v.setBackgroundResource(backgroundResource); Intent intent = new Intent(getActivity(), PlayerActivity.class); intent.putExtra(Video.VIDEO_TAG, videoModel); startActivity(intent); break; case ACTION_BOOKMARK_ID: if (bookmarked) { v.setBackgroundResource(backgroundResource); deleteFromBookmarks(); ((ImageView) v).setImageDrawable(res.getDrawable(R.drawable.star_outline)); } else { v.setBackgroundResource(backgroundResource); addToBookmarks(); ((ImageView) v).setImageDrawable(res.getDrawable(R.drawable.star)); } break; case ACTION_REMINDER_ID: if (!isReminderSet) { createReminderDialog((ImageView) v); } else { cancelReminder(liveTvProgram.getProgramId()); ((ImageView) v).setImageDrawable(res.getDrawable(R.drawable.alarm)); } break; } } </code></pre> <p>For Lubomir</p> <p>i have something like this but not working too:</p> <pre><code> @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.item_detail, container, false); ButterKnife.bind(this, view); View myView = view.findViewById(R.id.actions_container); int[] attrs = new int[]{R.attr.selectableItemBackground}; TypedArray typedArray = getActivity().obtainStyledAttributes(attrs); int backgroundResource = typedArray.getResourceId(0, 0); myView.setBackgroundResource(backgroundResource); loadImage(); init(); return view; } </code></pre> <p>ImageViews(actionbuttons) is creating in java for LinearLayout actions_container</p> <pre class="lang-xml prettyprint-override"><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;ImageView android:id="@+id/header_image" android:layout_width="250dp" android:layout_height="250dp" android:layout_alignParentLeft="true" android:layout_marginLeft="10dp" android:layout_marginStart="10dp" android:layout_marginTop="@dimen/detail_image_1_state" android:elevation="8dp"/&gt; &lt;RelativeLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginBottom="@dimen/detail_bottom_margin" android:layout_marginTop="@dimen/detail_top_margin" android:background="@color/primary_color"&gt; &lt;LinearLayout android:id="@+id/actions_container" android:layout_width="match_parent" android:layout_height="@dimen/detail_actions_height" android:layout_alignParentTop="true" android:background="@drawable/ripple_effect_image" android:elevation="2dp" android:orientation="horizontal" android:paddingLeft="300dp" android:paddingStart="300dp"/&gt; &lt;LinearLayout android:id="@+id/content_container" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/actions_container" android:orientation="vertical" android:paddingLeft="300dp" android:paddingStart="300dp"&gt; &lt;TextView android:id="@+id/title" style="@style/TextTitleStyle" android:layout_width="wrap_content" android:layout_height="wrap_content"/&gt; &lt;TextView android:id="@+id/subtitle" style="@style/TextSubtitleStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone"/&gt; &lt;TextView android:id="@+id/duration" style="@style/TextSubtitleStyle" android:layout_width="wrap_content" android:layout_height="wrap_content"/&gt; &lt;TextView android:id="@+id/season" style="@style/TextDescriptionStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone"/&gt; &lt;TextView android:id="@+id/episode" style="@style/TextDescriptionStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone"/&gt; &lt;TextView android:id="@+id/description" style="@style/TextDescriptionStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:maxLines="7"/&gt; &lt;/LinearLayout&gt; &lt;FrameLayout android:id="@+id/recommended_frame" android:layout_width="match_parent" android:layout_height="200dp" android:layout_alignParentBottom="true"&gt; &lt;android.support.v17.leanback.widget.HorizontalGridView android:id="@+id/recommendation" android:layout_width="match_parent" android:layout_height="wrap_content" android:clipChildren="false" android:clipToPadding="false" android:paddingLeft="10dp" android:paddingRight="10dp"/&gt; &lt;/FrameLayout&gt; &lt;TextView android:id="@+id/recommended_text" style="@style/TextHeaderStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@id/recommended_frame" android:text="@string/related_programs"/&gt; &lt;/RelativeLayout&gt; &lt;/RelativeLayout&gt; </code></pre> <p>Also my xml ripple effect file is like:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/dark_primary_color"&gt; &lt;item&gt; &lt;color android:color="@color/dark_primary_color" /&gt; &lt;/item&gt; &lt;item android:id="@android:id/mask"&gt; &lt;shape android:shape="rectangle"&gt; &lt;solid android:color="?android:colorAccent" /&gt; &lt;/shape&gt; &lt;/item&gt; &lt;/ripple&gt; </code></pre>
0
3,495
Koin Android: org.koin.error.NoBeanDefFoundException
<p>Got that message error</p> <pre><code>java.lang.RuntimeException: Unable to create application com.app.name.application.MainApplication: org.koin.error.BeanInstanceCreationException: Can't create bean Bean[class=com.app.name.general.preferences.Preferences] due to error : org.koin.error.NoBeanDefFoundException: No definition found to resolve type 'android.app.Application'. Check your module definition at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5830) at android.app.ActivityThread.-wrap1(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1673) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:172) at android.app.ActivityThread.main(ActivityThread.java:6637) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) Caused by: org.koin.error.BeanInstanceCreationException: Can't create bean Bean[class=com.app.name.general.preferences.Preferences] due to error : org.koin.error.NoBeanDefFoundException: No definition found to resolve type 'android.app.Application'. Check your module definition at org.koin.core.instance.InstanceFactory.createInstance(InstanceFactory.kt:63) at org.koin.core.instance.InstanceFactory.retrieveInstance(InstanceFactory.kt:26) at org.koin.KoinContext$resolveInstance$$inlined$synchronized$lambda$1.invoke(KoinContext.kt:85) at org.koin.KoinContext$resolveInstance$$inlined$synchronized$lambda$1.invoke(KoinContext.kt:23) at org.koin.ResolutionStack.resolve(ResolutionStack.kt:23) at org.koin.KoinContext.resolveInstance(KoinContext.kt:80) at com.app.name.constants.EnvironmentConstants$initEnvironmentVariables$$inlined$getKoinInstance$1$1.invoke(KoinComponent.kt:114) at kotlin.SynchronizedLazyImpl.getValue(Lazy.kt:131) at com.app.name.constants.EnvironmentConstants$initEnvironmentVariables$$inlined$getKoinInstance$1.getValue(Unknown Source:7) at com.app.name.constants.EnvironmentConstants.initEnvironmentVariables(EnvironmentConstants.kt:180) at com.app.name.application.MainApplication.onCreate(MainApplication.kt:59) at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1119) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5827) ... 8 more </code></pre> <p>But all dependencies were correct.</p> <p>Also I noticed that modules without <code>androidApplication()</code> argument works correctly.</p> <p>Code looks like:</p> <pre><code> startKoin(listOf( imageManagerModule, databaseRepositoryModule )) </code></pre> <p>ImageManager works perfectly</p> <pre><code>val imageManagerModule: Module = applicationContext { bean { ImageManagerImpl() as ImageManager } } </code></pre> <p>But Preferences crashes</p> <pre><code>val preferencesModule: Module = applicationContext { bean { PreferencesImpl(androidApplication()) as Preferences } } </code></pre>
0
1,059
C# How To Separate Login For Admin And User
<p>So basically Admin and User goes to different windows, here's the code</p> <pre><code>private void cmdEnter_Click(object sender, EventArgs e) { if (txtUsername.Text == "" &amp;&amp; txtPassword.Text == "") //Error when all text box are not fill { MessageBox.Show("Unable to fill Username and Password", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (txtUsername.Text == "") //Error when all text box are not fill { MessageBox.Show("Unable to fill Username", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (txtPassword.Text == "") //Error when all text box are not fill { MessageBox.Show("Unable to fill Password", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { try { string myConnection = "datasource=localhost;port=3306;username=root"; MySqlConnection myConn = new MySqlConnection(myConnection); MySqlCommand SelectCommand = new MySqlCommand("select * from boardinghousedb.employee_table where username='" + this.txtUsername.Text + "' and password='" + this.txtPassword.Text + "' ;", myConn); MySqlDataReader myReader; myConn.Open(); myReader = SelectCommand.ExecuteReader(); int count = 0; while (myReader.Read()) { count = count + 1; } if (count == 1) { MessageBox.Show("Username and Password . . . is Correct", "Confirmation Message", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); this.Hide(); Menu mm = new Menu(); mm.ShowDialog(); } else if (count &gt; 1) { MessageBox.Show("Duplicate Username and Password . . . Access Denied", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show("Username and Password is Not Correct . . . Please try again", "Error Message!", MessageBoxButtons.OK, MessageBoxIcon.Error); myConn.Close(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } </code></pre> <p>but I don't know how, other tutorials talks about local database but I'm using MySQL<a href="http://i.stack.imgur.com/6Ehd9.png" rel="nofollow">Here is the employee table, title=admin or user </a></p>
0
1,498
Hibernate Session is closed in spring transaction after calling method second time
<p>First of all I am a beginner in spring.I have created a simple Spring service that has DAO injected and transaction is managed by HibernateTransactionManager of spring, like as below.(And transaction configuration is used using annotations )</p> <pre><code>@Service(value="daopowered") public class UserServiceImplDao implements UserService { @Inject private UserDao userDao; @Override @Transactional public User autheticate( String userId, String password ) { return userDao.findByIdAndPassword(userId, password); } </code></pre> <p>My transaction configuration is following </p> <pre><code>&lt;bean id="txMgr" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;property name="sessionFactory" ref="sessionFactory" /&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;/bean&gt; &lt;tx:annotation-driven transaction-manager="txMgr" /&gt; </code></pre> <p>Now the problem is when I call authenticate method first time using some controller then it works fine ( does DB operations successfully) but after calling it again second time hibernate session is closed exception is coming ? Please guide me what I am doing it wrong or how to handle this scenario ? Why wont spring opens a new transaction when I call this method second time ?</p> <p>Exception Trace:</p> <pre><code>2013-05-22T21:04:18.041+0530 DEBUG [14208212-2] lerExceptionResolver Resolving exception from handler [com.akhi.store.controller.HomeController@5d9d277e]: org.springframework.orm.hibernate3.HibernateSystemException: Session is closed!; nested exception is org.hibernate.SessionException: Session is closed! 2013-05-22T21:04:18.044+0530 DEBUG [14208212-2] tusExceptionResolver Resolving exception from handler [com.akhi.store.controller.HomeController@5d9d277e]: org.springframework.orm.hibernate3.HibernateSystemException: Session is closed!; nested exception is org.hibernate.SessionException: Session is closed! 2013-05-22T21:04:18.044+0530 DEBUG [14208212-2] lerExceptionResolver Resolving exception from handler [com.akhi.store.controller.HomeController@5d9d277e]: org.springframework.orm.hibernate3.HibernateSystemException: Session is closed!; nested exception is org.hibernate.SessionException: Session is closed! 2013-05-22T21:04:18.046+0530 DEBUG [14208212-2] et.DispatcherServlet Could not complete request org.springframework.orm.hibernate3.HibernateSystemException: Session is closed!; nested exception is org.hibernate.SessionException: Session is closed! at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:658) at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.convertHibernateAccessException(AbstractSessionFactoryBean.java:245) at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.translateExceptionIfPossible(AbstractSessionFactoryBean.java:224) at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58) at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) at com.sun.proxy.$Proxy28.findByIdAndPassword(Unknown Source) </code></pre> <p>EDIT: The DAO code</p> <pre><code>@Repository public class UserDaoImpl extends GenericHibernateDAO&lt;User, Long&gt; implements UserDao { @Override public User findByIdAndPassword( String id, String password ) { Criteria crit = getSession().createCriteria(User.class).add(Restrictions.eq("userId", id)).add(Restrictions.eq("password", password)).setMaxResults(1); List&lt;?&gt; list = crit.list(); if (list.size() &gt; 0) return (User) list.get(0); else return null; } </code></pre> <p>and getSession() implementation is </p> <pre><code>protected Session getSession() { if (session == null) { session = sessionFactory.getCurrentSession(); } return session; } </code></pre> <p>Also the abstract DAO class has sessionfactory injected</p> <pre><code>public abstract class GenericHibernateDAO&lt;T, ID extends Serializable&gt; implements GenericDAO&lt;T, Long&gt; { private Class&lt;T&gt; persistentClass; protected Session session; @Autowired private SessionFactory sessionFactory; </code></pre>
0
1,711
Cloudformation S3bucket creation
<p>Here's the cloudformation template I wrote to create a simple S3 bucket, How do I specify the name of the bucket? Is this the right way?</p> <pre><code>{ "AWSTemplateFormatVersion": "2010-09-09", "Description": "Simple S3 Bucket", "Parameters": { "OwnerService": { "Type": "String", "Default": "CloudOps", "Description": "Owner or service name. Used to identify the owner of the vpc stack" }, "ProductCode": { "Type": "String", "Default": "cloudops", "Description": "Lowercase version of the product code (i.e. jem). Used for tagging" }, "StackEnvironment": { "Type": "String", "Default": "stage", "Description": "Lowercase version of the environment name (i.e. stage). Used for tagging" } }, "Mappings": { "RegionMap": { "us-east-1": { "ShortRegion": "ue1" }, "us-west-1": { "ShortRegion": "uw1" }, "us-west-2": { "ShortRegion": "uw2" }, "eu-west-1": { "ShortRegion": "ew1" }, "ap-southeast-1": { "ShortRegion": "as1" }, "ap-northeast-1": { "ShortRegion": "an1" }, "ap-northeast-2": { "ShortRegion": "an2" } } }, "Resources": { "JenkinsBuildBucket": { "Type": "AWS::S3::Bucket", "Properties": { "BucketName": { "Fn::Join": [ "-", [ { "Ref": "ProductCode" }, { "Ref": "StackEnvironment" }, "deployment", { "Fn::FindInMap": [ "RegionMap", { "Ref": "AWS::Region" }, "ShortRegion" ] } ] ] }, "AccessControl": "Private" }, "DeletionPolicy": "Delete" } }, "Outputs": { "DeploymentBucket": { "Description": "Bucket Containing Chef files", "Value": { "Ref": "DeploymentBucket" } } } } </code></pre>
0
1,156
Getting bad_array_new_length error when trying to load a text file into a dynamically allocated 2d array
<p>So the issue I'm having with this code is that when I run it, I get the error: <code>terminate called after throwing an instance of "std:bad_array_new_length" what(): std:: bad_array_new_length</code> There are no errors otherwise and the code compiles just fine. Below is the text file I'm trying to load:</p> <pre> 10 8 0 255 255 255 0 0 255 255 255 0 255 0 255 255 0 0 255 255 0 255 255 255 0 255 255 255 255 0 255 255 255 255 255 0 255 255 0 255 255 255 255 255 255 355 0 0 255 255 255 255 255 255 255 255 0 0 255 255 255 255 255 255 255 0 255 255 0 255 255 255 0 0 0 255 255 255 255 0 0 0 </pre> <p>The first two values (10/8) are the length(rows) and height(columns) and the rest are meant to be stored in the 2d array.</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include "image.h" // Has the prototypes for the functions using namespace std; int** load(string imageFile, int &amp;length, int &amp;height) { int** array = new int*[length]; ifstream file(imageFile); if(file.is_open()) { file &gt;&gt; length; // Takes the first value and stores it as length file &gt;&gt; height; // Takes the second value and stores it as height for(int i = 0; i &lt; length; i++) { array[i] = new int[height]; for(int j = 0; j &lt; height; j++) { file &gt;&gt; array[i][j]; } } } else { cout &lt;&lt; "Unable to open file." &lt;&lt; endl; return 0; } return array; } int main() { int height, length; int **image = load("../resource/imagecorrupted.txt", length, height); } </code></pre> <p>I should add that this is for a homework assignment, so I'm therefor pretty restricted in the things I can do. In main I do need to store the values from load into **image, as well as the function parameters being set out for me, and are unchangeable. Also, it's still pretty early on in the class so for this assignment we aren't expected to use structs or classes or anything like that. Thanks for any help/advice you can give me!</p> <p>EDIT:</p> <p>Thanks to @IgorTandetnik talking me through my issue, I found the fix. This new code works, should anyone have the same issue in the future and needs help:</p> <pre><code>int** load(string imageFile, int &amp;length, int &amp;height) { ifstream file(imageFile); if(file.is_open()) { file &gt;&gt; length; int** array = new int*[length]; file &gt;&gt; height; for(int i = 0; i &lt; length; i++) { array[i] = new int[height]; for(int j = 0; j &lt; height; j++) { file &gt;&gt; array[i][j]; } } return array; } else { cout &lt;&lt; "Unable to open file." &lt;&lt; endl; return 0; } } int main() { int height = 0; int length = 0; int **image = load("../resource/imagecorrupted.txt", length, height); } </code></pre>
0
1,234