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

stackoverflow questions for text classification: 'long'

This is pacovaldez/stackoverflow-questions filtered for 1024 GPT2 tokens or more in title + body

https://huggingface.co/datasets/pacovaldez/stackoverflow-questions


Downloads last month
2