id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23537200
2012-11-21 11:54:50.608 [10152:907] EmptyMark Image: <UIImage: 0x20819ae0> After App Enters the background and comes back to foreground. 2012-11-21 11:54:57.040 [10152:907] Current Image: <UIImage: 0x20819ae0> 2012-11-21 11:54:57.042 [10152:907] EmptyMark Image: <UIImage: 0x208cc580> I'm comparing the same image "emptymark.png" it is added to a button "Current Image" (logged) to the actual file "EmptyMark Image" (Logged) when I come back to the app after it has been in the background EmptyMark returns different from "Current Image" (the image on the button). I'm getting "EmptyMark Image" using [UIImage imageNamed:@"emptymark.png"] Should I be holding a reference to emptymark.png all the time rather then trying to compare from the file? A: You can hold the reference to UIImage as, self.image = [UIImage imageNamed:@"emptymark.png"]; When you are comparing using just [UIImage imageNamed:@"emptymark.png"], it is creating separate objects.
doc_23537201
Can I instantiate "core.sv" in both (riscv_top_tb.sv and tracelog.sv)? This is my TestBench file: riscv_top_tb.sv genvar r; generate for (r = 1; r < 32; r++) begin : gen_mprf_assign assign rv_vip_rf_if.x[r] = RISK_V.bancoDeRegistros.bancoReg[r]; end : gen_mprf_assign endgenerate //------------------------------------------------------------------------------ // Core instance //------------------------------------------------------------------------------ core #(.RamSize(RamSize)) RISK_V ( .CLK(CLK), .RESET_N(RESET_N), .IMEM_DIR(dir_rom), .IMEM_DATA(data_rom), .DMEM_DIR(dir_ram), .DMEM_DATA_R(dataR_ram), .DMEM_DATA_W(dataW_ram), .I_READ(I_READ), .D_READ(D_READ), .D_WRITE(D_WRITE) ); And this is my tracelog file: tracelog.sv core #(.RamSize(RamSize)) RISK_V ( .CLK(CLK), .RESET_N(RESET_N), .IMEM_DIR(dir_rom), .IMEM_DATA(data_rom), .DMEM_DIR(dir_ram), .DMEM_DATA_R(dataR_ram), .DMEM_DATA_W(dataW_ram), .I_READ(I_READ), .D_READ(D_READ), .D_WRITE(D_WRITE) ); assign mprf_int_alias.INT_00_ZERO = '0; assign mprf_int_alias.INT_01_RA = RISK_V.bancoDeRegistros.bancoReg[1]; assign mprf_int_alias.INT_02_SP = RISK_V.bancoDeRegistros.bancoReg[2]; If this is not possible, how should I do it? A: I'm not sure what you're trying to do, but it very much sounds like you're trying to copy the file in both TB and tracelog. In that case, you can simply do `include "risk_v_instantiation.sv" where the "risk_v_instantiation.sv" file has the text: core #(.RamSize(RamSize)) RISK_V ( .CLK(CLK), .RESET_N(RESET_N), .IMEM_DIR(dir_rom), .IMEM_DATA(data_rom), .DMEM_DIR(dir_ram), .DMEM_DATA_R(dataR_ram), .DMEM_DATA_W(dataW_ram), .I_READ(I_READ), .D_READ(D_READ), .D_WRITE(D_WRITE) ); You still have to handle signal declarations which you may be able to add to this file. A: You cannot instantiate a file anywhere. You can instantiate a module. A module can be instantiated inside another module. This way you build a hierarchy of module instances. There is always a top-level module(s) which is not instantiated by anything else, or defined by other means. Your hierarchy starts with this module and branches down to other instances. Testbench is usually instantiated as a part of this hierarchy (though it might have its own top). You can instantiate the same module in different hierarchies or multiple times in the same hierarchy (varying instance names). From a test bench you can access variables in any part of the hierarchy, using cross-module-references (xmr). You just need to provide the hierarchy path to the instance you are interested int. So, answering your question: yes, you can instantiate the same core module in different hierarchies. However there will be 2 different instances with in different levels of hierarchy with their own inputs, outputs, variables, and parameters. They will have different instance paths (despite that you name the local instances the same) and will require different xmr access paths to their internals.
doc_23537202
resolvers += "oracle" at "https://maven.oracle.com" credentials += Credentials("oracle download", "maven.oracle.com", "myEmail@gmail.com", "password") libraryDependencies ++= Seq( "com.oracle.jdbc" % "ojdbc8" % "12.2.0.1" ) I still get an [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: UNRESOLVED DEPENDENCIES :: [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: com.oracle.jdbc#ojdbc8;12.2.0.1: not found [warn] :::::::::::::::::::::::::::::::::::::::::::::: What is missing in the configuration? edit When changing the credentials to credentials += Credentials("maven.oracle.com", "maven.oracle.com", "E-Mail", "password") The result is [error] Unable to find credentials for [OAM 11g @ login.oracle.com]. [warn] module not found: com.oracle.jdbc#ojdbc8;11.2.0.4 [warn] ==== local: tried [warn] /Users/geoheil/.ivy2/local/com.oracle.jdbc/ojdbc8/11.2.0.4/ivys/ivy.xml [warn] ==== oracle: tried [warn] https://maven.oracle.com/com/oracle/jdbc/ojdbc8/11.2.0.4/ojdbc8-11.2.0.4.pom [info] Resolving org.apache#apache;14 ... [error] Unable to find credentials for [OAM 11g @ login.oracle.com]. [info] Resolving jline#jline;2.12.1 ... [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: UNRESOLVED DEPENDENCIES :: [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: com.oracle.jdbc#ojdbc8;11.2.0.4: not found [warn] :::::::::::::::::::::::::::::::::::::::::::::: How can I find the correct oracle realm? Unable to find credentials for [OAM 11g @ login.oracle.com] would suggest that OAM 11g is the realm, but that still results in the same problem. Also the https://blogs.oracle.com/dev2dev/get-oracle-jdbc-drivers-and-ucp-from-oracle-maven-repository-without-ides suggested OAM 11g does not work. For gradle, there seems to be a workaround: https://groups.google.com/forum/#!topic/gradle-dev/G8X_41lOIlU maven { url 'https://www.oracle.com/content/secure/maven/content' credentials { username 'user' password 'password' } but so far I could not get any option (correct realm via SSO, workaround) to work with SBT. edit2 The best workaround so far is Find Oracle JDBC driver in Maven repository edit3 find a reproducible example here: https://github.com/geoHeil/oracleJBCMavenSBT A: 1) I checkout your project on github 2) I run this command for find the path of my Maven installation: mvn -version 3) I edit the ....\apache-maven-3.5.0\conf\settings.xml file with your setting 4) I run this command: mvn clean install 5) I have the same error 6) I valid my account on Oracle official Web site 7) I edit the ....\apache-maven-3.5.0\conf\settings.xml file with my valid login/password 8) I run this command and I have a Maven BUILD SUCCESS: mvn clean install You need valid your Oracle account for resolve your problem. Note: If you use travic-ci, run this command: mvn clean install --settings settings.xml In your settings.xml file: <server> <id>maven.oracle.com</id> <username>${OTN_USERNAME}</username> <password>${OTN_PASSWORD}</password> <configuration> <basicAuthScope> <host>ANY</host> <port>ANY</port> <realm>OAM 11g</realm> </basicAuthScope> <httpConfiguration> <all> <params> <property> <name>http.protocol.allow-circular-redirects</name> <value>%b,true</value> </property> </params> </all> </httpConfiguration> </configuration> </server> in travic-ci, add 2 environment variables (https://travis-ci.org/YOUTORGANIZATION/YOURREPOSITORY/settings) : A: ... resolvers += "OAM 11g" at "https://maven.oracle.com", credentials += Credentials("OAM 11g", "login.oracle.com", "mail", "pass"), libraryDependencies += "com.oracle.jdbc" % "ojdbc8" % "18.3.0.0" exclude("com.oracle.jdbc", "ucp"), ... It works.
doc_23537203
Environment: .NET 6 The function does different tasks such as * *generate a transaction ID *Fetch data from Db based on an input parameter *Transform the data *Write the transformed data into DB *Write the transformed data into service bus topic When all these steps finishes, it needs to write the log into a service bus queue. Also the execution happens at function level as well as application layer For example the ID created immediately when Azure function being hit. Tranformation happens at application layer project. But I need to hold all these information into a single object and that object I am going to write into a service bus queue as a JSON message. Here is my class definition. Public class ServiceMessage { public Guid Id { get; set; } public int ProcessId { get; set; } public object? ProcessExecutionId { get; set; } public string? PrimaryObjectName { get; set; } public string? ServiceName { get; set; } public Status Status { get; set; } public List<Message>? Message { get; set; } } public sealed class Message { public Status Status { get; set; } public string? Remarks { get; set; } public string? Timestamp { get; set; } } public enum Status { Failure = 0, InProgress = 1, Success = 2 } While application progressing, I need to set each of these properties. Also there is a Message Array which is for holding any specific messages/error while any stages of the processing. I dont know how to handle this situation. I thought about declaring an object initially and passing the same object to different methods and there it got updated and that methods return back the object and the same for everywhere. But I believe its a bad approach. Could you please help me to handle this.
doc_23537204
JAVA_HOME and JENKINS_HOME environment variables defined on the .profile file About Java info: java -version openjdk version "11.0.11" 2021-04-20 OpenJDK Runtime Environment AdoptOpenJDK-11.0.11+9 (build 11.0.11+9) OpenJDK 64-Bit Server VM AdoptOpenJDK-11.0.11+9 (build 11.0.11+9, mixed mode) javac -version javac 11.0.11 which java /home/user/something/java/openjdk/jdk-11.0.11+9/bin/java But for the first execution to startup Jenkins, happens the following java -jar jenkins.war --httpPort=9090 Running from: /home/user/something/jenkins/bin/jenkins.war webroot: EnvVars.masterEnvVars.get("JENKINS_HOME") 2021-07-22 18:15:09.003+0000 [id=1] INFO org.eclipse.jetty.util.log.Log#initialized: Logging initialized @1892ms to org.eclipse.jetty.util.log.JavaUtilLog 2021-07-22 18:15:09.374+0000 [id=1] INFO winstone.Logger#logInternal: Beginning extraction from war file 2021-07-22 18:15:09.474+0000 [id=1] WARNING o.e.j.s.handler.ContextHandler#setContextPath: Empty contextPath 2021-07-22 18:15:09.782+0000 [id=1] INFO org.eclipse.jetty.server.Server#doStart: jetty-9.4.42.v20210604; built: 2021-06-04T17:33:38.939Z; git: 5cd5e6d2375eeab146813b0de9f19eda6ab6e6cb; jvm 11.0.11+9 2021-07-22 18:15:11.116+0000 [id=1] INFO o.e.j.w.StandardDescriptorProcessor#visitServlet: NO JSP Support for /, did not find org.eclipse.jetty.jsp.JettyJspServlet 2021-07-22 18:15:11.278+0000 [id=1] INFO o.e.j.s.s.DefaultSessionIdManager#doStart: DefaultSessionIdManager workerName=node0 2021-07-22 18:15:11.281+0000 [id=1] INFO o.e.j.s.s.DefaultSessionIdManager#doStart: No SessionScavenger set, using defaults 2021-07-22 18:15:11.284+0000 [id=1] INFO o.e.j.server.session.HouseKeeper#startScavenging: node0 Scavenging every 600000ms 2021-07-22 18:15:12.762+0000 [id=1] INFO hudson.WebAppMain#contextInitialized: Jenkins home directory: /home/user/something/jenkins/contents found at: EnvVars.masterEnvVars.get("JENKINS_HOME") 2021-07-22 18:15:13.025+0000 [id=1] SEVERE hudson.util.BootFailure#publish: Failed to initialize Jenkins java.lang.NullPointerException at java.desktop/sun.awt.FontConfiguration.getVersion(FontConfiguration.java:1262) at java.desktop/sun.awt.FontConfiguration.readFontConfigFile(FontConfiguration.java:225) at java.desktop/sun.awt.FontConfiguration.init(FontConfiguration.java:107) at java.desktop/sun.awt.X11FontManager.createFontConfiguration(X11FontManager.java:719) at java.desktop/sun.font.SunFontManager$2.run(SunFontManager.java:379) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.desktop/sun.font.SunFontManager.<init>(SunFontManager.java:324) at java.desktop/sun.awt.FcFontManager.<init>(FcFontManager.java:35) at java.desktop/sun.awt.X11FontManager.<init>(X11FontManager.java:56) Caused: java.lang.reflect.InvocationTargetException at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) at java.desktop/sun.font.FontManagerFactory$1.run(FontManagerFactory.java:84) Caused: java.lang.InternalError at java.desktop/sun.font.FontManagerFactory$1.run(FontManagerFactory.java:86) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.desktop/sun.font.FontManagerFactory.getInstance(FontManagerFactory.java:74) at java.desktop/java.awt.Font.getFont2D(Font.java:497) at java.desktop/java.awt.Font.getFamily(Font.java:1410) at java.desktop/java.awt.Font.getFamily_NoClientCode(Font.java:1384) at java.desktop/java.awt.Font.getFamily(Font.java:1376) at java.desktop/java.awt.Font.toString(Font.java:1869) at hudson.util.ChartUtil.<clinit>(ChartUtil.java:270) at hudson.WebAppMain.contextInitialized(WebAppMain.java:251) Caused: hudson.util.AWTProblem at hudson.WebAppMain.contextInitialized(WebAppMain.java:252) at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:1068) at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:572) at org.eclipse.jetty.server.handler.ContextHandler.contextInitialized(ContextHandler.java:997) at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:746) at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:379) at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1449) at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1414) at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:911) at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:288) at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:524) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:73) at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:169) at org.eclipse.jetty.server.Server.start(Server.java:423) at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:110) at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:97) at org.eclipse.jetty.server.Server.doStart(Server.java:387) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:73) at winstone.Launcher.<init>(Launcher.java:192) at winstone.Launcher.main(Launcher.java:369) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at Main._main(Main.java:375) at Main.main(Main.java:151) WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/home/user/something/jenkins/contents/war/WEB-INF/lib/groovy-all-2.4.12.jar) to method java.lang.Object.finalize() WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release 2021-07-22 18:15:13.834+0000 [id=1] INFO o.e.j.s.handler.ContextHandler#doStart: Started w.@27d57a2c{Jenkins v2.303,/,file:///home/user/something/jenkins/contents/war/,AVAILABLE}{/home/user/something/jenkins/contents/war} 2021-07-22 18:15:13.893+0000 [id=1] INFO o.e.j.server.AbstractConnector#doStart: Started ServerConnector@4c178a76{HTTP/1.1, (http/1.1)}{0.0.0.0:9090} 2021-07-22 18:15:13.893+0000 [id=1] INFO org.eclipse.jetty.server.Server#doStart: Started @6790ms 2021-07-22 18:15:13.897+0000 [id=22] INFO winstone.Logger#logInternal: Winstone Servlet Engine running: controlPort=disabled Through a secondary PC with a web browser the configuration should be possible, it because the server version does not have GUI - anyway Jenkins started with that error message - is possible use http://192.168.1.XX:9090 in a web browser - so Jenkins renders (in some way) the following message: Error AWT is not properly configured on this server. Perhaps you need to run your container with "-Djava.awt.headless=true"? See also: https://www.jenkins.io/redirect/troubleshooting/java.awt.headless java.lang.NullPointerException at java.desktop/sun.awt.FontConfiguration.getVersion(FontConfiguration.java:1262) at java.desktop/sun.awt.FontConfiguration.readFontConfigFile(FontConfiguration.java:225) at java.desktop/sun.awt.FontConfiguration.init(FontConfiguration.java:107) at java.desktop/sun.awt.X11FontManager.createFontConfiguration(X11FontManager.java:719) at java.desktop/sun.font.SunFontManager$2.run(SunFontManager.java:379) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.desktop/sun.font.SunFontManager.<init>(SunFontManager.java:324) at java.desktop/sun.awt.FcFontManager.<init>(FcFontManager.java:35) at java.desktop/sun.awt.X11FontManager.<init>(X11FontManager.java:56) Caused: java.lang.reflect.InvocationTargetException at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) at java.desktop/sun.font.FontManagerFactory$1.run(FontManagerFactory.java:84) Caused: java.lang.InternalError at java.desktop/sun.font.FontManagerFactory$1.run(FontManagerFactory.java:86) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.desktop/sun.font.FontManagerFactory.getInstance(FontManagerFactory.java:74) at java.desktop/java.awt.Font.getFont2D(Font.java:497) at java.desktop/java.awt.Font.getFamily(Font.java:1410) at java.desktop/java.awt.Font.getFamily_NoClientCode(Font.java:1384) at java.desktop/java.awt.Font.getFamily(Font.java:1376) at java.desktop/java.awt.Font.toString(Font.java:1869) at hudson.util.ChartUtil.<clinit>(ChartUtil.java:270) at hudson.WebAppMain.contextInitialized(WebAppMain.java:251) at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:1068) at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:572) at org.eclipse.jetty.server.handler.ContextHandler.contextInitialized(ContextHandler.java:997) at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:746) at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:379) at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1449) at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1414) at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:911) at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:288) at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:524) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:73) at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:169) at org.eclipse.jetty.server.Server.start(Server.java:423) at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:110) at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:97) at org.eclipse.jetty.server.Server.doStart(Server.java:387) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:73) at winstone.Launcher.<init>(Launcher.java:192) at winstone.Launcher.main(Launcher.java:369) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at Main._main(Main.java:375) at Main.main(Main.java:151) So executing now using Djava.awt.headless=true java -Djava.awt.headless=true -jar jenkins.war --httpPort=9090 Running from: /home/user/something/jenkins/bin/jenkins.war webroot: EnvVars.masterEnvVars.get("JENKINS_HOME") 2021-07-22 18:30:37.797+0000 [id=1] INFO org.eclipse.jetty.util.log.Log#initialized: Logging initialized @2214ms to org.eclipse.jetty.util.log.JavaUtilLog 2021-07-22 18:30:38.160+0000 [id=1] INFO winstone.Logger#logInternal: Beginning extraction from war file 2021-07-22 18:30:38.231+0000 [id=1] WARNING o.e.j.s.handler.ContextHandler#setContextPath: Empty contextPath 2021-07-22 18:30:38.477+0000 [id=1] INFO org.eclipse.jetty.server.Server#doStart: jetty-9.4.42.v20210604; built: 2021-06-04T17:33:38.939Z; git: 5cd5e6d2375eeab146813b0de9f19eda6ab6e6cb; jvm 11.0.11+9 2021-07-22 18:30:39.776+0000 [id=1] INFO o.e.j.w.StandardDescriptorProcessor#visitServlet: NO JSP Support for /, did not find org.eclipse.jetty.jsp.JettyJspServlet 2021-07-22 18:30:39.949+0000 [id=1] INFO o.e.j.s.s.DefaultSessionIdManager#doStart: DefaultSessionIdManager workerName=node0 2021-07-22 18:30:39.953+0000 [id=1] INFO o.e.j.s.s.DefaultSessionIdManager#doStart: No SessionScavenger set, using defaults 2021-07-22 18:30:39.956+0000 [id=1] INFO o.e.j.server.session.HouseKeeper#startScavenging: node0 Scavenging every 600000ms 2021-07-22 18:30:41.569+0000 [id=1] INFO hudson.WebAppMain#contextInitialized: Jenkins home directory: /home/user/something/jenkins/contents found at: EnvVars.masterEnvVars.get("JENKINS_HOME") 2021-07-22 18:30:41.840+0000 [id=1] SEVERE hudson.util.BootFailure#publish: Failed to initialize Jenkins java.lang.NullPointerException at java.desktop/sun.awt.FontConfiguration.getVersion(FontConfiguration.java:1262) at java.desktop/sun.awt.FontConfiguration.readFontConfigFile(FontConfiguration.java:225) at java.desktop/sun.awt.FontConfiguration.init(FontConfiguration.java:107) at java.desktop/sun.awt.X11FontManager.createFontConfiguration(X11FontManager.java:719) at java.desktop/sun.font.SunFontManager$2.run(SunFontManager.java:379) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.desktop/sun.font.SunFontManager.<init>(SunFontManager.java:324) at java.desktop/sun.awt.FcFontManager.<init>(FcFontManager.java:35) at java.desktop/sun.awt.X11FontManager.<init>(X11FontManager.java:56) Caused: java.lang.reflect.InvocationTargetException at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) at java.desktop/sun.font.FontManagerFactory$1.run(FontManagerFactory.java:84) Caused: java.lang.InternalError at java.desktop/sun.font.FontManagerFactory$1.run(FontManagerFactory.java:86) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.desktop/sun.font.FontManagerFactory.getInstance(FontManagerFactory.java:74) at java.desktop/java.awt.Font.getFont2D(Font.java:497) at java.desktop/java.awt.Font.getFamily(Font.java:1410) at java.desktop/java.awt.Font.getFamily_NoClientCode(Font.java:1384) at java.desktop/java.awt.Font.getFamily(Font.java:1376) at java.desktop/java.awt.Font.toString(Font.java:1869) at hudson.util.ChartUtil.<clinit>(ChartUtil.java:270) at hudson.WebAppMain.contextInitialized(WebAppMain.java:251) Caused: hudson.util.AWTProblem at hudson.WebAppMain.contextInitialized(WebAppMain.java:252) at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:1068) at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:572) at org.eclipse.jetty.server.handler.ContextHandler.contextInitialized(ContextHandler.java:997) at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:746) at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:379) at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1449) at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1414) at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:911) at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:288) at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:524) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:73) at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:169) at org.eclipse.jetty.server.Server.start(Server.java:423) at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:110) at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:97) at org.eclipse.jetty.server.Server.doStart(Server.java:387) at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:73) at winstone.Launcher.<init>(Launcher.java:192) at winstone.Launcher.main(Launcher.java:369) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at Main._main(Main.java:375) at Main.main(Main.java:151) WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/home/user/something/jenkins/contents/war/WEB-INF/lib/groovy-all-2.4.12.jar) to method java.lang.Object.finalize() WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release 2021-07-22 18:30:42.721+0000 [id=1] INFO o.e.j.s.handler.ContextHandler#doStart: Started w.@27d57a2c{Jenkins v2.303,/,file:///home/user/something/jenkins/contents/war/,AVAILABLE}{/home/user/something/jenkins/contents/war} 2021-07-22 18:30:42.781+0000 [id=1] INFO o.e.j.server.AbstractConnector#doStart: Started ServerConnector@b2c9a9c{HTTP/1.1, (http/1.1)}{0.0.0.0:9090} 2021-07-22 18:30:42.785+0000 [id=1] INFO org.eclipse.jetty.server.Server#doStart: Started @7204ms 2021-07-22 18:30:42.789+0000 [id=22] INFO winstone.Logger#logInternal: Winstone Servlet Engine running: controlPort=disabled How resolve this? More According with the 3rd output there is available/suggested the following link for more details * *https://www.jenkins.io/redirect/troubleshooting/java.awt.headless Which it targets to: * *Jenkins got java.awt.headless problem it indicates to install (for my case) * *sudo apt install ttf-dejavu *sudo apt install xvfb It does not work A: Thanks to the following link at Jenkins Jira * *AWT initialized even with -Djava.awt.headless=true Is mandatory install fontconfig[.x86_64], so was just enough execute * *sudo apt install fontconfig Note in jira was really suggested to install fontconfig.x86_64 but it does not exist on Ubuntu repositories. Perhaps is available for other distributions. So one of them should be viable, either fontconfig or fontconfig.x86_64 Once installed execute in peace: * *java -jar jenkins.war --httpPort=9090 (is not need it -Djava.awt.headless=true ) A: As you aren't using LTS, errors like this one could appear. My proposition is to use LTS version. Currently the latest one is 2.289.2 Maybe changing java 11 to 8 version could help, but I'm not sured about it.
doc_23537205
Jul 02, 2019 9:20:08 PM org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {[WORKING]} Exception in thread "main" java.lang.NoClassDefFoundError: net/bytebuddy/NamingStrategy$SuffixingRandom$BaseNameResolver at org.hibernate.orm.core@5.4.3.Final/org.hibernate.cfg.Environment.buildBytecodeProvider(Environment.java:345) at org.hibernate.orm.core@5.4.3.Final/org.hibernate.cfg.Environment.buildBytecodeProvider(Environment.java:337) at org.hibernate.orm.core@5.4.3.Final/org.hibernate.cfg.Environment.<clinit>(Environment.java:230) at org.hibernate.orm.core@5.4.3.Final/org.hibernate.boot.registry.StandardServiceRegistryBuilder.<init>(StandardServiceRegistryBuilder.java:78) at org.hibernate.orm.core@5.4.3.Final/org.hibernate.boot.registry.StandardServiceRegistryBuilder.<init>(StandardServiceRegistryBuilder.java:67) at org.hibernate.orm.core@5.4.3.Final/org.hibernate.boot.registry.StandardServiceRegistryBuilder.<init>(StandardServiceRegistryBuilder.java:58) at ProjectDBTest/ProjectDBTest2.HibernateUtil.getSessionFactory(HibernateUtil.java:28) at ProjectDBTest/ProjectDBTest2.App.main(App.java:28) Caused by: java.lang.ClassNotFoundException: net.bytebuddy.NamingStrategy$SuffixingRandom$BaseNameResolver at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ... 8 more Any help on how to resolve this would be greatly appreciated. Initially, I was getting 'java.lang.NoClassDefFoundError: java/sql/SQLException' exception and so I added 'requires java.sql' after seeing this as a suggested solution elsewhere on Stack Overflow, but now a the exception described above arises. I'm not sure where I'm gone wrong in my code or what is missing. Here is my module-info.java file: module ProjectDBTest { requires java.persistence; //requires lombok; requires javafx.graphics; requires org.hibernate.orm.core; requires java.naming; requires java.sql; exports ProjectDBTest2.DB; } main class: package ProjectDBTest2; import ProjectDBTest2.DB.Vocabulary; import org.hibernate.Session; import org.hibernate.Transaction; import java.util.List; /** * Hello world! * */ public class App { public static void main( String[] args ) { Vocabulary word1 = new Vocabulary(); word1.setUnitID(1); word1.setWord("test"); word1.setVocabClass("noun"); word1.setVocabDefinition("this is a test"); word1.setVocabID(7); System.out.println(word1.getUnitID()); Transaction transaction = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { transaction = session.beginTransaction(); session.save(word1); transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } try (Session session = HibernateUtil.getSessionFactory().openSession()) { List< Vocabulary > students = session.createQuery("from Vocabulary ", Vocabulary.class).list(); students.forEach(s -> System.out.println(s.getWord())); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } } } Hibernate util file: package ProjectDBTest2; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; public class HibernateUtil { private static StandardServiceRegistry registry; private static SessionFactory sessionFactory; public static SessionFactory getSessionFactory() { if (sessionFactory == null) { try { // Create registry registry = new StandardServiceRegistryBuilder().configure().build(); // Create MetadataSources MetadataSources sources = new MetadataSources(registry); // Create Metadata Metadata metadata = sources.getMetadataBuilder().build(); // Create SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build(); } catch (Exception e) { e.printStackTrace(); if (registry != null) { StandardServiceRegistryBuilder.destroy(registry); } } } return sessionFactory; } public static void shutdown() { if (registry != null) { StandardServiceRegistryBuilder.destroy(registry); } } } Persistence data class: import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; //@Data @Entity @Table(name = "vocabulary") public class Vocabulary { @Id @Column(name = "V_ID") private int vocabID; @Column(name = "V_WORD") private String word; @Column(name = "V_CLASS") private String vocabClass; @Column(name = "V_DEFINITION") private String vocabDefinition; @Column(name = "U_ID") private int unitID; public int getVocabID() { return vocabID; } public void setVocabID(int vocabID) { this.vocabID = vocabID; } public String getWord() { return word; } public void setWord(String word) { this.word = word; } public String getVocabClass() { return vocabClass; } public void setVocabClass(String vocabClass) { this.vocabClass = vocabClass; } public String getVocabDefinition() { return vocabDefinition; } public void setVocabDefinition(String vocabDefinition) { this.vocabDefinition = vocabDefinition; } public int getUnitID() { return unitID; } public void setUnitID(int unitID) { this.unitID = unitID; } } pom.xml: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>ProjectDBTest2</groupId> <artifactId>ProjectDBTest2.0</artifactId> <version>1.0-SNAPSHOT</version> <name>ProjectDBTest2.0</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/net.bytebuddy/byte-buddy --> <dependency> <groupId>net.bytebuddy</groupId> <artifactId>byte-buddy</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.16</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.3.Final</version> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok--> <!-- <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.8</version> <scope>provided</scope> </dependency> --> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.3.0.Final</version> </dependency> <dependency> <groupId>org.openjfx</groupId> <artifactId>javafx-graphics</artifactId> <version>13-ea+9</version> </dependency> <!-- https://mvnrepository.com/artifact/org.openjfx/javafx --> <dependency> <groupId>org.openjfx</groupId> <artifactId>javafx</artifactId> <version>13-ea+9</version> <type>pom</type> </dependency> <!-- https://mvnrepository.com/artifact/org.openjfx/javafx-base --> <dependency> <groupId>org.openjfx</groupId> <artifactId>javafx-base</artifactId> <version>13-ea+9</version> </dependency> <!-- https://mvnrepository.com/artifact/org.openjfx/javafx-controls --> <dependency> <groupId>org.openjfx</groupId> <artifactId>javafx-controls</artifactId> <version>13-ea+9</version> </dependency> </dependencies> <build> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle --> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle --> <plugin> <artifactId>maven-site-plugin</artifactId> <version>3.7.1</version> </plugin> <plugin> <artifactId>maven-project-info-reports-plugin</artifactId> <version>3.0.0</version> </plugin> </plugins> </pluginManagement> </build> </project> I'm using intelliJ ultimate 2019.1 and language level is set to 11. A: I finally managed to solve the issue by updating my module-info.java file to include: module AlienDB { requires static lombok; requires java.persistence; requires org.hibernate.orm.core; requires java.naming; requires java.sql; requires com.sun.xml.bind; requires net.bytebuddy; opens Aliens to org.hibernate.orm.core; exports Aliens; } Previously I was adding java.xml.bind which was causing further issues.
doc_23537206
<WhoisRecord xmlns="http://adam.kahtava.com/services/whois" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <DomainName>68.140.1.1</DomainName> <RegistryData><AbuseContact><Email>abuse-mail@verizonbusiness.com</Email><Name>abuse</Name><Phone>+1-800-900-0241</Phone></AbuseContact><AdministrativeContact><Email>stephen.r.middleton@verizon.com</Email><Name>Verizon Internet Services</Name><Phone>800-243-6994</Phone></AdministrativeContact><BillingContact i:nil="true"/><CreatedDate>2002-05-13T00:00:00-04:00</CreatedDate><RawText i:nil="true"/><Registrant><Address>22001 Loudoun County Parkway</Address><City>Ashburn</City><Country>US</Country><Name>UUNET Technologies, Inc.</Name><PostalCode>20147</PostalCode><StateProv>VA</StateProv></Registrant><TechnicalContact><Email>swipper@verizonbusiness.com</Email><Name>swipper</Name><Phone>+1-800-900-0241</Phone></TechnicalContact><UpdatedDate>2004-03-16T00:00:00-05:00</UpdatedDate><ZoneContact i:nil="true"/></RegistryData></WhoisRecord> My code looks like this: public class XMLParser { String streamTitle = ""; /** Called when the activity is first created. * @throws IOException * @throws SAXException */ public String startparse(String xml) throws SAXException, IOException { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = builderFactory.newDocumentBuilder(); builder.parse(xml); } catch (ParserConfigurationException e) { e.printStackTrace(); } return builderFactory.getAttribute("WhoisRecord").toString(); } } when i try to return something from startparse i simple get nothing. XMLParser xmlpar = new XMLParser(); Log.v("Faruk TEST ", "udss:"+xmlpar.startparse(temp)); Do some one know a simple solution for this problem? A: Try this i hope it is what you are looking for ... Android: parse XML from string problems A: I think that your call to builderFactory.getAttribute is wrong. DocumentBuilder.parse() returns a Document object, and this will contain the DOM that you've just parsed. You can use this to access the elements of the XML. A: Try this Working with XML-Android
doc_23537207
I have my MongoClient as (example): private static MongoClient client = new MongoClient("mongodb://localhost:27017"); And would like to check if it is running or not.
doc_23537208
<ul class="ul"> <li class="li"> <a>Some buddy</a> <ul class="ul"> <li class="li" id="testLi"> <a id="testView">test buddy</a> </li> </ul> </li> </ul> Please ignore class names. I have assigned ids to <li> and child` tags. and I also have a function written as bellow: $(document).ready(function () { $('#testView').click(function () { var ul = document.createElement('ul'); ul.className = 'ul'; var li = document.createElement('li'); li.className = 'li'; var a = document.createElement('a'); a.innerHTML = 'test buddy'; $(li).append(a); $(ul).append(li); $('#testLi').append(ul); }); }); Now if I click on <a id="testView">test buddy</a> my function does not get called. I think this because DOM is loaded and my new elements are get created in ready(). Please provide a solution. A: You will need to attach the event handler to the document and delegate the event to the element. You can do something like this: $(document).on('click', '#testView', function () { var ul = document.createElement('ul'); ul.className = 'ul'; var li = document.createElement('li'); li.className = 'li'; var a = document.createElement('a'); a.innerHTML = 'test buddy'; $(li).append(a); $(ul).append(li); $('#testLi').append(ul); }); This will apply to all the elements with this id regardless of whether they are created before document.ready() or not. A: Your code is working fine. I have added it to the snippet below. $(document).ready(function() { $('#testView').click(function() { var ul = document.createElement('ul'); ul.className = 'ul'; var li = document.createElement('li'); li.className = 'li'; var a = document.createElement('a'); a.innerHTML = 'test buddy'; $(li).append(a); $(ul).append(li); $('#testLi').append(ul); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="ul"> <li class="li"> <a>Some buddy</a> <ul class="ul"> <li class="li" id="testLi"> <a id="testView">test buddy</a> </li> </ul> </li> </ul>
doc_23537209
<form target="POPUPW" onsubmit="POPUPW = window.open('about:blank','POPUPW','width=400,height=400');" name="search1" action="popresult.php" method="POST"> <b>အကၡရာ</b> <select name="pre"> <option value="c1">က</option> <option value="c2">ခ</option> <option value="c3">ဂ</option> <option value="c4">ဃ</option> <option value="c5">င</option> <option value="c6">စ</option> <option value="c7">ဆ</option> <option value="c8">ဇ</option> <option value="c9">စ်</option> <option value="c10">ည</option> <option value="c11">ဋ</option> <option value="c12">ဌ</option> <option value="c13">ဍ</option> <option value="c14">ဎ</option> <option value="c15">ဏ</option> <option value="c16">တ</option> <option value="c17">ထ</option> <option value="c18">ဒ</option> <option value="c19">ဓ</option> <option value="c20">န</option> <option value="c21">ပ</option> <option value="c22">ဖ</option> <option value="c23">ဗ</option> <option value="c24">ဘ</option> <option value="c25">မ</option> <option value="c26">ယ</option> <option value="c27">ရ</option> <option value="c28">လ</option> <option value="c29">၀</option> <option value="c30">သ</option> <option value="c31">ဟ</option> <option value="c32">ဠ</option> <option value="c33">အ</option> <option value="c34">ကက</option> <option value="c35">ကခ</option> <option value="c36">ကဂ</option> <option value="c37">ကဃ</option> <option value="c38">ကင</option> <option value="c39">ကစ</option> <option value="c40">ကဆ</option> </select> <b>Number</b> <select name="one"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> </select> <select name="two"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> </select> <select name="three"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> </select> <select name="four"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> </select> <select name="five"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> </select> <select name="six"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> </select> <input type="submit" name="search" value="ထီတိုက္ရန္" style="font-family:Zawgyi-One;" /> </form> my php is <?php $output = NULL; $link = mysqli_connect("localhost","root","","searchdemo") or die("Unable to select database" . mysqli_error($link)); if(isset($_POST['search'])){ $spre = $_POST['pre']; $sone = $_POST['one']; $stwo = $_POST['two']; $sthree = $_POST['three']; $sfour = $_POST['four']; $sfive = $_POST['five']; $ssix = $_POST['six']; $query = mysqli_query ($link, "SELECT * FROM `346` WHERE pre = '$spre' AND one = '$sone' AND two = '$stwo' AND three = '$sthree' AND four = '$sfour' AND five = '$sfive' AND six = '$ssix'") or die("<b>Error</b> : ".mysqli_error($link)); $count = mysqli_num_rows($query); if ($count == 0){ $output = 'Try Again'; }else{ while($row = mysqli_fetch_array($query)){ extract($row); $price = $row['price']; $output = '<style="font-family:Zawgyi-One">ဂုဏ္ယူ၀မ္းေျမာက္ပါတယ္ခင္ဗ်ာ ... <br />လူႀကီးမင္းဟာ ယခုဆို သိန္းေပါင္း ' .$price. 'ကို ဆြတ္ခူးသြားႏိုင္ပါၿပီ</style>'; } } } ?> <html> You are searching for <b style="font-family:Zawgyi-One"><?php echo $spre; ?> - <?php echo $sone; ?><?php echo $stwo; ?><?php echo $sthree; ?><?php echo $sfour; ?><?php echo $sfive; ?><?php echo $ssix; ?></b><br /><br /> </html> <?php print ("$output <br />"); ?> But when I search, the result was shown in You are searching for c1 - 000000 But I like to show "c1" as က (က is unicode). And I will import CSV file into my database without including unicode. A: The content of the value="" is what the Browser send to PHP, if you want to see exactly whats in the option then code it like <select name="name"> <option value="Joe">Joe</option> <option value="Micheal">Micheal</option> <option value="Sean">Sean</option> </select> However it is normal to code something like an id in the value="<?php echo $id;?>" as then you can retrieve the data associated with the name more easily. Ah I just noticed that you said you were using multiple choice or wanted too at least. In that case you need to change the <select> tag like so <select name="name" multiple="multiple"> <option value="Joe">Joe</option> <option value="Micheal">Micheal</option> <option value="Sean">Sean</option> </select> Then in your PHP code the $_POST['name'] variable will be returned as an array, so you would processing like this :- if ( isset( $_POST['name'] ) ) { foreach ( $_POST['name'] as $selected_name ) { echo $selected_name; } }
doc_23537210
from datetime import datetime import sys import smtplib from email.message import EmailMessage from email.headerregistry import Address from email.utils import make_msgid from email.mime.image import MIMEImage attachment = '/user/file/test.png' import email.policy msg = EmailMessage() msg['To'] = Address("Srujan", 'myemail@example.com') msg['From'] = Address("Srujan", 'myemail@example.com') msg['Subject'] = "Nice message goes with it "+str(datetime.now()) id = make_msgid() msg.set_type('text/html') msg.set_content(" This is the Data Message that we want to send") html_msg = "<br> <b><u> This is the Text .... </u></b><br> <img src='cid:{image_id}' />".format(image_id=id[1:-1]) msg.add_alternative(html_msg, subtype="html") image_data = open(attachment, "rb") image_mime = MIMEImage(image_data.read()) image_data.close() msg.add_attachment(image_mime, cid=id, filename = "myown.png" ,) try: with smtplib.SMTP('example.com') as s: s.ehlo() s.starttls() s.ehlo() s.send_message(msg) s.close() print("Email sent!") except: print("Unable to send the email. Error: ", sys.exc_info()[0]) raise I noticed that the last part is a message/rfc822, which then contains the image/png. To: Srujan <"myemail@example.com"> From: Srujan <"myemail@example.com"> Subject: Nice message goes with it 2016-01-21 17:39:23.642762 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===============3463325241650937591==" --===============3463325241650937591== Content-Type: multipart/alternative; boundary="===============0739224896516732414==" --===============0739224896516732414== Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit This is the Data Message that we want to send --===============0739224896516732414== Content-Type: text/html; charset="utf-8" Content-Transfer-Encoding: 7bit MIME-Version: 1.0 <br> <b><u> This is the Text .... </u></b><br> <img src='cid:20160122013923.64205.76661' /> --===============0739224896516732414==-- --===============3463325241650937591== Content-Type: message/rfc822 Content-Transfer-Encoding: 8bit Content-Disposition: attachment; filename="myown.png" Content-ID: <20160122013923.64205.76661> MIME-Version: 1.0 Content-Type: image/png MIME-Version: 1.0 Content-Transfer-Encoding: base64 iVBORw0KGgoAAAANSUhEUgAAAyAAAAJYCAIAAAAVFBUnAAAABmJLR0QA/wD/AP+gvaeTAAAgAElE QVR4nOzdd2BUVfYH8HNfmZJAChAEQ1FAqoKgCAsWLEgTG4gKP11FQNG1AauIgGBXVhRUsCK4i6gI Now the attached message has two content-type values. Email comes with just text and with no image. I have done it successfully with MultiPart class, but looking to achieve that with EmailMessage. A: It is really a pity that Python docs on this subject are incomplete/wrong. I wanted to do the same thing and got the same problem (attachments got two content-types) Solved the problem by using the attach() method instead of add_attachment() on EmailMessage objects. The only caveat is that you have to transform the EmailMessage to multipart/mixed type before doing this. An example: from smtplib import SMTP from email.message import EmailMessage from email.mime.text import MIMEText from email.headerregistry import Address from ssl import SSLContext, PROTOCOL_TLSv1_2 # Creating and populating email data: msg = EmailMessage() msg['From'] = Address(display_name='Recipient', addr_spec='rcpt@example.org') msg['To'] = Address(display_name='Sender', addr_spec='sender@example.org') msg['Subject'] = 'An email for you' msg.set_content('This should be in the email body') # It is possible to use msg.add_alternative() to add HTML content too # Attaching content: att = MIMEText('This should be in an attached file') # Or use MIMEImage, etc # The following line is to control the filename of the attached file att.add_header('Content-Disposition', 'attachment', filename='attachment.txt') msg.make_mixed() # This converts the message to multipart/mixed msg.attach(att) # Don't forget to convert the message to multipart first! # Sending the email: with SMTP(host='smtp.example.org', port=587) as smtp_server: try: # You can choose SSL/TLS encryption protocol to use as shown # or just call starttls() without parameters smtp_server.starttls(context=SSLContext(PROTOCOL_TLSv1_2)) smtp_server.login(user='user@smtp.example.org', password='password') smtp_server.send_message(msg) except Exception as e: print('Error sending email. Details: {} - {}'.format(e.__class__, e))
doc_23537211
With the gaussian fit, I have no problem of value. Here's a print of my plot : I don't know what I'm doing wrong in my code for obtaining the mean of my exponential fit: plt.figure(1) plt.subplot(221) cycle = map(float,cycle) cycle = np.array(cycle) list_cycle1 = cycle[cycle < 1000 ] list_cycle2 = cycle[cycle >= 1000] plt.hist(list_cycle1, bins=10, normed=True) xt1 = plt.xticks()[0] xmin1, xmax1= min(xt1), max(xt1) lnspc1 = np.linspace(xmin1, xmax1, len(list_cycle1)) m1, s1 = stats.expon.fit(list_cycle1, moments='mv') pdf_e = stats.expon.pdf(lnspc1, m1, s1) plt.plot(lnspc1, pdf_e, label='expon pdf') list_mean_1.append(m1) list_se_1.append(s1) plt.hist(list_cycle2, bins=10, normed=True) xt2 = plt.xticks()[0] xmin2, xmax2= min(xt2), max(xt2) lnspc2 = np.linspace(xmin2, xmax2, len(list_cycle2)) m2, s2 = stats.norm.fit(list_cycle2) pdf_g = stats.norm.pdf(lnspc2, m2, s2) plt.plot(lnspc2, pdf_g, label="Norm") list_mean_2.append(m2) list_se_2.append(s2) I could add an example of list_cycle1 and list_cycle2 if you want. PS: I read this SciPy documentation and I don't understand where I fail in my code to obtain the mean of my exponential fit. A: stats.expon.fit returns the tuple (loc, scale). According to the doc, scale = 1 / lambda which is also the mean of the exponential distribution. Therefore, it is the second parameter that you want. If you want to force the location to be 0, you can pass in the floc parameter to fit.
doc_23537212
I cannot, however, access this same FTPS server from R using the RCurl library (R version=3.4.3, RCurl version = 1.95-4.9, windows 7 PC). I expect it has something to do with my invocation of getURL(). Here's what happens when I try to list the files in a directory on the FTPS server: library(RCurl) url <- "FTPS://<myIpaddress>/<path>/" userpwd <- "myname:mypasswd" filenames <- getURL(url, userpwd=userpwd, ftp.use.epsv = FALSE, dirlistonly = TRUE, .opts=curlOptions(verbose=TRUE)) It complains about connection refused on port 990 (presumably the default port for FTPS?). I happen to have the FTPS server setup to use port 21. Filezilla didn't require a port number so I had left it out here too. Explicitly specifying port 21, however, gives another problem... url <- "FTPS://<myIpaddress>:21/<path>/" This time the complaint is about "unknown protocol". Don't understand. I am using a FTPS server listening on port 21, I specify the same on the URL. What could be wrong? Can anyone recommend some ways to troubleshoot this further? For completeness here's the FTPS server configuration (it's a synology diskstation NAS)... A: Add ftp.ssl = TRUE to the getURL options for SFTP. This is the equivalent of --ftp-ssl in actual curl.
doc_23537213
(in script): var response = [{ "A":"a2", "B":"b2", "C":"c2" }, { "A":"a3", "B":"b3", "C":"c3" }, { "A":"a4", "B":"b4", "C":"c4" }]; $.each(response, function(i, item) { $('<tr>').html( //"<tr>" + "<td>" + response[i].A + "</td><td>" + response[i].B + "</td><td>" + response[i].C + "</td>" + "</tr>").appendTo('#MyTable tbody'); }); and I want to change one of column (just for exp it's will be "A") to be "edited" by text-box. I am tring this: ... `"<td><input type="text">" + response[i].A + "</td><td>" + response[i].B + "</td><td>" + response[i].C + "</td>" + "</tr>").appendTo('#MyTable tbody');`... but it's not working. any help please! A: Try saying This var firstcell = "<td><input type="text" value="VALUE"</td>"; firstcell = firstcell.replace('VALUE', response[i].A); Use this for first cell in each Row. After that append this in whole row. A: If i understood correctly, Instead of creating <tr>, later adding contents to it using html() and finally appending to do the <table>, you can directly add everything altogether to the <table> using append() method. $.each(response, function(i, item) { $('#MyTable tbody').append("<tr>" +"<td><input type='text' value='"+ response[i].A +"'/> </td><td><input type='text' value='"+ response[i].B +"'/></td><td><input type='text' value='"+ response[i].C +"'/></td>" + "</tr>"); });
doc_23537214
08-28 15:47:10.567: E/AndroidRuntime(32352): FATAL EXCEPTION: main 08-28 15:47:10.567: E/AndroidRuntime(32352): Process: com.sophos.smenc, PID: 32352 08-28 15:47:10.567: E/AndroidRuntime(32352): android.view.InflateException: Binary XML file line #10: Error inflating class <unknown> 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.LayoutInflater.createView(LayoutInflater.java:620) 08-28 15:47:10.567: E/AndroidRuntime(32352): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.LayoutInflater.rInflate(LayoutInflater.java:755) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.LayoutInflater.inflate(LayoutInflater.java:492) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.LayoutInflater.inflate(LayoutInflater.java:397) 08-28 15:47:10.567: E/AndroidRuntime(32352): at com.sophos.smenc.ui.adapter.SectionFileListAdapter.getView(SectionFileListAdapter.java:221) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.AbsListView.obtainView(AbsListView.java:2255) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.ListView.makeAndAddView(ListView.java:1790) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.ListView.fillDown(ListView.java:691) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.ListView.fillFromTop(ListView.java:752) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.ListView.layoutChildren(ListView.java:1630) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.AbsListView.onLayout(AbsListView.java:2087) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.View.layout(View.java:14817) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.ViewGroup.layout(ViewGroup.java:4631) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.LinearLayout.onLayout(LinearLayout.java:1434) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.View.layout(View.java:14817) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.ViewGroup.layout(ViewGroup.java:4631) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.FrameLayout.onLayout(FrameLayout.java:388) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.View.layout(View.java:14817) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.ViewGroup.layout(ViewGroup.java:4631) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java:1660) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.LinearLayout.onLayout(LinearLayout.java:1436) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.View.layout(View.java:14817) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.ViewGroup.layout(ViewGroup.java:4631) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.FrameLayout.onLayout(FrameLayout.java:388) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.View.layout(View.java:14817) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.ViewGroup.layout(ViewGroup.java:4631) 08-28 15:47:10.567: E/AndroidRuntime(32352): at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:374) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.View.layout(View.java:14817) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.ViewGroup.layout(ViewGroup.java:4631) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.widget.FrameLayout.onLayout(FrameLayout.java:388) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.View.layout(View.java:14817) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.ViewGroup.layout(ViewGroup.java:4631) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1983) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1740) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.Choreographer.doCallbacks(Choreographer.java:574) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.Choreographer.doFrame(Choreographer.java:544) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.os.Handler.handleCallback(Handler.java:733) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.os.Handler.dispatchMessage(Handler.java:95) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.os.Looper.loop(Looper.java:136) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.app.ActivityThread.main(ActivityThread.java:5001) 08-28 15:47:10.567: E/AndroidRuntime(32352): at java.lang.reflect.Method.invokeNative(Native Method) 08-28 15:47:10.567: E/AndroidRuntime(32352): at java.lang.reflect.Method.invoke(Method.java:515) 08-28 15:47:10.567: E/AndroidRuntime(32352): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 08-28 15:47:10.567: E/AndroidRuntime(32352): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 08-28 15:47:10.567: E/AndroidRuntime(32352): at dalvik.system.NativeStart.main(Native Method) 08-28 15:47:10.567: E/AndroidRuntime(32352): Caused by: java.lang.reflect.InvocationTargetException 08-28 15:47:10.567: E/AndroidRuntime(32352): at java.lang.reflect.Constructor.constructNative(Native Method) 08-28 15:47:10.567: E/AndroidRuntime(32352): at java.lang.reflect.Constructor.newInstance(Constructor.java:423) 08-28 15:47:10.567: E/AndroidRuntime(32352): at android.view.LayoutInflater.createView(L I have not changed anything in the adapter and as I could see when I remove android:background="?activatableItemBackground" it works. Do you have an idea what's the problem, I'm researching for hours but I can only think on an Android bug. This is my attrs.xml <resources> <attr name="state_red" format="boolean" /> <attr name="state_yellow" format="boolean" /> <!-- The ListItems reference this as background. In the styles.xml is this reference linked to an xml selector that controls the color of the view according to states. --> <declare-styleable name="BaseTheme"> <attr name="activatableItemBackground" format="reference" /> </declare-styleable> </resources> A: And as always, a short time after asking you get the solution by yourself: The problem was really strange, in my styles.xml I had following: <!-- Immediate parent theme to specify base values for custom attributes --> <style name="Theme.Base" parent="FrameworkRoot.Theme"> <!-- Defines the selector for the row view --> <item name="activatableItemBackground">@drawable/dna_list_selector_holo_light</item> </style> After reading somewhere that name collision is a possibility in styles I changed Theme.Base by Custom_Base_Thme and now it works, it was the only change I made.
doc_23537215
dfA A 1 1 2 1 3 1 4 1 dfB B 3 2 4 2 5 2 6 2 Desired result: A 1 1 2 1 3 2 4 2 What is the simplest way to do this? A: Try with update dfA.update(dfB.rename(columns = {'B':'A'}))
doc_23537216
def csv_import require 'csv' file = File.open("/#{Rails.public_path}/uploads/shate.csv") csv = CSV.open(file, "r:ISO-8859-15:UTF-8", {:col_sep => ";", :row_sep => :auto, :headers => :first_row}) csv.each do |row| #ename,esupp= row[1].split(/_/) #(ename,esupp,foo) = row[1]..split('_') abrakadabra = row[0].to_s() (ename,esupp) = abrakadabra.split(/_/) eprice = row[6] eqnt = row[1] # logger.info("1) ") # logger.info(ename) # logger.info("---") # logger.info(esupp) #---- #ename = row[4] #eprice = row[7] #eqnt = row[10] #esupp = row[12] if ename.present? && ename.size>3 search_condition = "*" + ename.upcase + "*" if esupp.present? #supplier = @suppliers.find{|item| item['SUP_BRAND'] =~ Regexp.new(".*#{esupp}.*") } supplier = Supplier.where("SUP_BRAND like ?", "%#{esupp}%").first logger.warn("!!! *** supp !!!") #logger.warn(supplier) end if supplier.present? @search = ArtLookup.find(:all, :conditions => ['MATCH (ARL_SEARCH_NUMBER) AGAINST(? IN BOOLEAN MODE)', search_condition.gsub(/[^0-9A-Za-z]/, '')]) @articles = Article.find(:all, :conditions => { :ART_ID => @search.map(&:ARL_ART_ID)}) @art_concret = @articles.find_all{|item| item.ART_ARTICLE_NR.gsub(/[^0-9A-Za-z]/, '').include?(ename.gsub(/[^0-9A-Za-z]/, '')) } @aa = @art_concret.find{|item| item['ART_SUP_ID']==supplier.SUP_ID} #| @articles if @aa.present? @art = Article.find_by_ART_ID(@aa) end if @art.present? @art.PRICEM = eprice @art.QUANTITYM = eqnt @art.datetime_of_update = DateTime.now @art.save end end logger.warn("------------------------------") end #logger.warn(esupp) end end Even if I delete and get only this, it is slow. def csv_import require 'csv' file = File.open("/#{Rails.public_path}/uploads/shate.csv") csv = CSV.open(file, "r:ISO-8859-15:UTF-8", {:col_sep => ";", :row_sep => :auto, :headers => :first_row}) csv.each do |row| end end Could anybody help me increase the speed using fastercsv? A: As it's name implies Faster CSV is Well Faster :) http://fastercsv.rubyforge.org also see. for some more info Ruby on Rails Moving from CSV to FasterCSV A: I don't think it will get much faster. That said, some testing shows that a significant part of time is spent for the transcoding (about 15% for my test case). So if you could skip that (e.g. by creating the CSV in UTF-8 already) you would see some improvement. Besides, according to ruby-doc.org the "primary" interface for reading CSVs is foreach, so this should be preferred: def csv_import import 'csv' CSV.foreach("/#{Rails.public_path}/uploads/shate.csv", {:encoding => 'ISO-8859-15:UTF-8', :col_sep => ';', :row_sep => :auto, :headers => :first_row}) do | row | # use row here... end end Update You could also try splitting the parsing into several threads. I reached some performance increase experimenting with this code (treatment of heading left out): N = 10000 def csv_import all_lines = File.read("/#{Rails.public_path}/uploads/shate.csv").lines # parts will contain the parsed CSV data of the different chunks/slices # threads will contain the threads parts, threads = [], [] # iterate over chunks/slices of N lines of the CSV file all_lines.each_slice(N) do | plines | # add an array object for the current chunk to parts parts << result = [] # create a thread for parsing the current chunk, hand it over the chunk # and the current parts sub-array threads << Thread.new(plines.join, result) do | tsrc, tresult | # parse the chunk parsed = CSV.parse(tsrc, {:encoding => 'ISO-8859-15:UTF-8', :col_sep => ";", :row_sep => :auto}) # add the parsed data to the parts sub-array tresult.replace(parsed.to_a) end end # wait for all threads to finish threads.each(&:join) # merge all the parts sub-arrays into one big array and iterate over it parts.flatten(1).each do | row | # use row (Array) end end This splits the input into chunks of 10000 lines and creates a parsing thread for each of the chunks. Each threads gets handed over a sub-array in the array parts for storing its result. When all threads are finished (after threads.each(&:join)) the results of all chunks in parts are joint and that's it. A: I'm curious how big the file is, and how many columns it has. Using CSV.foreach is the preferred way. It would be interesting to see the memory profile as your app is running. (Sometimes the slowness is due to printing, so make sure you don't do more of that than you need) You might be able to preprocess it, and exclude any row that doesn't have the esupp, as it looks like your code only cares about those rows. Also, you could truncate any right-side columns you don't care about. Another technique would be to gather up the unique components and put them in a hash. Seems like you are firing the same query multiple times. You just need to profile it and see where it's spending its time. A: check out the Gem smarter_csv! It can read CSV files in chunks, and you can then create Resque jobs to further process and insert those chunks into a database. https://github.com/tilo/smarter_csv
doc_23537217
please help me IdHTTP := TIdHTTP.Create(nil); try try Result:= IdHTTP.Get(strServerUrl + strMethodUrl + Number+'/'+User); except on E: Exception do begin ShowMessage('The server Is not Start'); Result:=''; end; end; finally IdHTTP.Free; end;
doc_23537218
MainActivity is as below @SuppressLint("SimpleDateFormat") public class RecorderActivity extends BaseActivity implements CamCoderView.Contract { //private CamCoderView ffc = null; //private CamCoderView std = null; private CamCoderView camcoder = null; private boolean hasTwoCameras = (Camera.getNumberOfCameras() > 1); private boolean singleShot = true; private ImageButton captureBtn; private ImageButton rotateBtn; private ImageButton doneBtn; private int cameraType = Camera.CameraInfo.CAMERA_FACING_BACK; private boolean isCapturePressed = false; private ArrayList<String> pathNames = new ArrayList<String>(); private String randomPathName; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_record_layout); WindowManager.LayoutParams layout = getWindow().getAttributes(); layout.screenBrightness = 1F; getWindow().setAttributes(layout); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); camcoder = CamCoderView.newInstance(false); getFragmentManager().beginTransaction() .replace(R.id.container, camcoder ).commit(); randomPathName = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); captureBtn = (ImageButton) findViewById(R.id.captureBtn); doneBtn = (ImageButton) findViewById(R.id.doneBtn); rotateBtn = (ImageButton) findViewById(R.id.rotateBtn); if (hasTwoCameras) rotateBtn.setEnabled(true); rotateBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (cameraType == Camera.CameraInfo.CAMERA_FACING_BACK) { cameraType = Camera.CameraInfo.CAMERA_FACING_FRONT; camcoder = CamCoderView.newInstance(true); getFragmentManager().beginTransaction() .replace(R.id.container, camcoder ).commit(); } else { cameraType = Camera.CameraInfo.CAMERA_FACING_BACK; camcoder = CamCoderView.newInstance(false); getFragmentManager().beginTransaction() .replace(R.id.container, camcoder ).commit(); } } }); doneBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); captureBtn.setOnTouchListener(new OnTouchListener() { @SuppressLint("SdCardPath") @Override public boolean onTouch(View arg0, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_DOWN) { if(isCapturePressed == false) { isCapturePressed = true; String path = getOutputMediaFile().getAbsolutePath(); pathNames.add(path); camcoder.startRecording(path); } } else if (event.getAction() == MotionEvent.ACTION_UP) { isCapturePressed = false; try { camcoder.stopRecording(); } catch (Exception e) { e.printStackTrace(); } } return false; } }); } @SuppressLint("DefaultLocale") @Override public void onBackPressed() { super.onBackPressed(); if (pathNames != null) { for (int i = 0 ; i < pathNames.size(); i++) { File file = new File(pathNames.get(i)); if(file.exists()) { file.delete(); } } } finish(); } @SuppressLint("SimpleDateFormat") private File getOutputMediaFile() { File filesDir = getDir("users", Context.MODE_PRIVATE); //Creating an internal dir; if(!filesDir.isDirectory()) { if (!filesDir.mkdirs()) { Log.d("MyCameraApp", "failed to create directory"); return null; } } File mediaFile; mediaFile = new File(filesDir.getPath() + File.separator + "vid_" + randomPathName + "_" + String.valueOf(pathNames.size()) +".mp4"); return mediaFile; } @Override public void onDestroy() { super.onDestroy(); } @Override public boolean isSingleShotMode() { return(singleShot); } @Override public void setSingleShotMode(boolean mode) { singleShot = mode; } @Override public void callUIMethodForStore(Intent intent) { } } CameraView is as follow public class CamCoderView extends CameraFragment { private FrameLayout preview; private static final String KEY_USE_FFC = "USE_FFC"; static CamCoderView newInstance(boolean useFFC) { CamCoderView f = new CamCoderView(); Bundle args = new Bundle(); args.putBoolean(KEY_USE_FFC, useFFC); f.setArguments(args); return(f); } @Override public void onCreate(Bundle state) { super.onCreate(state); setHost(new MyCameraHost(getActivity())); } @Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) { View cameraView = super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment, container, false); preview = (FrameLayout)view.findViewById(R.id.camera); preview.addView(cameraView); if(isAutoFocusAvailable()) { autoFocus(); } return view; } @Override public void onDestroy() { super.onDestroy(); } public class MyCameraHost extends SimpleCameraHost { boolean supportsFaces=false; public MyCameraHost(Context _ctxt) { super(_ctxt); } @Override public boolean useFrontFacingCamera() { return(getArguments().getBoolean(KEY_USE_FFC)); } @Override public boolean useSingleShotMode() { return false; } @Override public void saveImage(byte[] image) { } @Override public void autoFocusAvailable() { } @Override public void autoFocusUnavailable() { } @Override public void onCameraFail(CameraHost.FailureReason reason) { super.onCameraFail(reason); Toast.makeText(getActivity(), "Sorry, but you cannot use the camera now!", Toast.LENGTH_LONG).show(); } @Override public Parameters adjustPreviewParameters(Parameters parameters) { return(super.adjustPreviewParameters(parameters)); } } Contract getContract() { return((Contract)getActivity()); } interface Contract { boolean isSingleShotMode(); void setSingleShotMode(boolean mode); } public void startRecording(String path) { try { record(); } catch (Exception e) { e.printStackTrace(); } } } On my HTC SENSE it is working like a Charm, however my s3 is not working at all. A: Ok, the problem is fixed, it seems tht <style name="AppBaseTheme" parent="android:style/Theme.Light.NoTitleBar"> <!-- Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. --> </style> <!-- Application theme. --> <style name="AppTheme" parent="AppBaseTheme"> <!-- All customizations that are NOT specific to a particular API-level can go here. --> <!-- <item name="android:background">@drawable/main_bg</item> --> <!-- <item name="android:windowBackground">@drawable/main_bg</item> --> <item name="android:windowNoTitle">true</item> <item name="android:windowFullscreen">false</item> </style> Settings Theme on Application was causing this problem, i have removed this and now its working ok !! strange
doc_23537219
gcc does seem available, and I can compile an sample iphone project on xcode Any ideas? A: Such things can happen when: a) Installing Xcode 4.3[.1] and when Xcode 4.2 is removed (the installer ask for this) or if it was never installed. To fix this you need to install the optional "Command Line Tools" to get a complete installation. You can do this from inside Xcode using those steps: XCode 4.3 Command Line Tools Package with Invalid Checksum b) when you install Xcode in a non-default directory. In this case you'll need to tell MonoDevelop where the Apple SDK is located. You can change this in the MonoDevelop's preferences dialog, SDK locations.
doc_23537220
disk is full and cant log any more lines, shutdown the application. So what i need some pre checks before the log events, and if logger does these checks by itself i need those informations A: The standard appenders in log4j2 do not perform checks before writing. They would be expensive and still wouldn’t guarantee the log record could be written A: In addition to Ralph’s answer, Log4j2 is designed as an audit logging framework. This means that if logging is critical to your application, such that the application should fail if logging failed, Log4j2 can accomplish this. All built-in appenders have a configuration attribute ignoreExceptions for this purpose. From the manual: The default is true, causing exceptions encountered while appending events to be internally logged and then ignored. When set to false exceptions will be propagated to the caller, instead.
doc_23537221
I want to count the number of times each word appears in a body of text. I can do this with a simple regular expression. However, I have another list of words that capture context. In the example below the context is a list of pets. Let's call this WORD_LIST_2. I'd like to count the number of times each of the words in WORD_LIST_1 that are within X number of words of any of the words in WORK_LIST_2. My strategy is to extract the matches to WORD_LIST_1 words into an array using a regular expression and then create hash that counts the number of times each word is in this array. I can do easily when the context word (WORD_LIST_2) follows the WORD_LIST_1 word. However, I run into a problem when the WORD_LIST_2 word appears before the WORD_LIST_1 words, specifically when there multiple WORD_LIST_2 words. Below is the code. #!/usr/bin/perl -w #use strict; @colors = ("red", "blue", "green", "brown"); $WORD_LIST_1 = join("|",@colors); @pets = ("cat","dog","bird","fish"); $WORD_LIST_2 = join("|",@pets); #$text1 = "The red haired dog quickly and sharply ran away from the blue nosed cat."; #$text1 = "The green spotted cat drinks blue water."; #$text1 = "The brown feathered, green beaked bird flew away."; $text1 = "The fish with blue fins and red tails."; @finds = (); $within_N_words = 4; @finds = $text1 =~ m/\b(?=($WORD_LIST_1)\W+(?:\w+\W+){0,$within_N_words}?(?:$WORD_LIST_2))\b|\b(?=(?:$WORD_LIST_2)\W+(?:\w+\W+){0,$within_N_words}?($WORD_LIST_1))\b/gi; @finds = grep defined, @finds; print "\n\n", join("|", @finds), "\n\n"; Note that the fourth $text1 line has blue and red following fish. But it only returns "blue" and doesn't return "red" too. I've check the first three sentences that are commented out and they appear to be working well. My approach is based on this page: http://www.regular-expressions.info/near.html Thoughts I've considered includd using a positive look-behind, but I need to have variable lengths in the look behind. I've thought about reversing the entire text string and regular expression, then searching again. But this could result in double counting. I've also thought about searching for each WORD_LIST_1 word in individual regular expersions using some sort of loop. However, this takes a lot of time on my real data as the actual WORD_LIST_1 list is 500 or so words and I have multiple bodies of length text I want to search. Two other side notes: (1)the regular expression above occasionally returns empty elements into the @finds array. I can't figure out why. My work around is to use the grep defined line. What is the correct way to address this. Rather, why is my regular expression returning blank elements? (2) I'm still learning the "proper" way to use PERL. I've commented out use strict in this example as I don't believe in the context I am using perl it makes a difference. I'm sure someone can tell me why this is wrong of me. Good PERL programmers always seem to tell me I shouldn't run perl code without using strict, but no one yet has convinced me it is something I need to worry about. However, I'm open to learning. A: Well, first off - the text you give... looks like red is more than 4 words away from fish in the first place? But failing that - the problem is I think because your regex is "consuming" the text on the first match so it doesn't it the second match. In this, you start to hit the limitations of the regular expression engine - http://www.regular-expressions.info/keep.html How important is it that you use a single regular expression to do your search? Bear in mind that whilst a regular expression looks quite concise, it can be hard to read and computationally expensive. I would suggest therefore that your initial suggestion of splitting up your patterns isn't as bad as it sounds - in order to match 'red' and 'blue' on the second example, you need to allow for the conditions that'll permit duplicate matches. E.g. fish cat red red blue blue How many hits should you get here? You can use something like a hash to count duplicates of words and deduplicate 'relationships' though: my %matches = ( $text1 =~ m/ \b ($WORD_LIST_2) \W+ (?:\w+\W+){0,$within_N_words}? ($WORD_LIST_1)\b /gix ); print Dumper \%matches; We match into a hash, because then when we 'insert' paired words, we get key-value pairs: $VAR1 = { 'fish' => 'blue' }; But it may be of use to know - you can use qr in perl to "compile" a regex and see what you actually end up with. In your example: print qr /\b(?=($WORD_LIST_1)\W+(?:\w+\W+){0,$within_N_words}?(?:$WORD_LIST_2))\b|\b(?=(?:$WORD_LIST_2)\W+(?:\w+\W+){0,$within_N_words}?($WORD_LIST_1))\b/; (?^:\b(?=(red|blue|green|brown)\W+(?:\w+\W+){0,4}?(?:(?^:cat|dog|bird|fish)))\b|\b(?=(?:(?^:cat|dog|bird|fish))\W+(?:\w+\W+){0,4}?(red|blue|green|brown))\b) The first pattern doesn't match at all. The second does, but only once because it 'eats' the existing patterns. my @finds2 = ( $text1 =~ m/\b(?:$WORD_LIST_2)\W+(?:\w+\W+){0,$within_N_words}?($WORD_LIST_1)\b/gi ) Finds blue. Drop the 'nongreedy' modifier, and it'll find red. But because your pattern has 'eaten' the preceeding bits, it can't match twice with the g modifier. I don't think perl will support multi-matching in that context, because if you think about it, the number of comparisons needed quickly gets huge. I would also offer: * *check out the x modifier for writing your regexes when they get long. *You can compile regexes, and it's advantageous when using variables that are effectively static (like you are). So something like this: my @pets = qw (cat dog bird fish ); my $WORD_LIST_2 = join( "|", map {quotemeta} @pets ); $WORD_LIST_2 = qr/$WORD_LIST_2/; my @finds2 = ( $text1 =~ m/ \b (?:$WORD_LIST_2) \W+ (?:\w+\W+){0,$within_N_words}? ($WORD_LIST_1)\b /gix ); For 1: Because your capturing is both 'sides' of the alternation, but only one can match. So the one that doesn't returns undef. Split your pattern into two, and you won't have this problem. Or use ?| for branch reset. http://www.effectiveperlprogramming.com/2010/09/use-branch-reset-grouping-to-number-captures-in-alternations/ For 2: Why use strict and warnings? So I'd suggest ending up with something like: #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @colors = qw ( red blue green brown ); my $WORD_LIST_1 = join( "|", map {quotemeta} @colors ); $WORD_LIST_1 = qr/$WORD_LIST_1/; my @pets = qw (cat dog bird fish ); my $WORD_LIST_2 = join( "|", map {quotemeta} @pets ); $WORD_LIST_2 = qr/$WORD_LIST_2/; my $within_N_words = 4; while ( my $text1 = <DATA> ) { print $text1; my %matches = ( $text1 =~ m/(?| \b #word break ($WORD_LIST_2) \W+ (?:\w+\W+){0,$within_N_words}? #nongreedy 0-N 'words'. ($WORD_LIST_1) \b | \b ($WORD_LIST_1) \W+ (?:\w+\W+){0,$within_N_words}? ($WORD_LIST_2) \b ) /gix ); print Dumper \%matches; } __DATA__ The red haired dog quickly and sharply ran away from the blue nosed cat. The green spotted cat drinks blue water. The brown feathered, green beaked bird flew away. The fish with blue fins and red tails. This gives us both words and context: The red haired dog quickly and sharply ran away from the blue nosed cat. $VAR1 = { 'blue' => 'cat', 'red' => 'dog' }; The green spotted cat drinks blue water. $VAR1 = { 'green' => 'cat' }; The brown feathered, green beaked bird flew away. $VAR1 = { 'brown' => 'bird' }; The fish with blue fins and red tails. $VAR1 = { 'fish' => 'blue' }; (You can use values to extract just the words).
doc_23537222
Possible Duplicate: How thread-safe is enum in java? Let there be an enum class like public enum Type { ONE, TWO, THREE, FOUR } Is the Type.values() array thread safe to access in a for loop, e.g., in a static method? For example: public static void process() { for (Type type:Type.values()) { // Do something } } Furthermore, if one defines a static array variable with any subset of these values, will that be thread safe to read? For example: public static final Type[] TYPES = new Type[] {TWO, THREE}; public static void process() { for (Type type:TYPES) { // Do something } } In both cases, the process() method may belong to a different class than the definition of the Type enum and of the types array. Also, the TYPES array could be defined once in the Type enum and returned by a static method of that enum. So, given the above, if multiple threads are running the process() method simultaneously, will the code be thread safe (at least for just reading the values of the TYPES array)? A: The method Type.values() returns a new array every time. It does this because the array is mutable and it has to return a new copy each time to be thread safe. A: enum are guaranteed thread-safe they are immutable. So, threads can't modify the state of the enum. Second case, when you define as final, there also it will be threadsafe, you are not allowed to modify the reference of error. Remember, you are not allowed to change the "reference" only, but you can change the state of array. A: Others have already pointed out that the values() method returns a new array each time, so it is thread safe. However, to answer your second question: if one defines a static array variable with any subset of these values, will that be thread safe? No. Any public static array is not safe, because array elements are always mutable. That is, any thread could change TYPES[0] to be any other Type, which is not safe in the presence of multiple threads -- or indeed even in a single-threaded program. Much better would be to expose a List<Type>, which can then be safely made immutable (e.g., using Collections.unmodifiableList()).
doc_23537223
I just simply want that if the code exists more than once than in output table all of its Sq-In should be added up. Like in the above table A1 is repeated three times so all its SqIn are added up and it gives A1 81. Right now the id's of code's textbox are #code_0, #code_1,#code_2 and so on. where as the SqIn is #sqin_0, #sqin_1, #sqin_2 and so on... <table id="myTable"> <thead> <tr> <th>Codes</th> <th>room</th> <th>SqIn</th> </tr> </thead> <tbody> <tr> <td><input type="text" value="A1" /></td> <td><input type="text" value="1" /></td> <td><input type="text" value="25"/></td> </tr> <tr> <td><input type="text" value="B1" /></td> <td><input type="text" value="1"/></td> <td><input type="text" value="25"/></td> </tr> <tr> <td><input type="text" value="C1" /></td> <td><input type="text" value="1"/></td> <td><input type="text" value="25"/></td> </tr> <tr> <td><input type="text" value="A1" /></td> <td><input type="text" value="2"/></td> <td><input type="text" value="25"/></td> </tr> <tr> <td><input type="text" value="B1" /></td> <td><input type="text" value="1"/></td> <td><input type="text" value="25"/></td> </tr> <tr> <td><input type="text" value="C1"/></td> <td><input type="text" value="2"/></td> <td><input type="text" value="25"/></td> </tr> </tbody> </table> <button id=summarise ">Summarise</button> <table id="SummarizedTable"> //here the summary table should come. </table> JS SqIn: +(element.childNodes[1].firstElementChild.value) A: In close to a psuedo code form, but it will look like below: var myList = {}; $('input[id^="code"]').each(function(){ // Grab all input with ID begins with 'code' var myID = $(this).attr("id"); // Get the actual ID if( myList[myID] == '' ){ var value = 0; $('input').find('[id=' + myID + ']').each(function(){ value += $(this).next().val(); // Get the all elements next to all 'id=myID' }); myList[myID] = value; // Insert the total } }); for( var i in myList ){ var id = i; var value = myList[i]; // Draw the summary <td> using the id and the value here } A: * *Create an array to hold the cell information var cells = []; *Read in the cell information from the DOM and add each record to the array cells.push({code: 'A1', SqIn: 25}); *Use Array.prototype.reduce to combine and sum the cell information in the array. *Empty your tbody from the table *Add the cells from the result of your reduce (3) An example CSS table, th, td { border: 1px solid black; } HTML <table id="myTable"> <thead> <tr> <th>Codes</th> <th>SqIn</th> </tr> </thead> <tbody> <tr> <td>A1</td> <td>25</td> </tr> <tr> <td>B1</td> <td>25</td> </tr> <tr> <td>C1</td> <td>25</td> </tr> <tr> <td>A1</td> <td>50</td> </tr> <tr> <td>B1</td> <td>50</td> </tr> <tr> <td>C1</td> <td>50</td> </tr> </tbody> </table> <button id="summarise">Summarise</button> Javascript function emptyNode(node) { while (node.firstChild) { node.removeChild(node.firstChild); } } function summariseTable(tableId) { var tbody = document.getElementById(tableId).lastElementChild, reduced = Array.prototype.map.call(tbody.getElementsByTagName('tr'), function (element) { return { code: element.firstElementChild.textContent, SqIn: +(element.lastElementChild.textContent) }; }).reduce(function (acc, rowData) { if (!acc.hasOwnProperty(rowData.code)) { acc[rowData.code] = rowData.SqIn; } else { acc[rowData.code] += rowData.SqIn; } return acc; }, {}); emptyNode(tbody); Object.keys(reduced).forEach(function (code) { var row = document.createElement('tr'), tdCode = document.createElement('td'), tdSqIn = document.createElement('td'); tdCode.appendChild(document.createTextNode(code)); tdSqIn.appendChild(document.createTextNode(reduced[code])); row.appendChild(tdCode); row.appendChild(tdSqIn); tbody.appendChild(row); }); } document.getElementById('summarise').addEventListener('click', function () { summariseTable('myTable'); }, false); On jsFiddle This example replaces the content of the current table, but you can easily have it create a new table instead. If you have inputs in the tds then get the value of those instead.
doc_23537224
$stateProvider .state('calendar', { url: '/calendar/:category/:competition/:team', controller: 'calendarCtrl', templateUrl: 'app/modules/calendar/calendarView.html', }) To make my navigation work I also need access to the :category/:competition/:team-params in my pageCtrl. Can I configure this using the same way? Something like: $stateProvider .state("page", { abstract: true, controller: 'pageCtrl', // params: :category/:competition/:team }) Edit: Using $stateParams in the calendarCtrl works fine. I just can't figure out how I can make sure my pageCtrl also can get read the url. A: Since you're using ui.router, inject $stateParams in your controller(s) and then you can access those values like so: controller.js function($stateParams){ $stateParams.category $stateParams.competition $stateParams.team A: My suggestion would be - use more views - the UI-Router built feature. Multiple Named Views There is a working plunker Let's have the 'Parent' state which has this template: This blue is the parent template. Orange are child views <!-- HERE is one named view target --> <div ui-view="title">This is a title filled by child having access to param</div> ... <!-- HERE is other view target un-named --> <div ui-view></div> And its state is very simple. The interesting is the child state, which is taking care about both views: .state('parent', { abstract: true, url: "/parent", templateUrl: 'tpl.parent.html', }) .state('parent.child', { url: "/child/:id", views : { '': { templateUrl: 'tpl.child.html', }, 'title': { templateUrl: 'tpl.title.html', controller: 'TitleCtrl', }, } }) So, we do have a target for "some other view" title or side bar. Check it here And we can even place some default implementation there inside of our "non-abstract" parent state. There is extended plunker with non abstract parent state definition: .state('parent', { url: "/parent", views : { '': { templateUrl: 'tpl.parent.html', }, 'title@parent': { template: 'the parent own TITLE', }, } }) Check it here A: There is a way, how to grant access to latest/up-to-date $stateParams - including current state and its child(ren) as well. (working example here) It is surprisingly easy: .run(['$rootScope', '$state', '$stateParams', function ($rootScope, $state, $stateParams) { $rootScope.$state = $state; $rootScope.$stateParams = $stateParams; }]) And that's it. (check similar answer and some discussion here) With this approach, we will even in parent $scopes have updated reference to the latest $stateParams. While in our own, we will still receive just our own part .controller('ParentCtrl', ['$scope', '$stateParams', function ($scope, $stateParams) { $scope.currentStateParams = $stateParams; }]) The above is valid for states like these: .state('parent', { url: "/parent?area", templateUrl: 'tpl.html', controller: 'ParentCtrl', }) .state('parent.child', { url: "/child/:id", templateUrl: 'tpl.html', controller: 'ChildCtrl', }) Working example to play here. But I still would say, that this is a bit ... against the UI-Router. I would prefer this answer. Because in that case, each view (while injected into some parent area) is really aware about $stateParams, which belongs to that state. What we are doing here is introduction of some observer pattern (we should watch changes if we want to react in parent) and that would later bring more issues then profit
doc_23537225
Here is the idea of soft ripple animation: https://www.instagram.com/p/CBxl4KEgHm6 A: Basically you can use TouchableNativeFeedback to create a ripple effect Official Documentation With React Native Paper More Reference OR Simply you can use react-native-material-ripple npm library which can easily do your thing done :) A: thats a shimmer effect. check out react-native-shimmer-placeholder docs: https://www.npmjs.com/package/react-native-shimmer-placeholder
doc_23537226
<?xml version="1.0" encoding="utf-8" ?> <root> <paths> <item> <name>username</name> <path>user/name</path> </item> <item> <name>useremail</name> <path>concat(user/name,': ',user/email)</path> </item> </paths> <user> <name>John</name> <email>john@gmail.com</email> </user> </root> the output required to obtain such a document: <?xml version="1.0" encoding="utf-8"?> <results> <item name="username" value="John"/> <item name="useremail" value="John: john@gmail.com"/> </results> The point is that the number of path elements can vary, and their values can refer to different elements of the source document (including using functions). Is there a way to use the values of some elements as an expression of the search for other?
doc_23537227
....- Completion Code 1, Reason 2003 com.ibm.mq.MQException: Completion Code 1, Reason 2003 at com.ibm.mq.MQQueueManager.commit(MQQueueManager.java:795) Your help in resolving this would be most appreciated. A: Did you read the manual (InfoCenter): http://publib.boulder.ibm.com/infocenter/wmqv7/v7r0/index.jsp?topic=/com.ibm.mq.amqzao.doc/fm12100_.htm How often is your code doing a commit?
doc_23537228
The server side is a J2EE application extracting the data and blobs entered previously and doing some tests such as face recognition, alphanumeric matching etc. These tests are done asynchronously and continuously.I thaught to use the multithreading for these processes done by the server side. So is that recommended for such case ? Is there other solution ? A: There are several limitations in GAE that somewhat limit it's multiprocessing abilities: * *Each request can make up to 50 threads, but threads can not outlive the request, which itself has a 60 seconds limit. Also, threads must be created via GAE's own ThreadManager, which limits the use of most external processing libraries. *Background threads independent of current request are available and can be long-lived, but there is a limit of 10 background threads per instance. For async processing you should look into Task Queues - it has all above limitations, but can run for 10 minutes. You can start periodic processing via Cron jobs. Note that GAE instances are quite limited (default is single core 600MHz, 128Mb RAM). They are also quite expensive given how low-power they are. If you need more processing power you should look into Compute Engine (powerful, stand-alone, unmanaged, no GAE-services access, fairly priced for the power), or in your case preferably Managed VMs (powerful, managed, limited GAE-service access, same price as CE). So if you have light processing, use Task Queues, if you need more power use Managed VMs (currently in preview).
doc_23537229
the filter purpose is to insert FEC bits just before the H.264 NAL's header, what requires me to read the encoder's data on the bit LEVEL. I already made the FEC filter DLL and connected it using GraphEdit. Suppose I want to see some LOG msg with the video data(bits) entering my filter in the GraphEdit anyone knows how to generate those log msgs or log file? A: there're two possibilities: 1) implement logging of anything you need to know to external file in you FEC filter 2) you can put "smart tee" filter before (and/or after) your FEC filter to "tee" the stream and connect the second pin to "dump" filter (http://msdn.microsoft.com/en-us/library/dd388553(v=vs.85).aspx) that can write all received samples to the file for later analysis A: OutputDebugString and attaching a debugger will print the messages into the debug window of the IDE. On the other hand, you can use output logger like DbgView which capture all OutputDebugString messages in the system. A: Some tools for analyzing data flow between filters: Open source graph editor GraphStudioNext analyzer filter (and analyzer file writer) will show you a visual log of activity when inserted between two filters of interest. You'll need to build it yourself to get this feature for now. Geraint Davie's monitor filter will write a log file of activity to disk. See this question: How to debug c++ DirectShow filter for further techniques
doc_23537230
For scenarios and queries posted below, this database is used: Scenario 1 Am not able to figure out database name? I thought it's restaurants, but with this assumption, below code didn’t work, and getting PERMISSION_DENIED exception: service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if database == "restaurants"; } } } Scenario 2 Collection restaurants have 10 documents, as appearing in above screen, I have hard coded those 10, and allowed them to read and write as below, but its not working, and getting same PERMISSION_DENIED exception: service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read : if document in ['2uFMIc2BSH6oslxEABpB','8GMNVxVUb1HzRAk2QmmX', 'AryyMURod8AeWAfBVavF','AvnpKGMeUWDSfowFLpwa','H0qi7gI8WmSVobu19G49', 'H2xhfoj0Rn75BH9nnbuI','NRfgppqWRfj3DtHDlft4','R9gZ0hTxCPXwSeV2prNV', 'YgXXwndeIfZx6rUhdlc4','v22FlL7LBBY851N8sIvQ'] ; allow write : if document in ['2uFMIc2BSH6oslxEABpB','8GMNVxVUb1HzRAk2QmmX', 'AryyMURod8AeWAfBVavF','AvnpKGMeUWDSfowFLpwa','H0qi7gI8WmSVobu19G49', 'H2xhfoj0Rn75BH9nnbuI','NRfgppqWRfj3DtHDlft4','R9gZ0hTxCPXwSeV2prNV', 'YgXXwndeIfZx6rUhdlc4','v22FlL7LBBY851N8sIvQ'] ; } } } These 2 may not be very practical scenarios, but its more for my understanding. A: * *In your first example, database is the name of your database, which is probably something like "(default)". *In your second example, document is going to be the full path of your document; that's what that =** wildcard does -- it's a "everything else in my path" kind of wildcard. So it'll equal something like restaurants/2uFMIc2BSH6oslxEABpB If you want to create a rule that says, "A user can read any document in my restaurants collection" you want something like this: service cloud.firestore { match /databases/{database}/documents { match /restaurants/{restaurantID} { allow read, write: if true; } } } If you want to do something interesting with the document ID of your individual restaurants, you probably want to do something more like this: service cloud.firestore { match /databases/{database}/documents { match /restaurants/{restaurantID} { allow read, write: if restaurantID == '2uFMIc2BSH6oslxEABpB; ; } } }
doc_23537231
https://github.com/sheehan/job-dsl-gradle-example video: https://www.youtube.com/watch?v=SSK_JaBacE0 My gradle build was successful as it it has pulled all the dependencies required to get it work like visual studio intellisense. But somehow the DSL APIS(https://jenkinsci.github.io/job-dsl-plugin/) are not recognized. >> folder(basePath) { description 'This example shows how to create a set of jobs for each github branch, each in its own folder.' } The idea.gdsl file supposed to make it work. Content of idea.gdsl: >> def ctx = context(pathRegexp: /.*\/jobs\/.*groovy/) contributor(ctx, { delegatesTo(findClass('javaposse.jobdsl.dsl.DslFactory')) }) i am getting error "delegatesto can not be applied com.intellij.psi.psiclass" I am not able to understand what to do next. I am new Gradle and Intellij. Anyone used the github project and made it work? Any other solution?
doc_23537232
* *Lauch both the Game and the Task. *Start a game of the Game and immediately pause it. *Alt tab to the task. *Do it until a point determined in the program. At which point I am told to switch to the game. *Alt tab to the game *Unpause it and start a clockwatch. *When the clockwatch reaches X minutes (X determined in advance), pause the game. *Alt tab to the task. *Repeat steps 4-7 N number of times. I have no idea whether it is possible or what tools to use. I understood that a simple bash file won't be enough and I might need to use a "fake keyboard" program to force some inputs (such as "space bar" to pause the game). But I have no idea how to coordinate all of that. Thanks in advance for any help. Even telling me it's not possible is an acceptable answer :) EDIT : Edited the list for clarity A: From what information you have given, it is difficult to tell whether the complete process can be automated, but there are tools like AutoHotKey which you can use to write scripts to automate desktop applications. A simple script in autohotkey to start a program "Notepad", another program "Calculater", and switch back to "Notepad" and write "Hello World!" in it. SetTitleMatchMode, 2 Run "C:\Windows:\Notepad.exe" Run "calc.exe" WinActivate, Notepad Send, Hello World! The above is a very simple script. It does not activate the specific notepad window you want if multiple notepad windows are open. However, that can be automated too.
doc_23537233
CREATE PROCEDURE [dbo].[SP_SelectData_View] ( @Sort VARCHAR(MAX), @CONDITION VARCHAR(MAX) = '' @Values dbo.FlowStatus READONLY ) AS BEGIN DECLARE @STRQUERY NVARCHAR(MAX) IF @CONDITION IS NOT NULL AND @CONDITION != '' BEGIN SET @CONDITION = 'WHERE ' + @CONDITION END ELSE BEGIN SET @CONDITION = '' END IF @Sort IS NULL OR @Sort = '' BEGIN SET @Sort = 'Id Desc' END BEGIN SET @STRQUERY = 'SELECT A.* FROM ' + @Values + ' as FlowStatus' JOIN Tbl_A as A ON A.status = FlowStatus.StatusNowId AND B.flow = FlowStatus.FlowNowId ' + @CONDITION + ' Order By ' + @Sort EXEC(@STRQUERY) END END But in the code above, I got an error must declare scalar variable @Values I've searched for it and I think it is because the aliases is not detected because it's inside a string. But if I didn't put it in a string query, the @condition and @sort variable will be error. Is there a solution where I can do both calling the table-valued variable and query string variable together? A: There are several things wrong with the approach you currently have, as I and others have commented, Brent Ozar has a good reference on dynamic SQL https://www.brentozar.com/sql/dynamic/ I would say don't pass in some SQL, construct it in the stored proc; passing in parameters such as name which is used in the where, hence I have put a full working example. This also shows how to pass the user defined table type into the stored proc and then also pass it into the dynamic SQL. I hope this is a good enough example of the techniques, I had a bit of time so thought I would try and help as much as possible :) /* -------------------------------------------- Create a test table to run the stored proc against */ IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'MyTestTable')) BEGIN PRINT 'Creating table MyTestTable' CREATE TABLE [dbo].[MyTestTable]( Id BIGINT NOT NULL IDENTITY(1,1) PRIMARY KEY, [Name] NVARCHAR(50) NOT NULL ) INSERT INTO dbo.MyTestTable ([Name]) VALUES ('Andrew'), ('Bob'), ('john') -- SELECT * FROM MyTestTable END GO /* -------------------------------------------- Create the table type that we pass into the store proc */ IF NOT EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'FlowStatus') BEGIN PRINT 'Creating type [dbo].[FlowStatus]' CREATE TYPE [dbo].FlowStatus AS TABLE ( MyId BIGINT PRIMARY KEY, SomeText NVARCHAR(200) ) END GO /* -------------------------------------------- Create the stored proc with the User Defined table type */ CREATE OR ALTER PROCEDURE [dbo].[MyStoredProc] ( @SortBy VARCHAR(50), @SearchName VARCHAR(50), @Values dbo.FlowStatus READONLY ) AS BEGIN -- As your SQL gets more complex it is an idea to create seperate parts of the SQL DECLARE @SqlToExecute NVARCHAR(MAX) -- The primary data you want to get SET @SqlToExecute = N' SELECT T.Id, T.[Name], V.SomeText FROM MyTestTable AS T LEFT JOIN @Values AS V ON V.MyId = T.Id WHERE 1 = 1' -- We do this so that we can have many AND statements which could be expanded upon IF @SearchName IS NOT NULL BEGIN SET @SqlToExecute = @SqlToExecute + N' AND T.[Name] LIKE ''%' + @SearchName + '''' END IF @SortBy IS NOT NULL BEGIN SET @SqlToExecute = @SqlToExecute + N' ORDER BY ' + CASE WHEN @SortBy LIKE 'Name%' THEN N'T.[Name]' ELSE N'T.[Id]' END END -- Print out the script that will be run, useful for debugging you code PRINT @SqlToExecute EXEC sp_executesql @SqlToExecute, N'@Values dbo.FlowStatus READONLY', @Values END GO /* -------------------------------------------- Now lets test it -- Test Andrew */ DECLARE @flowStatusType AS dbo.FlowStatus INSERT INTO @flowStatusType(MyId, SomeText) VALUES(1, 'Test1'), (2, 'Test2') EXEC [dbo].[MyStoredProc] @SearchName = 'Andrew', @SortBy = 'Name', @Values = @flowStatusType GO -- Test Bob DECLARE @flowStatusType AS dbo.FlowStatus INSERT INTO @flowStatusType(MyId, SomeText) VALUES(1, 'Test1'), (2, 'Test2') EXEC [dbo].[MyStoredProc] @SearchName = 'Bob', @SortBy = 'Name', @Values = @flowStatusType GO Its also worth noting that if you can just join on the @Values without needing dynamic SQL then that is sure to be less work.
doc_23537234
function dialogPopup(saveScan){ consoleLog("starting"); //remove it if it exists if ($("#caseTagsPopup").length){ $("#caseTagsPopup").remove(); } //create a div to hold the dialog $('<div/>', { id: 'caseTagsPopup', class: '', title: "Please Select Case Tags" }).appendTo(document.body); $("#caseTagsPopup").html("<b>Please select the issue and click save.</b> <br>"); //append all the checkboxes to the div for each case tags $.each(allSettings.caseTagTypes, function(key, value) { //make the checkbox itself $('<input/>', { class: '', name: 'caseTagCheckBox', value: value.id, type: 'checkbox', id: value.sound }).appendTo("#caseTagsPopup"); //make the checkbox label $('<label/>', { name: 'caseTagLabel', id: "labelCaseTag" + value.id, 'for': "checkBoxCaseTag" + value.id, text: value.codeName }).appendTo("#caseTagsPopup"); //make a line break $('<br/>').appendTo("#caseTagsPopup"); }); //make the description label $('<textarea/>', { value: '', type: 'textarea', placeholder: 'Case tag message', id: 'caseTagMessage' }).appendTo("#caseTagsPopup"); //make the div a popup //make that div a jquery ui dialog popup = $("#caseTagsPopup").dialog({ resizable: false, height: "auto", width: 400, modal: true, closeOnEscape: false, resizable: true, position: { my: "center", at: "top", of: document }, buttons: { "Save": function() { if (checkBoxValidity('caseTagsPopup', 'input:checked')==true){ checkBoxValues = []; soundPlayValues = []; // if save button clicked, change alert icon image selectedRow.cells[0].firstElementChild.src ="/dev/img/exclamation_green.png"; $('input:checkbox[name="caseTagCheckBox"]').each(function() { if($(this).is(':checked')){ $(this).prop('checked',true).attr('checked', 'checked'); checkBoxValues.push($(this).val()); soundPlayValues.push($(this).attr('id')); } }); //do ajax call to save the tags on this case data = {"caseNum": savedScan.parsedData.case, "partIdentifier": savedScan.parsedData.part, "blockIdentifier": savedScan.parsedData.internalBlockId ? savedScan.parsedData.internalBlockId : '', "slideIdentifier": savedScan.parsedData.block ? savedScan.parsedData.block : '', "codeId": checkBoxValues, "eventId": savedScan.lastInsertId, "workstationIdSource": allSettings.workstationInfo.workstationId, "message": $("#caseTagMessage").val() ? $("#caseTagMessage").val() : '', "sound": soundPlayValues }; query("saveCaseTags", data, saveCaseTagsComplete, url="query.php"); $( this ).dialog("close"); } } } }); //open the dialog popup.dialog("open"); }
doc_23537235
Here is an example. I have a simple dataframe library(tidyverse) set.seed(123) df <- data.frame(time = seq(1,5,1), x = seq(1,5,1) + rnorm(n=5, sd=0.3)) > df time x 1 1 0.8318573 2 2 1.9309468 3 3 3.4676125 4 4 4.0211525 5 5 5.0387863 I would like to add the time at which x exceeds a particular value (e.g., x > 4) to a new column, named border_value. The following code does works: df <- df %>% mutate(border_value = min(.[.$x > 4, "time"])) > df time x border_value 1 1 0.8318573 4 2 2 1.9309468 4 3 3 3.4676125 4 4 4 4.0211525 4 5 5 5.0387863 4 Question I have a lot of dataframes, in which the values for x differ. Sometimes, the values do not exceed the border_value of x>4. In those cases, R generates an error: Warning message: In min(.[.$x > 4, "time"]) : no non-missing arguments to min; returning Inf I would like to alter my code so that this error does not occur, and R puts NA's in the column instead. Any idea how to do this? Update Based on this post, I was able to rewrite the code to: df <- df %>% mutate(border_value = ifelse(test = is.infinite(min(.[.$x > 7, "time"])), yes = NA, no = min(.[.$x > 4, "time"]))) This doesn't generate the Infs, but still generates the error... A: There are many ways you can write that. Here are a couple based on your use case, df %>% mutate(border_value = which(x > 4)[1]) df %>% mutate(border_value = time[x > 4][1]) Both will return NA if no value is found
doc_23537236
However, with jquery's .hide() applied to the last child, the element is just given display:none, therefore making the visually last element still showing its border-bottom. What's the best way to solve this, that is also reusable across other similar ul within the project? A: If you want to remove border-bottom of last 'li' element, then use following CSS:- .classname:last-child{ border-bottom:0; } Where classname is the class added to the 'li' element. .hide() will hide the last 'li' element, not border.
doc_23537237
I'm on MAC and I'm using SSH to connect with my VM. It's working fine but when I try to run the docker container I get an error: ubuntu@ubuntu-virtual-machine:~$ docker run -it -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=unix$DISPLAY -v /dev/snd:/dev/snd --privileged --name spotify jess/spotify (spotify:1): Gtk-WARNING **: cannot open display: unix How can I fix this? I tried already some things I read on the internet like: edit ~/.xinitrc and put the following in it: #! /bin/bash xhost +localhost & Also tried to ssh to my ubuntu in the following way: ssh ubuntu@IP -X and ssh ubuntu@IP -Y
doc_23537238
Question: What might cause this to occur?
doc_23537239
For example, in portrait mode, I have 2 UIImageViews on top and bottom that share the screen evenly. In landscape mode, the 2 UIImageViews are side by side. How can this be done using storyboard in Xcode 6? Things I have tried: * *Settings constraints on the views in storyboard with size classes. I set the base values for my 2 imageviews in w:Any h:Any, then moved to w:Compact h:Regular and set constraints for portrait view.Then I moved to w:Any h:Compact, moved the 2 imageviews side by side and set constraints for landscape view. Then I get conflicts in w:Compact h:Compact because of the constraints I have applied for and landscape and portrait orientation. I think it's because I moved the image views around for landscape orientation before settings the constraints that caused this problem. *Using 2 separate view controllers and have portrait view controller switch to landscape view controller when orientation changes using NSNotificationCenter and performSegueWithIdentifier to push the landscape view controller on top of my portrait view controller. This problem is that there's lots of data to be passed(lot of imageviews and labels). Is the a way to use only one view controller and a way to rearrange the imageviews/labels and apply new constraints on them when the orientation changes? Is -(void)viewDidLayoutSubviews{} where I put the code to rearrange the image views? Can someone point me in the right directions? Thanks! A: For this case I recommend to make layout programmatically via code. Here is example: https://dl.dropboxusercontent.com/u/48223929/Test.zip - (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; [self layoutImageViewsForViewSize:self.view.frame.size]; } - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { [self layoutImageViewsForViewSize:size]; } - (void)layoutImageViewsForViewSize:(CGSize)size { // Portrait mode if (size.height > size.width) { self.imageView1.frame = CGRectMake(0, 0, size.width, size.height / 2); self.imageView2.frame = CGRectMake(0, size.height / 2, size.width, size.height / 2); // Landscape mode } else { self.imageView1.frame = CGRectMake(0, 0, size.width / 2, size.height); self.imageView2.frame = CGRectMake(size.width / 2, 0, size.width / 2, size.height); } } For autolayout: - (void)layoutImageViewsForViewSize:(CGSize)size { // Portrait mode [self.view removeConstraints:self.view.constraints]; if (size.height > size.width) { NSString *heightLayoutFormatString = [NSString stringWithFormat:@"V:|[_imageView1(%.0f)][_imageView2(%.0f)]|", size.height / 2, size.height / 2]; [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:heightLayoutFormatString options:0 metrics:nil views:NSDictionaryOfVariableBindings(_imageView1, _imageView2)]]; [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:|[_imageView1(%.0f)]|", size.width] options:0 metrics:nil views:NSDictionaryOfVariableBindings(_imageView1)]]; [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"H:|[_imageView2(%.0f)]|", size.width] options:0 metrics:nil views:NSDictionaryOfVariableBindings(_imageView2)]]; // Landscape mode } else { NSString *widthLayoutFormatString = [NSString stringWithFormat:@"H:|[_imageView1(%.0f)][_imageView2(%.0f)]|", size.width / 2, size.width / 2]; [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:widthLayoutFormatString options:0 metrics:nil views:NSDictionaryOfVariableBindings(_imageView1, _imageView2)]]; [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|[_imageView1(%.0f)]|", size.height] options:0 metrics:nil views:NSDictionaryOfVariableBindings(_imageView1)]]; [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:|[_imageView2(%.0f)]|", size.height] options:0 metrics:nil views:NSDictionaryOfVariableBindings(_imageView2)]]; } [self.view setNeedsUpdateConstraints]; } Another solution for autolayout - make your custom subclass of UIView, which contains 2 image views, and layout it programmly without constraints - just setFrame. And then add this custom UIView to your storyboard
doc_23537240
created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) and settings.py file TIME_ZONE = 'UTC' USE_TZ = True using this date and time automatically saving PostgreSQL db in format of 2020-01-24 20:13:47.846445+05:30 with offset(+05:30) but i want to save it as 2020-01-24 14:43:47.846445+00:00 without offset means as 00 but if inspect one instance created_at row data using python manage.py shell i am getting required format(Django handling internally fine) so how to save date and time with offset 00:00 ? what is tried is using manually assigned timezone.now()(its value is 2020-01-24 14:43:47.846445+00:00) to updated_at but if i open PostgreSQL editor again showing same value as 2020-01-24 20:13:47.846445+05:30 instead of 2020-01-24 14:43:47.846445+00:00 all of the above in local laptop but tried another way i hosted my django in production server with ip location(sever cloud server location) is india now my db showing correct result as 2020-01-24 14:43:47.846445+00:00 with offset 00 i dont know how
doc_23537241
I usully do this agent=Mechanize.New page=agent.get("www.some_url.com/atributes") but insted of that I want to test if a page is attributed to that url before downloading it A: The only way to see if a page exists (and that you can reach it via the internet) is to perform an actual request. You could first do a HTTP HEAD request, which only requests the headers, not the actual content: url = "www.some_url.com/atributes" agent = Mechanize.New begin agent.head(url) page_exists = true rescue SocketError page_exists = false end if page_exists page = agent.get(url) # do something with page ... end But then again, you can just get rid of the extra request and rescue from errors directly with the GET request: url = "www.some_url.com/atributes" agent = Mechanize.New begin page = agent.get(url) # do something with page ... rescue SocketError puts "There is no such page." end
doc_23537242
this code is from index.jsp , the first page of my Web Application , the user will upload a video from this page : <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script type="text/javascript"> function validate(){ document.getElementById("mybutton").style.visibility="visible"; document.getElementById("file_browse").style.visibility="hidden"; } </script> <title>ADMIN PAGE</title> <style type="text/css"> #Text1 { width: 303px; height: 28px; margin-top: 0px; } #Button1 { width: 84px; margin-bottom: 4px; height: 27px; } #Button2 { width: 100px; height: 35px; } #Button3 { width: 100px; height: 35px; } .style1 { font-size: xx-large; } .style2 { color: #CC0000; word-spacing: inherit; } #Button4 { width: 113px; height: 32px; } #Button5 { width: 114px; height: 32px; } .newStyle1 { font-style: oblique; } .style3 { font-style: oblique; color: #FF0000; font-size: xx-large; } </style> </head> <body bgcolor="#E7EEE7"> <form id="form1" runat="server"> <div style="border-style: groove; border-width: thin;height: 77px; width: 999px; margin-right: 1px; margin-top: 0px"> &nbsp;&nbsp;<span class="style1"></span> <span class="style3">YouTUBE</span></span><span class="style2">&nbsp; </span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input id="Text1" type="text" /><input id="Button1" type="button" value="Search"/> <input id="Button2" type="button" value="Admin"/> <input id="Button3" type="button" value="Logout" /></div> </form> <div style="border-style: groove; border-width: thin;width: 155px; height: 906px; margin-top:0px;"> </div> <div style="border-style: groove; border-width: thin;height: 908px; width: 250px; margin-left: 750px; margin-top: -907px; margin-bottom: 0px; margin-right: 0px;"> </div> <div style="border-style: groove; border-width: thin; width: 586px; height: 487px; margin-left: 159px; margin-top: -910px; margin-right: 7px;"> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="600" height="344"> <object type="application/x-shockwave-flash" data="player.swf" width="580" height="444"> <param name="movie" value="Justin King Lesson 2.flv" /> <param name="wmode" value="transparent" /> <param name="bgcolor" value="#FFFFFF" /> <param name="quality" value="high" /> <param name="allowFullScreen" value="true" /> <param name="allowscriptaccess" value="always" /> <a href="http://www.adobe.com/go/getflash"> <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /> </a> <param name="flashvars" value="vdo=Justin King Lesson 2.flv&amp;autoplay=false" /> </object> </object> </div> <p> <input id="Button4" type="button" value="Upload"/> <input id="Button5" type="button" value="Download" /></p> <form ENCTYPE="multipart/form-data" ACTION= "VT" METHOD="POST"> <table style="margin-top:30px;margin-left:160px;"> <tr> <td colspan="1"><p align="center"/></td> <td> </td> <td><div id='file_browse_wrapper'> <input type="file" name="F1" id="file_browse" onclick="validate()" /></div></td> </tr> </table> <table style="margin-top:-37px;margin-left:164px;"> <div id="mybutton_wrapper"> <tr><td><p align="right"><input TYPE="submit" VALUE="" id="mybutton" style="visibility:hidden"/></p></td></tr> </div> <tr><td colspan="2"></td></tr> </table> </form> </body> </html> the uploading takes place by the execution of the VT.java servlet : package xugglerPack; import java.io.DataInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Random; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.awt.Image; public class VT extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); String user = ""; String contentType = request.getContentType(); if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) { DataInputStream in = new DataInputStream(request.getInputStream()); int formDataLength = request.getContentLength(); byte dataBytes[] = new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0; while (totalBytesRead < formDataLength) { byteRead = in.read(dataBytes, totalBytesRead, formDataLength); totalBytesRead += byteRead; } String file = new String(dataBytes); String saveFile = file.substring(file.indexOf("filename=\"") + 10); saveFile = saveFile.substring(0, saveFile.indexOf("\n")); saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\"")); int lastIndex = contentType.lastIndexOf("="); String boundary = contentType.substring(lastIndex + 1, contentType.length()); int pos; pos = file.indexOf("filename=\""); pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; int boundaryLocation = file.indexOf(boundary, pos) - 4; int startPos = ((file.substring(0, pos)).getBytes()).length; int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length; String rootPath = "C:\\Users\\JD\\Documents\\NetBeansProjects\\xuggler\\web"; session.setAttribute("myFolderpath", rootPath); FileOutputStream fileOut = new FileOutputStream(rootPath + "\\" + saveFile); fileOut.write(dataBytes, startPos, (endPos - startPos)); fileOut.flush(); fileOut.close(); String myFile = rootPath.concat("\\").concat(saveFile); Main main=new Main(); main.main(saveFile,myFile); RequestDispatcher rd = request.getRequestDispatcher("findSong.jsp"); rd.forward(request, response); } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; } } During the uploading an image is generated with Main.java from the video using Xuggler : package xugglerPack; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import com.xuggle.mediatool.IMediaReader; import com.xuggle.mediatool.MediaListenerAdapter; import com.xuggle.mediatool.ToolFactory; import com.xuggle.mediatool.event.IVideoPictureEvent; import com.xuggle.xuggler.Global; import java.util.Random; public class Main { public static final long SECONDS_BETWEEN_FRAMES = 50; private static final String outputFilePrefix = "C:\\Users\\JD\\Documents\\NetBeansProjects\\xuggler\\web\\"; // The video stream index, used to ensure we display frames from one and // only one video stream from the media container. private static long mVideoStreamIndex = SECONDS_BETWEEN_FRAMES; //public String saveFile = ""; // Time of last frame write private static long mLastPtsWrite = Global.DEFAULT_PTS_PER_SECOND + SECONDS_BETWEEN_FRAMES; public static final long MICRO_SECONDS_BETWEEN_FRAMES = (long) (Global.DEFAULT_PTS_PER_SECOND * SECONDS_BETWEEN_FRAMES); public void main(String saveFile, String inputFilename) { IMediaReader mediaReader = ToolFactory.makeReader(inputFilename); // stipulate that we want BufferedImages created in BGR 24bit color space mediaReader.setBufferedImageTypeToGenerate(BufferedImage.TYPE_3BYTE_BGR); mediaReader.addListener(new ImageSnapListener()); // read out the contents of the media file and // dispatch events to the attached listener while (mediaReader.readPacket() == null); } private static class ImageSnapListener extends MediaListenerAdapter { public void onVideoPicture(IVideoPictureEvent event) { if (event.getStreamIndex() != SECONDS_BETWEEN_FRAMES) { // if the selected video stream id is not yet set, go ahead an // select this lucky video stream if (mVideoStreamIndex == SECONDS_BETWEEN_FRAMES) { mVideoStreamIndex = event.getStreamIndex(); } // no need to show frames from this video stream else { return; } } // if uninitialized, back date mLastPtsWrite to get the very first frame if (mLastPtsWrite == Global.DEFAULT_PTS_PER_SECOND + SECONDS_BETWEEN_FRAMES) { mLastPtsWrite = event.getTimeStamp() + SECONDS_BETWEEN_FRAMES; // String outputFilename = dumpImageToFile(event.getImage()); dumpImageToFile(event.getImage()); } // if it's time to write the next frame /* if (event.getTimeStamp() - mLastPtsWrite >= MICRO_SECONDS_BETWEEN_FRAMES) { String outputFilename = dumpImageToFile(event.getImage()); // indicate file written double seconds = ((double) event.getTimeStamp()) / Global.DEFAULT_PTS_PER_SECOND; System.out.printf( "at elapsed time of %6.3f seconds wrote: %s\n", seconds, outputFilename); // update last write time mLastPtsWrite += MICRO_SECONDS_BETWEEN_FRAMES; } */ } private String dumpImageToFile(BufferedImage image) { try { Random rg = new Random(); int random = rg.nextInt(500); // long randomlong = rg.nextLong(); String outputFilepath = outputFilePrefix + random + ".png"; String outputFilename = random + ".png"; String parts[] = outputFilename.split("\\."); String part1 = parts[0]; System.out.println("the filename is splitted into two , where the name of the file is " + part1); ImageIO.write(image, "png", new File(outputFilepath)); DBHandler db = new DBHandler(); db.insertpic(outputFilename, part1, "me", outputFilepath); return outputFilename; } catch (IOException e) { e.printStackTrace(); return null; } } } } The problem as I stated before is that when i run my application , the video gets uploaded and the image gets generated that time, but next time when i upload videos, only the video gets uploaded not the images. I have to restart Tomcat to achieve the same again, so please help. Thanks in advance and sorry for making this a long topic. A: Try removing the static keyword for these two variables in the Main class: private static long mVideoStreamIndex = SECONDS_BETWEEN_FRAMES; private static long mLastPtsWrite = Global.DEFAULT_PTS_PER_SECOND + SECONDS_BETWEEN_FRAMES; If you make them static their value will be kept across calls and I doubt this is really what you want. Correct me if I'm wrong.
doc_23537243
com.mongodb.MongoCommandException: Command failed with error 16007 (Location16007): 'can't convert from BSON type object to String' on server 10.3.87.54:27017. The full response is { "ok" : 0.0, "errmsg" : "can't convert from BSON type object to String", "code" : 16007, "codeName" : "Location16007" } { "$project" : { "ss" : "$movieId", "dd" : "$title", "t" : { "$substr" : [{ "SUBSTR_fa81ecc633086358d21e299e466533bb" : { "$substr" : ["genres", 1, 8] } }, 1, 6] } } } image is here A: Try this: { $project : { ss : "$movieId", dd : "$title", t : {$substr : [{$substr : ["$genres", 1, 8]}, 1, 6] } } } If this doesn't work, paste your document structure & expected outcome.
doc_23537244
I have a docker-compose file in which all µ-services will be manual created. Now I have a problem. If I use discovery with akka-dns their is nothing found. If I use static and give them the exposed ports their is also not found. Where is my mistake? Docker compose file: security: container_name: panakeia-security image: nexus.familieschmidt.online/andre-user/panakeia/security-impl:latest environment: - APPLICATION_SECRET=hlPlU12MK?[oF1Xj`>xd>CtCjTHohfu0=ekVFOo?r]lH^GpFo5o?kurLFO6sQPzD - POSTGRESQL_URL=jdbc:postgresql://****SERVER-IP****:12000/panakeia - POSTGRESQL_USERNAME=panakeia - POSTGRESQL_PASSWORD=123456789 - INIT_USERNAME=test@test.de - INIT_USERPASS=123456 - REQUIRED_CONTACT_POINT_NR=1 - JAVA_OPTS=-Dconfig.resource=prod-application.conf -Dplay.server.pidfile.path=/dev/null expose: - 9000 - 15000 # - 8558 ports: - "15000:15000" - "14999:9000" networks: - panakeia-network My loader class class SecurityLoader extends LagomApplicationLoader { override def load(context: LagomApplicationContext): LagomApplication = new SecurityApplication(context) with ConfigurationServiceLocatorComponents { // override def staticServiceUri: URI = URI.create("http://localhost:9000") } //AkkaDiscoveryComponents override def loadDevMode(context: LagomApplicationContext): LagomApplication = new SecurityApplication(context) with LagomDevModeComponents override def describeService = Some(readDescriptor[SecurityService]) } and my production.conf include "application" play { server { pidfile.path = "/dev/null" } http.secret.key = "${APPLICATION_SECRET}" } db.default { url = ${POSTGRESQL_URL} username = ${POSTGRESQL_USERNAME} password = ${POSTGRESQL_PASSWORD} } user.init { username = ${INIT_USERNAME} password = ${INIT_USERPASS} } pac4j.jwk = {"kty":"oct","k":${JWK_KEY},"alg":"HS512"} lagom.persistence.jdbc.create-tables.auto = true //akka { // discovery.method = akka-dns // // cluster { // shutdown-after-unsuccessful-join-seed-nodes = 60s // } // // management { // cluster.bootstrap { // contact-point-discovery { // discovery-method = akka.discovery //// discovery-method = akka-dns // service-name = "security-service" // required-contact-point-nr = ${REQUIRED_CONTACT_POINT_NR} // } // } // } //} lagom.services { security-impl = "http://****SERVER-IP****:15000" // serviceB = "http://10.1.2.4:8080" } For other domains on the same server i have a reverse nginx. But not for this project. When I run http://SERVER-IP:14999 in browser I get a 404 NotFound typical Play screen message. :( I have no problem to write the compose file and to link them manual. I have also no problem to use akka-dns. But I will have no kubernetes or something else. Thanks for you help Here is a log of one the µ-service 2021-04-02T14:38:24.151Z [info] akka.event.slf4j.Slf4jLogger [] - Slf4jLogger started 2021-04-02T14:38:24.409Z [info] akka.remote.artery.tcp.ArteryTcpTransport [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=main, akkaSource=ArteryTcpTransport(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:24.409UTC] - Remoting started with transport [Artery tcp]; listening on address [akka://application@192.168.0.5:25520] with UID [-580933006609059378] 2021-04-02T14:38:24.427Z [info] akka.cluster.Cluster [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=main, akkaSource=Cluster(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:24.427UTC] - Cluster Node [akka://application@192.168.0.5:25520] - Starting up, Akka version [2.6.8] ... 2021-04-02T14:38:24.527Z [info] akka.cluster.Cluster [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=main, akkaSource=Cluster(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:24.527UTC] - Cluster Node [akka://application@192.168.0.5:25520] - Registered cluster JMX MBean [akka:type=Cluster] 2021-04-02T14:38:24.528Z [info] akka.cluster.Cluster [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=main, akkaSource=Cluster(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:24.527UTC] - Cluster Node [akka://application@192.168.0.5:25520] - Started up successfully 2021-04-02T14:38:24.552Z [info] akka.cluster.Cluster [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.internal-dispatcher-2, akkaSource=Cluster(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:24.552UTC] - Cluster Node [akka://application@192.168.0.5:25520] - No downing-provider-class configured, manual cluster downing required, see https://doc.akka.io/docs/akka/current/typed/cluster.html#downing 2021-04-02T14:38:24.552Z [info] akka.cluster.Cluster [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.internal-dispatcher-2, akkaSource=Cluster(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:24.552UTC] - Cluster Node [akka://application@192.168.0.5:25520] - No seed-nodes configured, manual cluster join required, see https://doc.akka.io/docs/akka/current/typed/cluster.html#joining 2021-04-02T14:38:25.383Z [info] akka.io.DnsExt [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=main, akkaSource=DnsExt(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:25.383UTC] - Creating async dns resolver async-dns with manager name SD-DNS 2021-04-02T14:38:25.386Z [info] akka.management.cluster.bootstrap.ClusterBootstrap [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=main, akkaSource=ClusterBootstrap(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:25.386UTC] - Bootstrap using default `akka.discovery` method: AggregateServiceDiscovery 2021-04-02T14:38:25.394Z [info] akka.management.internal.HealthChecksImpl [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=main, akkaSource=HealthChecksImpl(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:25.394UTC] - Loading readiness checks List(NamedHealthCheck(cluster-membership,akka.management.cluster.scaladsl.ClusterMembershipCheck)) 2021-04-02T14:38:25.394Z [info] akka.management.internal.HealthChecksImpl [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=main, akkaSource=HealthChecksImpl(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:25.394UTC] - Loading liveness checks List() 2021-04-02T14:38:25.488Z [info] akka.management.scaladsl.AkkaManagement [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=main, akkaSource=AkkaManagement(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:25.488UTC] - Binding Akka Management (HTTP) endpoint to: 192.168.0.5:8558 2021-04-02T14:38:25.541Z [info] akka.management.scaladsl.AkkaManagement [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=main, akkaSource=AkkaManagement(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:25.541UTC] - Including HTTP management routes for ClusterHttpManagementRouteProvider 2021-04-02T14:38:25.581Z [info] akka.management.scaladsl.AkkaManagement [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=main, akkaSource=AkkaManagement(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:25.581UTC] - Including HTTP management routes for ClusterBootstrap 2021-04-02T14:38:25.585Z [info] akka.management.cluster.bootstrap.ClusterBootstrap [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=main, akkaSource=ClusterBootstrap(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:25.584UTC] - Using self contact point address: http://192.168.0.5:8558 2021-04-02T14:38:25.600Z [info] akka.management.scaladsl.AkkaManagement [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=main, akkaSource=AkkaManagement(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:25.600UTC] - Including HTTP management routes for HealthCheckRoutes 2021-04-02T14:38:26.108Z [info] akka.management.scaladsl.AkkaManagement [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.default-dispatcher-18, akkaSource=AkkaManagement(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:26.108UTC] - Bound Akka Management (HTTP) endpoint to: 192.168.0.5:8558 2021-04-02T14:38:26.154Z [info] akka.management.cluster.bootstrap.ClusterBootstrap [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=main, akkaSource=ClusterBootstrap(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:26.154UTC] - Initiating bootstrap procedure using akka.discovery method... 2021-04-02T14:38:26.163Z [info] akka.management.cluster.bootstrap.internal.BootstrapCoordinator [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.default-dispatcher-5, akkaSource=akka://application@192.168.0.5:25520/system/bootstrapCoordinator, sourceActorSystem=application, akkaTimestamp=14:38:26.163UTC] - Locating service members. Using discovery [akka.discovery.aggregate.AggregateServiceDiscovery], join decider [akka.management.cluster.bootstrap.LowestAddressJoinDecider] 2021-04-02T14:38:26.164Z [info] akka.management.cluster.bootstrap.internal.BootstrapCoordinator [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.default-dispatcher-5, akkaSource=akka://application@192.168.0.5:25520/system/bootstrapCoordinator, sourceActorSystem=application, akkaTimestamp=14:38:26.163UTC] - Looking up [Lookup(application,None,Some(tcp))] 2021-04-02T14:38:26.189Z [info] akka.management.cluster.bootstrap.internal.BootstrapCoordinator [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.default-dispatcher-5, akkaSource=akka://application@192.168.0.5:25520/system/bootstrapCoordinator, sourceActorSystem=application, akkaTimestamp=14:38:26.189UTC] - Located service members based on: [Lookup(application,None,Some(tcp))]: [], filtered to [] 2021-04-02T14:38:26.195Z [info] play.api.db.DefaultDBApi [] - Database [default] initialized 2021-04-02T14:38:26.200Z [info] play.api.db.HikariCPConnectionPool [] - Creating Pool for datasource 'default' 2021-04-02T14:38:26.207Z [info] com.zaxxer.hikari.HikariDataSource [] - HikariPool-1 - Starting... 2021-04-02T14:38:26.218Z [info] com.zaxxer.hikari.HikariDataSource [] - HikariPool-1 - Start completed. 2021-04-02T14:38:26.221Z [info] play.api.db.HikariCPConnectionPool [] - datasource [default] bound to JNDI as DefaultDS 2021-04-02T14:38:26.469Z [info] akka.cluster.sharding.ShardRegion [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.internal-dispatcher-4, akkaSource=akka://application@192.168.0.5:25520/system/sharding/ProfileProcessor, sourceActorSystem=application, akkaTimestamp=14:38:26.469UTC] - ProfileProcessor: Idle entities will be passivated after [2.000 min] 2021-04-02T14:38:26.480Z [info] akka.cluster.sharding.typed.scaladsl.ClusterSharding [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=main, akkaSource=ClusterSharding(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:26.480UTC] - Starting Shard Region [ProfileEntity]... 2021-04-02T14:38:26.483Z [info] akka.cluster.sharding.ShardRegion [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.internal-dispatcher-3, akkaSource=akka://application@192.168.0.5:25520/system/sharding/ProfileEntity, sourceActorSystem=application, akkaTimestamp=14:38:26.483UTC] - ProfileEntity: Idle entities will be passivated after [2.000 min] 2021-04-02T14:38:26.534Z [info] play.api.Play [] - Application started (Prod) (no global state) 2021-04-02T14:38:26.553Z [info] play.core.server.AkkaHttpServer [] - Listening for HTTP on /0.0.0.0:9000 2021-04-02T14:38:27.188Z [info] akka.management.cluster.bootstrap.LowestAddressJoinDecider [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.default-dispatcher-5, akkaSource=LowestAddressJoinDecider(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:27.187UTC] - Discovered [0] contact points, confirmed [0], which is less than the required [2], retrying 2021-04-02T14:38:27.363Z [info] akka.management.cluster.bootstrap.internal.BootstrapCoordinator [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.default-dispatcher-5, akkaSource=akka://application@192.168.0.5:25520/system/bootstrapCoordinator, sourceActorSystem=application, akkaTimestamp=14:38:27.363UTC] - Looking up [Lookup(application,None,Some(tcp))] 2021-04-02T14:38:27.369Z [info] akka.management.cluster.bootstrap.internal.BootstrapCoordinator [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.default-dispatcher-19, akkaSource=akka://application@192.168.0.5:25520/system/bootstrapCoordinator, sourceActorSystem=application, akkaTimestamp=14:38:27.369UTC] - Located service members based on: [Lookup(application,None,Some(tcp))]: [], filtered to [] 2021-04-02T14:38:28.183Z [info] akka.management.cluster.bootstrap.LowestAddressJoinDecider [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.default-dispatcher-19, akkaSource=LowestAddressJoinDecider(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:28.183UTC] - Discovered [0] contact points, confirmed [0], which is less than the required [2], retrying 2021-04-02T14:38:28.563Z [info] akka.management.cluster.bootstrap.internal.BootstrapCoordinator [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.default-dispatcher-5, akkaSource=akka://application@192.168.0.5:25520/system/bootstrapCoordinator, sourceActorSystem=application, akkaTimestamp=14:38:28.563UTC] - Looking up [Lookup(application,None,Some(tcp))] 2021-04-02T14:38:28.564Z [info] akka.management.cluster.bootstrap.internal.BootstrapCoordinator [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.default-dispatcher-18, akkaSource=akka://application@192.168.0.5:25520/system/bootstrapCoordinator, sourceActorSystem=application, akkaTimestamp=14:38:28.564UTC] - Located service members based on: [Lookup(application,None,Some(tcp))]: [], filtered to [] 2021-04-02T14:38:29.183Z [info] akka.management.cluster.bootstrap.LowestAddressJoinDecider [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.default-dispatcher-5, akkaSource=LowestAddressJoinDecider(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:29.183UTC] - Discovered [0] contact points, confirmed [0], which is less than the required [2], retrying 2021-04-02T14:38:29.724Z [info] akka.management.cluster.bootstrap.internal.BootstrapCoordinator [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.default-dispatcher-22, akkaSource=akka://application@192.168.0.5:25520/system/bootstrapCoordinator, sourceActorSystem=application, akkaTimestamp=14:38:29.723UTC] - Looking up [Lookup(application,None,Some(tcp))] 2021-04-02T14:38:29.729Z [info] akka.management.cluster.bootstrap.internal.BootstrapCoordinator [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.default-dispatcher-18, akkaSource=akka://application@192.168.0.5:25520/system/bootstrapCoordinator, sourceActorSystem=application, akkaTimestamp=14:38:29.729UTC] - Located service members based on: [Lookup(application,None,Some(tcp))]: [], filtered to [] 2021-04-02T14:38:30.183Z [info] akka.management.cluster.bootstrap.LowestAddressJoinDecider [akkaAddress=akka://application@192.168.0.5:25520, sourceThread=application-akka.actor.default-dispatcher-18, akkaSource=LowestAddressJoinDecider(akka://application), sourceActorSystem=application, akkaTimestamp=14:38:30.183UTC] - Discovered [0] contact points, confirmed [0], which is less than the required [2], retrying It looks like the startup process is completly going wrong. Inside of the securityapplication class it should be generated a user with this code val newUUID = UUID.randomUUID() clusterSharding.entityRefFor(Profile.typedKey,newUUID.toString).ask[ProfileConfirmation](reply => CreateProfile(username,password,Some(EmailAddress(username)),Set(SuperAdminRole), PersonalData("","",""),reply ))(30.seconds).map{ case ProfileCmdAccepted(profile) => s"Profile ${profile.login} created" case ProfileCmdRejected(err) => s"ERROR while default user init: $err" case a => s"a: $a" } But there is throwing a Timeout exception. I think the cluster service is not initialized. At demo all working. Do someone has an idea? A: Okay found it in the production conf I added lagom.services { security-service = "http://"${REMOTE_IP}":15000" binary-service = "http://"${REMOTE_IP}":15001" } lagom.cluster.bootstrap.enabled = false In the lagom Application loader in method load I inheriated my application from ConfigurationServiceLocatorComponents And now really important! The docker must configured! I used docker compose. First adding a netowrk! networks: panakeia-network: # driver: bridge ipam: driver: default config: - subnet: 172.28.0.0/16 AND now I give the cluster.seed-nodes.0 the ip of the service! And name the system! That is also important! security: container_name: panakeia-security image: security-impl:latest environment: - APPLICATION_SECRET=**** - POSTGRESQL_URL=jdbc:postgresql://postgres-database:5432/panakeia - POSTGRESQL_USERNAME=???? - POSTGRESQL_PASSWORD=****** - INIT_USERNAME=test@test.de - INIT_USERPASS=******* - JWK_KEY=****** - REQUIRED_CONTACT_POINT_NR=1 - KAFKA_BROKER=REALLY_IP/OR_KAFKA_SERVICE_NAME:9092 - REMOTE_IP=???? - JAVA_OPTS=-Dconfig.resource=prod-application.conf -Dplay.server.pidfile.path=/dev/null -Dakka.cluster.seed-nodes.0=akka://panakeia@172.28.1.5:25520 -Dplay.akka.actor-system=panakeia expose: - 9000 - 15000 ports: - "15000:15000" - "14999:9000" networks: panakeia-network: ipv4_address: 172.28.1.5 With this way it looks like it possible to create a simple and small µ-services cluster without complex systems like kubernetes.
doc_23537245
for(int i = 100000; i > 0; i--) {} for(int i = 1; i < 100001; i++) {} A: This is because in bytecode comparison with 0 is a different operation than comparison with a non-zero number. Actually i < 10001 requires to first load the number on stack then execute comparison, while i > 0 is executed as one operation. Of course there will be no speed difference in most cases because of JVM optimizations. But we can try to make it visible by running the code with -Xint option (interpreted mode execution only). A: Piyush Bhardwaj I tested both the loops in online compiler but my increment loop is executing faster then decrement loop. Program execution depends upon many factors. When sometimes we run the same program on same machine many times we gets different execution times. So it depends upon many factors. See the results for(int i = 1; i < 100001; i++) { } Increment loop -- http://ideone.com/irdY0e for(int i = 100000; i > 0; i--) { } Decrement loop -- http://ideone.com/yDO9Jf Sir Evgeniy Dorofeev has given an excellent explanation which an expert only can give. Finally, you need to consider the performance of your CPU. When considering a benchmark to determine the overall performance of a Java application, bear in mind that bytecode execution, native code execution, and graphics each play a role. Their impact varies depending on the nature of the specific application.
doc_23537246
use Closure; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; class VerifyCsrfToken extends BaseVerifier { public function handle($request, Closure $next) { return parent::handle($request, $next); } } Javascript: $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': 'wrong-token-to-test', 'X-XSRF-TOKEN': 'another-wrong-token-to-test', } }); Blade: $.ajax({ method: "POST", url: "{{url("login/$user")}}", data: { "email": $("#email").val(), "password": CryptoJS.SHA256($('#password').val()).toString(), "_token": "{{csrf_token()}}" } }) Even using the wrong Http header value ('wrong-token-to-test') for csrf token does not result in any token mismatching exception. The request is handled normally. Does that mean Laravel is not checking for the X-CSRF-TOKEN header? A: Laravel first tries to get the CSRF token from the parameter called _token in the get or post, and if missing, THEN it tries to get it from a X-CSRF-TOKEN. Here is the implementation logic in the code in /vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken, method tokensMatch : $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN'); But you are already effectively including the _token parameter (and with correct value) in your ajax post: "_token": "{{csrf_token()}}" So it doesn't matter what you send in the X-CSRF-TOKEN header.
doc_23537247
Buggy Code using System; public class Program { public static void Main() { Console.WriteLine(System.Text.RegularExpressions.Regex.Replace("Aa-_", "[ -_]", "x")); } } Output: xaxx Expected: Aaxx Non Buggy Code using System; public class Program { public static void Main() { Console.WriteLine(System.Text.RegularExpressions.Regex.Replace("Aa-_", "[ _-]", "x")); } } Output = Expected: Aaxx Notes I used https://dotnetfiddle.net/ to evaluate my expressions. I got the same results as my local VS.
doc_23537248
SOCKET ListenSocket; struct sockaddr_in saServer; // Bind the listening socket using the information in the sockaddr structure bind( ListenSocket,(SOCKADDR*) &saServer, sizeof(saServer) ); Here are the declarations for the two structs. This is technically undefined behavior, correct? struct sockaddr { ushort sa_family; char sa_data[14]; }; struct sockaddr_in { short sin_family; u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; }; A: Between the dawn of C (going back at least to 1974) and 1989, if two structures shared a Common Initial Sequence, the language unambiguously allowed code to use a pointer of one structure type to inspect CIS members of the other. In the C99 standard, that permission was restricted to cases where both structure types are part of a union type whose complete declaration was visible at the point where the CIS value is inspected; some people insist that because the authors of the 1989 meant to impose such a restriction it applies to C89 as well. In addition, some compiler writers insist that because the authors of the Standard only meant for that guarantee to apply to accesses made through lvalues of union type, they'll ignore the part of the Standard that says that a definition of a "complete union type" must be visible. Implementations are allowed to provide guarantees beyond those required by the Standard. Because non-psychic people writing code prior to C99 had no reason to expect that they would need to include otherwise-unnecessary union declarations in order to exploit the CIS guarantees, and because a lot of code written from that era relies upon those guarantees despite a lack of such declarations, anyone wanting to write an implementation suitable for use with such code must support them whether or not the Standard requires such support. While there is no particularly good reason why updates to the header file shouldn't include a union type declaration, I'm not sure how many compilers would care about its presence or absence. The compilers I've seen either support the CIS guarantees even without a complete union type declaration visible, or dishonor the CIS guarantees (ignoring the Standard) even when the declaration is present.
doc_23537249
I need to write a mongo query to get the results { "_id" : ObjectId("5d637b5ce27c7d60e5c42ae7"), "name" : "Bangalore", "movies" : [ { "name" : "KGF", "theatres" : [ { "name" : "PVR", "seats" : 45 }, { "name" : "IMAX", "seats" : 46 } ] }, { "name" : "Avengers", "theatres" : [ { "name" : "IMAX", "seats" : 50 } ] } ], "_class" : "com.BMS_mongo.ZZ_BMS_mongo_demo.Entity.CityInfo" } I have written this code : db.cities.aggregate( [ { "$unwind" : "$movies" }, { "$unwind" : "$theatres" } , { "$group" : { _id : "$movies.theatre`enter code here`s.seats" , total : { "$sum" : "$seats" } } } ] ) My schema: A: The following query can get us the expected output: db.collection.aggregate([ { $unwind:"$movies" }, { $unwind:"$movies.theatres" }, { $group:{ "_id":"$movies.name", "movie":{ $first:"$movies.name" }, "totalSeats":{ $sum:"$movies.theatres.seats" } } }, { $project:{ "_id":0 } } ]).pretty() Data set: { "_id" : ObjectId("5d637b5ce27c7d60e5c42ae7"), "name" : "Bangalore", "movies" : [ { "name" : "KGF", "theatres" : [ { "name" : "PVR", "seats" : 45 }, { "name" : "IMAX", "seats" : 46 } ] }, { "name" : "Avengers", "theatres" : [ { "name" : "IMAX", "seats" : 50 } ] } ], "_class" : "com.BMS_mongo.ZZ_BMS_mongo_demo.Entity.CityInfo" } Output: { "movie" : "Avengers", "totalSeats" : 50 } { "movie" : "KGF", "totalSeats" : 91 } A: Query: db.movie.aggregate([{ $unwind: { path: "$movies",} }, { $unwind: { path: "$movies.theatres",} }, { $group: { _id: "$movies.name", "moviename": { $first: "$movies.name" }, "totalSeats": { $sum: "$movies.theatres.seats" }} }]) A: I got the answer using this query ... db.cities.aggregate( [ { "$match" : { "name" : "Bangalore" } }, { "$unwind" : "$movies" } , { "$match" : {"movies.name" : "KGF"} }, { "$unwind" : "$theatres" }, { "$group" : { _id : "$movies.name", total : { "$sum" : "$movies.theatres.seats" } } } ] )
doc_23537250
Here is how I add Textviews to the Gridview gridView = (GridView) findViewById(R.id.gridView1); String[] arrayEmpty = new String[] {"", "", "", "", "", "", "", "", ""}; ArrayList<String> listEmpty = new ArrayList<String>(Arrays.asList(arrayEmpty)); gridView.setAdapter(new ArrayAdapter<String>(this,R.layout.list_item,list)); Here is my Layout.XML <?xml version="1.0" encoding="utf-8"?> <TableRow android:id="@+id/tableRow1" android:layout_width="match_parent" android:background="#999999" android:layout_weight="1" android:layout_height="match_parent"> <GridView android:id="@+id/gridView1" android:clickable="true" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:background="#5C5C5C" android:layout_weight="1" android:numColumns="3" > </GridView> <GridView android:id="@+id/gridView2" android:clickable="true" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:background="#5C5C5C" android:layout_weight="1" android:numColumns="3" > </GridView> <GridView android:id="@+id/gridView3" android:clickable="true" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:background="#5C5C5C" android:layout_weight="1" android:numColumns="3" > </GridView> <TableRow android:id="@+id/tableRow2" android:layout_width="match_parent" android:background="#999999" android:layout_weight="1" android:layout_height="match_parent"> <GridView android:id="@+id/gridView4" android:clickable="true" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:background="#5C5C5C" android:layout_weight="1" android:numColumns="3" > </GridView> <GridView android:id="@+id/gridView5" android:clickable="true" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:background="#5C5C5C" android:layout_weight="1" android:numColumns="3" > </GridView> <GridView android:id="@+id/gridView6" android:clickable="true" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:background="#5C5C5C" android:layout_weight="1" android:numColumns="3" > </GridView> <TableRow android:id="@+id/tableRow3" android:layout_width="match_parent" android:background="#999999" android:layout_height="match_parent" android:layout_weight="1" android:layout_marginBottom="15dp"> <GridView android:id="@+id/gridView7" android:clickable="true" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:background="#5C5C5C" android:layout_weight="1" android:numColumns="3" > </GridView> <GridView android:id="@+id/gridView8" android:clickable="true" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:background="#5C5C5C" android:layout_weight="1" android:numColumns="3" > </GridView> <GridView android:id="@+id/gridView9" android:clickable="true" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:background="#5C5C5C" android:layout_weight="1" android:numColumns="3" > </GridView> <TableRow android:layout_weight="1" android:layout_height="match_parent"> <Button android:id="@+id/solve_button" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="5dp" android:layout_weight="1" android:text="@string/solve" /> <Button android:id="@+id/clear_button" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="5dp" android:layout_weight="1" android:text="@string/_clear" /> </TableRow> And this is a screenshot of what I had But this is what I need my Layout to be with all Devices. Maybe I should use weights, but I don`t know how A: Check this Sudoku project - Git Hub Also Check This Here you can find layout and source code for Sudoku and also other useful things. A: Here's a trick: For a completely uniform table or grid, you don't need TableView or GridView at all. Just put everything inside LinearLayout with size=0 and layoutWeight=1. That size=0 seems counter-intuitive, but combined with the layoutWeight=1, it has the effect of giving all child widgets the exact same size, regardless of their contents. So do something like this: <!-- Outer container; a vertical layout that fills the screen --> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <!-- first row --> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1"> <!-- contents of the first row --> <!-- first item in first row --> <View android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" /> <!-- second item in first row --> <View android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" /> <!-- third item in first row --> <View android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" /> </LinearLayout> <!-- second row --> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1"> <!-- contents of the second row. --> <!-- etc --> </LinearLayout> <!-- third row --> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1"> <!-- contents of the third row --> <!-- etc --> </LinearLayout> <Button android:id="@+id/solveButton" android:layout_width="fill_parent" android:layout_width="wrap_content" /> <Button android:id="@+id/clearButton" android:layout_width="fill_parent" android:layout_width="wrap_content" /> </LinearLayout>
doc_23537251
I need to open Dialog for button click. When button 1 clicked some text appears and when button2 clicked something other text appears as dialog. My code btn1.setOnClickListener{ showCustomDialog() } btn2.setOnClickListener{ showCustomDialog() } private lateinit var alertDialog: AlertDialog fun showCustomDialog() { val inflater: LayoutInflater = this.getLayoutInflater() val dialogView: View = inflater.inflate(R.layout.dialog_custom_view, null) val headerbtn = dialogView.findViewById<TextView>(R.id.header) headerbtn.text = "Header Message" val dialogBuilder: AlertDialog.Builder = AlertDialog.Builder(context!!) dialogBuilder.setOnDismissListener(object : DialogInterface.OnDismissListener { override fun onDismiss(arg0: DialogInterface) { } }) dialogBuilder.setView(dialogView) alertDialog = dialogBuilder.create(); alertDialog.window!!.getAttributes().windowAnimations = R.style.PauseDialogAnimation alertDialog.show() } A: Send the String to the Function then put it on TextView. btn1.setOnClickListener{ showCustomDialog("This is Text 1") } btn2.setOnClickListener{ showCustomDialog("This is Text 2") } Function : fun showCustomDialog(data: String) { val inflater: LayoutInflater = this.getLayoutInflater() val dialogView: View = inflater.inflate(R.layout.dialog_custom_view, null) val headerbtn = dialogView.findViewById<TextView>(R.id.header) headerbtn.text = data val dialogBuilder: AlertDialog.Builder = AlertDialog.Builder(context!!) dialogBuilder.setOnDismissListener(object : DialogInterface.OnDismissListener { override fun onDismiss(arg0: DialogInterface) { } }) dialogBuilder.setView(dialogView) alertDialog = dialogBuilder.create(); alertDialog.window!!.getAttributes().windowAnimations = R.style.PauseDialogAnimation alertDialog.show() }
doc_23537252
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/download" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <EditText android:id="@+id/edit_message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="@string/edit_message" /> <Button android:layout_weight="2" android:layout_width="2dp" android:layout_height="wrap_content" android:text="@string/button1" android:onClick="sendMessage"/> </LinearLayout> second activity activity_display_message.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:background="@drawable/ool" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="com.example.admin.startanotheractivity.DisplayMessageActivity"> <TextView android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> So , when i click on the button present inside activity_main.xml the background set to the second activity didn't get dispalyed. A: If you want to open activity_display_message from your activity_main, you need to use startActivity(intent) on button click. yourButton.setOnClickListener(new OnClickListener() { @Override public void onClick() { Intent intent = new Intent(MainActivity.this, DisplayMessageActivity.class); startActivity(intent); } }) A: What exactly are you trying to ask? Do you want to replace the first activity with second? Or add the second activity as a component to the first activity? If yes , then you should just inflate the second activity[component] in the first activity dynamically, as follows: Inflate second activity->add to->First activity's linear layout/or whichever layout
doc_23537253
Here is the existing working code: const toggleSubMenus = (() => { let parents = document.querySelectorAll(".deeper"); parents.forEach(function(parent) { let btn = parent.querySelector(".js-expand-submenu"); let child = parent.querySelector(".nav-child"); btn.addEventListener("click", (e) => { parent.classList.toggle("is-expanded"); child.classList.toggle("expanded"); }, false); }); })(); ul ul.is-hidden { display: flex; flex-direction: column; max-height: 0; overflow: hidden; } ul ul.expanded { max-height: 600px; } <ul> <li class="item deeper parent"> <a href="#">Item One</a> <button class="js-expand-submenu"> Expander </button> <ul class="nav-child is-hidden"> <li class="item deeper parent"> <a href="#">Sub Item One</a> <ul class="nav-child is-hidden"> <li> <a href="#">Sub Sub Menu Item</a> </li> </ul> </li> <li> <a href="#">Sub Item Two</a> </li> <li> <a href="#">Sub Item Three</a> </li> </ul> </li> <li class="item deeper parent"> <a href="#">Item Two</a> <button class="js-expand-submenu"> Expander </button> <ul class="nav-child is-hidden"> <li> <a href="#">Sub Item One</a> </li> <li> <a href="#">Sub Item Two</a> </li> <li> <a href="#">Sub Item Three</a> </li> </ul> </li> <li class="item deeper parent"> <a href="#">Item Three</a> </li> </ul> A: Here is my updated code with the solution included: const toggleSubMenus = (() => { let buttons = document.querySelectorAll(".js-expand-submenu"); buttons.forEach(function(button) { button.addEventListener("click", (e) => { let target = e.target; let parent = target.closest(".deeper"); let child = parent.querySelector(".nav-child"); parent.classList.toggle("is-open"); child.classList.toggle("is-expanded"); document.querySelectorAll(".nav-child.is-expanded").forEach(function(childExpanded) { if (childExpanded !== child) { childExpanded.classList.remove("is-expanded"); } }); }, false); }); })(); ul .nav-child { display: flex; flex-direction: column; max-height: 0; overflow: hidden; } ul .nav-child.is-expanded { max-height: 600px; } <ul> <li class="item deeper parent"> <a href="#">Item One</a> <button class="js-expand-submenu"> Expander </button> <ul class="nav-child"> <li> <a href="#">Sub Item One</a> </li> <li> <a href="#">Sub Item Two</a> </li> <li> <a href="#">Sub Item Three</a> </li> </ul> </li> <li class="item deeper parent"> <a href="#">Item Two</a> <button class="js-expand-submenu"> Expander </button> <ul class="nav-child"> <li class="item deeper parent"> <a href="#">Sub Item One</a> <ul class="nav-child"> <li> <a href="#">Sub Sub Menu Item One</a> </li> <li> <a href="#">Sub Sub Menu Item Two</a> </li> </ul> </li> <li> <a href="#">Sub Item Two</a> </li> <li> <a href="#">Sub Item Three</a> </li> </ul> </li> <li class="item deeper parent"> <a href="#">Item Three</a> </li> </ul>
doc_23537254
In a charting object, defined with namespace: xmlns:charting="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit" I am drawing a simple bar chart. <charting:Chart Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3" Visibility="{Binding Path=MyCurrentResultsView, Converter={StaticResource ResourceKey=NullObjectToVisibilityConverter}}" Background="Transparent" Foreground="White" Margin="50,0,50,0" Height="350" HorizontalAlignment="Stretch" Title="{Binding Path=MyCurrentResultsView.Name}"> <charting:ColumnSeries Height="350" Foreground="Black" ItemsSource="{Binding Path=MyCurrentResultsView.ResultsView}" IndependentValueBinding="{Binding Key}" DependentValueBinding="{Binding Value}"> </charting:ColumnSeries> </charting:Chart> What I'd like to do is to show the value of each column above the column (or even inside the column rectangle if possible: these are percentage values and the idea is to make them more visible on the bar chart). I have been looking at the styling information, but here this is more than just style. I see two possibilities. Either: * *For each column item in the series, define a transformation that positions a frame above each column, creates a text box whose label is set to the dependent value, then draws the text box inside the frame. *Find some kind of property on "ColumnSeries" or "? ColumnItem ?" that "enables" the display of the bound value above the column. Total shot in the dark here. Thanks. A: I would try to change the ColumnDatapointTemplate like this: <charting:ColumnSeries Height="350" Foreground="Black" ItemsSource="{Binding Path=MyCurrentResultsView.ResultsView}" IndependentValueBinding="{Binding Key}" DependentValueBinding="{Binding Value}"> <charting:ColumnSeries.DataPointStyle> <Style TargetType="charting:ColumnDataPoint"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="charting:ColumnDataPoint"> <Grid> <Rectangle Fill="{TemplateBinding Background}" Stroke="Black"/> <Grid Margin="0 -20 0 0" HorizontalAlignment="Center" VerticalAlignment="Top"> <TextBlock Text="{TemplateBinding FormattedDependentValue}" Margin="2"/> </Grid> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </charting:ColumnSeries.DataPointStyle> </charting:ColumnSeries> Play a bit with vertical alignments and/or margins and you will be able to get infos into the columns and other. Hope this help!
doc_23537255
(setq-default c-basic-offset 4 c-default-style "linux") (setq-default tab-width 4 indent-tabs-mode t) (define-key c-mode-base-map (kbd "RET") 'newline-and-indent) I'm getting a warning when I open up emacs: Warning (initialization): An error occurred while loading c:/home/.emacs: Symbol's value as variable is void: c-mode-base-map To ensure normal operations, you should investigate and remove the cause of the error in your initialization file. Start Emacs with the --debug-init option to view a complete error backtrace. I ran --debug-init and this is what it returned. I don't know what I means: Debugger entered--Lisp error: (void-variable c-mode-base-map) (define-key c-mode-base-map (kbd "RET") (quote newline-and-indent)) eval-buffer(#<buffer *load*> nil "c:/home/.emacs" nil t) ; Reading at buffer position 311 load-with-code-conversion("c:/home/.emacs" "c:/home/.emacs" t t) load("~/.emacs" t t) A: What this means is that, at the point at which you invoke define-key, c-mode-base-map is not yet defined by anything. The usual fix is to find out where this is defined and require that module. In this case: (require 'cc-mode) However there are other possible fixes as well, for example setting the key-binding in a mode hook, or using eval-after-load. Which one you use is up to you; I tend to do the KISS approach since I don't generally care about startup time; but if you do you may want something lazier.
doc_23537256
SELECT dbo.Divisions.DivisionShortcut, COUNT(DISTINCT dbo.UserQuiz.Username) AS [Number of Participants] FROM dbo.Divisions INNER JOIN dbo.employee ON dbo.Divisions.SapCode = dbo.employee.DivisionCode INNER JOIN dbo.UserQuiz ON dbo.employee.Username = dbo.UserQuiz.Username INNER JOIN dbo.Quiz ON dbo.UserQuiz.QuizID = dbo.Quiz.QuizID WHERE (dbo.Quiz.QuizID = @QuizID) GROUP BY dbo.Divisions.DivisionShortcut This SqlDataSource lets the user enter the number of the Quiz, and it will retrieve the total number of participants in that quiz. I want to convert this SqlDataSource to a DataTable and read a column from it. So how to do that? A: The SqlDataSource has a Select method which you can call to get back a DataView from your SqlDataSource - see the MSDN documentation on that. SqlDataSource dataSource = new SqlDataSource(connectionString, selectSql); DataView view = (DataView)dataSource.Select(args); DataTable table = view.ToTable(); Is that what you're looking for?? A: Let me say you have an SqlDataSource named as SqlDataSource1 DataSourceSelectArguments args = new DataSourceSelectArguments(); DataView view = (DataView)SqlDataSource1.Select(args); DataTable dt = view.ToTable(); Now you can read a column easily from this dt(DataTable) e.g. int columnNumber = 0; for(int i=0;i<dt.Rows.Count;i++) { MessageBox.Show(dt.Rows[i][columnNumber].ToString()); } Reference
doc_23537257
Does this only affect new customers, or will users who have downloaded the app while it was still available be able to redownload it from their "past purchases" section in the App Store or iTunes? I know that this has been asked in the past, but those answers either predate or do not mention the "past purchases" feature of the App Store. (For example, I am still able to download a certain bird-themed jumping game from that section, even though it is no longer listed in the store; however, in that case, the app has probably only been depublished even though the associated developer account is still available.) A: Apple documents about expired membership - Expired Memberships If your Apple Developer Program membership expires, your apps will no longer be available for download and you will not be able to submit new apps or updates. You will lose access to pre-release software, Certificates, Identifiers & Profiles, and Technical Support Incidents. However, your apps will still function for users who have already installed or downloaded them, and you will still have access to iTunes Connect and free development resources. If your Apple Developer Enterprise Program membership expires, your apps will no longer be available for download and will no longer function for those who have already installed or downloaded them. You will still have access to free development resources. This means If your developer account expired then yours app not available for download for both new and old user.But still app will be functional if user already install or downloaded into their device. In this case In App purchase will be work. But He/She if delete the app then he/she can't download further this app until developer account renew. A: After seeing your question I decided to test this for myself. I was able to locate Tap Tap Revenge 3 in my purchase history, download it, and install it on my iPhone 5c running iOS 8.3. The game doesn't function anymore as the game servers have shut down, but it was able to run beyond the launch image at least, which suggests that the app can indeed run provided it doesn't have compatibility issues or depend on any servers that have been taken offline. Tapulous shut down in January 2014 and I don't expect their developer account to still be active today. According to the linked article, IAPs cannot be restored, so there is that. I can confirm that the app itself is still available for download in my purchase history, however.
doc_23537258
e.g.: Access {$host}/hello/word I expect yii load in mobile path: application.controller.mobile.HelloController So I add this in config file, but it not work. 'import'=>array( 'application.models.*', 'application.components.*', 'application.controllers.mobile.*', ), Actual yii always load the application.controller.HelloController, It's not found. I have muilt site (web2.0, mobile) in one application so only to do this for namespace A: I haven't checked out this myself but I think you should try this: 'import'=>array( 'application.models.*', 'application.components.*', 'application.controllers.*', 'application.controllers.mobile.*', ), You might have to include controllers directory before including any other classes (controllers) inside of it. A: 1. If mobile is a directory inside controllers directory where you have saved all the controllers files then try this 'application.controllers.mobile.*', 2. If mobile is a controller file inside the controllers directory then 'application.controllers.MobileController', 3. If you want to access only the HelloController which is inside mobile directory which is further inside controllers directory then 'application.controllers.mobile.HelloController', 4. If HelloController is inside controllers directory then 'application.controllers.HelloController',
doc_23537259
thanks! A: File, recent projects. If it's only showing 4 or 5 then go to Tools, Options and under Environment, select General and modify the # in the recent files section.
doc_23537260
So I create a control and provide its handle. Then, when I check the native window using Spy++, I see that my control is wrapped in additional 'control' with window class = "Static" and title "This is a static!". I have several problems with it: * *Resize events sent to my control by a hosting window have to be re-sent to the "Static" so it also gets resized (otherwise my control get partially hidden within the static's size). *The static does not have WS_EX_CONTROLPARENT, which causes KB149501 to appear (in short, whole application hangs on lost focus). *If I apply WS_EX_CONTROLPARENT, listbox within the static stops redrawing. I think I have been doing something wrong, but I am not sure what. Google does not help, since static is a C# keyword as well so it occurs quite often in WinForms results. A: I mostly solved the redrawing problem using DoubleBuffered=True, so probably this is it. I still think I am doing something wrong, but at least it works now.
doc_23537261
Here's an example of what's going on: s = "2222-33-44" # => "2222-33-44"} require 'yaml' # => true YAML::dump s # ArgumentError: invalid date YAML::ENGINE.yamler = 'syck' # => "syck" YAML::dump s # => "--- \"2222-33-44\"\n" A: I have found that it is a known bug. It has been fixed but looks like the version in RubyGems is not containing the fix. Also as the git repository doesn't have a proper .gemspec is not easy way to install from the repo. You can fork the repo and add a proper .gemspec and use a Gemfile that points to your fork repo. Also you can ask kindly to Aaron to release the fix.
doc_23537262
Possible Duplicate: The simplest way to resize an UIImage? I am using camera of ipod device to capture image and after taking image i want to resize it as per user need in my application . But by enabling editing : true in camera code , it shows the image in rectangle format of the image's middle section only.Thanks in advance for help.Note that I want image croapping here. it means image accutaly resize according to croaped image. A: this may help you - (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize AndImage:(UIImage*)sourceImage { UIImage *newImage = nil; CGSize imageSize = sourceImage.size; CGFloat width = imageSize.width; CGFloat height = imageSize.height; CGFloat targetWidth = targetSize.width; CGFloat targetHeight = targetSize.height; CGFloat scaleFactor = 0.0; CGFloat scaledWidth = targetWidth; CGFloat scaledHeight = targetHeight; CGPoint thumbnailPoint = CGPointMake(0.0,0.0); if (CGSizeEqualToSize(imageSize, targetSize) == NO) { CGFloat widthFactor = targetWidth / width; CGFloat heightFactor = targetHeight / height; if (widthFactor > heightFactor) scaleFactor = widthFactor; // scale to fit height else scaleFactor = heightFactor; // scale to fit width. scaledWidth = width * scaleFactor; scaledHeight = height * scaleFactor; // center the image if (widthFactor > heightFactor) { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; } else if (widthFactor < heightFactor) { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; } } UIGraphicsBeginImageContext(targetSize); // this will crop CGRect thumbnailRect = CGRectZero; thumbnailRect.origin = thumbnailPoint; thumbnailRect.size.width = scaledWidth; thumbnailRect.size.height = scaledHeight; [sourceImage drawInRect:thumbnailRect]; newImage = UIGraphicsGetImageFromCurrentImageContext(); if(newImage == nil) NSLog(@"could not scale image"); //pop the context to get back to the default UIGraphicsEndImageContext(); return newImage; } A: Here you can do to resize image. UIImage* resizedImage(UIImage *inImage, CGRect thumbRect) { CGImageRef imageRef = [inImage CGImage]; CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef); // There's a wierdness with kCGImageAlphaNone and CGBitmapContextCreate // see Supported Pixel Formats in the Quartz 2D Programming Guide // Creating a Bitmap Graphics Context section // only RGB 8 bit images with alpha of kCGImageAlphaNoneSkipFirst, kCGImageAlphaNoneSkipLast, kCGImageAlphaPremultipliedFirst, // and kCGImageAlphaPremultipliedLast, with a few other oddball image kinds are supported // The images on input here are likely to be png or jpeg files if (alphaInfo == kCGImageAlphaNone) alphaInfo = kCGImageAlphaNoneSkipLast; // Build a bitmap context that's the size of the thumbRect CGContextRef bitmap = CGBitmapContextCreate( NULL, thumbRect.size.width, // width thumbRect.size.height, // height CGImageGetBitsPerComponent(imageRef), // really needs to always be 8 4 * thumbRect.size.width, // rowbytes CGImageGetColorSpace(imageRef), alphaInfo ); // Draw into the context, this scales the image CGContextDrawImage(bitmap, thumbRect, imageRef); // Get an image from the context and a UIImage CGImageRef ref = CGBitmapContextCreateImage(bitmap); UIImage* result = [UIImage imageWithCGImage:ref]; CGContextRelease(bitmap); // ok if NULL CGImageRelease(ref); return result; } Hope, it'll help.
doc_23537263
How can I, using multisite, limit a function to only given site? I use such function to adapt homepage regarding user state: function switch_homepage() { if ( is_user_logged_in() ) { $page = 4284; // for logged in users update_option( 'page_on_front', $page ); update_option( 'show_on_front', 'page' ); } else { $page = 4133; // for logged out users update_option( 'page_on_front', $page ); update_option( 'show_on_front', 'page' ); } } I want the code to just work on a main site. Thanks for you help! A: You can test if the current site is the main site with this code: if ( is_main_site() ) { // Do stuff only for the main site } Another option is to add your code in a plugin and then activate the plugin only on the main site.
doc_23537264
To add a link to the search results when no direct match is found. Detail: I want to add a link to the search results when no direct match is found. My thought was to try and detect a direct match then add the link to the results, assuming its not already there. A good example of this is Github's milestone search on an issue. If you search for a milestone that doesn't exist a link is presented to create one instead. Flow: * *User inputs text * *If a direct match IS found - no link displayed *If NO direct match found - display link to create object I'm just not sure how or if I can detect a direct match and then add a datum. Any help on how to implement this or if it's possible would be appreciated?
doc_23537265
public class RunSecondApp { public Response runAppB(ApplicationBAdapter applicationBAdapter){ return applicationBAdapter.run(request); } Inside App B there are many invocations to current date (in Blaze Advisor it's CurrentLocalDate method - I think it's compiling to Java's LocalDate method but I'm not sure). Now what I need is to somehow mock the current date so that this invocations to current date in App B would return not today's date but a substitute. Changing the system date is not an option. I've read about PowerMock, JMockito, Expectations.class but every time I try this it's failing. Did anyone try something similar to this?
doc_23537266
Possible Duplicate: Spring 3 RequestMapping: Get path value Does anyone knows how to map everything under a certain URL and then catch that mapped value into a request variable? @RequestMapping("/content/{path:.*}") // matches only one level @RequestMapping("/content/**") // matches everything, can't catch // the actual value matched by the two stars @RequestMapping("/content/{path:**}") // does not compute What I need to map is: /content/a.gif /content/a/b.gif /content/a/b/c.gif /content/a/b/c/d.gif It's really frustrating because it is such a common scenario.
doc_23537267
if a % b == 0: print('</div> <div class="row" ') else: print('<div class="item">') I couldn't use forloop.counter result must be like this a b d f b f d k d k a b A: You can use the built in divisibleby templatetag like this: {% for obj in objects %} {% if forloop.first or forloop.counter0|divisibleby:4 %} <div class="row" > {% endif %} <span>{{ obj }}</span> {% if forloop.counter|divisibleby:4 or forloop.last %} </div> {% endif %} {% endfor %} Take note that we use forloop.counter0 in the first condition. Note the 0 in the end.
doc_23537268
{ "html_attributions" : [], "result" : { "opening_hours" : { "open_now" : true, "weekday_text" : [ "Monday: 8:00 AM – 7:00 PM", "Tuesday: 8:00 AM – 7:00 PM", "Wednesday: 8:00 AM – 2:30 PM", "Thursday: 8:00 AM – 7:00 PM", "Friday: 8:00 AM – 7:30 PM", "Saturday: 8:00 AM – 6:00 PM", "Sunday: Closed" ] } }, "status" : "OK" } which I convert to a JSONObject using JSONObject resultJSON = new JSONObject(result); I want to get the value of inner weekday_text key but it seems that the final output is not in UTF-8 (\u2013 unicode characters appear instead): System.out.println(resultJSON.getJSONObject("result").getJSONObject("opening_hours").getJSONArray("weekday_text").toString()); ["Monday: 8:00 AM \u2013 7:00 PM","Tuesday: 8:00 AM \u2013 7:00 PM","Wednesday: 8:00 AM \u2013 2:30 PM","Thursday: 8:00 AM \u2013 7:00 PM","Friday: 8:00 AM \u2013 7:30 PM","Saturday: 8:00 AM \u2013 6:00 PM","Sunday: Closed"] What am I missing here? A: You are seeing unicode escape sequences because of how toString is implemented. It is implemented this way probably to make it clear which characters are in the string, which makes it easier to debug your code, because sometimes different code points can look very similar. The actual strings are still unescaped. Printing individual strings in the array will not show escape sequences: System.out.println(resultJSON.getJSONObject("result").getJSONObject("opening_hours").getJSONArray("weekday_text").getString(0)); A: You can use a OutputStreamWriter to manage the output encoding. JSONObject resultJSON = new JSONObject(result); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(out, "utf-8"); resultJSON.write(writer); writer.flush(); String jSONStringUTF8 = new String(out.toByteArray(),"utf-8"); JSONObject newJSON = new JSONObject(jSONStringUTF8); String value = newJSON.getString("content");
doc_23537269
I'm wondering how to fix this annoying issue so they always stay in position regardless of screen size?? I have this as my CSS: .wrapper{ margin:0 auto; width: 80%; display: table-cell; } .gridf{ float:left; margin-right:3px; width:200px; min-height:200px; border:1px solid white; } .grid{ float:left; margin-left: 3px; margin-right:3px; width:200px; min-height:200px; border:1px solid white; } .gridl{ float:left; margin-left: 3px; width:200px; min-height:200px; border:1px solid white; } My HTML: <div style="overflow: hidden;"> <div class="wrapper"> <div class="gridf"></div> <div class="grid"></div> <div class="grid"></div> <div class="gridl"></div> </div> </div> Please help :D A: Your wrapper is a percentage width container with 4 fixed-width child elements floated. The width of the wrapper is dependent on the width of the viewport. If the viewport is narrowed to the point that the wrapper's width is less than that of the 4 child element widths together, then naturally they won't all fit and therefore will wrap. The fix is to make sure your wrapper doesn't get smaller than the combination of the children. So, add up with widths, borders and margins of the child elements and then give the wrapper a min-width attribute equal to that. A: Hi i think you should this check to this demo .wrapper { margin: 0 auto; width: 80%; border: solid 1px red; overflow: hidden; } .gridf, .grid, .gridl { Background: green; width: 24%; min-height: 100px; float: left; margin: 2px 0; } .gridf {} .grid { margin: 2px 1%; } .gridl { background: yellow; } <div class="wrapper"> <div class="gridf">One</div> <div class="grid">Two</div> <div class="grid">Three</div> <div class="gridl">Four</div> </div> A: Although this is an old post, I think that the problem, which I also run into, is the fact that you want all these cells to be of a fixed size, and not %, right? The solution you chose changed initial format where you specified width:200px; Well, I would suggest to look here: http://jsfiddle.net/gn2bg/ The ONLY one thing I did is to add inner wrapper around your cells: .inwrapper{ float:left; overflow: hidden; min-width: 830px; } and new html as this: <div class="wrapper"> <div class="inwrapper"> <div class="gridf"></div> <div class="grid"></div> <div class="grid"></div> <div class="gridl"></div> </div> </div> Notice that your wrapper requires 80% of space. The inwrapper, however, tells that its size is fixed - 830px (total of all internal div sizes plus room for padding.) This way inwrapper uses 'elbows' to stretch the width, and override these 80% of 'wrapper' I understand that you already made decision as to what is your best solution. I am leaving this response to anyone else in the future who needs exact answer to your exact question. A: You can try removing the table-cell display rule from the wrapper and setting percentages (or min-widths) on the child divs like this jsFiddle example. A: That should do the trick : <div class="wrapper"> <div style="width:850px"> <div class="gridf"></div> <div class="grid"></div> <div class="grid"></div> <div class="gridl"></div> </div> </div> And that will be supported on any browser. http://jsfiddle.net/5GrKU/3/ A: HTML <div style="overflow: hidden;"> <div class="wrapper"> <div class="gridf"></div> <div class="grid"></div> <div class="grid"></div> <div class="gridl"></div> </div> </div> CSS .wrapper{ margin:0 auto; width: 80%; display: inline; } .gridf{ float:left; margin-right:3px; width:20%; min-height:200px; border:1px solid red; } .grid{ float:left; margin-left: 3px; margin-right:3px; width:20%; min-height:200px; border:1px solid red; } .gridl{ float:left; margin-left: 3px; width:20%; min-height:200px; border:1px solid red; } for you reference i have also added the URL of the demo. http://jsfiddle.net/sg8FE/ UPDATE just change display:inline in wrapper class to display:block rest all is right and the div's are centered. A: by giving a fixed width in your inner divs you are forcing them to have that width no matter what is the size of the view port. And giving the outer div a width of 80% you are shrinking its size with the width of your view port. You need to do either giving fixed width to all those divs or giving a relative width to all.
doc_23537270
I have a column of ID that the format is like "C_1_1", "C_1_11", "C_12_11". The criteria was using the string before the first '' symbol and string after second '' symbol to find matching ID like head and tail e.g. "C_20_2" <-- "C_" and "2". In VBA I tried to use Filter function to filter data that match "C" then 2nd filter that match "_2" However, the problem I am facing is that because the middle part of the ID is also in a format of "_xx" so there will be unwanted data like in the picture below that all the non-highlighted data is not relevant. Is there any suggestion I can filter or extract only the data in yellow colour? Any suggestion would be appreciated. Thank you so much. A: Filter Data Excel If you have Microsoft 365, without too much thinking, in cell G2 you could simply use: =FILTER(FILTER(A2:A100,LEFT(A2:A100,LEN(H2))=TEXT(H2,"@")),RIGHT(FILTER(A2:A100,LEFT(A2:A100,LEN(H2))=TEXT(H2,"@")),LEN(H3))=TEXT(H3,"@")) VBA Sub FilterData() Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code Dim ws As Worksheet: Set ws = wb.Sheets("Data") Dim sStr As String: sStr = CStr(ws.Range("H2").Value) Dim eStr As String: eStr = CStr(ws.Range("H3").Value) Dim rg As Range Set rg = ws.Range("A2", ws.Cells(ws.Rows.Count, "A").End(xlUp)) Dim Data(): Data = rg.Value Dim sr As Long, dr As Long, cString As String For sr = 1 To UBound(Data, 1) cString = CStr(Data(sr, 1)) If cString Like sStr & "*" & eStr Then dr = dr + 1 Data(dr, 1) = cString End If Next sr With rg.EntireRow.Columns("G") .Resize(dr).Value = Data .Resize(ws.Rows.Count - .Row - dr + 1).Offset(dr).ClearContents End With End Sub
doc_23537271
This question has been asked multiple times before for standard SQL Server: * *How can I clear the SQL Server query cache? Answer: DBCC DROPCLEANBUFFERS; *How to let SQL Server know not to use Cache in Queries? Answer: DBCC FREEPROCCACHE; Or there's always the WITH RECOMPILE option. However, none of these options appear to have support in the SQL CE world. I am accessing the database via a C# application, using the SqlCeCommand class, so I am looking for either a code hack or an SQL command to clear the execution plan cache from the database between calls. A: There is no execution plan cache between calls, but the first access to the database will load the database file, and the engine dll files into memory from disk, and this is costly.
doc_23537272
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'component' of null TypeError: Cannot read property 'component' of null at PreActivation.webpackJsonp.../../../router/@angular/router.es5.js.PreActivation.traverseRoutes (http://localhost:4200/vendor.bundle.js:77976:71) at http://localhost:4200/vendor.bundle.js:77954:19 at Array.forEach (native) at PreActivation.webpackJsonp.../../../router/@angular/router.es5.js.PreActivation.traverseChildRoutes (http://localhost:4200/vendor.bundle.js:77953:29) at PreActivation.webpackJsonp.../../../router/@angular/router.es5.js.PreActivation.traverseRoutes (http://localhost:4200/vendor.bundle.js:77985:22) This is my routing code: const appRoutes: Routes = [ { path: '', component: HomeComponent }, { path: 'sobre', component: SobreComponent }, { path: 'c/:concurso', component: ConcursoItemComponent , children: [ { path: ':cargo', component: CargoItemComponent, children: [ { path: ':disc', component: DisciplinaItemComponent, children: [{ path: ':assunto', component: AssuntoItemComponent }] } ] } ] }, ]; I want to make the following nested rules, each one using the variables to inform the nested components of each route: / /c/:concurso/ /c/:concurso/:cargo/ /c/:concurso/:cargo/:disc/ /c/:concurso/:cargo/:disc/:assunto On each level, I will need all the upper variables to make the correct querying of the related objects of the API. Thanks for any help! A: Just thought I'd add a comment for the benefit of those who stumble across this for the same reason I did. If your template uses conditional rendering, and those conditions are satisfied asynchronously, the router-outlet cannot be inside the conditional markup because the framework might try to render the markup before the condition is satisfied. For example: <div *ngIf="someAsyncCall()"> <header>{{some result from the async call}}</header> <router-outlet></router-outlet> </div> may fail depending on how quickly the async call finishes. It's always safer to include only the static parts of a the markup in the conditional rendering. As in: <div *ngIf="someAsyncCall()"> <header>{{some result from the async call}}</header> </div> <router-outlet></router-outlet> I got bit by wrapping the entire page in a "busy indicator" directive which pretty much guaranteed that the router-outlet would not be available all the time. Seems obvious in hindsight, but.... A: As this article (https://angular-2-training-book.rangle.io/handout/routing/child_routes.html) states when dealing with child routes, just as you define a router-outlet for the root of your application, you must define a router-outlet for your parent component (in this case the ConcursoItemComponent. And technically also the CargoItemComponent & DisciplinaItemComponent) So you have 2 options. * *Define a router-outlet in the ConcursoItemComponent. This way the router will know where to load the child component (CargoItemComponent) when the user visits c/:concurso/:cargo *Don't use child routes and instead make all of your routes at the top router level (root of the application) { path: 'c/:concurso, component: ConcursoItemComponent }, { path: 'c/:concurso/:cargo, component: CargoComponent }, { path: 'c/:concurso/:cargo/:disc, component: DisciplinaItemComponent }, { path: 'c/:concurso/:cargo/:disc/:assunto, component: AssuntoItemComponent } This way the router will always insert the component into the router-outlet at the root of the application. A: If anyone interested in going with Child route structure. You could follow this model. I found this in ngx-breadcrumbs. const myRoutes : Route[] = { { path: '', component: HomeComponent }, { path: 'about', component: AboutComponent }, { path: 'person', children: [ { path: '', component: PersonListComponent }, { path: ':id', component: PersonDetailComponent } ] }, { path: 'folder', children: [ { path: '', component: FolderComponent }, { path: ':id', component: FolderComponent } ] } };
doc_23537273
So my cython function signature is as follows: cpdef cnmi_gradient_2d(double[:, :] jhlog, double[:, :] reflog, double[:, :] warlog, int width, int height): I intend these to be numpy arrays in the pure python code and pass it to on to this function. At some point in the code, I access these arrays as: for y in range(height): for x in range(width): jl = jhlog[x, y] rl = reflog[x, 0] wl = warlog[0, y] When I cythonise the code, I get the following warning: Index should be typed for more efficient access. I am not sure what I am supposed to do with this? I followed this guide here: http://docs.cython.org/en/latest/src/userguide/numpy_tutorial.html but not sure what I should be doing to solve this warning.
doc_23537274
Below is the file I'm trying to replace. I just want to change some words in "sheetname" : "Main" [ { "sheetname": "Main", "emp_details": [ [ "スバム", "ksing.shubh@gmail.com", "marble", "intern" ], [ "Gaurav", "gaurav.singh@cobol.in", "snacks", "デボロッパ" ], [ "ニキル", "nikhil@geeksforgeeks.org", "tennis", "Full Time" ] ] }, { "sheetname": "Next", "emp_details": [ [ "スバム", "ksing.shubh@gmail.com", "fabrics", "intern" ], [ "Gaurav", "gaurav.singh@cobol.in", "xenom", "デボロッパ" ], [ "ニキル", "nikhil@geeksforgeeks.org", "hiltop", "Full Time" ] ] } ,{ "sheetname": "Last", "emp_details": [ [ "スバム", "ksing.shubh@gmail.com", "trend", "intern" ], [ "Gaurav", "gaurav.singh@cobol.in", "souvenir", "デボロッパ" ], [ "ニキル", "nikhil@geeksforgeeks.org", "urban", "Full Time" ] ] } ] What I'm trying to do is to replace certain words in the "Main" "sheet" i.e. sheetname = Main; Thanks in advance. Any help would be great! Below is my code: import os, re directory = os.listdir('/Users/Unicorn/Desktop/for all/change') os.chdir('/Users/Unicorn/Desktop/for all/change') for file in directory: open_file = open(file,'r', encoding='utf-8') read_file = open_file.read() # changing value regex = re.compile('Gaurav') # change value read_file = regex.sub('Singh', read_file) write_file = open(file,'w', encoding='utf-8') write_file.write(read_file) A: Naming you data from file as data: data = [ { "sheetname": "Main", "emp_details": [ [ "スバム", "ksing.shubh@gmail.com", "marble", "intern" ], [ "Gaurav", "gaurav.singh@cobol.in", "snacks", "デボロッパ" ], [ "ニキル", "nikhil@geeksforgeeks.org", "tennis", "Full Time" ] ] }, { "sheetname": "Next", "emp_details": [ [ "スバム", "ksing.shubh@gmail.com", "fabrics", "intern" ], [ "Gaurav", "gaurav.singh@cobol.in", "xenom", "デボロッパ" ], [ "ニキル", "nikhil@geeksforgeeks.org", "hiltop", "Full Time" ] ] } ,{ "sheetname": "Last", "emp_details": [ [ "スバム", "ksing.shubh@gmail.com", "trend", "intern" ], [ "Gaurav", "gaurav.singh@cobol.in", "souvenir", "デボロッパ" ], [ "ニキル", "nikhil@geeksforgeeks.org", "urban", "Full Time" ] ] } ] import re word_to_replace = 'Gaurav' word_to_assign = 'Singh' for dictionary in data: if dictionary.get('sheetname') == 'Main': list_data = dictionary.get('emp_details') new_data = [] for item in list_data: if word_to_replace in item: new_item = [] for word in item: if word.lower().find(word_to_replace.lower()) == 0: new_word = re.sub(word_to_replace, word_to_assign, word) if new_word == word: new_word = re.sub(word_to_replace.lower(), word_to_assign.lower(), word) new_item.append(new_word) else: new_item.append(word) new_data.append(new_item) else: new_data.append(item) dictionary['emp_details'] = new_data Output: [{'sheetname': 'Main', 'emp_details': [['スバム', 'ksing.shubh@gmail.com', 'marble', 'intern'], ['Singh', 'singh.singh@cobol.in', 'snacks', 'デボロッパ'], ['ニキル', 'nikhil@geeksforgeeks.org', 'tennis', 'Full Time']]}, {'sheetname': 'Next', 'emp_details': [['スバム', 'ksing.shubh@gmail.com', 'fabrics', 'intern'], ['Gaurav', 'gaurav.singh@cobol.in', 'xenom', 'デボロッパ'], ['ニキル', 'nikhil@geeksforgeeks.org', 'hiltop', 'Full Time']]}, {'sheetname': 'Last', 'emp_details': [['スバム', 'ksing.shubh@gmail.com', 'trend', 'intern'], ['Gaurav', 'gaurav.singh@cobol.in', 'souvenir', 'デボロッパ'], ['ニキル', 'nikhil@geeksforgeeks.org', 'urban', 'Full Time']]}] A: that is a json data, if you save it in a file, it can be loaded with json module and simply iterate then add your condition import json import os import sys directory = os.listdir('/Users/Unicorn/Desktop/for all/change') os.chdir('/Users/Unicorn/Desktop/for all/change') for file in directory: open_file = open(file,'r', encoding='utf-8') read_file = open_file.read() open_file.close() # loads json file so it can be treated just like dictionary/list object in python data_json = json.loads(read_file) # iterate sheet item in data for sheet in data_json: # this is where you put your condition for sheetname == "Main" if sheet['sheetname'] == 'Main': # iterate over emp_detail because it is a list for emp_detail in sheet['emp_details']: # this is my simple method to replace item on a list if 'Gaurav' in emp_detail: emp_detail[emp_detail.index('Gaurav')] = 'Singh' data_final = json.dumps(data_json) open_file = open(file,'w', encoding='utf-8') open_file.write(data_final) open_file.close()
doc_23537275
Thanx, regards. A: You could take a look at docmosis which has a cloud-based document generator. It can generate PDFs and stream them back to the iPad or send as email. You upload a template to the cloud using the Docmosis web site, then you can generate documents from your iPad by sending a request (with data, images etc) to the Docmosis cloud.
doc_23537276
databaseRef.child("First_Secondary_Grade").child("0").child("0").queryOrderedByKey().observe(.childAdded, with: { (snapshot) in if let dictoinary = snapshot.value as? [String: AnyObject] { let dataofthequsation = structofthedata() dataofthequsation.setValuesForKeys(dictoinary) } }) A: i think i figured it out let databaseRef = FIRDatabase.database().reference() var gotitall = 0 // First you need to observe single event to get the real count of children in swift 3 observe will count the keys inside a child. That's why! databaseRef.child("First_Secondary_Grade").child("0").child("0").observeSingleEvent(of:.value, with:{ (snap) in gotitall = Int(snap.childrenCount) databaseRef.child("First_Secondary_Grade").child("0").child("0").observe(.childAdded, with: { snapshot in if let dictoinary = snapshot.value as? [String: AnyObject] { let dataofthequsation = structofthedata() dataofthequsation.setValuesForKeys(dictoinary) self.dataofthequsation.append(dataofthequsation) // this is will run when the block runs through all children if gotitall == self.dataofthequsation.count { completion() } } }) })
doc_23537277
df['sum'] = df.sum(axis=1) when excuting that line I get the warning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy checking that link the talk goes on about ways to use loc in multiindex dataframes. My dataframe is not multinidex. What is the correct way to assign a column named "sum" with the addition of all the int values of the df? This would not help to avoid the warning x = df.sum(axis=1).copy() df['sum'] = x
doc_23537278
t="1234567890" result = re.sub(r'(\d)(?=(\d{3})+$)',r'\1,',t) print("insert commas every three digits",result) this works fine: insert commas every three digits: 1,234,567,890 while t="1234567890" result = re.sub(r'(\d)(?=(\d{3})+)$',r'\1,',t) print("insert commas every three digits:",result) doesn't. insert commas every three digits: 1234567890 I truly do not understand why does $ doesnot work in the second code, some help is needed on this. A: The $ anchor is part of the lookahead in the original regex: match a digit followed by groups of triple digits until end of line. Your broken variant looks for a digit before end of line, with a lookahead requiring groups of triple digits after the matched digit but before end of line.
doc_23537279
C# Code: var itemLists = new List<GetFiftyItemsData>(); itemLists.Add(new GetFiftyItemsData { SellerId = sellerId, }.ThirdPartyData.Add(new ThirdPartyData { })); Model class: class GetFiftyItemsData { public long SellerId { get; set; } public List<ThirdPartyData> ThirdPartyData { get; set; } } A: This should do it itemLists.Add(new GetFiftyItemsData { SellerId = sellerId, ThirdPartyData = new List<ThirdPartyData> { // item, // item }) }); And it's better not to name your field/property and type the same (ThirdPartyData). A: I suggest you could declare variable step by step, let it be more readable, new ThirdPartyData first, then assign to GetFiftyItemsData, and add to itemLists. long sellerId = 1; List<ThirdPartyData> ThirdPartyData = new List<ThirdPartyData>(); ThirdPartyData.Add(new ThirdPartyData() { }); itemLists.Add(new GetFiftyItemsData { SellerId = sellerId, ThirdPartyData = ThirdPartyData });
doc_23537280
I already built some code that is plotting a few different metrics per class. Plot_metric() is a self defined function. gs = gridspec.GridSpec(1, 5, width_ratios=[5, 1, 1, 1, 1]) ax1 = plt.subplot(gs[0]) ax2 = plt.subplot(gs[1]) ax3 = plt.subplot(gs[2]) ax4 = plt.subplot(gs[3]) ax5 = plt.subplot(gs[4]) skplot.metrics.plot_confusion_matrix(confusion_y_test, confusion_y_pred, ax=ax1, labels=[0,1,2,3,4]) plot_metric(accuracy_per_class_array, "Class accuracy", ax2, cmap=plt.cm.Blues) plot_metric(precision_per_class_array, "Class precision", ax3, cmap=plt.cm.Blues) plot_metric(recall_per_class_array, "Class recall", ax4, cmap=plt.cm.Blues) plot_metric(f1_per_class_Array, "Class F1", ax5, cmap=plt.cm.Blues) I use every axis to plot a different metric and the confusion matrix as you can see in the picture. But why is the last column smaller than the others? I would like it to be the same height as the other plots. Update: The code of the plot_metric(): def plot_metric(metric_array, metric_name, axis, display_labels=None, cmap="viridis"): """ plotted_cm : instance of `ConfusionMatrixDisplay` Result of `sklearn.metrics.plot_confusion_matrix` axis : matplotlib `AxesSubplot` Result of `fig, (ax1, ax2) = plt.subplots(1, 2)` display_labels : list of labels or None Human-readable class names cmap : colormap, optional Optional colormap """ n_classes = len(metric_array) if display_labels is None: labels = np.arange(n_classes) else: labels = display_labels axis.imshow( np.array(metric_array).reshape(n_classes, 1), interpolation="nearest", cmap=cmap, ) for i, value in enumerate(metric_array): axis.text(0, i, format(value, ".2g"), ha="center", va="center") axis.set( yticks=np.arange(len(metric_array)), xlabel=metric_name, yticklabels=labels, ) axis.tick_params( axis="x", bottom=False, labelbottom=False, ) axis.set_ylim((len(metric_array) - 0.5, -0.5))
doc_23537281
doc_23537282
How do I accomplish what I need to do? Thanks A: Use this regex to extract fixed part separately and all numbers separately: (?mi)^foo\\s+(\\d+)\\s+bar((?:\\s+\\d+)*)$ Then on the group(2) just use: String[] nums = matcher.group(2).split("\\s+"); to get all numbers after bar. RegEx Demo
doc_23537283
Everytime when I resume this fragment, the listview inside the child-fragmnet is not recreating. Rather than it appending the same elements below. I mean if there are 5 list-items in real, everytime after resuming there will be 5 more same items at the end. I have notifyDataSetChanged() but it is not working. This is my child-fragment code: public class ChaptersListFragment extends SherlockListFragment { OnChapterSelectListener mCallback; ArrayAdapter<String> mAdapter = null; public interface OnChapterSelectListener { public void onChapterSelected(int position); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (mAdapter != null) mAdapter.clear(); // I try this but not working List<String> items = new ArrayList<String>(); for (int i = 0; i < CompetitiveProgramming.chapterList.size(); i++) { items.add(CompetitiveProgramming.chapterList.get(i).chapterTitle); } mAdapter = new ArrayAdapter<String>(getSherlockActivity(), R.layout.list_layout, items); mAdapter.notifyDataSetChanged(); // I try this but not working setListAdapter(mAdapter); } @Override public void onStart() { super.onStart(); if (getFragmentManager().findFragmentById(R.id.sub_category_fragment) != null) { getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); } } @Override public void onResume() { super.onResume(); mAdapter.notifyDataSetChanged(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallback = (OnChapterSelectListener) getParentFragment(); } catch (ClassCastException e) { throw new ClassCastException(getParentFragment().toString() + " must implement OnChapterSelectListener"); } } @Override public void onListItemClick(ListView l, View v, int position, long id) { mCallback.onChapterSelected(position); getListView().setItemChecked(position, true); } } Moreover when I am changing the orientation, the listview is recreating and there is only 5 items then. However, after resuming several times. the application is crashed with the following logcat: 08-21 01:16:09.114: E/AndroidRuntime(664): FATAL EXCEPTION: main 08-21 01:16:09.114: E/AndroidRuntime(664): java.lang.IllegalStateException: No activity 08-21 01:16:09.114: E/AndroidRuntime(664): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1075) 08-21 01:16:09.114: E/AndroidRuntime(664): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1070) 08-21 01:16:09.114: E/AndroidRuntime(664): at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1861) 08-21 01:16:09.114: E/AndroidRuntime(664): at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1474) 08-21 01:16:09.114: E/AndroidRuntime(664): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:931) 08-21 01:16:09.114: E/AndroidRuntime(664): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088) 08-21 01:16:09.114: E/AndroidRuntime(664): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682) 08-21 01:16:09.114: E/AndroidRuntime(664): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444) 08-21 01:16:09.114: E/AndroidRuntime(664): at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429) 08-21 01:16:09.114: E/AndroidRuntime(664): at android.os.Handler.handleCallback(Handler.java:587) 08-21 01:16:09.114: E/AndroidRuntime(664): at android.os.Handler.dispatchMessage(Handler.java:92) 08-21 01:16:09.114: E/AndroidRuntime(664): at android.os.Looper.loop(Looper.java:123) 08-21 01:16:09.114: E/AndroidRuntime(664): at android.app.ActivityThread.main(ActivityThread.java:4627) 08-21 01:16:09.114: E/AndroidRuntime(664): at java.lang.reflect.Method.invokeNative(Native Method) 08-21 01:16:09.114: E/AndroidRuntime(664): at java.lang.reflect.Method.invoke(Method.java:521) 08-21 01:16:09.114: E/AndroidRuntime(664): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 08-21 01:16:09.114: E/AndroidRuntime(664): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 08-21 01:16:09.114: E/AndroidRuntime(664): at dalvik.system.NativeStart.main(Native Method) And this the parent fragment which is holding the above child fragment: public class CompetitiveProgramming extends SherlockProgressFragment implements OnChapterSelectListener, OnSubChapterSelectListener { View mContentView; static public List<Chapter> chapterList = new ArrayList<Chapter>(); private ProcessTask processTask = null; Fragment chapterFragment = null; Fragment subChapterFragment = null; Fragment subSubChapterFragment = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mContentView = inflater.inflate( R.layout.competitive_programming_exercise, container, false); return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setContentShown(false); setContentView(mContentView); processTask = new ProcessTask(); processTask.execute(); } protected class ProcessTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { InputStream inputStream = null; try { inputStream = getSherlockActivity().getAssets().open( CommonUtils.FILE_COMPETITIVE_PROGRAMMING_3); JsonReader reader = new JsonReader(new InputStreamReader( inputStream)); reader.beginArray(); // array #1 while (reader.hasNext()) { String chapterTitle = null; List<SubChapter> subList = new ArrayList<SubChapter>(); reader.beginObject(); // object #2 while (reader.hasNext()) { reader.skipValue(); chapterTitle = reader.nextString(); reader.skipValue(); reader.beginArray(); // array #3 while (reader.hasNext()) { String subChapterTitle = null; List<SubSubChapter> subSubList = new ArrayList<SubSubChapter>(); reader.beginObject(); // object #4 while (reader.hasNext()) { reader.skipValue(); subChapterTitle = reader.nextString(); reader.skipValue(); reader.beginArray(); // array #5 while (reader.hasNext()) { reader.beginArray(); // array #6 String subSubChapterTitle = reader .nextString(); // sub-sub-category // title List<ProblemList> problemsList = new ArrayList<ProblemList>(); while (reader.hasNext()) { int signedProblemID = reader.nextInt(); // problemNo String title = reader.nextString(); if (signedProblemID < 0) problemsList.add(new ProblemList( Math.abs(signedProblemID), title, true)); else problemsList.add(new ProblemList( signedProblemID, title, false)); } reader.endArray(); // array #6 subSubList.add(new SubSubChapter( subSubChapterTitle, problemsList)); } reader.endArray(); // array #5 } reader.endObject(); // object #4 subList.add(new SubChapter(subChapterTitle, subSubList)); } reader.endArray(); // array #3 } reader.endObject(); // object #2 chapterList.add(new Chapter(chapterTitle, subList)); } reader.endArray(); // array #1 reader.close(); } catch (IOException e) { // nothing } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // nothing } } } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); FragmentTransaction transaction = getChildFragmentManager() .beginTransaction(); chapterFragment = new ChaptersListFragment(); if (mContentView.findViewById(R.id.fragment_container) != null) { transaction.replace(R.id.fragment_container, chapterFragment); } else { subChapterFragment = new SubChaptersListFragment(); subSubChapterFragment = new SubSubChaptersListFragment(); transaction.replace(R.id.category_fragment, chapterFragment); transaction.replace(R.id.sub_category_fragment, subChapterFragment); transaction.replace(R.id.sub_sub_category_fragment, subSubChapterFragment); } transaction.commit(); setContentShown(true); } } static protected class Chapter { String chapterTitle; List<SubChapter> subchapterList; public Chapter(String chapterTitle, List<SubChapter> subchapterList) { this.chapterTitle = chapterTitle; this.subchapterList = subchapterList; } } static protected class SubChapter { String subChapterTitle; List<SubSubChapter> subsubchapterList; public SubChapter(String subChapterTitle, List<SubSubChapter> subsubchapterList) { this.subChapterTitle = subChapterTitle; this.subsubchapterList = subsubchapterList; } } static protected class SubSubChapter { String subSubChapterTitle; List<ProblemList> problemList; public SubSubChapter(String subSubChapterTitle, List<ProblemList> problemList) { this.subSubChapterTitle = subSubChapterTitle; this.problemList = problemList; } } static public class ProblemList { Integer problemNo; String problemTitle; boolean isStarred; public ProblemList(Integer problemNo, String problemTitle, boolean isStarred) { this.problemNo = problemNo; this.isStarred = isStarred; this.problemTitle = problemTitle; } } @Override public void onChapterSelected(int position) { SubChaptersListFragment subChaptersListFrag = (SubChaptersListFragment) getChildFragmentManager() .findFragmentById(R.id.sub_category_fragment); if (subChaptersListFrag != null) { subChaptersListFrag.updateList(position); } else { subChapterFragment = new SubChaptersListFragment(); Bundle args = new Bundle(); args.putInt(SubChaptersListFragment.CHAPTER_POSITION, position); subChapterFragment.setArguments(args); FragmentTransaction transaction = getChildFragmentManager() .beginTransaction(); transaction.replace(R.id.fragment_container, subChapterFragment); transaction.commit(); } } @Override public void onSubChapterSelected(int prev, int position) { SubSubChaptersListFragment subSubChaptersListFrag = (SubSubChaptersListFragment) getChildFragmentManager() .findFragmentById(R.id.sub_sub_category_fragment); if (subSubChaptersListFrag != null) { subSubChaptersListFrag.updateList(prev, position); } else { subSubChapterFragment = new SubSubChaptersListFragment(); Bundle args = new Bundle(); args.putIntArray(SubSubChaptersListFragment.POSITIONS, new int[]{prev, position}); subSubChapterFragment.setArguments(args); FragmentTransaction transaction = getChildFragmentManager() .beginTransaction(); transaction.replace(R.id.fragment_container, subSubChapterFragment); transaction.commit(); } } @Override public void onStop() { super.onStop(); if (processTask != null && processTask.getStatus() != AsyncTask.Status.FINISHED) { processTask.cancel(true); } } } How can I solve it? If any more code snippet is required, let me know in comment :) A: I am not answering on the listview appending/refreshing problem, but the app crashing is due to a bug in the ChildFragmentManager. Basically, the ChildFragmentManager ends up with a broken internal state when it is detached from the activity. See the link below and add that snippet in your parentFragment class. solution to this problem
doc_23537284
nasa=imread('nasaNoise _1_','jpg'); N_Fourier=fft2(nasa); N_Fourier=fftshift(N_Fourier); N_Fourier=abs(N_Fourier); N_Fourier=log(N_Fourier+1); N_Fourier=mat2gray(N_Fourier); %Now doing the inverse N_inverse=ifft2(N_Fourier); N_inverse=abs(N_inverse); N_inverse=uint8(N_inverse); imshow(N_inverse);
doc_23537285
The error that I am getting is Unexpected Beginning of Statement (near 'brand') Brand is on the second line of the SQL statement. The data that I am trying to enter: INSERT INTO 'vehicles' ('reg_no', 'category', 'brand', 'description', 'dailyrate') VALUES ('BA5923W', 'car', 'Toyota', 'black 4 door 2.6 engine ', '9.99'), ('BA6611A', 'car', 'NISSAN ', '4 Door Saloon, Automatic', '9.99'), ('BM1245a', 'car', 'Golf', NULL, '9.00'), ('GA5955E', 'truck', 'NISSAN CABSTAR 3.0', 'Lorry, Manual ', '18.99') cheers A: Fixed. I was not closing the block of SQL code that created the table, which comes before this. A: You have an syntax error at you query. For columns names you should use Grave Accent ` char like (`reg_no`, `category`, `brand`, `description`, `dailyrate`) and for data line Apostrophe ' char like ('BA5923W', 'car', 'Toyota', 'black 4 door 2.6 engine ', '9.99')
doc_23537286
01 to 1 02 to 2 all the way to 9? Thanks A: I assume the input is a string? $str = "01"; $anInt = intval($str); You may think that the leading 0 would mean this is interpreted as octal, as in many other languages/APIs. However the second argument to intval is a base. The default value for this is 10. This means 09->9. See the first comment at the intval page, which states that the base deduction you might expect only happens if you pass 0 in as the base. A: $x="01"; $x=+$x; $x="02"; $x=+$x; ... or $x=+"01"; should work for both int, and string A: Do (int)$str; instead. It's up to 4x faster than intval(). A: $str = "05"; $last = $str[1]; A: $i = substr($input, 1, 1); A: If you want to use the generic regular expression solution: 's/[0]([0-9])/\1/' (add in anchors as appropriate) A: $str='05'; if(strpos($str,'0')==0 && strpos($str,'0') != false ){ $new = intval(substr($str,1)); } A: you can use the predefined php function . intval() For Ex: $convert = intval(01); echo $convert ; It will print 1(one);
doc_23537287
Referring to other solutions on stackOverFlow, i have used different import methods like import stripe from './stripe'; import * as stripe from './stripe'; but none of them can solve my problem. What's wrong with my code? Here are the codes: For Stripe file: import React from 'react' import { Element } from "@stripe/react-stripe-js" import { loadStripe } from '@stripe/stripe-js' import "./Stripe.css" const PaymentForm = require ('./PaymentForm.js') const PUBLIC_KEY = "pk_test_XXXXXXX" const stripeTestPromise = loadStripe(PUBLIC_KEY) export default function Stripe() { return ( <Element stripe={stripeTestPromise}> <PaymentForm /> </Element> ) } For paymentFrom file: import React, { useState } from 'react' import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js" import * as axios from 'axios' import "./Stripe.css" const CARD_OPTIONS = { iconStyle: "solid", style: { base: { iconColor: "#c4f0ff", color:"fff", fontWeight: 500, fontSize: "16px", fontSmoothing:"antialiased", }, invaild: { iconColor: "#ffc7ee", color: "ffc7ee" } } } export default function PaymentForm() { const [success, setSuccess] = useState(false) const stripe = useStripe() const elements = useElements() const handleSubmit = async (e) => { e.preventDefault() const { error, paymentMethod } = await stripe.createPaymentMethod({ type: "card", card: elements.getElement(CardElement) }) if (!error) { try { const { id } = paymentMethod const response = await axios.post('http://localhost:8080/checkout', { amount: 500, id }) if (response.data.success) { console.log('Successful payment') setSuccess(true) } } catch (error) { console.log('Error', error) } } else { console.log(error.message) } } return ( <div> {!success ? <form onSubmit={handleSubmit}> <fieldset className="FormGroup"> <div className="FormRow"> <CardElement options={CARD_OPTIONS} /> </div> </fieldset> <button>Pay</button> </form > : <div> <h2>You just bought a sweet saptula</h2> </div> } </div> ) } A: I'd like to put a comment but I don't have the reputation to do it, so I'll submit an answer: If you're trying to insert the elements provider following the documentation the provider needs to be inserted this way: import {Elements} from '@stripe/react-stripe-js'; you are importing this like import {Element} from '@stripe/react-stripe-js'; it's possible that the element you're importing it's an interface or another object and not the provider you want
doc_23537288
When I compare language names with no accents it works and the compare is true. When I compare languages with accents, it doesn't think they are equal. In this case they are NOT equal (but should be). Language = "Español"; MonoTouch.Foundation.NSString s = new MonoTouch.Foundation.NSString(Language); MonoTouch.Foundation.NSString l = new MonoTouch.Foundation.NSString ("Español"); In this example they ARE equal (notice no accents). Language = "Deutsch"; MonoTouch.Foundation.NSString s = new MonoTouch.Foundation.NSString(Language); MonoTouch.Foundation.NSString l = new MonoTouch.Foundation.NSString ("Deutsch"); I have tried cultureinvariate compares to no avail. Am I missing something fundamental here? I am using MonoTouch 1.4.4 A: the following matches as you require ignoring accents: var Language = "Español" ; MonoTouch.Foundation.NSString s = new MonoTouch.Foundation.NSString(Language); MonoTouch.Foundation.NSString l = new MonoTouch.Foundation.NSString ("Español"); int result = String.Compare(s,l, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace);
doc_23537289
I am trying to understand how to use keras for supply chain forecasting and i keep getting errors that i can't find help for elsewhere. I've tried to do similar tutorials; sunspot forecasting tutorial, pollution multivariate tutorial etc but i'm still not understanding how the input_shape argument works or how to organize my data to get it to be accepted by keras. My dataset is a single time series describing the number of products we sold every month. I took that single time series, 107 months, and turned it into a 30 row, 77 column data set. I created a training set and test set from that. from command prompt: Successfully uninstalled Keras-1.2.0 Successfully installed keras-2.0.0 Python Version: 3.5.4 Here's the code and respective errors i'm getting. model = Sequential() model.add(LSTM(input_shape=(77, 1), output_dim = 10)) Traceback C:\Python35\lib\site-packages\keras\backend\tensorflow_backend.py in concatenate(tensors, axis) 1219 A tensor. -> 1220 """ 1221 zero = _to_tensor(0., x.dtype.base_dtype) AttributeError: module 'tensorflow' has no attribute 'concat_v2' During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-42-ee393fff874d> in <module>() 1 model = Sequential() ----> 2 model.add(LSTM(input_shape=(77, 1), output_dim = 10)) 3 #model.add(Dense(10, activation = 'relu')) 4 #model.add(Dense(1, activation = 'softmax')) C:\Python35\lib\site-packages\keras\models.py in add(self, layer) 292 '`Sequential.from_config(config)`?') 293 return layer_module.deserialize(config, custom_objects=custom_objects) --> 294 295 296 def model_from_yaml(yaml_string, custom_objects=None): C:\Python35\lib\site-packages\keras\engine\topology.py in create_input_layer(self, batch_input_shape, input_dtype, name) 396 397 # Check ndim. --> 398 if spec.ndim is not None: 399 if K.ndim(x) != spec.ndim: 400 raise ValueError('Input ' + str(input_index) + C:\Python35\lib\site-packages\keras\engine\topology.py in __call__(self, x, mask) 541 # Handle automatic shape inference (only useful for Theano). 542 input_shape = _collect_input_shape(inputs) --> 543 544 # Actually call the layer, collecting output(s), mask(s), and shape(s). 545 output = self.call(inputs, **kwargs) C:\Python35\lib\site-packages\keras\layers\recurrent.py in build(self, input_shape) 761 constants.append(dp_mask) 762 else: --> 763 constants.append([K.cast_to_floatx(1.) for _ in range(3)]) 764 765 if 0 < self.recurrent_dropout < 1: C:\Python35\lib\site-packages\keras\backend\tensorflow_backend.py in concatenate(tensors, axis) 1220 """ 1221 zero = _to_tensor(0., x.dtype.base_dtype) -> 1222 inf = _to_tensor(np.inf, x.dtype.base_dtype) 1223 x = tf.clip_by_value(x, zero, inf) 1224 return tf.sqrt(x) C:\Python35\lib\site-packages\tensorflow\python\ops\array_ops.py in concat(values, axis, name) 1041 ops.convert_to_tensor(axis, 1042 name="concat_dim", -> 1043 dtype=dtypes.int32).get_shape( 1044 ).assert_is_compatible_with(tensor_shape.scalar()) 1045 return identity(values[0], name=scope) C:\Python35\lib\site-packages\tensorflow\python\framework\ops.py in convert_to_tensor(value, dtype, name, preferred_dtype) 674 name=name, 675 preferred_dtype=preferred_dtype, --> 676 as_ref=False) 677 678 C:\Python35\lib\site-packages\tensorflow\python\framework\ops.py in internal_convert_to_tensor(value, dtype, name, as_ref, preferred_dtype) 739 740 if ret is None: --> 741 ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) 742 743 if ret is NotImplemented: C:\Python35\lib\site-packages\tensorflow\python\framework\constant_op.py in _constant_tensor_conversion_function(v, dtype, name, as_ref) 111 as_ref=False): 112 _ = as_ref --> 113 return constant(v, dtype=dtype, name=name) 114 115 C:\Python35\lib\site-packages\tensorflow\python\framework\constant_op.py in constant(value, dtype, shape, name, verify_shape) 100 tensor_value = attr_value_pb2.AttrValue() 101 tensor_value.tensor.CopyFrom( --> 102 tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape, verify_shape=verify_shape)) 103 dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype) 104 const_tensor = g.create_op( C:\Python35\lib\site-packages\tensorflow\python\framework\tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape) 372 nparray = np.empty(shape, dtype=np_dt) 373 else: --> 374 _AssertCompatible(values, dtype) 375 nparray = np.array(values, dtype=np_dt) 376 # check to them. C:\Python35\lib\site-packages\tensorflow\python\framework\tensor_util.py in _AssertCompatible(values, dtype) 300 else: 301 raise TypeError("Expected %s, got %s of type '%s' instead." % --> 302 (dtype.name, repr(mismatch), type(mismatch).__name__)) 303 304 TypeError: Expected int32, got <tf.Variable 'lstm_7_W_i:0' shape=(1, 10) dtype=float32_ref> of type 'Variable' instead. A: I think that the problem goes around TF version. Version compatibility between Keras and TF is a problem that probably anyone has faced, as TF API changes a lot in a small period of time. I think that for Keras 2.2.X you need a TF version > 1.10.X Try updating it and see if the problem is fixed!
doc_23537290
Code: Dim xl0 As New Excel.Application Dim xlw As New Excel.Workbook Dim xlsh As Worksheet Set xlsh = Sheet3 Set xlw = xl0.Workbooks.Open("\\Addition\RCA.xlsx") xl0.Worksheets.Add xl0.xlsh.Cells(1, 1) = RANGECheck xl0.xlsh.Cells(1, 2) = RCAInput xlw.save xlw.Close Set xl0 = Nothing Set xlw = Nothing Also, the above code enters value in first row, what can we do to add the value after the last row having value?
doc_23537291
SharedPreferences.Editor prefEditor = sharedPreferences.edit(); int balance = sharedPreferences.getInt("balance", 0); prefEditor.putInt(balance, balance1); prefEditor.commit(); A: From the comments beneath your question, I understand that you simply wish to update a value within sharedpreferences. Your first line is fine: SharedPreferences.Editor prefEditor = sharedPreferences.edit(); This next line is then optional. Use it if you want to get at the existing value held under the key "balance" before you replace it. Otherwise it is not required and has no bearing on the 3rd line of code which replaces "balance" with a new value. int balance = sharedPreferences.getInt("balance", 0); Then I think your 3rd line should become: prefEditor.putInt("balance", balance1); That will replace the value held under the key "balance" with whatever value is held in balance1. Notice the quotes around "balance" that you did not have in your original code.
doc_23537292
I want to plot a stereographic projection with contoruf and want to color the higher parts in the Z direction in Matplotlib. For that i have two questions. * *I’m plotting with contourf before im using meshgrid and griddata, the the other edges are not smooth how can i smooth them? i *I want to have a log scale in Z how can i do that, i tried to use ticker.LogLocator but then i got just some parts colored. Here my code: # craation of a 2D grid xi = np.linspace(min(X), max(X)) yi = np.linspace(min(Y), max(Y)) X1, Y1 = np.meshgrid(xi, yi) ##### interpolation Z1 = griddata(X, Y, Z,xi,yi) plt.contourf(X1,Y1,Z1,50,cmap=plt.cm.rainbow,vmax=abs(Z1).max(), locator=ticker.LogLocator) plt.colorbar() plt.xlim(-1,1) plt.ylim(-1,1) plt.show() plt.set_zscale('log') plt.set_xlabel('X') plt.set_ylabel('Y') plt.show() A: Answering the first question: You can smooth the contour values doing: zmin = Z1.min() zmax=Z1.max() levels=linspace(zmin, zmax, 400) and then pass levels as an argument to plt.contourf(). To smooth the outer edges you have to use more values in your 2-D grid, which can be achieved passing the number of values you want when using linspace(): nx = 1000 ny = 1000 xi = np.linspace(min(X), max(X), nx) yi = np.linspace(min(Y), max(Y), ny)
doc_23537293
How can i open the new popup , when trying to open the same web page in default web browser like chrome , IE they are opening the pop up. For creating the pop up i am using the following code. Group group= new Group(); Scene scene= new Scene(group); fxpanel.setScene(scene); WebView webview = new WebView (); group.getChildren().add(webview); it().getScreenSize().height); webview.setVisible(true); webview.getEngine().setOnAlert(null); eng= webview.getEngine(); eng.setJavaScriptEnabled(true); try{ String url ="http://www.lawcrux.com/mkwebchatblog/loginp.aspx"; eng.load(url); eng.setCreatePopupHandler( new Callback<PopupFeatures, WebEngine>() { @Override public WebEngine call(PopupFeatures config) { JOptionPane.showMessageDialog(null,"clicked"); return eng; } }); A: You need to create WebView popup window yourself and provide WebEngine from callback. If you need new window, create new Stage with that WebView (not Swing one, JOptionPane can't store JavaFX WebView). See next example: WebView wv = new WebView(); wv.getEngine().setCreatePopupHandler(new Callback<PopupFeatures, WebEngine>() { @Override public WebEngine call(PopupFeatures p) { Stage stage = new Stage(StageStyle.UTILITY); WebView wv2 = new WebView(); stage.setScene(new Scene(wv2)); stage.show(); return wv2.getEngine(); } }); StackPane root = new StackPane(); root.getChildren().add(wv); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); wv.getEngine().load("http://www.i-am-bored.com/pop_up_blocker_test.html");
doc_23537294
I wrote the below code String s = new String("Tushar"); String s1 = new String("Tushar"); System.out.println("String HashCode"); System.out.println(s.hashCode()); System.out.println(s1.hashCode()); StringBuffer stringBuffer = new StringBuffer("Tushar"); StringBuffer stringBuffer1 = new StringBuffer("Tushar"); System.out.println("StringBuffer HashCode"); System.out.println(stringBuffer.hashCode()); System.out.println(stringBuffer1.hashCode()); StringBuilder stringBuilder = new StringBuilder("Tushar"); StringBuilder stringBuilder1 = new StringBuilder("Tushar"); System.out.println("StringBuilder HashCode"); System.out.println(stringBuilder.hashCode()); System.out.println(stringBuilder1.hashCode()); The output was as follows String HashCode -1778537625 -1778537625 StringBuffer HashCode 715152323 99120402 StringBuilder HashCode 1616769989 942619632 Why the hashcodes of StringBuilders and StringBuffers don't match. Are these just memory locations to which they are allocated or the hash code is created based upon the string passed? EDIT: Understanding : The hashcode of the value remains same irrespective of the way it is created. Confusion : What are the values printed (hash of instance variable, what does is mean?). A: Every class can choose to calculate the hash code in it's own way. Hash codes don't have meaning, and very simple rules (abbreviated): * *Objects where equals() return true must return same hash code. *Objects where equals() return false should return different hash code, to the best ability of the class, to ensure better performance of hash tables such as HashMap and HashSet. Since a String with value "ABC" and a StringBuilder with value "ABC" are not equal, there is no requirement that they return the same hash code. If you extract a String value from the StringBuilder, then that string value must have same hash code as another string of the same value, and it will, so the following two expression will return the same value: new String("ABC").hashCode() new StringBuilder("AB").append("C").toString().hashCode() As a side note: Neither StringBuilder nor StringBuffer implements equals() and hashCode(), so their equality is based on identity, not value. Two StringBuilder objects with same value will still not be "equal", and will therefore (most likely) not have same hash code. A: The lines stringBuilder.hashCode() and stringBuffer.hashCode() gets you the hash of the instances of the stringBuilder and stringBuffer hence the difference. Since the String are immutable (see my edit), getting the hash of the string of the stringBuilder and stringBuffer will be the same. So: System.out.println(stringBuffer.toString().hashCode()); System.out.println(stringBuffer1.toString().hashCode()); System.out.println(stringBuilder.toString().hashCode()); System.out.println(stringBuilder1.toString().hashCode()); all will return the same hash edit: Note also, that the computing of the hash of the string is: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] So, even that there is only one copy of the string "abc" in memory, the hash of the same string return the same value at each run.
doc_23537295
my code: <?php $target_dir = "uploads/"; $target_file = $target_dir . date('d_m_Y_H_i_s') . '_'. $_FILES["fileToUpload"]["name"]; if($target_file = null) { echo"nada"; } $uploadOk = 1; $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo ""; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo ""; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". basename( date('d_m_Y_H_i_s') . '_'. $_FILES["fileToUpload"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } ?> A: Using str_replace would be the easiest way in my opinion. $target_file = $target_dir . date('d_m_Y_H_i_s') . '_'. str_replace(' ','-',$_FILES["fileToUpload"]["name"]);
doc_23537296
<li class="taf"><h3><a href="26eOfferCode%3DGSONESTP-----------" id="pa1"> Citibank <b>Credit Card</b> - Save over 5% on fuel | Citibank.co.in</a> </h3>Get the IndianOil Citibank <b>Card</b>. Apply Now! <br /> <a href="e%253DGOOGLE ------">Get 10X Rewards On Shopping</a> - <a href="S%2526eOfferCode%253DGSCCSLEX ------">Save Over 5% On Fuel</a> <br /> <cite>www.citibank.co.in/<b>CreditCards</b></cite> </li> From this html i need to extract the lines beforeth of < br > tag line1 : Get the IndianOil Citibank Card. Apply Now! line2 : Get 10X Rewards On Shopping - Save Over 5% On Fuel how it would supposed to do in python? A: I think you just asked for the line before each <br/>. This following code will do it for the sample you've provided, by striping out the <b> and <a> tags and printing the .tail of each element whose following-sibling is a <br/>. from lxml import etree doc = etree.HTML(""" <li class="taf"><h3><a href="26eOfferCode%3DGSONESTP-----------" id="pa1"> Citibank <b>Credit Card</b> - Save over 5% on fuel | Citibank.co.in</a> </h3>Get the IndianOil Citibank <b>Card</b>. Apply Now! <br /> <a href="e%253DGOOGLE ------">Get 10X Rewards On Shopping</a> - <a href="S%2526eOfferCode%253DGSCCSLEX ------">Save Over 5% On Fuel</a> <br /> <cite>www.citibank.co.in/<b>CreditCards</b></cite> </li>""") etree.strip_tags(doc,'a','b') for element in doc.xpath('//*[following-sibling::*[name()="br"]]'): print repr(element.tail.strip()) Yields: 'Get the IndianOil Citibank Card. Apply Now!' 'Get 10X Rewards On Shopping -\n Save Over 5% On Fuel' A: Solution without relaying on <br> tags: import lxml.html html = "..." tree = lxml.html.fromstring(html) line1 = ''.join(tree.xpath('//li[@class="taf"]/text() | b/text()')[:3]).strip() line2 = ' - '.join(tree.xpath('//li[@class="taf"]//a[not(@id)]/text()')) A: As with all parsing of HTML you need to make some assumptions about the format of the HTML. If we can assume that the previous line is everything before the <br> tag up to a block level tag, or another <br> then we can do the following... from BeautifulSoup import BeautifulSoup doc = """ <li class="taf"><h3><a href="26eOfferCode%3DGSONESTP-----------" id="pa1"> Citibank <b>Credit Card</b> - Save over 5% on fuel | Citibank.co.in</a> </h3>Get the IndianOil Citibank <b>Card</b>. Apply Now! <br /> <a href="e%253DGOOGLE ------">Get 10X Rewards On Shopping</a> - <a href="S%2526eOfferCode%253DGSCCSLEX ------">Save Over 5% On Fuel</a> <br /> <cite>www.citibank.co.in/<b>CreditCards</b></cite> </li> """ soup = BeautifulSoup(doc) Now we have parsed the HTML, next we define the list of tags we don't want to treat as part of the line. There are other block tags really, but this does for this HTML. block_tags = ["div", "p", "h1", "h2", "h3", "h4", "h5", "h6", "br"] We cycle through each <br> tag stepping back through its siblings until we either have no more, or we hit a block level tag. Each time we loop we get add the node to the front of our line. NavigableStrings don't have name attributes, but we want to include them hence the two part test in the while loop. for node in soup.findAll("br"): line = "" sibling = node.previousSibling while sibling is not None and (not hasattr(sibling, "name") or sibling.name not in block_tags): line = unicode(sibling) + line sibling = sibling.previousSibling print line A: I dont know whether you want to use lxml or beautiful soup. But for lxml using xpath here is an example import lxml from lxml import etree import urllib2 response = urllib2.urlopen('your url here') html = response.read() imdb = etree.HTML(html) titles = imdb.xpath('/html/body/li/a/text()')//xpath for "line 2" data.[use firebug] The xpath I used is for your given html snippet. It may change in the original context. You can also give cssselect in lxml a try. import lxml.html import urllib data = urllib.urlopen('your url').read() doc = lxml.html.fromstring(data) elements = doc.cssselect('your csspath here') // CSSpath[using firebug extension] for element in elements: print element.text_content()
doc_23537297
int fd=socket(AF_INET, SOCK_RAW, IPPROTO_RAW); struct sockaddr_ll sa; memset(sa, 0, sizeof(sa)); // ip4h is the IPv4 datagram unwrapped in the user space and ready to be // sent to the kernel if (sendto(fd, iph, iplen, 0, (struct sockaddr *)&sa, sizeof(sa)) != iplen) { // Error processing. } The above injects full IPv4 packets (including the IPv4 headers), and the IPv4 payload gets processed appropriately by the Linux stack. How should the above be modified for use with IPv6 packets? The following adjustments I tried did not work: int fd=socket(AF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL)); sa.sll_family=AF_PACKET; sa.sll_protocol=htons(ETH_P_IPV6); sa.sll_halen=ETH_ALEN; sa.sll_ifindex=2; // <index of eth0> if (sendto(fd, iph, iplen, 0, (struct sockaddr *)&sa, sizeof(sa)) != iplen) { // Error processing. } Any thoughts on why the above doesn't work with raw IPv6 datagrams? 'tcpdump ip6' does show the IPv6 packets I'm inserting, which suggests the kernel sees them! It just happens to be ignoring them as well.
doc_23537298
But now, the application that I'm coding has 3 different methods for Log in/sign up: * *Normal login (username/password) *Connect with Facebook *Connect with RunKeeper Each one of those methods works nice if you use them separately. For example I can do a normal login with username and password, I get this information from the user and I send It to the server using HTTPRequest library and the server gives me a valid access_token to log in with no problem. Same with Facebook or runKeeper. But if I do the following steps anything works: * *I log in with Facebok or RunKeeper (doesn't matter which one) using an account that it's already linked to a certain user (we can call him X). *I request to Facebook/RunKeeper the access_token and the userID of the user and I send this information to my server. *My server gives me a valid access_token for the user X and I load the dashboard with his information. *The user X Logs out and I clear all the information in NSUserDefaults and synchronize it. *The user Y logs in using using his username and password (log in method number 1). *My server gives me a valid access_token for the user Y and I load the dashboard with his information. *The user Y logs out and I clear all the stored data in NSUserDefaults and synchronize it. *Finally any other user (Z for example) logs in again using Facebook/runKeeper. *I get all the information required from the social network and I send it to my server. *My server gives me a valid access_token and I load the dashboard, but it's not the dashboard of the user Z, It's the dashboard from the last user that has logged in using username/password. I know that reading those steps you can think that It's a problem with the server, but i did some tests using cURL and the response for the tokens are always correct. Then I thought that it could be some problem in the iOS App but I couldn't see anything with the breakpoints and the NSLogs i did. The i read about the cache in the ASIHttpRequest library and I added thos two lines of code in all my requests to the server for disabling all the cache system but it didn't work: [request setCachePolicy: ASIDoNotWriteToCacheCachePolicy | ASIDoNotReadFromCacheCachePolicy]; [request addRequestHeader:@"Cache-Control" value:@"no-cache"]; I don't know if anyone of you had the same problem or If you've got any idea of what can I try, but It will be very appreciated. If you need more information just tell me an i'll see what can i do Thanks! A: the important advice to stop use ASIHTTPRequest because it's not working well with ios 7 i'm facing many issues with ios 7 after release it to production you can use this instead AFNetwork
doc_23537299
[Fact] public async Task UploadPermitFileAsync_ShouldWork() { var stream = File.OpenRead(@"D:\Repos\administrationservice\AdministrationService.Tests\Test.pdf"); var file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name)) { Headers = new HeaderDictionary(), ContentType = "application/pdf" }; await GovRequest<FormFile, string> (file, HttpMethod.Post, "TaskController/Upload"); } private async Task GovRequest<M, T>(M model, HttpMethod httpMethod, string apiUrl) { var data = JsonConvert.SerializeObject(model); var httpContent = new StringContent(data, Encoding.UTF8, "application/json"); var request = new HttpRequestMessage(httpMethod, $"https://localhost:44365/{apiUrl}") { Content = httpContent }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _tokenApiModel.Result.AccessToken); var response = await _client.SendAsync(request); var responseBody = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject<SuccessRespondModel<T>>(responseBody); Assert.True(result.Success); }