date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/20
1,375
4,165
<issue_start>username_0: Consider these three arrays: ``` $Trucks: Serial=> 12345 Wheels => 4 Color => Black $Trailers: Serial=>4321 Length=>42 $Forklifts: Serial=>5678 ForkLength=>24 ``` What I'm looking to do is end up with a single array, which would end up with the columns `Serial, Wheels, Color, Length, ForkLength` And the contents should end up looking like this ``` Serial,Wheels,Color,Length,ForkLength 12345,4,Black,NULL,NULL 4321,NULL,NULL,42,NULL 5678,NULL,NULL,NULL,24 ``` Is this possible? I have tried the following code, but I end up with weird results, like some of the columns duplicating for trailers and forklifts. ``` $columns = Array("TraderCategory", "Make", "Model", "Year", "Last_Update", "VIN", "Trim", "Price", "Ext_Color", "Int_Color", "Engine", "HP", "Wheelbase", "Suspension", "KM", "Transmission", "Description", "NewUsed", "Torque", "Rear_Axle", "Front_Axle", "Differential", "Brakes", "StockNum", "ditl_Inventory", "new_truckStatus", "statuscode", "ditl_ShowonTrader", "new_truckId", "MainPic", "MainPicModified", "ExtraPics", "ExtraPicsModified", "Width", "Length"); foreach ($columns as $key => column) { $finalArray[$column] = $truckinfoData[$key]; } foreach ($columns as $key => column) { $finalArray[$column] = $trailerinfoData[$key]; } foreach ($columns as $key => column) { $finalArray[$column] = $forkliftinfoData[$key]; } return $finalArray; ```<issue_comment>username_1: You're very close. There is a bug in all of your foreach loops. The keys of your `$columns` array are just numbers (it is an indexed array), so you should do something like this: ``` foreach($columns as $column) { $finalArray[$column] = $truckinfoData[$column]; } ``` And similarly for the other loops. Upvotes: 1 <issue_comment>username_2: You can collect the keys from your various input arrays using `array_merge` to generate the columns. (If you already have an array with a list of columns, you don't need to do this part.) ``` $columns = array_keys(array_merge($trucks, $trailers, $forklifts)); ``` Then make a row template from the columns filled with null values. ``` $template = array_fill_keys($columns, null); ``` Your final array can be constructed by merging the input arrays onto the template. ``` foreach ([$trucks, $trailers, $forklifts] as $array) { $result[] = array_merge($template, $array); } ``` `array_merge($template, $array);` will merge replace the null values in `$template` with the values of any of the corresponding keys that are defined in `$array`. [Executable example at 3v4l.org.](https://3v4l.org/S0shX) Upvotes: 2 <issue_comment>username_3: You could loop over the keys, create an array, and fill with NULL is the key doesn't exists, or with the key exists, and add this array to the `$finalArray`: ``` $Trucks = ['Serial'=> 12345, 'Wheels' => 4, 'Color' => 'Black']; $Trailers = ['Serial'=> 4321, 'Length'=> 42]; $Forklifts = ['Serial'=> 5678, 'ForkLength' => 24]; // If keys should be dynamic: $keys = array_keys(array_merge($Trucks, $Trailers, $Forklifts)); $finalArray = [$keys]; foreach (['Trucks', 'Trailers', 'Forklifts'] as $array_name) { $data = []; foreach($keys as $idx => $column) { $data[$idx] = NULL ; if (isset($$array_name[$column])) $data[$idx] = $$array_name[$column] ; } $finalArray[] = $data ; } print_r($finalArray) ; ``` Outputs (reformatted) : ``` Array ( [0] => Array ([0] => Serial [1] => Wheels [2] => Color [3] => Length [4] => ForkLength ) [1] => Array ([0] => 12345 [1] => 4 [2] => Black [3] => NULL [4] => NULL ) [2] => Array ([0] => 4321 [1] => NULL [2] => NULL [3] => 42 [4] => NULL ) [3] => Array ([0] => 5678 [1] => NULL [2] => NULL [3] => NULL [4] => 24 ) ) ``` Or, without variable variables: ``` $finalArray = [$keys]; foreach ([$Trucks, $Trailers, $Forklifts] as &$array) { $data = []; foreach($keys as $idx => $column) { $data[$idx] = NULL ; if (isset($array[$column])) $data[$idx] = $array[$column] ; } $finalArray[] = $data ; } ``` Upvotes: 2 [selected_answer]
2018/03/20
4,929
18,426
<issue_start>username_0: I am following a tutorial on Spring MVC and after attempting to implement Hibernate validation, I'm now getting `HTTP Status 500 - Servlet.init() for servlet dispatcher threw exception` when running the application on the server. I took the 3 Hibernate jar dependencies out of the POM.xml and it served up the home page without any issue (I had to comment the Hibernate validation annotations in the Customer object class) but when I added them back in (annotations were still commented) I got the error again! Does anybody have any idea why the Hibernate Jars are causing this error? * Tomcat version: 7.0.67 * Java version: 1.8.0\_131 Stack trace ----------- ``` INFO: Mapped "{[/student/processForm]}" onto public java.lang.String com.luv2code.springdemo.mvc.StudentController.processForm(com.luv2code.springdemo.mvc.Student) Mar 20, 2018 9:22:01 PM org.hibernate.validator.internal.util.Version INFO: HV000001: Hibernate Validator 6.0.0.Final Mar 20, 2018 9:22:01 PM org.springframework.context.support.AbstractApplicationContext refresh WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager Mar 20, 2018 9:22:01 PM org.springframework.web.servlet.FrameworkServlet initServletBean SEVERE: Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1710) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:676) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:642) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:690) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:558) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:499) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:172) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5327) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5617) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.NoClassDefFoundError: javax/el/ELManager at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.buildExpressionFactory(ResourceBundleMessageInterpolator.java:87) at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.(ResourceBundleMessageInterpolator.java:46) at org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultMessageInterpolator(ConfigurationImpl.java:420) at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:267) at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706) ... 28 more Caused by: java.lang.ClassNotFoundException: javax.el.ELManager at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1856) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1705) ... 35 more Mar 20, 2018 9:22:01 PM org.apache.catalina.core.ApplicationContext log SEVERE: StandardWrapper.Throwable org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/el/ELManager at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1710) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:676) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:642) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:690) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:558) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:499) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:172) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5327) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5617) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.NoClassDefFoundError: javax/el/ELManager at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.buildExpressionFactory(ResourceBundleMessageInterpolator.java:87) at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.(ResourceBundleMessageInterpolator.java:46) at org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultMessageInterpolator(ConfigurationImpl.java:420) at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:267) at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706) ... 28 more Caused by: java.lang.ClassNotFoundException: javax.el.ELManager at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1856) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1705) ... 35 more Mar 20, 2018 9:22:01 PM org.apache.catalina.core.StandardContext loadOnStartup SEVERE: Servlet [dispatcher] in web application [/spring-mvc-demo] threw load() exception java.lang.ClassNotFoundException: javax.el.ELManager at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1856) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1705) at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.buildExpressionFactory(ResourceBundleMessageInterpolator.java:87) at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.(ResourceBundleMessageInterpolator.java:46) at org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultMessageInterpolator(ConfigurationImpl.java:420) at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:267) at org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean.afterPropertiesSet(OptionalValidatorFactoryBean.java:40) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:676) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:642) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:690) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:558) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:499) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:172) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5327) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5617) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) ``` POM.xml ------- ``` 4.0.0 spring-mvc-demo spring-mvc-demo 0.0.1-SNAPSHOT war 5.0.2.RELEASE org.springframework spring-context ${org.springframework.version} org.springframework spring-aop ${org.springframework.version} org.springframework spring-webmvc ${org.springframework.version} org.springframework spring-web ${org.springframework.version} com.fasterxml classmate 1.3.4 org.jboss.logging jboss-logging 3.3.2.Final javax.validation validation-api 2.0.1.Final javax.servlet javax.servlet-api 4.0.0 provided javax.servlet jstl 1.2 javax.el javax.el-api 3.0.0 org.hibernate.validator hibernate-validator 6.0.0.Final org.hibernate.validator hibernate-validator-annotation-processor 6.0.8.Final org.hibernate hibernate-validator-cdi 6.0.8.Final src maven-compiler-plugin 3.3 1.8 1.8 maven-war-plugin 2.6 WebContent false ``` Controller ---------- ``` package com.luv2code.springdemo.mvc; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/customer") public class CustomerController { @RequestMapping("/showForm") public String showForm(Model theModel) { theModel.addAttribute("customer", new Customer()); return "customer-form"; } } ``` Home Controller --------------- ``` package com.luv2code.springdemo.mvc; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HomeController { @RequestMapping("/") public String showPage() { return "main-menu"; } } ``` Main menu jsp ------------- ``` Spring MVC Demo Spring MVC Demo - Home Page --------------------------- --- [Hello World form](hello/showForm) [Student form](student/showForm) [Customer form](customer/showForm) ``` Customer Object --------------- ``` package com.luv2code.springdemo.mvc; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class Customer { private String firstName; @NotNull(message="is required") @Size(min=1) private String lastName; public Customer() { } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } ```<issue_comment>username_1: Looking at the exception that you've provided and also at your pom file it looks like you are missing ``` org.glassfish javax.el 3.0.1-b09 ``` it's an implementation for the EL, so you need to add it (and probably drop the api one) Also I've noticed that for the validator you have 6.0.0.Final as a version - you'd better have all version consistent. For simple validation in Spring it should be enough to have: ``` org.hibernate.validator hibernate-validator 6.0.8.Final ``` and EL dependency mentioned above. Upvotes: 4 [selected_answer]<issue_comment>username_2: I had the same problem and the issue was with Tomcat 7. Using cargo solved the problem. Use the dependencies of javax.el and javax.el-api ``` org.glassfish javax.el 3.0.1-b09 javax.el javax.el-api 3.0.0 ``` Add cargo plugin to run tomcat. ``` org.codehaus.cargo cargo-maven2-plugin 1.6.5 tomcat8x http://repo1.maven.org/maven2/org/apache/tomcat/tomcat/8.5.9/tomcat-8.5.9.zip ``` Use the following run configurations. ``` cargo:run ``` Upvotes: 1 <issue_comment>username_3: Some time the problem is not about the dependency my issue, I was using Tomcat 7 then I use tomcat 9 It worked. Writing so that If has some else must try my solution Upvotes: 0
2018/03/20
1,413
4,220
<issue_start>username_0: So I need to compare a string against another string to see if any parts of the string match. This would be useful for checking if a list of salespeople IDs against the ones that are listed to a specific GM or if falls outside of that GMs list of IDs: ``` ID_SP ID_GM NEEDED FIELD (overlap) 136,338,342 512,338,112 338 512,112,208 512,338,112 512,112 587,641,211 512,338,112 null ``` I'm struggling on how to achieve this. I'm guessing some sort of UDF? I realize this would be much easier to have done prior to using the for XML path(''), but I'm hoping for a solution that doesn't require me to unravel the data as that will blow up the overall size of the dataset.<issue_comment>username_1: No, that is not how you do it. You would go back to the raw data. To get the ids in common: ``` select tbob.id from t tbob join t tmary on tbob.id = tmary.id and tbob.manager = 'Bob' and tmary.manager = 'Mary'; ``` Upvotes: 2 <issue_comment>username_2: Since the data set isn't two raw sources, but one 'concatenated field' and a hardcoded string field that is a list of GMIDs (same value for every row) then the correct answer (from the starting point of the question) is to use something like nodes('/M') as Split(a). Then you get something like this: ``` ID_SP ID_GM 136 512,338,112 338 512,338,112 342 512,338,112 ``` and can do something like this: ``` case when ID_GM not like '%'+ID_SP+'%'then 1 else 0 end as 'indicator' ``` From here you can aggregate back and sum the indicator field and say that if > 0 then the ID\_SP exists in the list of ID\_GMs Hope this helps someone else. Upvotes: 1 <issue_comment>username_3: -- Try This ``` Declare @String1 as varchar(100)='512,112,208'; Declare @String2 as varchar(100)='512,338,112'; WITH FirstStringSplit(S1) AS ( SELECT CAST('' + REPLACE(@String1,',','') + '' AS XML) ) ,SecondStringSplit(S2) AS ( SELECT CAST('' + REPLACE(@String2,',','') + '' AS XML) ) SELECT STUFF( ( SELECT ',' + part1.value('.','nvarchar(max)') FROM FirstStringSplit CROSS APPLY S1.nodes('/x') AS A(part1) WHERE part1.value('.','nvarchar(max)') IN(SELECT B.part2.value('.','nvarchar(max)') FROM SecondStringSplit CROSS APPLY S2.nodes('/x') AS B(part2) ) FOR XML PATH('') ),1,1,'') ``` Upvotes: 0 <issue_comment>username_4: Gordon is correct, that you should not do this. This ought do be done with the raw data. the following code will "go back to the raw data" and solve this with an easy `INNER JOIN`. The `CTE`s will create derived tables (all the many rows you want to avoid) and check them for equality (Not using indexes! One more reason to do this in advance): ``` DECLARE @tbl TABLE(ID INT IDENTITY,ID_SP VARCHAR(100),ID_GM VARCHAR(100)); INSERT INTO @tbl VALUES ('136,338,342','512,338,112') ,('512,112,208','512,338,112') ,('587,641,211','512,338,112'); WITH Splitted AS ( SELECT t.* ,CAST('' + REPLACE(t.ID\_SP,',','') + '' AS xml) AS PartedSP ,CAST('' + REPLACE(t.ID\_GM,',','') + '' AS xml) AS PartedGM FROM @tbl AS t ) ,SetSP AS ( SELECT Splitted.ID ,Splitted.ID_SP ,x.value('text()[1]','int') AS SP_ID FROM Splitted CROSS APPLY PartedSP.nodes('/x') AS A(x) ) ,SetGM AS ( SELECT Splitted.ID ,Splitted.ID_GM ,x.value('text()[1]','int') AS GM_ID FROM Splitted CROSS APPLY PartedGM.nodes('/x') AS A(x) ) ,BackToYourRawData AS --Here is the point you should do this in advance! ( SELECT SetSP.ID ,SetSP.SP_ID ,SetGM.GM_ID FROM SetSP INNER JOIN SetGM ON SetSP.ID=SetGM.ID AND SetSP.SP_ID=SetGM.GM_ID ) SELECT ID ,STUFF(( SELECT ',' + CAST(rd2.SP_ID AS VARCHAR(10)) FROM BackToYourRawData AS rd2 WHERE rd.ID=rd2.ID ORDER BY rd2.SP_ID FOR XML PATH('')),1,1,'') AS CommonID FROM BackToYourRawData AS rd GROUP BY ID; ``` The result ``` ID CommonID 1 338 2 112,512 ``` Upvotes: 0
2018/03/20
524
1,673
<issue_start>username_0: I am in the process of learning React and trying a sample code from a book. The code is simple it is supposed to display vowels in different colors defined in the ReactDOM.render but instead it displays them all in one color coming from the style tag. Attached below is the code ``` Styling in React #container { padding: 50px; background-color: #FFF; } div div div { padding: 10px; margin: 10px; background-color: #ffde00; color: #333; display: inline-block; font-family: monospace; font-size: 32px; text-align: center; } var destination = document.querySelector("#container"); class Letter extends React.Component { render() { var letterStyle = { padding:10, margin:10, backgroundColor:this.props.bgcolor, color:"#333", display:"inline-block", fontFamily:"monospace", fontSize:32, textAlign:"center" }; return ( <div> {this.props.children} </div> ); } } ReactDOM.render( <div> <Letter bgcolor="#58B3FF">A</Letter> <Letter bgcolor="#FF605F">E</Letter> <Letter bgcolor="#FFD52E">I</Letter> <Letter bgcolor="#49DD8E">O</Letter> <Letter bgcolor="#AE99FF">U</Letter> </div>, destination ); } ```<issue_comment>username_1: It looks like you aren't using letterStyle anywhere. Try the following: ``` render() { var letterStyle = { padding:10, margin:10, backgroundColor:this.props.bgcolor, color:"#333", display:"inline-block", fontFamily:"monospace", fontSize:32, textAlign:"center" }; return ( {this.props.children} ); } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Try {this.props.bgcolor} you need a {} to use dynamic variables. Upvotes: 0
2018/03/20
749
2,442
<issue_start>username_0: Is there any way that I can create or modify an AzureAD App to allow the OAuth 2.0 Implicit flow via the Azure CLI 2.0? I'm able to create app registrations without issue using [az ad app create](https://learn.microsoft.com/en-gb/cli/azure/ad/app?view=azure-cli-latest#az_ad_app_update)<issue_comment>username_1: It does not look like the Azure CLI 2.0 exposes the `OAuth2AllowImplicitFlow` property to be set, however the [Azure Active Directory PowerShell 2.0](https://learn.microsoft.com/en-us/powershell/module/azuread/New-AzureADApplication?view=azureadps-2.0) does expose this property: > > `-Oauth2AllowImplicitFlow` > > > Specifies whether this web application can request OAuth2.0 implicit > flow tokens. The default is false. > > > Type: Boolean > > > Position: Named > > > Default value: None > > > Accept pipeline input: False > > > Accept wildcard characters: False > > > Let me know if this helps. Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use CLI to call Graph API to do achieve that. This method needs to create `service principal` in your AAD Tenant, and assign `Company Admin role` to it. **Get an authentication token** ``` curl -X "POST" "https://login.microsoftonline.com/$TENANTID/oauth2/token" \ -H "Cookie: flight-uxoptin=true; stsservicecookie=ests; x-ms-gateway-slice=productionb; stsservicecookie=ests" \ -H "Content-Type: application/x-www-form-urlencoded" \ --data-urlencode "client_id=$APPID" \ --data-urlencode "grant_type=client_credentials" \ --data-urlencode "client_secret=$<PASSWORD>" \ --data-urlencode "resource=https://graph.windows.net/" ``` **Set the AAD applicaiton Oauth2AllowImplicitFlow to be true:** ``` curl -X "PATCH" "https://graph.windows.net/$TENANTID/applications/$ObjectId?api-version=1.6" \ -H "Authorization: Bearer $ACCESSTOKEN" \ -H "Content-Type: application/json" \ -d $'{"oauth2AllowImplicitFlow":true}' ``` After few seconds, Oauth2AllowImplicitFlow of your application has been set to be true. Additional, as [@Shawn](https://stackoverflow.com/users/1396977/shawn-tabrizi) said that Azure CLI doesn't have this cmdlet to set AAD Application,but Azure Powershell have. However Azure CLI is an important tool for Linux platform to use Azure. I think we can post this feature feedback in [this Page](https://github.com/Azure/azure-cli/issues). Azure Team will review it. Hope this helps! Upvotes: 0
2018/03/20
904
2,937
<issue_start>username_0: I've been trying to make a word generator, which displays your input in a big font in the console. For this, I need to print the respective variable based on the character's in the user's input (e.g. if the user types `"a"`, then the variable `a` should be printed). How do I do so? This is my code: ```py a = [ "@@@@@", "@ @", "@ @", "@@@@@", "@ @", "@ @", "@ @" ] b = [ "@@@@ ", "@ @", "@ @", "@@@@ ", "@ @", "@ @", "@@@@ " ] c = [ "@@@@@", "@ ", "@ ", "@ ", "@ ", "@ ", "@@@@@" ] input_word = input("Which word would you like to display?") for c in input_word: # How do I print the variable whose name is equal to the value of `c` here? pass ```<issue_comment>username_1: It does not look like the Azure CLI 2.0 exposes the `OAuth2AllowImplicitFlow` property to be set, however the [Azure Active Directory PowerShell 2.0](https://learn.microsoft.com/en-us/powershell/module/azuread/New-AzureADApplication?view=azureadps-2.0) does expose this property: > > `-Oauth2AllowImplicitFlow` > > > Specifies whether this web application can request OAuth2.0 implicit > flow tokens. The default is false. > > > Type: Boolean > > > Position: Named > > > Default value: None > > > Accept pipeline input: False > > > Accept wildcard characters: False > > > Let me know if this helps. Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use CLI to call Graph API to do achieve that. This method needs to create `service principal` in your AAD Tenant, and assign `Company Admin role` to it. **Get an authentication token** ``` curl -X "POST" "https://login.microsoftonline.com/$TENANTID/oauth2/token" \ -H "Cookie: flight-uxoptin=true; stsservicecookie=ests; x-ms-gateway-slice=productionb; stsservicecookie=ests" \ -H "Content-Type: application/x-www-form-urlencoded" \ --data-urlencode "client_id=$APPID" \ --data-urlencode "grant_type=client_credentials" \ --data-urlencode "client_secret=$<PASSWORD>" \ --data-urlencode "resource=https://graph.windows.net/" ``` **Set the AAD applicaiton Oauth2AllowImplicitFlow to be true:** ``` curl -X "PATCH" "https://graph.windows.net/$TENANTID/applications/$ObjectId?api-version=1.6" \ -H "Authorization: Bearer $ACCESSTOKEN" \ -H "Content-Type: application/json" \ -d $'{"oauth2AllowImplicitFlow":true}' ``` After few seconds, Oauth2AllowImplicitFlow of your application has been set to be true. Additional, as [@Shawn](https://stackoverflow.com/users/1396977/shawn-tabrizi) said that Azure CLI doesn't have this cmdlet to set AAD Application,but Azure Powershell have. However Azure CLI is an important tool for Linux platform to use Azure. I think we can post this feature feedback in [this Page](https://github.com/Azure/azure-cli/issues). Azure Team will review it. Hope this helps! Upvotes: 0
2018/03/20
1,246
4,385
<issue_start>username_0: So I've read around this and will provide relevant properties at the end. I'm looking to store a custom ToolStrip button image size in my.settings and load them at startup, changing them to a user set size.. The code I run at startup is: ``` Dim tss As New List(Of ToolStrip) tss = GetAllControls(Me).OfType(Of ToolStrip)().ToList For Each ts In tss ts.BackColor = My.Settings.ToolStripBGColor ts.ImageScalingSize = New Size(My.Settings.ToolStripImgScalingSize, My.Settings.ToolStripImgScalingSize) ts.ResumeLayout() ts.Invalidate() ts.Refresh() Next ToolStripContainer.Invalidate() ToolStripContainer.Refresh() ``` This does change the properties of all of the ToolStips. However, the images initially display at the default 16x16 UNTIL I drag them into another area of the ToolStripContainer. It then resizes correctly. This tends to imply to me that it's something to so with the draw of these containers/controls (hence the blanket bombing of .invalidate, .resumelayout and .refresh!) Regarding proprieties, the relevant ones within designer view: **ToolStripButton** .autosize = true .imagescaling = SizeToFit **ToolStrip** .autosize = true .imagesclaing = 16,16 (later modified by code) **ToolStripContainer** * couldn't see any that would effect this!?? This is one of those where you go round in circles for half a day over what essentially could be due to a janky aspect of .net! Could be me though...<issue_comment>username_1: Getting this to work with `AutoSize=True` is always a bit confusing. I've found that if you set it to `False` with layout suspended and then set it to `True` with layout enabled, that you can get the desired effect. That description is probably clear as mud, so here is the code pattern. ``` With ToolStrip1 .SuspendLayout() .AutoSize = False .ImageScalingSize = New Size(40, 40) .ResumeLayout() .AutoSize = True End With ``` Upvotes: 2 <issue_comment>username_2: Imports System.Drawing : Imports Microsoft.VisualBasic Imports Microsoft.Win32 : Imports System Imports System.IO : Imports System.Windows.Forms ``` Public Class Form1 Inherits Form ``` Private toolStripItem1 As ToolStripButton Private toolStrip1 As ToolStrip Public Sub New() ``` toolStrip1 = New System.Windows.Forms.ToolStrip() toolStrip1.Size = New System.Drawing.Size(580,40) toolStrip1.BackColor = System.Drawing.Color.MistyRose toolStrip1.AutoSize = True toolStripItem1 = New System.Windows.Forms.ToolStripButton() toolStrip1.SuspendLayout() Me.SuspendLayout() toolStrip1.Items.AddRange(New System.Windows.Forms.ToolStripButton() _ {toolStripItem1}) toolStrip1.Location = New System.Drawing.Point(0, 0) toolStrip1.Name = "toolStrip1" toolStripItem1.AutoSize = False toolStripItem1.Size = New System.Drawing.Size(110,95) toolStripItem1.BackgroundImage = Image.FromFile("D:\Book4\Resources\icos\CUT.png") toolStripItem1.Name = "toolStripItem1" toolStripItem1.Text = "Cut" toolStripItem1.Font = New System.Drawing.Font("Segoe UI", 16.0!, _ System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, _ CType(0, Byte)) toolStripItem1.TextAlign = System.Drawing.ContentAlignment.TopCenter AddHandler Me.toolStripItem1.Click, New System.EventHandler _ (AddressOf Me.toolStripItem1_Click) Me.AutoScaleDimensions = New System.Drawing.SizeF(6F, 13F) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(1500,900) Me.BackColor = ColorTranslator.FromHtml("#808080") Me.Controls.Add(Me.toolStrip1) Me.Name = "Form1" toolStrip1.ResumeLayout(False) Me.ResumeLayout(False) Me.PerformLayout() ``` End Sub Public Sub Form1\_Loaded(sender As Object, e As EventArgs) \_ ``` Handles MyBase.Load ``` Try ``` Dim ico As New System.Drawing.Icon("D:\Resources\icos\kvr.ico") Me.Icon = ico ``` Catch ex As Exception End Try End Sub Public Shared Sub Main() ``` Dim form1 As Form1 = New Form1() form1.ShowDialog() ``` End Sub Private Sub toolStripItem1\_Click(ByVal sender As Object,ByVal e As EventArgs) ``` System.Windows.Forms.MessageBox.Show("Successfully enlarged ToolStripButtonImage size") ``` End Sub End Class Upvotes: 0
2018/03/20
893
2,516
<issue_start>username_0: ``` cd /home/foo/ for f in `seq -w 01 10` do cat $f > /home/foo/cloned_files/"$f".$i done ``` **situation:** i have only 1 file in /home/foo. i want to clone that file 10 times and add the iteration number to the filename. in the end, i should have 10 files identical in content but with a suffix indicating its sequence number. **example:** /home/foo/xfile.txt after executing the script, i should have: xfile.txt.01, xfile.txt.02, xfile.txt.03...xfile.txt.10 in /home/foo/cloned\_files/ any help would be much appreciated. thank you<issue_comment>username_1: Try this, the canonical way using your tag: in pure [bash](/questions/tagged/bash "show questions tagged 'bash'") : ``` for i in {01..10}; do cp "filename" "/path/to/xfile.txt.$i" done ``` if you need the integer range to be dynamic : ``` integer=10 # <= variable for i in $(seq -w 1 $integer); do cp "filename" "/path/to/xfile.txt.$i" done ``` And like @<NAME> said in comments, a more portable solution (seq is not bash related, it's an external command) : ``` for ((i=1; i<=10; i++)); do printf -v num '%02d' "$i" cp "filename" "/path/to/xfile.txt.$num" done ``` To go further : [TestsAndConditionals](http://mywiki.wooledge.org/BashGuide/TestsAndConditionals#Conditional_Loops) `man cp` : > > CP(1) > > > NAME > > > cp - copy files and directories > > > Notes : ------- * stop using backticks ``` in 2018, we recommend to use instead `$( )` * learn how to quote properly, it's very important in shell : > > "Double quote" every literal that contains spaces/metacharacters and *every* expansion: `"$var"`, `"$(command "$var")"`, `"${array[@]}"`, `"a & b"`. Use `'single quotes'` for code or literal `$'s: 'Costs $5 US'`, `ssh host 'echo "$HOSTNAME"'`. See > > <http://mywiki.wooledge.org/Quotes> > > <http://mywiki.wooledge.org/Arguments> > > <http://wiki.bash-hackers.org/syntax/words> > > > Upvotes: 3 [selected_answer]<issue_comment>username_2: Another option using **GNU Parallel** ``` parallel --dry-run cp file /elsewhere/file.{} ::: {01..10} ``` **Sample Output** ``` cp file /elsewhere/file.07 cp file /elsewhere/file.08 cp file /elsewhere/file.09 cp file /elsewhere/file.06 cp file /elsewhere/file.05 cp file /elsewhere/file.04 cp file /elsewhere/file.03 cp file /elsewhere/file.02 cp file /elsewhere/file.01 cp file /elsewhere/file.10 ``` Remove `--dry-run` and run the command again to actually do it if the output looks good. Upvotes: 2
2018/03/20
2,991
8,700
<issue_start>username_0: I've written a regex in PHP7 for validating URI schemes, with the intention of supporting every scheme listed by IANA [here](https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml "here"); permanent, provisional or historical. So far I've gotten as far as `shttp` in the permanent protocols. The regex is written in my code as a defined constant: ``` define('URL_VALIDATION_REGEX', '/\b(?:'. 'aaas?|about|acap|acct|cap|cid|coaps?(?:\+(?:tcp|ws))?|crid|data|dav|dict|dns|example|file|ftp|geo|'. 'go|gopher|h323|iax|icap|im(?:ap)?|info|ipps?|iris(?:.(?:beep|lwz|xpcs?))?|jabber|ldap|mailto|'. 'mid|msrps?|mtqp|mupdate|news|nfs|nih?|nntp|opaquelocktoken|pkcs11|pop|pres|reload|rtsp[su]?|service|'. 'session|s?https?'. '):\/\//i'); ``` The part of the code that is the problem is `s?https?`; obviously this regex will return a match if the scheme provided is `http`, `https` and `shttp`, but also erroneously `shttps`. I could just remove `s?https?` and add `https?` and `shttp` to the regex, and this would work, but it seems inelegant to me to do it this way. My question is, does PHP7 allow a regex that will work like `s?https?` but exclude `shttps` returning a match without having to put the string shttps as a literal or placing `https?` and `shttp` as separate parts of the regex?<issue_comment>username_1: idk about improving the regex, but a combination of parse\_url, in\_array, and strtolower() seems to work fine, this code, including the opcode compilation, runs in about 52 milliseconds on my laptop, and excluding the opcode compilation, 30 milliseconds (because in a production environment, opcodes would be cached after first execution anyway) ``` php declare(strict_types = 1); $tests=array( 'http://foo.bar'=true, 'irc://irc.freenode.net/#anime'=>true, 'foobar://wtf'=>false, 'shouldfail://wat'=>false ); foreach($tests as $test=>$expected){ echo "$test: "; if(in_array(strtolower(parse_url( $test, PHP_URL_SCHEME )),array('aaa','aaas','about','acap','acct','acr','adiumxtra','afp','afs','aim','appdata','apt','attachment','aw','barion','beshare','bitcoin', 'blob','bolo','browserext','callto','cap','chrome','chrome-extension','cid','coap','coap+tcp','coap+ws','coaps','coaps+tcp','coaps+ws', 'com-eventbrite-attendee','content','conti','crid','cvs','data','dav','diaspora','dict','dis','dlna-playcontainer','dlna-playsingle','dns','dntp','dtn', 'dvb','ed2k','example','facetime','fax','feed','feedready','file','filesystem','finger','fish','ftp','geo','gg','git','gizmoproject','go','gopher', 'graph','gtalk','h323','ham','hcp','http','https','hxxp','hxxps','hydrazone','iax','icap','icon','im','imap','info','iotdisco','ipn','ipp','ipps', 'irc','irc6','ircs','iris','iris.beep','iris.lwz','iris.xpc','iris.xpcs','isostore','itms','jabber','jar','jms','keyparc','lastfm','ldap','ldaps', 'lvlt','magnet','mailserver','mailto','maps','market','message','microsoft.windows.camera','microsoft.windows.camera.multipicker', 'microsoft.windows.camera.picker','mid','mms','modem','mongodb','moz','ms-access','ms-browser-extension','ms-drive-to','ms-enrollment','ms-excel', 'ms-gamebarservices','ms-gamingoverlay','ms-getoffice','ms-help','ms-infopath','ms-inputapp','ms-lockscreencomponent-config','ms-media-stream-id', 'ms-mixedrealitycapture','ms-officeapp','ms-people','ms-project','ms-powerpoint','ms-publisher','ms-restoretabcompanion','ms-search-repair', 'ms-secondary-screen-controller','ms-secondary-screen-setup','ms-settings','ms-settings-airplanemode','ms-settings-bluetooth','ms-settings-camera', 'ms-settings-cellular','ms-settings-cloudstorage','ms-settings-connectabledevices','ms-settings-displays-topology','ms-settings-emailandaccounts', 'ms-settings-language','ms-settings-location','ms-settings-lock','ms-settings-nfctransactions','ms-settings-notifications','ms-settings-power', 'ms-settings-privacy','ms-settings-proximity','ms-settings-screenrotation','ms-settings-wifi','ms-settings-workplace','ms-spd','ms-sttoverlay', 'ms-transit-to','ms-useractivityset','ms-virtualtouchpad','ms-visio','ms-walk-to','ms-whiteboard','ms-whiteboard-cmd','ms-word','msnim','msrp', 'msrps','mtqp','mumble','mupdate','mvn','news','nfs','ni','nih','nntp','notes','ocf','oid','onenote','onenote-cmd','opaquelocktoken','pack','palm', 'paparazzi','pkcs11','platform','pop','pres','prospero','proxy','pwid','psyc','qb','query','redis','rediss','reload','res','resource','rmi', 'rsync','rtmfp','rtmp','rtsp','rtsps','rtspu','secondlife','service','session','sftp','sgn','shttp','sieve','sip','sips','skype','smb','sms','smtp', 'snews','snmp','soap.beep','soap.beeps','soldat','spiffe','spotify','ssh','steam','stun','stuns','submit','svn','tag','teamspeak','tel','teliaeid', 'telnet','tftp','things','thismessage','tip','tn3270','tool','turn','turns','tv','udp','unreal','urn','ut2004','v-event','vemmi','ventrilo', 'videotex','vnc','view-source','wais','webcal','wpid','ws','wss','wtai','wyciwyg','xcon','xcon-userid','xfire','xmlrpc.beep','xmlrpc.beeps', 'xmpp','xri','ymsgr','z39.50','z39.50r','z39.50s'),true) === $expected){ echo "OK"; }else{ echo "FAIL"; } echo "\n"; } ``` * and this is all of them, not just the subset your regex includes (i extracted them from [the csv file](https://www.iana.org/assignments/uri-schemes/uri-schemes-1.csv)) * adding an in-php benchmark, `$start=microtime(true);` before the loop, and `$end=microtime(true);var_dump($end-$start);` after the loop, claims that the loop itself uses 0.1 milliseconds, on my laptop, so there's that. `double(0.00010299682617188)` Upvotes: 0 <issue_comment>username_2: I decided to follow @sin's comment of going full *trie*; upon consideration that speed being to me a keep part of elegant code. I believe the code is still readable as it's listed alphabetically: ``` define('URL_VALIDATION_REGEX', '/\b(?:'. 'a(?:aas?|bout|c(?:ap|ct|r)|diumxtra|f[ps]|im|p(?:pdata|t)|ttachment|w)|'. 'b(?:arion|eshare|itcoin|lob|olo|rowserext)|'. 'c(?:a(?:llto|p)|hrome(?:-extension)?|id|o(?:aps?(?:\+(?:tcp|ws))?|m-eventbrite-attendee|'. 'nt(?:ent|i))|rid|vs)|'. 'd(?:a(?:ta|v)|i(?:aspora|ct|s)|lna-play(?:container|single)|n(?:s|tp)|tn|vb)|'. 'e(?:d2k|xample)|'. 'f(?:a(?:cetime|x)|eed(?:ready)?|i(?:(?:le(?:system)?)|nger|sh)|tp)|'. 'g(?:eo|g|i(?:t|zmoproject)|o(?:pher)?|raph|talk)|'. 'h(?:323|am|cp|ttps?|xxps?|ydrazone)|'. 'i(?:ax|c(?:ap|on)|m(?:ap)?|nfo|otdisco|p(?:n|ps?)|r(?:c[6s]?|is(?:.(?:beep|lwz|xpcs?))?)|sostore|'. 'tms)|'. 'j(?:a(?:bber|r)|ms)|'. 'keyparc|'. 'l(?:astfm|daps?|vlt)|'. 'm(?:a(?:gnet|il(?:server|to)|ps|rket)|essage|i(?:crosoft.windows.camera(?:.(?:multi)?picker)?|d)|ms|'. 'o(?:dem|ngodb|z)|s(?:-(?:access|browser-extension|drive-to|e(?:nrollment|xcel)|'. 'g(?:am(?:ebarservices|ingoverlay)|etoffice)|help|in(?:fopath|putapp)|'. 'lockscreencomponent-config|m(?:edia-stream-id|ixedrealitycapture)|officeapp|p(?:eople|roject|'. 'owerpoint|ublisher)|restoretabcompanion|s(?:e(?:arch-repair|condary-screen-(?:controller|setup)|'. 'ttings(?:-(?:airplanemode|bluetooth|c(?:amera|ellular|loudstorage|onnectabledevices)|'. 'displays-topology|emailandaccounts|l(?:anguage|oc(?:ation|k))|n(?:fctransactions|otifications)|'. 'p(?:ower|r(?:ivacy|oximity))|screenrotation|w(?:ifi|orkplace)))?)|pd|ttoverlay)|transit-to|'. 'useractivityset|v(?:irtualtouchpad|isio)|w(?:alk-to|hiteboard(?:-cmd)?|ord))|nim|rps?)|tqp|'. 'u(?:mble|pdate)|vn)|'. 'n(?:ews|fs|ih?|ntp|otes)|'. 'o(?:cf|id|nenote(?:-cmd)?|paquelocktoken)|'. 'p(?:a(?:ck|lm|parazzi)|kcs11|latform|op|r(?:es|o(?:spero|xy))|wid|syc)|'. 'q(?:b|uery)|'. 'r(?:e(?:diss?|load|s(?:ource)?)|mi|sync|t(?:mf?p|sp[su]?))|'. 's(?:e(?:condlife|rvice|ssion)|ftp|gn|http|i(?:eve|ps?)|kype|m(?:b|s|tp)|n(?:ews|mp)|o(?:ap.beeps?|'. 'ldat)|p(?:iffe|otify)|sh|t(?:eam|uns?)|ubmit|vn)|'. 't(?:ag|e(?:amspeak|l(?:iaeid|net)?)|ftp|hi(?:ngs|smessage)|ip|n3270|ool|urns?|v)|'. 'u(?:dp|nreal|rn|t2004)|'. 'v(?:-event|e(?:mmi|ntrilo)|ideotex|nc|iew-source)|'. 'w(?:ais|ebcal|pid|ss?|tai|yciwyg)|'. 'x(?:con(?:-userid)?|fire|m(?:lrpc.beeps?|pp)|ri)|'. 'ymsgr|'. 'z39.50[rs]?'. '):\/\//'); ``` Note the code contains the full list of schemes from IANA, not my original subset. Upvotes: 1
2018/03/20
718
2,994
<issue_start>username_0: We have code similar to the following in our app ``` val pendingIntent = PendingIntent.getActivity(ctx, id.toInt(), intent, PendingIntent.FLAG_CANCEL_CURRENT) val builder = NotificationCompat.Builder(ctx, Channel.TEST_CHANNEL.channelId) builder.setTicker(tickerText) .setContentTitle(contentTitle) .setContentText(contentText) .setVibrate(vibrate) .setSmallIcon(icon) .setAutoCancel(true) .setLights(-0xff0100, 300, 1000) .setSound(uri) .setContentIntent(pendingIntent) .setStyle(NotificationCompat.BigTextStyle().bigText(contentText)) .addAction(R.drawable.ic_notification, ctx.getString(R.string.notification), piAction) val notification = builder.build() val nf = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager nf.notify(NOTIFICATION_TAG, id.toInt(), notification) } ``` Starting recently we noticed that notifications on some device running Android 8+ started disappearing briefly after being shown, without user's interaction. Setting `auto-cancel` to `false` helps, but the user experience degrades. The `id` is a unique item id from the database. This may be important thing to note - technically we can have a notification with such `id` be shown, removed/canceleld by user, and later some time used again for a similar notification with the same id. Can this be the reason?<issue_comment>username_1: Only thing I found uncertain is **NotificationCompat.Builder** Android oreo now uses **Notification.Builder** instead of **NotificationCompat.Builder**. Might be you have to check android version like: ``` if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //Use Notification.Builder } else { // Use NotificationCompat.Builder. } ``` I don't think unique id will be an issue for disappearing notification. Google has created open source sample for this new changes. Please refer to it for more info. <https://github.com/googlesamples/android-NotificationChannels> Upvotes: -1 <issue_comment>username_2: We've updated the support libs and tried the following method on builder for luck: ``` builder.setTicker(tickerText) ... .setTimeoutAfter(-1) ... ``` Setting this param to a positive value delayed the notification disappearing by that amount of time (so it did affect). Thus we tried a negative number, the notifications seem to stay there now. *I couldn't find any reasonable documentation explaining this, so this answer is not 100%, but keeping it here for now for others to try and see if it helps them*. Upvotes: 1 <issue_comment>username_3: .setAutoCancel(false) May be it will work for you. Upvotes: -1 <issue_comment>username_4: Disable your application from auto optimize from battery optimization setting in android OREO. Notification will stay as long as you want Upvotes: 0
2018/03/20
411
1,695
<issue_start>username_0: ``` int number; // In some process wait(&number); ``` Im doing a wait call on a process and want to know if this is safe or will I get undefined behavior?.<issue_comment>username_1: Only thing I found uncertain is **NotificationCompat.Builder** Android oreo now uses **Notification.Builder** instead of **NotificationCompat.Builder**. Might be you have to check android version like: ``` if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //Use Notification.Builder } else { // Use NotificationCompat.Builder. } ``` I don't think unique id will be an issue for disappearing notification. Google has created open source sample for this new changes. Please refer to it for more info. <https://github.com/googlesamples/android-NotificationChannels> Upvotes: -1 <issue_comment>username_2: We've updated the support libs and tried the following method on builder for luck: ``` builder.setTicker(tickerText) ... .setTimeoutAfter(-1) ... ``` Setting this param to a positive value delayed the notification disappearing by that amount of time (so it did affect). Thus we tried a negative number, the notifications seem to stay there now. *I couldn't find any reasonable documentation explaining this, so this answer is not 100%, but keeping it here for now for others to try and see if it helps them*. Upvotes: 1 <issue_comment>username_3: .setAutoCancel(false) May be it will work for you. Upvotes: -1 <issue_comment>username_4: Disable your application from auto optimize from battery optimization setting in android OREO. Notification will stay as long as you want Upvotes: 0
2018/03/20
857
3,248
<issue_start>username_0: I'm trying to style the card header on a bootstrap 4 accordion, but I can't seem to override the preset class style. I want to change `.btn-link` so that it is not underlined when active or when visited, but `.btn-link:active` and `.btn-link:visited` don't seem to change anything in the output, and I can't work out why. Is it because I need to change the bootstrap css code itself? I'm doing this in CodePen so I don't have access to that from there. If anyone has encountered this problem before, I'd be glad to hear from you! Here is the link to the pen in CodePen: <https://codepen.io/jreecebowman/full/dmpLRp/> (the accordion is in the 'products' section. Otherwise, the code is below. Thanks in advance! html for the first card in the accordion: ``` ##### Collapsible Group Item #1 Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica... ``` corresponding css: ``` #products { padding-top:100px; min-height:100%; position:relative; background-color:whitesmoke; #accordion1, #accordion2 { box-shadow:0px 0px 5px 0px lightgray; #headingOne { .btn-link { color:navy; opacity:0.8; } .btn-link:hover { opacity:1.0; text-decoration:none; } .btn-link:active { text-decoration:none; } .btn-link:visited { text-decoration:none !important; } } } ``` }<issue_comment>username_1: Only thing I found uncertain is **NotificationCompat.Builder** Android oreo now uses **Notification.Builder** instead of **NotificationCompat.Builder**. Might be you have to check android version like: ``` if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //Use Notification.Builder } else { // Use NotificationCompat.Builder. } ``` I don't think unique id will be an issue for disappearing notification. Google has created open source sample for this new changes. Please refer to it for more info. <https://github.com/googlesamples/android-NotificationChannels> Upvotes: -1 <issue_comment>username_2: We've updated the support libs and tried the following method on builder for luck: ``` builder.setTicker(tickerText) ... .setTimeoutAfter(-1) ... ``` Setting this param to a positive value delayed the notification disappearing by that amount of time (so it did affect). Thus we tried a negative number, the notifications seem to stay there now. *I couldn't find any reasonable documentation explaining this, so this answer is not 100%, but keeping it here for now for others to try and see if it helps them*. Upvotes: 1 <issue_comment>username_3: .setAutoCancel(false) May be it will work for you. Upvotes: -1 <issue_comment>username_4: Disable your application from auto optimize from battery optimization setting in android OREO. Notification will stay as long as you want Upvotes: 0
2018/03/20
537
2,063
<issue_start>username_0: ``` if open(file1).read() == open(file2).read(): print('match') ``` Do I need to close these files after comparing them? I know I need to when doing the following, but is this different? ``` target = open(file1) ```<issue_comment>username_1: **Yes you do**. You could also use the `with` keyword to open each file individually and get the contents to compare them. This will handle closing the file pointer for you when it leaves the scope. In your case, this would look like the following: ``` with open(file1, 'r') as f: content1 = f.read() with open(file2, 'r') as f: content2 = f.read() if content1 == content2: print('match') ``` And is explained further here: <https://docs.python.org/2/tutorial/inputoutput.html> Upvotes: 1 <issue_comment>username_2: In both cases you describe (named or unnamed file objects), failing to explicitly `close` the file will work (mostly) deterministically on the reference interpreter, known as CPython (since it is reference counted), but behave non-deterministically on alternate interpreters (almost all of which are garbage collected, not reference counted, so the cleanup may not happen, or may be delayed arbitrarily). Even when assigning to a name like `target`, on CPython, the implicit close will usually occur as soon as the function in question returns (barring the open file becoming involved in a reference cycle which can delay the cleanup indefinitely). Best practice is to always use `with` statements, whether or not you would have assigned to a name, to get guaranteed deterministic cleanup on all Python interpreters: ``` with open(file1) as f1, open(file2) as f2: if f1.read() == f2.read(): print('match') ``` You still don't need to call `close` here, because the `with` statement guarantees that anything shy of a hard exit from the interpreter (e.g. by calling `os._exit` or triggering a segfault) will close the files when the flow of execution leaves the `with` block (by `return`ing, by an exception bubbling out, etc.). Upvotes: 3
2018/03/20
346
1,145
<issue_start>username_0: I can create a BQ view by calling client.create\_table but I could not find a way to update the SQL of the view. To create: ``` table = bigquery.Table(table_ref) table.view_query = view_query client.create_table(table) ``` To update? (does not work) ``` table = client.get_table(table_ref) table.view_query = view_query client.update_table(table, []) ``` Thoughts?<issue_comment>username_1: I used CREATE OR REPLACE VIEW statement. ``` job = client.query('CREATE OR REPLACE VIEW `{}.{}.{}` AS {}'.format(client.project, dataset, view_name, view_query)) job.result() ``` Upvotes: 1 <issue_comment>username_2: The second argument to `update_table` is a list of fields to update in the API. By passing an empty list you are saying: don't update anything. Instead, pass in `['view_query']` as the update properties list. ``` table = client.get_table(table_ref) table.view_query = view_query client.update_table(table, ['view_query']) ``` Or as Elliot suggested in the comments, you can use [DDL](https://cloud.google.com/bigquery/docs/data-definition-language) to do this operation. Upvotes: 3 [selected_answer]
2018/03/20
451
1,599
<issue_start>username_0: I have a unit test with a test-specific settings file, which includes: ``` EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' EMAIL_FILE_PATH = '/my/file/path' ``` This wasn't working, so I dropped into the debugger to check the settings in the middle of running my test: ``` ipdb> from django.conf import settings ipdb> settings.EMAIL_BACKEND 'django.core.mail.backends.locmem.EmailBackend' ipdb> settings.EMAIL_FILE_PATH '/my/file/path' ``` The file path setting worked, but the backend setting didn't! Does anyone know why? What else could I check/configure? Is this something for a bug report? Django 1.11<issue_comment>username_1: Follow this example to override the settings in your tests: <https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.SimpleTestCase.settings> Upvotes: 0 <issue_comment>username_2: This is documented behaviour. Django replaces the regular email backend with a dummy one. You then access the "sent" emails in your tests with `mail.outbox`. [See the docs](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#email-services) for more info. I believe you might be able to override the `EMAIL_BACKEND` for a single test or testcase with [`override_settings`](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.override_settings) ``` from django.test import TestCase, override_settings class MyTest(TestCase): @override_settings(EMAIL_BACKEND='django.core.mail.backends.filebased.EmailBackend') def test_email(self): ... ``` Upvotes: 3 [selected_answer]
2018/03/20
531
1,881
<issue_start>username_0: Update. Here is my code. I am importing 400 csv files into 1 list. Each csv file is 200 rows and 5 columns. My end goal is to sum the values from the 4th column of each row or each csv file. The below code imports all the csv files. However, I am struggling to isolate 4th column of data from each csv file from the large list. ``` for i in range (1, 5, 1): data = list() for i in range(1,400,1): datafile = 'particle_path_%d' % i data.append(np.genfromtxt(datafile, delimiter = "", skip_header=2)) print datafile ``` I want to read 100 csv files into 100 different arrays in python. For example: array1 will have csv1 array2 will have csv2 etc etc. Whats the best way of doing this? I am appending to a list right now but I have one big list which is proving difficult to split into smaller lists. My ultimate goal is to be able to perform different operations of each array (add, subtract numbers etc)<issue_comment>username_1: Follow this example to override the settings in your tests: <https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.SimpleTestCase.settings> Upvotes: 0 <issue_comment>username_2: This is documented behaviour. Django replaces the regular email backend with a dummy one. You then access the "sent" emails in your tests with `mail.outbox`. [See the docs](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#email-services) for more info. I believe you might be able to override the `EMAIL_BACKEND` for a single test or testcase with [`override_settings`](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.override_settings) ``` from django.test import TestCase, override_settings class MyTest(TestCase): @override_settings(EMAIL_BACKEND='django.core.mail.backends.filebased.EmailBackend') def test_email(self): ... ``` Upvotes: 3 [selected_answer]
2018/03/20
1,381
5,445
<issue_start>username_0: I'm trying to setup Room database backup functionality. Problem is that sql database file doesn't contain latest set of data in the app once downloaded. It always misses some most recent records. Is there a proper way to export room database? P.S. I didn't face similar problems when handled my db with sqliteHelper, so I suppose it must have something to do with Room. Way I'm doing it: ``` @Throws(IOException::class) private fun copyAppDbToDownloadFolder(address: String) { val backupDB = File(address, "studioDb.db") val currentDB = applicationContext.getDatabasePath(StudioDatabase.DB_NAME) if (currentDB.exists()) { val src = FileInputStream(currentDB).channel val dst = FileOutputStream(backupDB).channel dst.transferFrom(src, 0, src.size()) src.close() dst.close() } } ```<issue_comment>username_1: I've solved it. When exporting (saving) sql database which you handle with Room, you have to export(and later import) both - your\_database.bd and your\_database.wal files. Later is a journal and afaiu keeps latest records. Upvotes: 3 [selected_answer]<issue_comment>username_2: I had same issue. you don't need to copy wal (write ahead log file) it's a temporary file. According to [documentation](https://www.sqlite.org/tempfiles.html) we need to close all connection to database before importing or exporting database. This solved my problem and now i have to copy only main database file. Example of database class: ``` public abstract class AppDB extends RoomDatabase { private static final Object sLock = new Object(); private static AppDB INSTANCE; // create new database connection public static AppDB getInstance(final Context context) { synchronized (sLock) { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder(context.getApplicationContext(), AppDB.class, "packagename") .build(); } return INSTANCE; } } // close database public static void destroyInstance(){ if (INSTANCE.isOpen()) INSTANCE.close(); INSTANCE = null; } } ``` Upvotes: 3 <issue_comment>username_3: You need to use > > JournalMode.TRUNCATE > > > in your AppDatabase.java: ``` private static AppDatabase sInstance; public static AppDatabase getDatabase(final Context context) { if (sInstance == null) { synchronized (AppDatabase.class) { if (sInstance == null) { sInstance = Room.databaseBuilder(context, AppDatabase.class, DATABASE_NAME) .setJournalMode(JournalMode.TRUNCATE) .build(); } } } return sInstance; } ``` This method will not create **db.bad** and **db.wal** files that's creating hindrance in exporting room db. ***For exporting the DB file:*** > > Link: [Exporting db with creating folder on daily basis](https://stackoverflow.com/questions/6540906/simple-export-and-import-of-a-sqlite-database-on-android/53167018#53167018) > > > Upvotes: 4 <issue_comment>username_4: kotlin:This works for me ``` private fun exportDb() { val TABLE_NAME = "order_table" val exportDir = File(getExternalStorageDirectory(), "/CSV")// your path where you want save your file if (!exportDir.exists()) { exportDir.mkdirs() } val file = File(exportDir, "$TABLE_NAME.csv") try { file.createNewFile() val db: MenuItemsDatabase = MenuItemsDatabase.getDatabase(requireActivity()) val csvWrite = CSVWriter(FileWriter(file)) val curCSV: Cursor = db.query("SELECT * FROM order_table", null) csvWrite.writeNext(curCSV.getColumnNames()) while (curCSV.moveToNext()) { //Which column you want to exprort val arrStr = arrayOfNulls(curCSV.getColumnCount()) for (i in 0 until curCSV.getColumnCount() - 1) arrStr[i] = curCSV.getString(i) csvWrite.writeNext(arrStr) } csvWrite.close() curCSV.close() Toast.makeText(context, "Exported", Toast.LENGTH\_SHORT).show() } catch (sqlEx: java.lang.Exception) { //Log.e("Payment fragment", "Exported error", sqlEx) Toast.makeText(context, "Exported error", Toast.LENGTH\_SHORT).show() } } ``` Upvotes: 2 <issue_comment>username_5: **I had the same problem and I solved it by copying the 3 files that are generated. I work correctly. And the same is done to import.** ``` copyDataFromOneToAnother(application.getDatabasePath(AppDatabase.DATABASE_NAME).absolutePath, Environment.getExternalStorageDirectory().toString() + "/DATABASE_NAME.db") copyDataFromOneToAnother(application.getDatabasePath(AppDatabase.DATABASE_NAME).absolutePath + "-shm", Environment.getExternalStorageDirectory().toString() + "/DATABASE_NAME.db" + "-shm") copyDataFromOneToAnother(application.getDatabasePath(AppDatabase.DATABASE_NAME).absolutePath + "-wal", Environment.getExternalStorageDirectory().toString() + "/DATABASE_NAME" + "-wal") ``` ``` private fun copyDataFromOneToAnother(fromPath: String, toPath: String) { val inStream = File(fromPath).inputStream() val outStream = FileOutputStream(toPath) inStream.use { input -> outStream.use { output -> input.copyTo(output) } } } ``` Upvotes: 0
2018/03/20
636
2,140
<issue_start>username_0: [![enter image description here](https://i.stack.imgur.com/0jhyK.png)](https://i.stack.imgur.com/0jhyK.png) I am working on an auction script with a table that looks like the attached image. Within an auction two users can place the same bid amount, for example two players could place a bid of '1' which would give that bid amount a total count of two. I need a query which gets all of a users single bid amount along with the total count of that bid amount within the scope of the auction id. As it stands I first get the users bids: ``` SELECT bid_amount FROM all_bids WHERE auction_id = '129' AND user_id = '9' ``` And then I am looping through each amount in PHP and doing the following ``` SELECT COUNT(*) FROM all_bids WHERE auction_id = '129' AND bid_amount = 'xxx' ``` But this is of course very power hungry and I am sure it can be done all in one query. I have got as far as ``` SELECT bid_amount,COUNT(*) FROM (SELECT bid_amount FROM all_bids WHERE auction_id = '129' AND user_id ='9') as foo GROUP BY bid_amount ``` Which returned the correct bid amounts but the counts were all **1** which is wrong as I guess my incorrect query is only counting the values within the subquery and not outside of the bids that just that user placed<issue_comment>username_1: ``` SELECT a.*, b.cnt from all_bids a join (select bid_amount,COUNT(*) cnt from all_bids group by bid_amount) b on a.bid_amount=b.bid_amount WHERE a.auction_id = '123' AND a.player_id = '456' ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: I think you want `group by`: ``` select bid_amount, count(*) from all_bids where auction_id = 123 and player_id = 456 group by bid_amount; ``` Note that you do not need single quotes for a numeric constant. Hmmm. You might want this phrased as: ``` select ab.bid_amount, count(*) from all_bids ab where ab.auction_id = 123 and ab.bid_amount in (select ab2.bid_amount from all_bids ab2 where ab2.auction_id = ab.auction_id and ab2.player_id = 456 ) group by ab.bid_amount; ``` Upvotes: 0
2018/03/20
572
1,963
<issue_start>username_0: In my application one of third party API returning timestamp in epoch. Sometime it returns epoch time in seconds and sometime in miliseconds not confirmed. My application using below code to convert it to java date and display to user but when I am receiving time in miliseconds it is failing on year. ``` String time = "1519377196185"; //Time in miliseconds //String time = "1521575819"; //Time in seconds. String timeZone = "US/Pacific"; long epochdate = Long.parseLong(time); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy hh:mm a"); LocalDateTime date34 = Instant.ofEpochSecond(epochdate) .atZone(ZoneId.of(timeZone)) .toLocalDateTime(); String date = date34.format(formatter).toString(); System.out.println("date : " + date); ``` if I use `Instant.ofEpochMilli(epochdate)` for miliseconds then it is working fine. So my question is how I can know that coming timestamp is in miliseconds or seconds so on that basis I will switch between `ofEpochMilli` and `ofEpochSecond`<issue_comment>username_1: ``` SELECT a.*, b.cnt from all_bids a join (select bid_amount,COUNT(*) cnt from all_bids group by bid_amount) b on a.bid_amount=b.bid_amount WHERE a.auction_id = '123' AND a.player_id = '456' ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: I think you want `group by`: ``` select bid_amount, count(*) from all_bids where auction_id = 123 and player_id = 456 group by bid_amount; ``` Note that you do not need single quotes for a numeric constant. Hmmm. You might want this phrased as: ``` select ab.bid_amount, count(*) from all_bids ab where ab.auction_id = 123 and ab.bid_amount in (select ab2.bid_amount from all_bids ab2 where ab2.auction_id = ab.auction_id and ab2.player_id = 456 ) group by ab.bid_amount; ``` Upvotes: 0
2018/03/20
1,320
3,160
<issue_start>username_0: All, I have a dataframe with Dates on the first column and categories across as such: ``` Accounts <- c('A','B','C','D', 'A','B','C','D', 'A','B','C','D') Dates <- as.Date(c('2016-01-31', '2016-01-31','2016-01-31','2016-01-31', '2016-02-28','2016-02-28','2016-02-28','2016-02-28', '2016-03-31','2016-03-31','2016-03-31','2016-03-31')) Balances <- c(100,NA,NA,NA, 90,50,10,NA, 80,40,5,120) Origination <- data.frame(Dates,Accounts,Balances) library(reshape2) Origination <- dcast(Origination,Dates ~ Accounts, value.var = "Balances") Dates A B C D 1 2016-01-31 100 NA NA NA 2 2016-02-28 90 50 10 NA 3 2016-03-31 80 40 5 120 ``` The goal is to sum rows where the prior values is NA. I tried to used lag or shift but don't have the knowledge to pull it off. So for this dataframe I would like a Totals column at the end it values 60 (50 + 10) and 120 for February and March. Is this doable? Regards, Aksel<issue_comment>username_1: Shift the selection down a row, filter out all the non-NA's as 0, and then use `rowSums`: ``` sel <- rbind(FALSE, !is.na(head(Origination[-1], -1))) #sel # A B C D #[1,] FALSE FALSE FALSE FALSE #[2,] TRUE FALSE FALSE FALSE #[3,] TRUE TRUE TRUE FALSE rowSums(replace(Origination[-1], sel, 0), na.rm=TRUE) #[1] 100 60 120 ``` If you want the first row to be totally excluded, rather than totally included, just change the `FALSE` to `TRUE`: ``` sel <- rbind(TRUE, !is.na(head(Origination[-1], -1))) rowSums(replace(Origination[-1], sel, 0), na.rm=TRUE) #[1] 0 60 120 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: username_1's solution looks great. however, if you want to avoid printing total value of January, try this ``` Origination.matrix.select<-rbind(F,is.na(Origination[-1]))[-4,] Total<-rowSums(as.matrix(Origination[,2:5])*Origination.matrix.select,na.rm=T) Total # [1] 0 60 120 ``` Upvotes: 2 <issue_comment>username_3: One option is to continue the chain form `reshape2::dcast` and use `dplyr::mutate_at` to find desired output. ``` library(tidyverse) library(reshape2) Origination %>% dcast(Dates~Accounts, value.var = "Balances" ) %>% mutate_at(vars(c("A","B","C","D")), funs(ifelse(!is.na(lag(.)), NA, (.)))) %>% mutate(sum = rowSums(select(.,-Dates), na.rm = TRUE)) %>% select(Dates, sum) # Dates sum # 1 2016-01-31 100 # 2 2016-02-28 60 # 3 2016-03-31 120 ``` Note: `row_number()==1` condition should be added part of `ifelse` in `mutate_at` if sum for `January` is expected as `0`. **Data** ``` Accounts <- c('A','B','C','D', 'A','B','C','D', 'A','B','C','D') Dates <- as.Date(c('2016-01-31', '2016-01-31','2016-01-31','2016-01-31', '2016-02-28','2016-02-28','2016-02-28','2016-02-28', '2016-03-31','2016-03-31','2016-03-31','2016-03-31')) Balances <- c(100,NA,NA,NA, 90,50,10,NA, 80,40,5,120) Origination <- data.frame(Dates,Accounts,Balances) ``` Upvotes: 1
2018/03/20
1,224
4,463
<issue_start>username_0: An Apollo server is setup, and it responds correctly to the query when using graphiql. An existing react-redux app with server side rendering needs to start using graphql and make this query. A component of this app has been setup to do the same query, it seems to be doing the network request, but it fails with ``` Error: {"graphQLErrors":[],"networkError":{},"message":"Network error: Failed to fetch"} ``` Any troubleshooting advice?<issue_comment>username_1: I was running apollo client on localhost, and apollo server on someDomain.com, so it was a CORS issue. After loading the page that does the query in chrome incognito mode and refreshing, this error was found in the chrome dev tools console: ``` httpLink.js:71 OPTIONS https://someDomain.com/graphql 405 (Method Not Allowed) (anonymous) @ httpLink.js:71 ... (index):1 Failed to load https://someDomain.com/graphql: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:8443' is therefore not allowed access. The response had HTTP status code 405. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. ``` A quick fix for this (test only) setup was to setup cors on the express apollo server like this post suggests. <https://blog.graph.cool/enabling-cors-for-express-graphql-apollo-server-1ef999bfb38d> Upvotes: 2 <issue_comment>username_2: It really is cors issue. I tried to fix it by using express. But it didn't work with Apollo GraphQL. ```js const corsOptions = { origin: "http://localhost:3000", credentials: true }; app.use(cors(corsOptions)); ``` So, I tried configuring cors inside GraphQL server and It Worked. **For Apollo Server** ```js const corsOptions = { origin: "http://localhost:3000", credentials: true }; const server = new ApolloServer({ typeDefs, resolvers, cors: corsOptions }); server.listen().then(({ url }) => { console.log(` Server ready at ${url}`); }); ``` **For GraphQL Yoga** ```js const options = { cors: corsOptions }; server.start(options, () => console.log("Server is running on http://localhost:4000") ); ``` Upvotes: 3 <issue_comment>username_3: You can have this error as well if you pass a `null` HEADER in your request through Apollo, so something like: ``` const middlewareLink = setContext(() => ({ headers: { 'authorization': `Bearer ${FeedierExchanger.token}` || null } })); ``` Change it to: ``` const middlewareLink = setContext(() => ({ headers: { 'authorization': `Bearer ${FeedierExchanger.token}` || '' } })); ``` Or remove this part: ``` || '' ``` If you've the correct backend validation. Upvotes: -1 <issue_comment>username_4: All you need to do to make the following work is to enable cors library for your Apollo-Graphql server ``` yarn add cors / npm install cors ``` Now got to you app.js or server.js ( Basically the entry file of your server ) add the following lines to it > > const cors = require('cors'); > > > app.use(cors()); // Make sure you have express initialised before this. > > > Upvotes: 2 <issue_comment>username_5: Try using the cors middleware at the top of your code. This initializes the cross-origin resource sharing first before the graphql endpoint is created. ```js enter const { urlencoded } = require("express"); const express = require("express"); const app = express(); //create an express application const helmet = require("helmet"); //require helment from node modules const cors = require("cors"); //cross-origin-resource sharing const mR = require("./routes/main"); const schema = require("./graph-schema/schema"); const mongoose = require("mongoose"); //cross-origin-resources-sharing defined at the top before your graphql endpoint app.use( cors({ optionsSuccessStatus: 200, //option sucess status origin: "http://localhost:3000", //origin allowed to access the server }) ); //connect to database mongoose.connect("mongodb://localhost:27017/Graphql_tutorial", { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, }); //graphql area const { graphqlHTTP } = require("express-graphql"); //This allows express to understand graphql and lunch its api. app.use( "/graphql", graphqlHTTP({ schema, graphiql: true, }) );//code here ``` Upvotes: 0
2018/03/20
355
1,268
<issue_start>username_0: According to [the MDN docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values) the following javascript is valid: ``` const o = {foo: 1, bar: 'baz'} console.log(Object.values(o)); ``` and indeed if I run this code in the Firefox developer tools console, I get the expected output: ``` Array [ 1, "baz" ] ``` But in the [REPL of node.js](https://nodejs.org/api/repl.html), I am told that `Object.values` is not a function. Although other Object constructor methods *are* present, such as `is()` and `freeze()`. Why is this, and how can I know beforehand what the node REPL supports and what it doesn't?<issue_comment>username_1: This is entirely dependent on the Node version you have installed. See <https://node.green/> for feature compatibility. <https://node.green/#ES2017-features-Object-static-methods-Object-values> Answers your specific concern. Upvotes: 2 <issue_comment>username_2: Use `node --version` before running repl, or check `process.versions` while in repl. Once the version is known, you can checkout <http://node.green> and you will know exactly what to expect. We can guess you're running Node < 7.x, you may want to upgrade to latest LTS. Upvotes: 1 [selected_answer]
2018/03/20
782
2,674
<issue_start>username_0: How to export data frames which are created in google colab to your local machine? I have cleaned a data set on google colab. Now I want to export the data frame to my local machine. `df.to_csv` is saving file to the virtual machine and not my local machine.<issue_comment>username_1: Try this ``` from google.colab import files files.download("data.csv") ``` Update(Sep 2018): now it's even easier * open the left pane * select 'Files' tab * click 'Refresh' * right click the file, then download Update (Jan 2020): the UI changes * click on the `folder icon` on the left pane (3rd icon) * click 'Refresh' * right click the file, then download Upvotes: 6 <issue_comment>username_2: You can download the csv to your associated google drive. First you must install PyDrive. ``` !pip install -U -q PyDrive from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from google.colab import files from oauth2client.client import GoogleCredentials auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) ``` This will generate a token in a browser for you to then paste into an input box that will be shown in your notebook. Save your pandas data frame `df.to_csv('mydataframe.csv', sep='\t')` To keep things neat you can create a new folder in your drive and then use the following: `file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList() for file1 in file_list: print('title: %s, id: %s' % (file1['title'], file1['id']))` which will list the files and folders in your google drive and their id that you will need for the following step. `file = drive.CreateFile({'parents':[{u'id': '`*id of folder you want to save in*`'}]}) file.SetContentFile("mydataframe.csv") file.Upload()` It will now be in your google drive in the given folder. Upvotes: 1 <issue_comment>username_3: Try this: First you can save the file using pandas `to_csv` functionality later on you can download that file using google colab files functionality. ``` from google.colab import files df.to_csv('filename.csv') files.download('filename.csv') ``` Upvotes: 6 <issue_comment>username_4: > > ### [Downloading files to your local file system](https://colab.research.google.com/notebooks/snippets/drive.ipynb#scrollTo=hauvGV4hV-Mh) > > > `files.download` will invoke a browser download of the file to your local computer. > > > > ```py > from google.colab import files > > with open('example.txt', 'w') as f: > f.write('some content') > > files.download('example.txt') > > ``` > > Upvotes: 2
2018/03/20
583
2,027
<issue_start>username_0: I'm developing a file tree. With the code I have now I can only show and hide all the directories on the tree, it doesn't matter which node I click. I need to be able to maintain the same class name but only show/hide the element I click on. Check the code snippet please. ```js function init_php_file_tree() { $(this).on('click', function() { $(this).toggleClass('closed'); $('.pft-directory ul').toggle(); }); }; jQuery(init_php_file_tree); ``` ```html * [Parent directory](#) + File Name + Another File Name + Directory Name + Another Directory Name * [Parent directory](#) + File Name + Another File Name + Directory Name + Another Directory Name ```<issue_comment>username_1: You can change your code look like this ``` $('.pft-directory ul').toggle(); => $(this).find("ul").toggle(); ``` Upvotes: 0 <issue_comment>username_2: You need to select the correct elements `.pft-directory` and use the function `children` to show/hide the `ul` elements. ``` +-- Correct selector | v $('.pft-directory').on('click', function() { $(this).toggleClass('closed'); $(this).children('ul').toggle(); ^ | +---- Get the 'ul' elements }); ``` ```js function init_php_file_tree() { $('.pft-directory').on('click', function() { $(this).toggleClass('closed'); $(this).children('ul').toggle(); }); }; jQuery(init_php_file_tree); ``` ```html * [Parent directory](#) + File Name + Another File Name + Directory Name + Another Directory Name * [Parent directory](#) + File Name + Another File Name + Directory Name + Another Directory Name ``` Upvotes: 1 <issue_comment>username_3: Can you change your code a bit to target specific element like the one below? ```js function init_php_file_tree() { $('.pft-directory') .on('click', function() { $(this).children('ul').toggle(); }) .children("ul").hide(); }; jQuery(init_php_file_tree); ``` Upvotes: 1 [selected_answer]
2018/03/20
777
2,985
<issue_start>username_0: I have a visual studio package that does not write all the data needed to a blank excel file. More specifically, the package goes through these steps: 1. Copies a template excel file to overwrite a shell file. 2. Connects to a SQL DB. 3. Runs a Select Statement. 4. Converts one column to unicode. 5. Pastes to shell file. There are a few more steps afterward (like emailing the excel file) but those work fine. The issue comes up for step 4. when Visual Studio or SSIS runs the package, I pull about 1400 rows. When I just run the select statement in SQL Server Management Studio or as a connection in Excel I pull about 2800 rows. 2800 is the right number. I've tried building the process from scratch (excel files, connection files, etc.) but that rebuild elicits the same result. It's like Visual Studio just doesn't like the select statement. Double checked the mappings - all good. The data is pasting and being delivered fine, just not enough. No errors on visual studio either - it gives me that lovely (albeit confusing) check mark. This was running as an automated package for about a year before this happened and I have no explanation. Seriously a headscratcher. The only other clue I have is that when I pull the data manually with the select statement, there are no null values in a particular column, but when I run the package with that exact same select statement the output contains a null in the referenced column - almost as if the select statement in Visual Studio is pulling slightly different data than the manual pull, but the statements are exactly the same, so I don't know why that would be. Any ideas?<issue_comment>username_1: You can change your code look like this ``` $('.pft-directory ul').toggle(); => $(this).find("ul").toggle(); ``` Upvotes: 0 <issue_comment>username_2: You need to select the correct elements `.pft-directory` and use the function `children` to show/hide the `ul` elements. ``` +-- Correct selector | v $('.pft-directory').on('click', function() { $(this).toggleClass('closed'); $(this).children('ul').toggle(); ^ | +---- Get the 'ul' elements }); ``` ```js function init_php_file_tree() { $('.pft-directory').on('click', function() { $(this).toggleClass('closed'); $(this).children('ul').toggle(); }); }; jQuery(init_php_file_tree); ``` ```html * [Parent directory](#) + File Name + Another File Name + Directory Name + Another Directory Name * [Parent directory](#) + File Name + Another File Name + Directory Name + Another Directory Name ``` Upvotes: 1 <issue_comment>username_3: Can you change your code a bit to target specific element like the one below? ```js function init_php_file_tree() { $('.pft-directory') .on('click', function() { $(this).children('ul').toggle(); }) .children("ul").hide(); }; jQuery(init_php_file_tree); ``` Upvotes: 1 [selected_answer]
2018/03/20
201
668
<issue_start>username_0: I'm using an `onclick` event to call a JS function from PHP. Here is my code: I'm inside a function so I need to do it via PHP, because then I do a return: ``` $html = ''; return $html; ``` My JS: ``` function setGetSku(sku) { //Gettng error here var conf = confirm("Are you sure?"); if (conf == true) { .... my code... } } ```<issue_comment>username_1: Just add quote ....onclick="setGetSku("'.$row['sku'].'")"... Upvotes: 1 <issue_comment>username_2: Ok i have fixed, in case someone is looking for the same this is the answer, you need to pass an string using quote in my case: ``` $html = ' ``` Upvotes: 0
2018/03/20
1,328
3,348
<issue_start>username_0: This is more of a curiosity Say I have the following code ``` >>> my_immutable = (1, 2) >>> my_immutable[0] += 1 TypeError: 'tuple' object does not support item assignment ``` This is expected, because unlike C, Python does not modify the underlying int, but rather creates a new one (observed in the code below) ``` >>> x = 1 >>> id(x) 33156200 >>> x += 1 >>> id(x) 33156176 ``` If I want to modify the underlying integer in the tuple, I can hackly do something like ``` >>> hacked_immutable = ([1], [2]) >>> hacked_immutable[0][0] += 1 >>> hacked_immutable ([2], [2]) ``` My question is: is there a nicer way of doing it (ideally performant and ideally already in the standard library)? Some wrapper class around int maybe? Edit: I did not have a specific software that had to adhere to this. It was more of a thought exercise of why are things like this. I think the three questions I had were: * Why are `int`s immutable? (still not sure) * Is there a way to force them to be mutable? (wim's answer) * Is there a nice way to force them to be mutable (like `Integer` vs `int` in Java) - I think the answer is NO? Thanks a lot for the discussion!<issue_comment>username_1: Use a list rather than a tuple: ``` my_container = [1, 2] ``` `tuple` is immutable - you can't modify them. `int` is immutable - you can't modify them. The closest you can get is using [ctypes](https://docs.python.org/3/library/ctypes.html) to monkeypatch the value. But this is not "nice" by any stretch of the imagination and you will probably segfault your Python runtime if anything else happens to be using that integer. ``` >>> t = (42, 43) >>> import ctypes >>> ctypes.cast(id(42), ctypes.POINTER(ctypes.c_int))[6] = 666 >>> t (666, 43) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Here's what it looks like with your small integers: ``` >>> hacked_immutable = ([1], [2]) >>> hacked_immutable ([1], [2]) >>> id(hacked_immutable) 139813228968072 >>> id(hacked_immutable[0]) 139813228055688 >>> id(hacked_immutable[0][0]) 139813227530592 >>> id(hacked_immutable[1]) 139813228056008 >>> id(hacked_immutable[1][0]) 139813227530624 >>> >>> >>> hacked_immutable[0][0] += 1 >>> hacked_immutable ([2], [2]) >>> id(hacked_immutable) 139813228968072 >>> id(hacked_immutable[0]) 139813228055688 >>> id(hacked_immutable[0][0]) 139813227530624 >>> id(hacked_immutable[1]) 139813228056008 >>> id(hacked_immutable[1][0]) 139813227530624 ``` Note that there is only one, single `2` object. However, let's take a look with not-small integers: ``` >>> hacked_immutable = ([314159], [314160]) >>> id(hacked_immutable) 139813228056200 >>> id(hacked_immutable[0]) 139813228055688 >>> id(hacked_immutable[0][0]) 139813228644176 >>> id(hacked_immutable[1]) 139813228056008 >>> id(hacked_immutable[1][0]) 139813228644528 >>> >>> >>> hacked_immutable[0][0] += 1 >>> hacked_immutable ([314160], [314160]) >>> id(hacked_immutable[0]) 139813228055688 >>> id(hacked_immutable[0][0]) 139813229186864 >>> id(hacked_immutable[1]) 139813228056008 >>> id(hacked_immutable[1][0]) 139813228644528 ``` The Python run-time system still creates a new integer object for the first element. `314160` exists in two places. This is from caching small integers, not from any property of the implementation of im/mutable objects. Upvotes: 2
2018/03/20
1,104
2,560
<issue_start>username_0: Are there any way to multiple text wording with formula? Also how do I change the decimal to 0.00?? Thanks in advance! Current working code ``` ="Should be at " &CONCATENATE(NETWORKDAYS("3/4/2018",TODAY()-1)/35*(100)) ``` I would like to add wording after formula like this ``` ="Should be at " &CONCATENATE(NETWORKDAYS("3/4/2018",TODAY()-1)/35*(100)) "% to Goal" ```<issue_comment>username_1: Use a list rather than a tuple: ``` my_container = [1, 2] ``` `tuple` is immutable - you can't modify them. `int` is immutable - you can't modify them. The closest you can get is using [ctypes](https://docs.python.org/3/library/ctypes.html) to monkeypatch the value. But this is not "nice" by any stretch of the imagination and you will probably segfault your Python runtime if anything else happens to be using that integer. ``` >>> t = (42, 43) >>> import ctypes >>> ctypes.cast(id(42), ctypes.POINTER(ctypes.c_int))[6] = 666 >>> t (666, 43) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Here's what it looks like with your small integers: ``` >>> hacked_immutable = ([1], [2]) >>> hacked_immutable ([1], [2]) >>> id(hacked_immutable) 139813228968072 >>> id(hacked_immutable[0]) 139813228055688 >>> id(hacked_immutable[0][0]) 139813227530592 >>> id(hacked_immutable[1]) 139813228056008 >>> id(hacked_immutable[1][0]) 139813227530624 >>> >>> >>> hacked_immutable[0][0] += 1 >>> hacked_immutable ([2], [2]) >>> id(hacked_immutable) 139813228968072 >>> id(hacked_immutable[0]) 139813228055688 >>> id(hacked_immutable[0][0]) 139813227530624 >>> id(hacked_immutable[1]) 139813228056008 >>> id(hacked_immutable[1][0]) 139813227530624 ``` Note that there is only one, single `2` object. However, let's take a look with not-small integers: ``` >>> hacked_immutable = ([314159], [314160]) >>> id(hacked_immutable) 139813228056200 >>> id(hacked_immutable[0]) 139813228055688 >>> id(hacked_immutable[0][0]) 139813228644176 >>> id(hacked_immutable[1]) 139813228056008 >>> id(hacked_immutable[1][0]) 139813228644528 >>> >>> >>> hacked_immutable[0][0] += 1 >>> hacked_immutable ([314160], [314160]) >>> id(hacked_immutable[0]) 139813228055688 >>> id(hacked_immutable[0][0]) 139813229186864 >>> id(hacked_immutable[1]) 139813228056008 >>> id(hacked_immutable[1][0]) 139813228644528 ``` The Python run-time system still creates a new integer object for the first element. `314160` exists in two places. This is from caching small integers, not from any property of the implementation of im/mutable objects. Upvotes: 2
2018/03/20
393
1,272
<issue_start>username_0: I'm trying to write a program to delete leading spaces in a poorly formatted C++ program. I get this error in line 24: `cout << removeLeadingSpaces(s) << endl;`, please help. ``` #include using namespace std; string removeLeadingSpaces(string line) { bool start = false; string newline; for (int i = 0; i < line.size(); i++) { if (!isspace(line[i]) && start==false) { start = true; } if (start==true) newline += line[i]; } return newline; } void printindented() { string s; while (getline(cin, s)) cout << removeLeadingSpaces(s) << endl; } int main() { cout << printindented() << endl; } ```<issue_comment>username_1: The problematic line is ``` cout << printindented() << endl; ``` in `main`. The line ``` cout << removeLeadingSpaces(s) << endl; ``` in `printindented` is just fine. Change the line in `main` to: ``` printindented(); ``` Upvotes: 2 <issue_comment>username_2: In int main you're trying to print a function that returns `void` which is causing the error. Also you should use proper indentation and next time word your question a bit better by giving more insight into the problem. Fixed code ``` int main() { printindented(); // Can't print void cout << printindented() << endl; } ``` Upvotes: 1
2018/03/20
2,234
5,569
<issue_start>username_0: Sorry, if the title does not do this question justice, but please recommend a new title, if you have a better one. What i need to accomplish is i need to take QtyOnHand (for a given AffectedDate) / sum(IssQty) based on a range between RecDates. So if the AffectedDate = '2015-2' then i want to sum all of the IssQty where RecDate is between '2014-2' and '2015-1'. I want this type of formula for every AffectedDate row. So it can calculate on the fly, meaning it will always take the AffectedDates year and month and - 12 and then sum together the IssQty, based on the RecDate. Here are some Examples. ``` ItemKey RecDate IssQty AffectedDate QtyOnHand 20406 2014-1 751.898 2014-1 842.132 20406 2014-2 744.102 2014-2 539.03 20406 2014-5 493.847 2014-5 486.183 20406 2014-7 494.834 2014-7 1314.209 20406 2014-8 494.217 2014-8 819.992 20406 2014-9 741.017 2014-9 1401.975 20406 2014-10 889.714 2014-10 512.261 20406 2014-12 740.647 2014-12 640.19 20406 2015-2 496.068 2015-2 144.122 20406 2015-3 496.068 2015-3 530.054 20406 2015-5 370.941 2015-5 159.113 20406 2015-7 989.668 2015-7 492.19 20406 2015-8 792.228 2015-8 890.662 20406 2015-9 744.102 2015-9 1028.56 ``` 1. AffectedDate = '2015-3' so take the QtyOnHand for that AffectedDate [530.054] / Sum(IssQty) between the RecDate of '2014-03' and '2015-02' 2. AffectedDate = '2015-5' so take the QtyOnHand for that AffectedDate [159.113] / Sum(IssQty) between the RecDate of '2014-05' and '2015-04' These are examples of how i want this formula to work.<issue_comment>username_1: You could solve your issue with only one `sum` window function if you did not have gaps in your dates. So you need self join. Here is one option using `apply` ``` select *, a.QtyOnHand / c.total from myTable a outer apply ( select total = sum(IssQty) from myTable b where b.RecDate between dateadd(mm, -12, a.AffectedDate) and dateadd(mm, -1, a.AffectedDate) ) c ``` Upvotes: 0 <issue_comment>username_2: Ok, let's start at the basics first. Like Mr Bertrand said `2014-1` is not a date, it's a varchar that looks like you're saying "2014 minus 1" (which is 2013). I assume that what it's really meant to represent is the 1st month of 2014, however, if you want to store dates, store them as a `date`. you'll note that `CONVERT(date,'2014-1`) will fail. I'm not going to cover converting these values to dates, but i have HAD to do it in my sample data; maybe that'll help you. ``` CREATE TABLE #Sample (ItemKey int, RecDate date, --The source data is not a date IssQty decimal(10,3), AffectedDate date, --The sourse data is not a date QtyOnHand decimal(10,3)); INSERT INTO #Sample SELECT ItemKey, CONVERT(date,CASE LEN(RecDate) WHEN 6 THEN STUFF(RecDate,5,1,'0') + '01' WHEN 7 THEN REPLACE(RecDate,'-','') + '01' END), IssQty, CONVERT(date,CASE LEN(AffectedDate) WHEN 6 THEN STUFF(AffectedDate,5,1,'0') + '01' WHEN 7 THEN REPLACE(AffectedDate,'-','') + '01' END), QtyOnHand FROM (VALUES (20406,'2014-1',751.898,'2014-1',842.132 ), (20406,'2014-2',744.102,'2014-2',539.03 ), (20406,'2014-5',493.847,'2014-5',486.183 ), (20406,'2014-7',494.834,'2014-7',1314.209 ), (20406,'2014-8',494.217,'2014-8',819.992 ), (20406,'2014-9',741.017,'2014-9',1401.975 ), (20406,'2014-10',889.714,'2014-10',512.261), (20406,'2014-12',740.647,'2014-12',640.19 ), (20406,'2015-2',496.068,'2015-2',144.122 ), (20406,'2015-3',496.068,'2015-3',530.054 ), (20406,'2015-5',370.941,'2015-5',159.113 ), (20406,'2015-7',989.668,'2015-7',492.19 ), (20406,'2015-8',792.228,'2015-8',890.662 ), (20406,'2015-9',744.102,'2015-9',1028.56 )) V(ItemKey, RecDate, IssQty, AffectedDate, QtyOnHand); ``` Next, we're missing some months here, which is a problem, as you want the last 12 months of data. Thus we need to fill those in. I'll be using a Calendar table (you'll need to Google this, mine his called DimDate here). Then, because we have a record for every row, we can use `ROWS BETWEEN` resulting in: ``` WITH MaxMin AS( SELECT ItemKey, MIN(AffectedDate) AS MinDate, MAX(AffectedDate) AS MaxDate FROM #Sample GROUP BY ItemKey), WithNewColumn AS( SELECT MM.ItemKey, S.RecDate, S.IssQty, DD.[Date] AS AffectedDate, S.QtyOnHand, S.QtyOnHand / SUM(S.IssQty) OVER (PARTITION By MM.ItemKey ORDER BY DD.[Date] ROWS BETWEEN 13 PRECEDING AND 1 PRECEDING) AS YourNewColumn FROM MaxMin MM JOIN DimDate DD ON DD.[Date] BETWEEN MM.MinDate AND MM.MaxDate AND DD.[Calendar Day] = 1 LEFT JOIN #Sample S ON MM.ItemKey = S.ItemKey AND DD.[Date] = S.AffectedDate) SELECT * FROM WithNewColumn WHERE RecDate IS NOT NULL --eliminate the NULLs (if you want to). if not, this isn't needed, nor the CTE above ORDER BY ItemKey, AffectedDate; ``` Upvotes: 2 [selected_answer]
2018/03/20
1,038
3,749
<issue_start>username_0: I have an `onload` function within a `for` statement that is producing unexpected results. The `for` loop loops through an array of images. I'm wanting this loop to execute an `onload` for each image in the array, and only proceed to the next iteration in the `for` loop once that's done. The `onload` is waiting for an image element to load before it executes. ``` for (index = 0; index < lightboxImages.length; index++) { console.log('index :' + index); // when the current image has finished loading lightboxImages[index].onload = function() { console.log('image ' + index + ' loaded.'); }; } ``` There are only three elements in the array, and with my `console.log` statements I'm expecting something like this in the console: ``` index : 0 image 0 loaded. index : 1 image 1 loaded. index : 2 image 2 loaded. ``` But instead I'm getting output like this: ``` index : 0 index : 1 index : 2 image 3 loaded. image 3 loaded. image 3 loaded. ``` How can I prevent iteration until the `onload` is finished? I also tried something like this: ``` // just an index variable as an example var counter = 2; toImage(i) { if (i == counter) { console.log('hooray'); } else { toImage(i++); } } toImage(0); ``` This was causing a callstack issue that was crashing the page - I didn't include it in the original post, because I figured it was a whole separate issue, but maybe I should have in retrospect. I guess my attempt at recursion here is wrong.<issue_comment>username_1: **An alternative is recursive calls:** ``` function loop(lightboxImages, index) { if (index === lightboxImages.length) return; lightboxImages[index].onload = function() { console.log('image ' + index + ' loaded.'); loop(lightboxImages, ++index); }; } loop(lightboxImages, 0); ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You console.log is showing the CURRENT value of index. You see, the loop has finished and index is now at 3 when the onloads are fired. You need to pass the index as a LOCAL variable to the onload handler. It is a common 'issue' for many programmers in dealing with asynchronous coding ;) Upvotes: 0 <issue_comment>username_3: Assigning to `onload` only assigns an event handler: it doesn't mean that the current thread stops and waits for the load to finish. I suggest using `reduce` and `await` instead. ``` function loadImages(lightboxImages) { lightboxImages.reduce(async (lastPromise, image, i) => { await lastPromise; return new Promise((resolve, reject) => { image.onload = () => { console.log(`image ${i} loaded.`); resolve(); }; }); }, Promise.resolve()); } ``` Upvotes: 0 <issue_comment>username_4: You can solve this with a closure. ```js var someFakeImages = [ { onload: function () {} }, { onload: function () {} }, { onload: function () {} } ]; var onloadFunc = function(i) { return function () { console.log('image ' + i + ' loaded.'); } }; for (index = 0; index < someFakeImages.length; index++) { console.log('index: ' + index); // when the current image has finished loading someFakeImages[index].onload = onloadFunc(index); } someFakeImages[0].onload(); someFakeImages[1].onload(); someFakeImages[2].onload(); ``` You can find out more about closures on the MDN website: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures> Basically with the above, you are creating a new function with a snapshot of the value of `index` at the time of assigning the onload handler. In your posted code, you are actually using the current value of `index` at the time of *executing* the onload handler. Upvotes: 1
2018/03/20
319
867
<issue_start>username_0: I need to sort the following dictionary by age but I don't figure how: ``` 1 {'name':'ste', 'surname':'pnt', 'age':21} 2 {'name':'test', 'surname':'black','age':24} 3 {'name':'check', 'surname':'try', 'age':41} ``` This is the output of a `for` cycle: ``` for k, v in d.items(): print(k, v) ```<issue_comment>username_1: So your dictionary is already sorted by age, but... ``` for key in sorted(mydict.iterkeys()): print "%s: %s" % (key, mydict[key]) ``` <https://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/> Upvotes: -1 <issue_comment>username_2: ``` d = { 1 : {'name':'ste', 'surname':'pnt', 'age':21}, 2 : {'name':'test', 'surname':'black','age':24}, 3 : {'name':'check', 'surname':'try', 'age':41}, } sorted(d.values(),key=lambda it: it['age']) ``` Upvotes: 2 [selected_answer]
2018/03/20
799
2,097
<issue_start>username_0: I have some data like so: ``` a <- c(1, 2, 9, 18, 6, 45) b <- c(12, 3, 34, 89, 108, 44) c <- c(0.5, 3.3, 2.4, 5, 13,2) df <- data.frame(a, b,c) ``` I need to create a function to lag a lot of variables at once for a very large time series analysis with dozens of variables. So i need to lag a lot of variables without typing it all out. In short, I would like to create variables `a.lag1`, `b.lag1` and `c.lag1` and be able to add them to the original `df` specified above. I figure the best way to do so is by creating a custom function, something along the lines of: ``` lag.fn <- function(x) { assign(paste(x, "lag1", sep = "."), lag(x, n = 1L) return (assign(paste(x, "lag1", sep = ".") } ``` The desired output is: ``` a.lag1 <- c(NA, 1, 2, 9, 18, 6, 45) b.lag1 <- c(NA, 12, 3, 34, 89, 108, 44) c.lag1 <- c(NA, 0.5, 3.3, 2.4, 5, 13, 2) ``` However, I don't get what I am looking for. Should I change the environment to the global environment? I would like to be able to use `cbind` to add to orignal `df`. Thanks.<issue_comment>username_1: Easy using `dplyr`. Don't call data frames `df`, may cause confusion with the function of the same name. I'm using `df1`. ``` library(dplyr) df1 <- df1 %>% mutate(a.lag1 = lag(a), b.lag1 = lag(b), c.lag1 = lag(c)) ``` Upvotes: 2 <issue_comment>username_2: The data frame statement in the question is invalid since `a`, `b` and `c` are not the same length. What you can do is create a zoo series. Note that the lag specified in `lag.zoo` can be a vector of lags as in the second example below. ``` library(zoo) z <- merge(a = zoo(a), b = zoo(b), c = zoo(c)) lag(z, -1) # lag all columns lag(z, 0:-1) # each column and its lag ``` Upvotes: 2 <issue_comment>username_3: We can use `mutate_all` ``` library(dplyr) df %>% mutate_all(funs(lag = lag(.))) ``` Upvotes: 2 [selected_answer]<issue_comment>username_4: If everything else fails, you can use a simple base R function: ``` my_lag <- function(x, steps = 1) { c(rep(NA, steps), x[1:(length(x) - steps)]) } ``` Upvotes: 1
2018/03/20
576
1,907
<issue_start>username_0: When I'm trying to print the values of an array, its memory location is getting printed instead of values. What am I doing wrong? ``` int main() { int list[3]; for (int i=0; i<3; i++) { list[i] = i; std::cout< ``` OUTPUT: 0x7ffffef79550<issue_comment>username_1: C++ doesn't provide an overload for arrays when using the iostream library. If you want to print the values of an array, you'll need to write a function or find one somebody else has written. What's happening under the hood is `list` is decaying to an `int*`, and that's what you're seeing printed. Upvotes: 2 <issue_comment>username_2: This looks like a typographical error: ``` std::cout << list ``` You want to print a specific element of the array, right? ``` std::cout << list[i] ``` When printing "the whole array" without index, the pointer to first element is printed (see the other answer for reason). Upvotes: 2 <issue_comment>username_3: ``` std::cout << list << std::endl; ``` You're printing the array object itself. What do you expect to see? The name of the array identifier? The address of the first element in the array? (actually this is what happens in your case). Or do you expect the array to neatly iterate over it's elements and build a comma separated string of all the values and output it to the stream? If this is what you want, you have to implement it yourself. ``` template std::ostream& operator<<(std::ostream& out, int (&arr)[N]) { std::copy(std::begin(arr), std::end(arr), std::ostream\_iterator{out, ", "}); return out; } ``` ``` int main() { int arr[] = {1, 2, 3, 4, 5}; std::cout << arr << std::endl; // Ok, prints "1, 2, 3, 4, 5, ". } ``` Upvotes: 2 <issue_comment>username_4: You need to dereference the list. Instead of: ``` std::cout << list << std::endl; ``` do: ``` std::cout << *list << std::endl; ``` Upvotes: 0
2018/03/20
594
1,974
<issue_start>username_0: Back with another SQL question about joins. I have 3 tables: ``` user: id, username, name, city, state, private rides: id, creator, title, datetime, city, state posts: id, title, user, date, state, city ``` I need to get the users from the user table, and based on the id of user, get the number of posts and rides for each person. Such as, user with id 25 has 2 rides and 4 posts, while the user with id 27 has 2 rides and 2 posts. The problem I am having, is that both users are coming back with 4 posts and rides each. ``` user.id = rides.creator = posts.user //just so you know what fields equals the user id ``` Here is my code: ``` select u.id, u.username, u.state, u.city, count(p.id) as TotalPosts, count(r.id) as TotalRides from user u left join posts p on p.user=u.id left join rides r on r.creator=u.id where private='public' group by u.id order by u.username, u.state asc; ``` If I separate them out, and just join the posts or the rides, I get the correct totals back. I tried switching the order of the joins, but I got the same results. Not sure what is going on. Any ideas or thoughts are appreciated.<issue_comment>username_1: Your problem is a Cartesian product along two different dimensions. The best solution is to pre-aggregate the data: ``` select u.id, u.username, u.state, u.city, p.TotalPosts, r.TotalRides from user u left join (select user, count(*) as totalposts from posts p group by user ) p on p.user = u.id left join (select creator, count(*) as totalrides from rides r group by creator ) r on r.creator = u.id where u.private = 'public' group by u.id order by u.username, u.state asc; ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: you can always use a sub select. `select u.*, (select count(*) from posts where user = u.id) as 'posts', (select count(*) from rides where creator = u.id) as 'rides' from users u where .....` Upvotes: 0
2018/03/20
747
2,955
<issue_start>username_0: Given that there's no Union in scala, I have a three functions that accept different parameters, but are otherwise exactly the same. How would I best implement this without repeating myself like I do now? ``` import scala.sys.process._ def function1(command:String):String = { ... command.!! // scala sys process execution } def function2(command:Seq[String]):String = { ... command.!! // scala sys process execution } def function3(command:ProcessBuilder):String = { ... command.!! // scala sys process execution } ```<issue_comment>username_1: I have no idea why you have `!!` defined on `String`, so I can't help you there. But let's say all you do is use `toString`. Then your method works on any type which supports `toString`, which in Scala is literally everything. So just take `Any`. ``` def function(command: Any): String = { // Do something with command.toString } ``` If you actually do need different cases for different types, you can use [case classes](https://docs.scala-lang.org/tour/case-classes.html) and dispatch based on the different types. ``` sealed trait Foo case class FooString(value: String) case class FooSeq(value: Seq[String]) case class FooPB(value: ProcessBuilder) def function(arg: Foo): String = { arg match { case FooString(str) => "It's a string!" case FooSeq(str) => "It's a sequence!" case FooPB(str) => "It's a process builder!" } } ``` Since your trait is `sealed`, you'll get a compiler warning if you forget any cases in the pattern match. Thus, you can safely handle every case and be confident you have done so. In summary, if you want to support multiple types, see if the functionality you desire is available in a common supertype (in the above example, `Any`). This could be a trait or a parent class. Common candidates for this are `Seq` or `Iterable`. If you need different behavior based on a select few types, define a sealed trait and some case classes that inherit from it, so you can pattern match on all the different possibilities. Upvotes: 1 <issue_comment>username_2: There is an implicit conversion loaded from `import scala.sys.process._` that will convert from `String` and `Seq[String]` to `ProcessBuilder`, that is what is making possible to execute the `!` in those 2 types, you can use that same implicit conversion to call function3 with any of those types ``` import scala.sys.process._ function3(Seq("")) function3("") def function3(command:ProcessBuilder):String = { ... command.!! } ``` this code should compile, you dont need `function1` or `function2`. THIS WILL NOT WORK IF `import scala.sys.process._` IS NOT IN THE SCOPE OF THE `function2` CALL. You can find the implicit definitions in the package object in `scala.sys.process`, if you look at it you will see that is extending `ProcessImplicits` which is defining the implicit conversions Upvotes: 3 [selected_answer]
2018/03/20
898
2,657
<issue_start>username_0: I have a problem doing the following `SELECT` statement: I want to select only `articles` that are exactly related to some given `tags`. Here is my (simplified) schema: [![enter image description here](https://i.stack.imgur.com/O2as8.png)](https://i.stack.imgur.com/O2as8.png) And here are the (simplified) datas: [![enter image description here](https://i.stack.imgur.com/JkaEN.png)](https://i.stack.imgur.com/JkaEN.png) I want to select only `articles` related to `tags` **89** `AND` **137**. That should return only `article (ID 3)` which is only related to `tags` ID **89** and **137**. I was thinking about doing this with two queries, but maybe one of you can tell me how to do it in only one. Thks!<issue_comment>username_1: Here is a simple way, assuming no duplicates in `article_tag`: ``` select article_id from article_tag group by article_id having count(*) = sum( tag_id in (89, 137) ); ``` This does exactly what you want. The `sum()` can return 0 (if the tags are not in the article), 1 (if one is), or 2 (if both are). The `count(*)` is saying that these matches are the only tags for the article. Upvotes: 0 <issue_comment>username_2: As I understand it you want to select article ids which relate ONLY to tags 89 **and** 137 and no others? So ID 3 in your sample data, but not ID 4 and 5 (which only relate to one of them) or 6 (which relates to both of them, but also other tags). You can achieve that with this query: ``` select a1.article_id from article_tag a1 where a1.tag_id = 89 and exists (select * from article_tag a2 where a2.article_id = a1.article_id and a2.tag_id = 137) and not exists (select * from article_tag a3 where a3.article_id = a1.article_id and a3.tag_id != 137 and a3.tag_id != 89) ``` Upvotes: 2 <issue_comment>username_3: ``` select id as article_id from article a where exists (select 1 from article_tag b where b.article_id = a.id and b.tag_id = 89) and exists (select 1 from article_tag c where c.article_id = a.id and c.tag_id = 137) and not exists (select 1 from article_tag d where d.article_id = a.id and d.tag_id not in (89,137)) ``` Upvotes: 1 <issue_comment>username_4: I came with another solution, which does less subrequests: ``` SELECT at1.article_id FROM article_tag at1 INNER JOIN article_tag at2 ON at1.article_id = at2.article_id WHERE at1.tag_id = 89 AND at2.tag_id = 137 AND not exists ( SELECT * FROM article_tag at3 WHERE at3.article_id = at1.article_id AND at3.tag_id != 137 AND at3.tag_id != 89 ) ``` Thank you @username_3 and @username_2 for your inspiration. Upvotes: 1 [selected_answer]
2018/03/20
1,328
4,522
<issue_start>username_0: I would like the --import parameter to have a "sub-parameter" that will only work on this parameter, nowhere else. Example: ``` app.pl --import --fresh ``` output: command working ``` app.pl --export ``` output: command working ``` app.pl --export --fresh ``` output: command not found Can this be achieved by GetOpt::Long? Please, guide me a little.<issue_comment>username_1: I think that without resorting to partial parsing the closest you can get to with Getopt::Long is this: ``` use strict; use warnings; use Data::Dumper; use Getopt::Long; GetOptions('export=s%{1,5}'=>\my %export, 'another_option=s'=>\my $ao); print Dumper({ 'export'=> \%export, 'another_option'=>$ao}); ``` --- ``` perl t1.pl --export fresh=1 b=2 c=3 --another_option value ``` --- ``` $VAR1 = { 'export' => { 'c' => '3', 'b' => '2', 'fresh' => '1' }, 'another_option' => 'value' }; ``` Here `export=s%{1,5}` parses `--export fresh=1 b=2 c=3` into hash `%export`. `s%{1,5}` expects from 1 to 5 `key=value` pairs Upvotes: 3 [selected_answer]<issue_comment>username_2: Options can indeed require a parameter. The parameter doesn't use `--`, though. ``` GetOptions( 'help' => \&help, 'import:s' => \$opt_import, ) or usage(); defined($opt_import) && ( $opt_import eq '' || opt_import eq 'fresh' ) or usage("Invalid value for --import"); @ARGV == 0 or usage("Incorrect number of arguments"); # Convert into booleans for convenience. $opt_fresh = defined($opt_import) && $opt_import eq 'fresh'; $opt_import = defined($opt_import); ``` The above accepts the following: ``` app.pl --import fresh app.pl --import app.pl ``` Note that using `=s` instead of `:s` will make providing a value mandatory. --- Sample helpers: ``` use FIle::Basename qw( basename ); sub usage { my $basename = basename($0); print("usage: $basename [options]\n"); print(" $basename --help\n"); print("\n"); print("Options:\n"); print("\n"); print(" --import [fresh]\n"); exit(0); } sub usage { if (@_) { chomp( my $msg = shift ); warn("$msg\n"); } my $basename = basename($0); warn("Try '$basename --help' for more information.\n); exit(1); } ``` Upvotes: 2 <issue_comment>username_3: I take the purpose for this invocation, that matters for implementation here, to be the following. There is a flag (call it `$fresh`) that need be set under the `--import` option, along with other flag(s) associated with `--import`. Additionally, there may be an independent option `--fresh`, which sets the `$fresh` flag. While [Getopt::Long](http://perldoc.perl.org/Getopt/Long.html) doesn't support nested options this can be achieved using its other facilities. Set `--import` to take an optional argument with `:`, and set variables [in a sub](http://perldoc.perl.org/Getopt/Long.html#User-defined-subroutines-to-handle-options). If the word `fresh` is submitted as the value set the corresponding (`$fresh`) flag. ``` use warnings; use strict; use feature 'say'; use Getopt::Long; my ($import, $fresh); GetOptions( 'import:s' => sub { $import = 1; $fresh = 1 if $_[1] eq 'fresh'; }, 'fresh!' => \$fresh # if independent --fresh option is needed ); say 'import: ', $import // 'not submitted'; #/ say 'fresh: ', $fresh // 'not submitted'; ``` The sub receives two arguments, the option name and value, and the value is used to check whether `fresh` was passed. The code as it stands does nothing for other words that may be passed, but it can be made to abort (with a usage message) if any value other than `fresh` is submitted. Whatever particular reasons there are to require this invocation can be coded in the sub. If a separate `--fresh` option is indeed provided then the user need be careful since it is possible to submit conflicting values for `$fresh` – one with `--import` and another in `--fresh` itself. This can be checked for in the code. The option `--import` still works as a simple flag on its own. Valid invocations are ``` gol.pl --import # $import is 1 gol.pl --import fresh # $import is 1, $fresh is 1 gol.pl --fresh # $fresh is 1 ``` Since `fresh` is set in a sub as a value of `--import` it cannot be set with any other options. This differs from the requirement by having `fresh` as a word, without dashes. Upvotes: 2
2018/03/20
400
1,416
<issue_start>username_0: In which format should i enter IMG SRC to a Result in Javascript? ``` var result = document.getElementById('test'); result.innerHTML = price + "img src='catcoin.png'"; ```<issue_comment>username_1: ``` document.getElementById('test').src = "catcoin.png"; ``` Upvotes: 0 <issue_comment>username_2: I'd suggest avoiding assigning to innerHTML generally unless it's the only decent option. You can append a new `img` element to a container like this: ``` result.appendChild(document.createElement('img')).src = 'catcoin.png'; ``` Upvotes: 2 <issue_comment>username_3: ``` var el = document.querySelector("#test") var img = document.createElement("img"); img.setAttribute('src', 'catcoin.png'); el.appendChild(img) ``` Upvotes: 0 <issue_comment>username_4: Hey so don't use text to add elements in JavaScript. ``` var elem = document.createElement("img"); elem.src = 'test.png'; ``` Then append this new image element to result: ``` document.getElementById("test").appendChild(elem); ``` Upvotes: 0 <issue_comment>username_5: With plain js: ```js var price = '$ 04.89'; var test = document.getElementById('test'); while (test.firstChild) {/* optional cleanup, faster than test.innerHTML = '' */ test.removeChild(test.firstChild); } test.appendChild(document.createTextNode(price)); test.appendChild(document.createElement('img')).src = 'caticon.png'; ``` Upvotes: 0
2018/03/20
3,406
13,277
<issue_start>username_0: So I have the following code: ``` #region Dropshadow [DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")] private static extern IntPtr CreateRoundRectRgn ( int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, int nWidthEllipse, int nHeightEllipse ); [DllImport("dwmapi.dll")] public static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset); [DllImport("dwmapi.dll")] public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize); [DllImport("dwmapi.dll")] public static extern int DwmIsCompositionEnabled(ref int pfEnabled); private bool m_aeroEnabled; public struct MARGINS { public int leftWidth; public int rightWidth; public int topHeight; public int bottomHeight; } protected override CreateParams CreateParams { get { m_aeroEnabled = CheckAeroEnabled(); CreateParams cp = base.CreateParams; if (!m_aeroEnabled) { cp.ClassStyle |= 0x00020000; } return cp; } } private bool CheckAeroEnabled() { if (Environment.OSVersion.Version.Major >= 6) { int enabled = 0; DwmIsCompositionEnabled(ref enabled); return (enabled == 1) ? true : false; } return false; } protected override void WndProc(ref Message m) { switch (m.Msg) { case 0x0085: if (m_aeroEnabled) { int v = 2; DwmSetWindowAttribute(Handle, 2, ref v, 4); MARGINS margins = new MARGINS() { bottomHeight = 1, leftWidth = 0, rightWidth = 0, topHeight = 0 }; DwmExtendFrameIntoClientArea(Handle, ref margins); } break; default: break; } base.WndProc(ref m); } #endregion ``` This makes a Dropshadow using GDI. The only issue however, is I had to make it keep a 1 pixel height border on the top (it can be any edge, just top is hardest to notice on my app). This makes a line on my app at the top essentially degrading viewing experience. Is it possible to do this with no border at all? (The bottomHeight = 1 code is where its all about. If I set it to 0, and topHeight to 1, the line will be on the bottom. Setting all of them to 0, shows no dropshadow at all.) Turns out, its to do with my padding, I need to leave 1 pixel line empty on atleast 1 edge for the Dropshadow to work. I chose to use Padding to make that 1 pixel line and I set the top padding to 1. This sets the line at the top. The bottomHeight = 1 doesnt matter at all. It's just there as it requires atleast one of them to be non 0. If I remove the Padding and Top Line etc. And in the CreateParams overide, if I remove the aero enabled check, it shows a dropshadow similar like this: [![enter image description here](https://i.stack.imgur.com/OI6V8.png)](https://i.stack.imgur.com/OI6V8.png)<issue_comment>username_1: This is a Form class that uses DWM to render it's borders/shadow. As described, you need to register an Attribute, [`DWMWINDOWATTRIBUTE`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa969530(v=vs.85).aspx), and the related Policy, [`DWMNCRENDERINGPOLICY`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa969529(v=vs.85).aspx), settings it's value to Enabled. Then set the attribute with [`DwmSetWindowAttribute()`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa969524(v=vs.85).aspx) and the desired effect with [`DwmExtendFrameIntoClientArea()`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa969512(v=vs.85).aspx), [`DwmEnableBlurBehindWindow()`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa969508(v=vs.85).aspx) and so on. All the declarations needed are here. This is the Form class (named "Borderless", in a spark of creativity). I tried to make it look like what you already have posted, to minimize the "impact". The Form is a standard WinForms Form with `FormBorderStyle = None`. ``` public partial class Borderless : Form { public Borderless() => InitializeComponent(); protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); WinApi.Dwm.DWMNCRENDERINGPOLICY Policy = WinApi.Dwm.DWMNCRENDERINGPOLICY.Enabled; WinApi.Dwm.WindowSetAttribute(this.Handle, WinApi.Dwm.DWMWINDOWATTRIBUTE.NCRenderingPolicy, (int)Policy); if (DWNCompositionEnabled()) { WinApi.Dwm.WindowBorderlessDropShadow(this.Handle, 2); } //if (DWNCompositionEnabled()) { WinApi.Dwm.WindowEnableBlurBehind(this.Handle); } //if (DWNCompositionEnabled()) { WinApi.Dwm.WindowSheetOfGlass(this.Handle); } } private bool DWNCompositionEnabled() => (Environment.OSVersion.Version.Major >= 6) ? WinApi.Dwm.IsCompositionEnabled() : false; protected override void WndProc(ref Message m) { switch (m.Msg) { case (int)WinApi.WinMessage.WM_DWMCOMPOSITIONCHANGED: { WinApi.Dwm.DWMNCRENDERINGPOLICY Policy = WinApi.Dwm.DWMNCRENDERINGPOLICY.Enabled; WinApi.Dwm.WindowSetAttribute(this.Handle, WinApi.Dwm.DWMWINDOWATTRIBUTE.NCRenderingPolicy, (int)Policy); WinApi.Dwm.WindowBorderlessDropShadow(this.Handle, 2); m.Result = (IntPtr)0; } break; default: break; } base.WndProc(ref m); } } ``` These are all the declarations needed, plus others that might become useful. Note that I only use the `internal` attribute form Win32 APIs, which are called using helpr methods. It's a partial class because the `Winapi` class is a extensive class library. You can change it to whatever you are used to. > > I suggest to keep the `[SuppressUnmanagedCodeSecurityAttribute]` > attribute for the Win32 APIs declarations. > > > > ``` public partial class WinApi { public enum WinMessage : int { WM_DWMCOMPOSITIONCHANGED = 0x031E, //The system will send a window the WM_DWMCOMPOSITIONCHANGED message to indicate that the availability of desktop composition has changed. WM_DWMNCRENDERINGCHANGED = 0x031F, //WM_DWMNCRENDERINGCHANGED is called when the non-client area rendering status of a window has changed. Only windows that have set the flag DWM_BLURBEHIND.fTransitionOnMaximized to true will get this message. WM_DWMCOLORIZATIONCOLORCHANGED = 0x0320, //Sent to all top-level windows when the colorization color has changed. WM_DWMWINDOWMAXIMIZEDCHANGE = 0x0321 //WM_DWMWINDOWMAXIMIZEDCHANGE will let you know when a DWM composed window is maximized. You also have to register for this message as well. You'd have other windowd go opaque when this message is sent. } public class Dwm public enum DWMWINDOWATTRIBUTE : uint { NCRenderingEnabled = 1, //Get only atttribute NCRenderingPolicy, //Enable or disable non-client rendering TransitionsForceDisabled, AllowNCPaint, CaptionButtonBounds, NonClientRtlLayout, ForceIconicRepresentation, Flip3DPolicy, ExtendedFrameBounds, HasIconicBitmap, DisallowPeek, ExcludedFromPeek, Cloak, Cloaked, FreezeRepresentation } public enum DWMNCRENDERINGPOLICY : uint { UseWindowStyle, // Enable/disable non-client rendering based on window style Disabled, // Disabled non-client rendering; window style is ignored Enabled, // Enabled non-client rendering; window style is ignored }; // Values designating how Flip3D treats a given window. enum DWMFLIP3DWINDOWPOLICY : uint { Default, // Hide or include the window in Flip3D based on window style and visibility. ExcludeBelow, // Display the window under Flip3D and disabled. ExcludeAbove, // Display the window above Flip3D and enabled. }; public struct MARGINS { public int leftWidth; public int rightWidth; public int topHeight; public int bottomHeight; public MARGINS(int LeftWidth, int RightWidth, int TopHeight, int BottomHeight) { leftWidth = LeftWidth; rightWidth = RightWidth; topHeight = TopHeight; bottomHeight = BottomHeight; } public void NoMargins() { leftWidth = 0; rightWidth = 0; topHeight = 0; bottomHeight = 0; } public void SheetOfGlass() { leftWidth = -1; rightWidth = -1; topHeight = -1; bottomHeight = -1; } } [SuppressUnmanagedCodeSecurityAttribute] internal static class SafeNativeMethods { //https://msdn.microsoft.com/en-us/library/windows/desktop/aa969508(v=vs.85).aspx [DllImport("dwmapi.dll")] internal static extern int DwmEnableBlurBehindWindow(IntPtr hwnd, ref DWM_BLURBEHIND blurBehind); //https://msdn.microsoft.com/it-it/library/windows/desktop/aa969512(v=vs.85).aspx [DllImport("dwmapi.dll")] internal static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset); //https://msdn.microsoft.com/en-us/library/windows/desktop/aa969515(v=vs.85).aspx [DllImport("dwmapi.dll")] internal static extern int DwmGetWindowAttribute(IntPtr hwnd, DWMWINDOWATTRIBUTE attr, ref int attrValue, int attrSize); //https://msdn.microsoft.com/en-us/library/windows/desktop/aa969524(v=vs.85).aspx [DllImport("dwmapi.dll")] internal static extern int DwmSetWindowAttribute(IntPtr hwnd, DWMWINDOWATTRIBUTE attr, ref int attrValue, int attrSize); [DllImport("dwmapi.dll")] internal static extern int DwmIsCompositionEnabled(ref int pfEnabled); } public static bool IsCompositionEnabled() { int pfEnabled = 0; int result = SafeNativeMethods.DwmIsCompositionEnabled(ref pfEnabled); return (pfEnabled == 1) ? true : false; } public static bool IsNonClientRenderingEnabled(IntPtr hWnd) { int gwaEnabled = 0; int result = SafeNativeMethods.DwmGetWindowAttribute(hWnd, DWMWINDOWATTRIBUTE.NCRenderingEnabled, ref gwaEnabled, sizeof(int)); return (gwaEnabled == 1) ? true : false; } public static bool WindowSetAttribute(IntPtr hWnd, DWMWINDOWATTRIBUTE Attribute, int AttributeValue) { int result = SafeNativeMethods.DwmSetWindowAttribute(hWnd, Attribute, ref AttributeValue, sizeof(int)); return (result == 0); } public static bool WindowEnableBlurBehind(IntPtr hWnd) { //Create and populate the Blur Behind structure DWM_BLURBEHIND Dwm_BB = new DWM_BLURBEHIND(true); int result = SafeNativeMethods.DwmEnableBlurBehindWindow(hWnd, ref Dwm_BB); return (result == 0); } public static bool WindowExtendIntoClientArea(IntPtr hWnd, WinApi.Dwm.MARGINS Margins) { // Extend frame on the bottom of client area int result = SafeNativeMethods.DwmExtendFrameIntoClientArea(hWnd, ref Margins); return (result == 0); } public static bool WindowBorderlessDropShadow(IntPtr hWnd, int ShadowSize) { MARGINS Margins = new MARGINS(0, ShadowSize, 0, ShadowSize); int result = SafeNativeMethods.DwmExtendFrameIntoClientArea(hWnd, ref Margins); return (result == 0); } public static bool WindowSheetOfGlass(IntPtr hWnd) { MARGINS Margins = new MARGINS(); Margins.SheetOfGlass(); //Margins set to All:-1 - Sheet Of Glass effect int result = SafeNativeMethods.DwmExtendFrameIntoClientArea(hWnd, ref Margins); return (result == 0); } public static bool WindowDisableRendering(IntPtr hWnd) { DWMNCRENDERINGPOLICY NCRP = DWMNCRENDERINGPOLICY.Disabled; int ncrp = (int)NCRP; // Disable non-client area rendering on the window. int result = SafeNativeMethods.DwmSetWindowAttribute(hWnd, DWMWINDOWATTRIBUTE.NCRenderingPolicy, ref ncrp, sizeof(int)); return (result == 0); } } } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: I set the `bottomHeight` to 3, and I found that the border height was included in the form size (the form's size didn't change). So I set a `BackgroundImage` to this form, and the border was hidden by the image. Upvotes: 0
2018/03/20
3,074
12,267
<issue_start>username_0: I have some interesting behavior that I am stuck on I've got a vb.net page that allows the user to add and remove items from a form dynamically, the Add and Remove functions are both using jQuery on the front end ``` function remRow(clicked_id) { console.log("Start remRow"); $("#hdnID").val(clicked_id); document.getElementById("remrow").click(); console.log("End remRow"); } ``` This clicks a hidden button within an update panel who's event handler in the code behind removes the selected row from array of HtmlGenericControl. The reason for the extra step of the jQuery is the list of possible form elements they can add comes through ajax on the front end, but the HtmlGenericControl is on the back end. The remRow function is attached to a dynamically created button as part of the array of HtmlGenericControl On Chrome and Firefox the form element is removed immediately as needed, on IE a single click will show in console as ``` Start remRow End remRow ``` and the row will not be removed, a double click will show ``` Start remRow End remRow Start remRow End remRow ROW REMOVED! ``` and while the row has been removed from the array of HtmlGenericControl it still remains on the screen until a third single click. My addRow function is identical to the remRow function and works fine every time in all browsers, its only the removing row function with this behavior I've tried several different ideas, such as wrapping the function contents in a ``` $('document').ready(function(){}); ``` and using other methods of clicking the button such as ``` $("#remRow").click() ``` I'm not sure why code working perfectly on Chrome and Firefox is failing on IE edit: @BojanIvanac remrow is a button within the update panel ``` ``` code behind: ``` Private Sub btnremrow_Click(sender As Object, e As EventArgs) Handles remrow.Click RemoveRow() // Gets called on double click, does not update UpdatePanel End Sub ```<issue_comment>username_1: This is a Form class that uses DWM to render it's borders/shadow. As described, you need to register an Attribute, [`DWMWINDOWATTRIBUTE`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa969530(v=vs.85).aspx), and the related Policy, [`DWMNCRENDERINGPOLICY`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa969529(v=vs.85).aspx), settings it's value to Enabled. Then set the attribute with [`DwmSetWindowAttribute()`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa969524(v=vs.85).aspx) and the desired effect with [`DwmExtendFrameIntoClientArea()`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa969512(v=vs.85).aspx), [`DwmEnableBlurBehindWindow()`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa969508(v=vs.85).aspx) and so on. All the declarations needed are here. This is the Form class (named "Borderless", in a spark of creativity). I tried to make it look like what you already have posted, to minimize the "impact". The Form is a standard WinForms Form with `FormBorderStyle = None`. ``` public partial class Borderless : Form { public Borderless() => InitializeComponent(); protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); WinApi.Dwm.DWMNCRENDERINGPOLICY Policy = WinApi.Dwm.DWMNCRENDERINGPOLICY.Enabled; WinApi.Dwm.WindowSetAttribute(this.Handle, WinApi.Dwm.DWMWINDOWATTRIBUTE.NCRenderingPolicy, (int)Policy); if (DWNCompositionEnabled()) { WinApi.Dwm.WindowBorderlessDropShadow(this.Handle, 2); } //if (DWNCompositionEnabled()) { WinApi.Dwm.WindowEnableBlurBehind(this.Handle); } //if (DWNCompositionEnabled()) { WinApi.Dwm.WindowSheetOfGlass(this.Handle); } } private bool DWNCompositionEnabled() => (Environment.OSVersion.Version.Major >= 6) ? WinApi.Dwm.IsCompositionEnabled() : false; protected override void WndProc(ref Message m) { switch (m.Msg) { case (int)WinApi.WinMessage.WM_DWMCOMPOSITIONCHANGED: { WinApi.Dwm.DWMNCRENDERINGPOLICY Policy = WinApi.Dwm.DWMNCRENDERINGPOLICY.Enabled; WinApi.Dwm.WindowSetAttribute(this.Handle, WinApi.Dwm.DWMWINDOWATTRIBUTE.NCRenderingPolicy, (int)Policy); WinApi.Dwm.WindowBorderlessDropShadow(this.Handle, 2); m.Result = (IntPtr)0; } break; default: break; } base.WndProc(ref m); } } ``` These are all the declarations needed, plus others that might become useful. Note that I only use the `internal` attribute form Win32 APIs, which are called using helpr methods. It's a partial class because the `Winapi` class is a extensive class library. You can change it to whatever you are used to. > > I suggest to keep the `[SuppressUnmanagedCodeSecurityAttribute]` > attribute for the Win32 APIs declarations. > > > > ``` public partial class WinApi { public enum WinMessage : int { WM_DWMCOMPOSITIONCHANGED = 0x031E, //The system will send a window the WM_DWMCOMPOSITIONCHANGED message to indicate that the availability of desktop composition has changed. WM_DWMNCRENDERINGCHANGED = 0x031F, //WM_DWMNCRENDERINGCHANGED is called when the non-client area rendering status of a window has changed. Only windows that have set the flag DWM_BLURBEHIND.fTransitionOnMaximized to true will get this message. WM_DWMCOLORIZATIONCOLORCHANGED = 0x0320, //Sent to all top-level windows when the colorization color has changed. WM_DWMWINDOWMAXIMIZEDCHANGE = 0x0321 //WM_DWMWINDOWMAXIMIZEDCHANGE will let you know when a DWM composed window is maximized. You also have to register for this message as well. You'd have other windowd go opaque when this message is sent. } public class Dwm public enum DWMWINDOWATTRIBUTE : uint { NCRenderingEnabled = 1, //Get only atttribute NCRenderingPolicy, //Enable or disable non-client rendering TransitionsForceDisabled, AllowNCPaint, CaptionButtonBounds, NonClientRtlLayout, ForceIconicRepresentation, Flip3DPolicy, ExtendedFrameBounds, HasIconicBitmap, DisallowPeek, ExcludedFromPeek, Cloak, Cloaked, FreezeRepresentation } public enum DWMNCRENDERINGPOLICY : uint { UseWindowStyle, // Enable/disable non-client rendering based on window style Disabled, // Disabled non-client rendering; window style is ignored Enabled, // Enabled non-client rendering; window style is ignored }; // Values designating how Flip3D treats a given window. enum DWMFLIP3DWINDOWPOLICY : uint { Default, // Hide or include the window in Flip3D based on window style and visibility. ExcludeBelow, // Display the window under Flip3D and disabled. ExcludeAbove, // Display the window above Flip3D and enabled. }; public struct MARGINS { public int leftWidth; public int rightWidth; public int topHeight; public int bottomHeight; public MARGINS(int LeftWidth, int RightWidth, int TopHeight, int BottomHeight) { leftWidth = LeftWidth; rightWidth = RightWidth; topHeight = TopHeight; bottomHeight = BottomHeight; } public void NoMargins() { leftWidth = 0; rightWidth = 0; topHeight = 0; bottomHeight = 0; } public void SheetOfGlass() { leftWidth = -1; rightWidth = -1; topHeight = -1; bottomHeight = -1; } } [SuppressUnmanagedCodeSecurityAttribute] internal static class SafeNativeMethods { //https://msdn.microsoft.com/en-us/library/windows/desktop/aa969508(v=vs.85).aspx [DllImport("dwmapi.dll")] internal static extern int DwmEnableBlurBehindWindow(IntPtr hwnd, ref DWM_BLURBEHIND blurBehind); //https://msdn.microsoft.com/it-it/library/windows/desktop/aa969512(v=vs.85).aspx [DllImport("dwmapi.dll")] internal static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset); //https://msdn.microsoft.com/en-us/library/windows/desktop/aa969515(v=vs.85).aspx [DllImport("dwmapi.dll")] internal static extern int DwmGetWindowAttribute(IntPtr hwnd, DWMWINDOWATTRIBUTE attr, ref int attrValue, int attrSize); //https://msdn.microsoft.com/en-us/library/windows/desktop/aa969524(v=vs.85).aspx [DllImport("dwmapi.dll")] internal static extern int DwmSetWindowAttribute(IntPtr hwnd, DWMWINDOWATTRIBUTE attr, ref int attrValue, int attrSize); [DllImport("dwmapi.dll")] internal static extern int DwmIsCompositionEnabled(ref int pfEnabled); } public static bool IsCompositionEnabled() { int pfEnabled = 0; int result = SafeNativeMethods.DwmIsCompositionEnabled(ref pfEnabled); return (pfEnabled == 1) ? true : false; } public static bool IsNonClientRenderingEnabled(IntPtr hWnd) { int gwaEnabled = 0; int result = SafeNativeMethods.DwmGetWindowAttribute(hWnd, DWMWINDOWATTRIBUTE.NCRenderingEnabled, ref gwaEnabled, sizeof(int)); return (gwaEnabled == 1) ? true : false; } public static bool WindowSetAttribute(IntPtr hWnd, DWMWINDOWATTRIBUTE Attribute, int AttributeValue) { int result = SafeNativeMethods.DwmSetWindowAttribute(hWnd, Attribute, ref AttributeValue, sizeof(int)); return (result == 0); } public static bool WindowEnableBlurBehind(IntPtr hWnd) { //Create and populate the Blur Behind structure DWM_BLURBEHIND Dwm_BB = new DWM_BLURBEHIND(true); int result = SafeNativeMethods.DwmEnableBlurBehindWindow(hWnd, ref Dwm_BB); return (result == 0); } public static bool WindowExtendIntoClientArea(IntPtr hWnd, WinApi.Dwm.MARGINS Margins) { // Extend frame on the bottom of client area int result = SafeNativeMethods.DwmExtendFrameIntoClientArea(hWnd, ref Margins); return (result == 0); } public static bool WindowBorderlessDropShadow(IntPtr hWnd, int ShadowSize) { MARGINS Margins = new MARGINS(0, ShadowSize, 0, ShadowSize); int result = SafeNativeMethods.DwmExtendFrameIntoClientArea(hWnd, ref Margins); return (result == 0); } public static bool WindowSheetOfGlass(IntPtr hWnd) { MARGINS Margins = new MARGINS(); Margins.SheetOfGlass(); //Margins set to All:-1 - Sheet Of Glass effect int result = SafeNativeMethods.DwmExtendFrameIntoClientArea(hWnd, ref Margins); return (result == 0); } public static bool WindowDisableRendering(IntPtr hWnd) { DWMNCRENDERINGPOLICY NCRP = DWMNCRENDERINGPOLICY.Disabled; int ncrp = (int)NCRP; // Disable non-client area rendering on the window. int result = SafeNativeMethods.DwmSetWindowAttribute(hWnd, DWMWINDOWATTRIBUTE.NCRenderingPolicy, ref ncrp, sizeof(int)); return (result == 0); } } } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: I set the `bottomHeight` to 3, and I found that the border height was included in the form size (the form's size didn't change). So I set a `BackgroundImage` to this form, and the border was hidden by the image. Upvotes: 0
2018/03/20
699
2,028
<issue_start>username_0: I have a dataset which looks like below ``` ADVERTISER YR REVENUE --------------------------------- Altus Dental 2015 5560.00 Altus Dental 2016 48295.00 Altus Dental 2017 39920.00 ``` I'm trying to find CAGR - year over year and taking an average of them, meaning ``` CAGR = (((REVENUE(2016)/REVENUE(2015)) - 1) + ((REVENUE(2017)/REVENUE(2016)) - 1) ) / 2 ``` And Finally I will need an output something like this ``` ADVERTISER CAGR -------------------- Altus Dental 3.75 ``` How can I accomplish this in SQL? Please help me in providing an effective solution for this.<issue_comment>username_1: Here is one way: ``` select advertiser, (((t16.revenue/t15.revenue) - 1) + ((t17.revenue/t16.revenue) - 1) ) / 2 as cagr from t t15 join t t16 on t15.advertiser = t16.advertiser and t15.yr = 2015 and t16.yr = 2016 join t t17 on t15.advertiser = t17.advertiser and t17.yr = 2017 ``` Upvotes: 0 <issue_comment>username_2: I'm assuming there won't be "holes" in the list of years. This should work for n years, and n advertisers: ``` SELECT advertiser, SUM(revenue) / (COUNT(*) - 1) AS CAGR FROM (SELECT advertiser, COALESCE((revenue/revenue_old - 1), 0) as revenue FROM (SELECT s.advertiser, s.revenue, LAG(s.revenue, 1) OVER(PARTITION BY s.advertiser ORDER BY s.yr) AS revenue_old FROM table_1 s)) GROUP BY advertiser; ``` Upvotes: 0 <issue_comment>username_3: Calculate the CAGR (revenue/prev\_revenue - 1) for each year and calculate the average CAGR (assume your dbms supports the `LAG` function) ``` select advertiser, avg(cagr) as CAGR from ( select advertiser, yr, revenue, revenue/prev_revenue - 1 as cagr from (select *, lag(revenue, 1) over (partition by advertiser order by yr) as prev_revenue from test ) t ) t1 group by advertiser ``` Upvotes: 1
2018/03/20
1,109
3,166
<issue_start>username_0: I am trying to write a df to a csv from a loop, each line represents a df, but I am finding some difficulties once the headers are not equal for all dfs, some of them have values for all dates and others no. I am writing the df using a function similar to this one: ``` def write_csv(): for name, df in data.items(): df.to_csv(meal+'mydf.csv', mode='a') ``` and it creates a csv for each meal (lunch an dinner) each df is similar to this: ``` Name Meal 22-03-18 23-03-18 25-03-18 Peter Lunch 12 10 9 ``` or: ``` Name Meal 22-03-18 23-03-18 25-03-18 Peter Dinner 12 10 9 ``` I was trying to use pandas concatenate, but I am not finding a way to implement this in the function. My goal is to have the headers with all the dates (as the example of desired output), independent if the DataFrame appended to the csv have or not values in all dates. ``` Actual output: Name Meal 22-03-18 23-03-18 25-03-18 Peter Lunch 12 10 9 Mathew Lunch 12 11 11 10 9 Ruth Lunch 9 9 8 9 Anna Lunch 10 12 11 13 10 output with headers: Name Meal 22-03-18 23-03-18 25-03-18 Peter Lunch 12 10 9 Name Meal 21-03-18 22-03-18 23-03-18 24-03-18 25-03-18 Mathew Lunch 12 11 11 10 9 Name Meal 21-03-18 22-03-18 24-03-18 25-03-18 Ruth Lunch 9 9 8 9 Name Meal 21-03-18 22-03-18 23-03-18 24-03-18 25-03-18 Anna Lunch 10 12 11 13 10 Output desired: Name Meal 21-03-18 22-03-18 23-03-18 24-03-18 25-03-18 Peter Lunch 12 10 9 Mathew Lunch 12 11 11 10 Ruth Lunch 9 9 8 9 Anna Lunch 10 12 11 13 10 ```<issue_comment>username_1: can you try something like this? not sure if is exactly what you want, but it will concatenate dataframes without fully overlapping columns ``` def write_csv(): df2 = pd.DataFrame() for name, df in data.items(): df2 = df2.append(df) df2.to_csv('mydf.csv') ``` Upvotes: 1 <issue_comment>username_2: You could use the header = False flag for to\_csv after the first iteration. ``` def write_csv(): for i, (name, df) in enumerate(data.items()): df.to_csv('mydf.csv', mode='a', header=(i==0)) ``` Upvotes: 2 <issue_comment>username_3: Using the following logic(@username_1) I get my desired output. it was necessary to create an empty df, than populate it, then groupby meal and print to csv. main\_df= pd.DataFrame() ``` for name, df in data.items(): main_df = pd.concat([main_df, df]) main_df_group = main_df.groupby('Meal') for name, group in main_df_group: mydf_group = group mydf_group.to_csv(meal+ ...) ``` Upvotes: 0
2018/03/20
340
1,396
<issue_start>username_0: I have a Spring boot project using spring security and Oauth2 and I'm noticing some bad behaviour which could be caused by actuator. To be sure I want to remove it from the project but I can't find it explicitly mentionned in my Maven dependencies. Any idea on how to do it?<issue_comment>username_1: Use `mvn dependency:tree` to print all the transitive dependencies as a tree structure. It's a standard maven-dependency-plugin [mojo](https://maven.apache.org/plugins/maven-dependency-plugin/tree-mojo.html). Once you find the dependency that introduces it use section with correct to remove the actuator from the project. Upvotes: 2 <issue_comment>username_2: Find where it is with dependencies hiearchy and exclude it. This official [documentation](https://docs.spring.io/spring-boot/docs/2.2.1.RELEASE/maven-plugin/examples/exclude-dependency.html) may help you to do so. Upvotes: 3 [selected_answer]<issue_comment>username_3: It is not quite clear to me whether you want to exclude the actuator dependencies from your classpath or whether you want to disable the behaviour from your container. If it is the latter, you should be able to do so through your application.properties, i.e.: management.endpoints.enabled-by-default=false I am pretty sure you can disable also by using annotations on your spring boot application class as an alternative. Upvotes: 2
2018/03/20
291
1,159
<issue_start>username_0: I am running Dgraph database and the interface through the suggested docker images. Is it possible to run a command that drops all the data from the database and keeps the schema? Or at the very least drop both the data and schema? Or would I just have to delete the docker images and rebuild them?<issue_comment>username_1: Unfortunatelly, currently there's only command for dropping both schema and all data. You'll have to use the following HTTP call (or use the query directly in Ratel dashboard, since it uses HTTP communication): ``` curl -X POST localhost:8080/alter -d '{"drop_all": true}' ``` There's also possibility to drop a predicate: ``` curl -X POST localhost:8080/alter -d '{"drop_attr": "your_predicate_name"}' ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: Drop all data from Dgraph Ratel itself by navigating to the 'Schema' section and click 'Bulk Edit'. There it gives an option to Drop all data along with schema as a button 'Drop All'. Click 'Drop All' button, then enter 'DROP ALL' in the text box appeared in the pop-up and click 'Drop All' button. It removes all schemas and data Upvotes: 2
2018/03/20
1,650
4,636
<issue_start>username_0: I want to rewrite the following python code functionally: ``` lst = [0.0] * 10 for pos in [2,5]: lst[pos] = 1.0 ``` This is my attempt, but is incorrect: ``` lst = (lambda zeros: map( lambda pos: zeros[pos] = 1.0, [2,5]) )([0.0] * 10) ``` The error I get is `lambda cannot contain assignment`. Using list comprehension, the solution is: ``` lst = [ 1.0 if x in [2,5] else 0.0 for x in range(10) ] ```<issue_comment>username_1: I do prefer the list comprehension in your own answer, but if I were to do it with more of a functional touch, I think I would use a `lambda` function and a `map`: ``` lazy = map(lambda element: 1 if element in [2,5] else 0, range(10)) ``` Note that `map` is a lazy iterator in Python 3. If you want an evaluated `list` you have to enclose the line in an explicit `list(...)` constructor: ``` lst = list(map(lambda element: 1 if element in [2,5] else 0, range(10))) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: The list comprehension method is probably better, but if you're looking for functional how about this: ``` lst = [0.0] * 10 lst = map(lambda (i, x): 1.0 if i in {2,5} else x, enumerate(lst)) #[0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0] ``` By using `enumerate(lst)` as the iterable for `map()`, we get both the index and the value. In this case, we yield 0 if `i` is in `{2, 5}`. Otherwise we keep the value `x`. If you're using python3, you have to wrap the call to `map()` with `list()`. However, that approach is [not recommended](https://docs.python.org/3/whatsnew/3.0.html#views-and-iterators-instead-of-lists) as it wastefully creates a list. Upvotes: 1 <issue_comment>username_3: Another way you can do this is with generic function `unfold` ``` def unfold (f, acc): return f ( lambda x, next: [x] + unfold (f, next) , lambda x: [x] , acc ) def main (ones): def value (i): return 1 if i in ones else 0 return unfold ( lambda next, done, i: done (value (i)) if i >= 10 else next (value (i), i + 1) , 0 ) print (main ( { 2, 5 })) # [0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0] ``` `unfold` can be used in interesting ways ``` def alphabet (): return unfold ( lambda next, done, c: done (c) if c == 'z' else next (c, chr (ord (c) + 1)) , 'a' ) print (alphabet ()) # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] ``` Python's lambda syntax is really rigid its awkward ternary syntax make functional expressions painful to write. In the example below, we pre-define a function `gen` using some imperative syntaxes to help readability, then we pass it to `unfold` - this program also shows that `state` can be a complex value ``` def fib (n): def gen (next, done, state): (n, a, b) = state if n == 0: return done (a) else: return next (a, (n - 1, b, a + b)) return unfold (gen, (n, 0, 1)) print (fib (20)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765] ``` Of course all of this pain exists for a reason - it's a signal indicating that we're doing something wrong. A seasoned python programmer would never write `main`, `alphabet`, or `fib` like we did above. So it's not *pythonic* (as they say), but it's *functional*, and hopefully that answers your question. --- Below, we dramatically simplify `unfold` - instead of passing `next` and `done` helpers to the user lambda, we ask the user to return a tuple that encodes their choice: `(value, None)` says `value` is the last value in the sequence, `(value, nextState)` will produce the next value and continue with the next state. The trade-off here is the `unfold` is a little less complicated, but it requires the user to know the special tuple signalling to write their program. Before, `next` and `done` kept this worry out of the user's mind. Either way is fine, I share this just to give another alternative ``` def unfold (f, acc): (x, nextAcc) = f (acc) if nextAcc is None: return [x] else: return [x] + unfold (f, nextAcc) def fib (n): def gen (state): (n, a, b) = state if n == 0: return (a, None) else: return (a, (n - 1, b, a + b)) return unfold (gen, (n, 0, 1)) print (fib (20)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765] ``` Upvotes: 1
2018/03/20
805
2,798
<issue_start>username_0: I have several functions, click events delegated to a `.container` (this is generated dinamically) ``` $('.Container').on('click', '.a', function(){$(document).Function1();}); $('.Container').on('click', '.b', function(){$(document).Function2();}); $('.Container').on('click', '.c', function(){$(document).Function3();}); $('.Container').on('click', '.d', function(){$(document).Function4();}); $('.Container').on('click', '.e', function(){$(document).Function5();}); $('.Container').on('click', '.f', function(){$(document).Function6();}); ``` It works well, but how do I summarize all those callings into a single `on("click"` event?<issue_comment>username_1: HTML ``` ``` Jquery ``` $('.Container').on('click', '[data-fav-animal]', function() { var myFav = $(this).data('fav-animal'); WhichFunction(myFav); }); function WhichFunction(faveAnimal){ switch(faveAnimal) { case 'pig': doThis(); break; case 'cow';: doThat(); break; default: doThatOtherThing(); } return; } ``` Using something like a data attribute could give you more control. You could remove the letter classes and selector and use data attribute instead even. Also could use Enums to eliminate all the hardcode strings. ``` $('.Container').on('click', '.a, .b, .c, .d, .e, .f', function() { var myFav = $(this).data('fav-animal'); WhichFunction(myFav); }); ``` If the classes must remain on the DOM elements. ``` var functionName = "blah"; window[functionName](); ``` Allows execute of a function in global scope, just by knowing its name. This would allow you to remove the switch in code above and retain/gain flexibility. Upvotes: 2 [selected_answer]<issue_comment>username_2: You could do this in general following a pattern of. ``` $('.Container').on('click', '.a, .b', function(){ var $this = $(this); if ($this.hasClass('a')) { //do something } else if ($this.hasClass('b')) { //do something } }); ``` The trade off being you've moved the conditional from the child selector into the logic itself. Some might argue that this reduces readability and while I'm probably in that camp as well, this is indeed possible to do. Upvotes: 1 <issue_comment>username_3: This would kind of work: ```js let elements = ['.a', '.b', '.c', '.d', '.e', '.f'] let funcs = {}; // create Function1...6 for (let i=0; i < elements.length; i++) { funcs['Function'+(i+1)] = function() { console.log(elements[i]); } } $('.Container').on('click', elements.join(', '), function(e) { funcs[`Function${(elements.indexOf('.'+e.target.className)+1)}`]() }) ``` ```html * a * b * c * d * e * f ``` Let me know if that is what you were looking for. Upvotes: 0
2018/03/20
925
3,123
<issue_start>username_0: How object of Derived class `D d` can be accessed in friend class of `Base B`? Since there is no relationship between `D` and `F` then how it is possible to access private member `b_var` of object of `D` in friend class? ``` #include #include using namespace std; class B { //Base class int b\_var; friend class F; }; class D : public B { //Derived Class int d\_var; }; class F { //This class is a friend class of B public: //So it should access objects of B Not Derived Class void func(D &d) { // object LIke in example d d.b\_var = 5; cout << "I accessed D's Private Member b\_var :" << d.b\_var; } }; int main() { cout << "fine"; } ```<issue_comment>username_1: > > Since there is no relationship between D and F then how it is possible to access private member b\_var of object of D in friend class? > > > `F` has access to the base `B` of the class `D`, because it is a public base. Furthermore, `F` has access to private members of `B`, including `b_var`, because `F` is a friend of `B`. Thus, `F` has access to `b_var` that is a member of the base `B` of the class `D`. Perhaps it helps to visualize the accessibility to use a more qualified name lookup. `d.b_var` is same as `d.B::b_var`. Upvotes: 1 <issue_comment>username_2: What is happening here is that class `F` is a friend of class `B` which means it has full access to its members; `private, protected, public`. Class `D` is a child of class `B` it inherits all members of class `A` but `private` members. So trying to access private base class members will issue an erorr eg: ``` class D : public B{ void func(){ std::cout << b_var << std::endl; // error cannot access private members } }; ``` As you can see `D` is derived from `B` but cannot access `b_var` because it is `private`. You can make it access it if you declare the child to be friend of the parent: ``` class B{ int b_var; friend class D; }; class D : public B{ public: void func(){ cout << b_var; // ok now! because D is friend of its parent then it has access to its private data. } } ``` In your example class `D` is a child of class `B` so it cannot access `b_var` because it is private. But class `F` has full access to the class `B` so it can access its `private, public, protected` members: ``` class B{ int b_var = 10; friend class F; }; class D : public B{ int d_var; }; class F{ public: void func(D d){ cout << d.b_var; // it is a hack to encapsulation here B b; cout << b.b_var << endl; // ok here because F is friend of B. } }; ``` As you can see above that that `F` has full access to class `B` it uses a `D` object and granted to it this privilege. Normally `D` cannot access `B` private data but `F` grants access to it. * Friendship is not transitive (a friend of your friend is not your friend) * Friendship is not inherited (your friend's children are not your friends) * Friendship is not commutative (being me your friend doesn't mean being you my friend necessarily). Upvotes: 0
2018/03/20
303
1,173
<issue_start>username_0: I have an application made of multiple microservices. I would like to visualize it for newer developer to understand the flow chart. In some previous experiences, I have seen people draw flowchart like this one below. **Question: What is this kind of flow chart called? Is there any software tool that can draw it?** [flow chart](https://i.stack.imgur.com/tSkgz.png)<issue_comment>username_1: Use <https://www.planttext.com/> for creating the flowchart, You need to first understand the syntax for creating the flowchart. Upvotes: 1 <issue_comment>username_2: This diagram is called "Sequence Diagram". You can learn about its annotation at [IBM Rational site](https://www.ibm.com/developerworks/rational/library/3101.html) You can use tools like [Visual Paradigm](https://www.visual-paradigm.com) to draw it. They have a community version for non-commercial use. Upvotes: 1 [selected_answer]<issue_comment>username_3: This diagram is called "sequence diagram". You can use <https://www.zenuml.com> for creating sequence diagram. It comes with a super-developer-friendly syntax and is real-time. Disclaimer: I am the author :) Upvotes: 1
2018/03/20
885
3,005
<issue_start>username_0: ᕼello! I think I have a somewhat tricky postgres situation: `parent`s have `child`ren. `child`ren have an `age`, and a flag that they are the `appreciated`. **The rule:** a parent can't appreciate two children of the same age! My question is: *how to enforce this rule*? Current schema: ``` CREATE TABLE parent ( id SERIAL PRIMARY KEY, name VARCHAR(50) NOT NULL ); CREATE TABLE child ( id SERIAL PRIMARY KEY, parent INTEGER REFERENCES parent(id) NOT NULL, name VARCHAR(50) NOT NULL, age INTEGER NOT NULL, appreciated BOOLEAN NOT NULL ); ``` Put some values in: ``` INSERT INTO parent(name) VALUES ('bob'), -- assume bob's id = 0 ('mary'); -- assume mary's id = 1 INSERT INTO child(parent, name, age, appreciated) VALUES (0, 'child1', 10, FALSE), -- Bob has children 1, 2, 3 (0, 'child2', 10, FALSE), (0, 'child3', 15, FALSE), (1, 'child4', 20, FALSE), -- Mary has children 4, 5, 6 (1, 'child5', 20, FALSE), (1, 'child6', 10, FALSE); ``` All fine so far. No child is appreciated, which is always valid. Mary is allowed to appreciate child6: ``` UPDATE child SET appreciated=TRUE WHERE name='child6'; ``` Bob is allowed to appreciate child2. child2 is the same age as child6 (who is already appreciated), but child6 is not Bob's child. ``` UPDATE child SET appreciated=TRUE WHERE name='child2'; ``` Bob now *cannot* appreciate child1. This child1 is the same age as child2, and child2 is already appreciated. ``` UPDATE child SET appreciated=TRUE WHERE name='child2'; -- This needs to FAIL! ``` How do I enforce such a constraint? I'm open to all kinds of solutions, but modifying the general schema is not an option. Thanks in advance!<issue_comment>username_1: You might want to use a trigger that activates BEFORE the insert/update and that fails if the constraint you create is not satisfied. I suppose it should be like ``` create trigger before insert or update on for each row declare dummy number; begin select count(\*) into dummy from where (appreciated=TRUE and :new.child = child and :new.age = age); if dummy > 0 then raise\_application\_error(-20001,'Too many appreciated children'); end if; end; ``` [Some documentation](https://www.postgresql.org/docs/9.1/static/sql-createtrigger.html) Upvotes: 2 <issue_comment>username_2: The simplest thing I would think to do is add a flag grateful(?) == false to the parent model and when child.appreciated == true { parent.grateful == true } Check the value of parent.grateful in the function that acts on child.appreciated. If parent.grateful == true return "sorry this parent has already shown their appreciation." LOL this is an interesting concept though. Good Luck. :) Upvotes: 0 <issue_comment>username_3: How about a `UNIQUE` partial index, like so: ``` CREATE UNIQUE INDEX ON child(parent,age) WHERE appreciated; ``` So every pair of `parent`,`age` has to be unique, but only when appreciated children are considered. Upvotes: 3 [selected_answer]
2018/03/20
1,356
4,897
<issue_start>username_0: I have the following code working on my local eclipse setup which is accepting a JSON and printing it on the console using this `System.out.println(person);` Since, there is `toString` method in the `Person.java` class, in order to see the output, I have to pass the JSON in the following manner via POSTMAN `{"name":"Mickey","surname":"Mouse"}` This will print the following on the console: `16:05:16,409 INFO [stdout] (default task-4) Person [name=Mickey, surname=Mouse]` **MyQuestion:** If I have to accept a valid JSON like the following: ``` [{ "name": "FirstName", "value": "Mickey" }, { "name": "LastName", "value": "Mouse" }] ``` Is it possible to use something else than the `toString` method in the `Person.java` class which will print the above JSON on the console? **HelloWorldApplication.java** ``` package com.thejavageek.jaxrs; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; @ApplicationPath("/rest") public class ExampleApplication extends Application { } ``` **HelloWorldService.java** ``` package com.mypackage.jaxrs; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import com.mypackage.jaxrs.model.Person; @Path("/HelloWorld") public class HelloWorldService { @POST @Path("/writePersonToDB") @Consumes(MediaType.APPLICATION_JSON) public void writePersonToDB(Person person) { System.out.println(person); } } ``` **Person.java** ``` package com.mypackage.jaxrs.model; public class Person { private String name; private String surname; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } @Override public String toString() { return "Person [name=" + name + ", surname=" + surname + "]"; } } ```<issue_comment>username_1: As always, Mkyong has the answer. Check out his post [here](https://www.mkyong.com/java/how-to-enable-pretty-print-json-output-jackson/). In a nutshell, you need to serialize your Java object into a String. The framework will let you do it in XML or JSON (which is what you are looking for). You use Jackson for pretty-printing. ``` ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(person)); ``` NB: other posts refer to GSON which is another library for JSON in Java. Upvotes: 1 <issue_comment>username_2: First: your method `public void writePersonToDB(Person person)` will not take input as you defined ``` [{ "name": "FirstName", "value": "Mickey" }, { "name": "LastName", "value": "Mouse" }] ``` it is an Array or List, so you have to have a method which accepts `Array` or better a `List` as input Second: what prevents you to create a method which will print your input (whatever it is - `Person` or `List`) in format you need? If you'd like print in JSON format use @david-brossard answer to do that. If you'd like another format as you have in `Person.toString()` build your own... all is up to you. Upvotes: 0 <issue_comment>username_3: > > I have the following code working on my local eclipse setup which is > accepting a JSON and printing it on the console using this > System.out.println(person); -- > > > If I am not mistaken, by the time you get to this line `System.out.println(person);` that JSON is being converted to Java object. And all Java objects have a `toString()` method, which is invoked when you try and, in your case, print the object in console. > > Is it possible to use something else than the toString method in the > Person.java class which will print the above JSON on the console? > > > `toString()` is just one way for an object to be converted to a string. But I suggest you not to rush looking for other solutions, but you can simply override it this way: ``` public String toString() { StringBuilder sb = new StringBuilder("Person:\n"); sb.append("name: ").append(this.getName()).append("\n") append("surname: ").append(this.getSurname()).append("\n"); return sb.toString(); } ``` Or if you want this exactly like you state > > [{ > "name": "FirstName", > "value": "Mickey" }, { > "name": "LastName", > "value": "Mouse" }] > > > You can always modify `toString()` method with the use of a `StringBuilder` object accordingly. Please, try and maybe you will be happier with the outcome. If that does not satisfy you, then you can look into Jackson's pretty-printing. For that simply check other threads on stackOverflow and you will see what I mean. Upvotes: 1 [selected_answer]
2018/03/20
2,073
4,626
<issue_start>username_0: I want to fill missing values in my pandas series, if there are less than 3 consecutive NANs. **Original series with missing values:** ``` s=pd.Series(pd.np.random.randn(20)) s[[1,3,5,7,12,13,14,15, 18]]=pd.np.nan ``` Gives: ``` 0 0.444025 1 NaN 2 0.631753 3 NaN 4 -0.577121 5 NaN 6 1.299953 7 NaN 8 -0.252173 9 0.287641 10 0.941953 11 -1.624728 12 NaN 13 NaN 14 NaN 15 NaN 16 0.998952 17 0.195698 18 NaN 19 -0.788995 ``` BUT, using pandas.fillna() with a limit only fills the # of values specified (not number of CONSECUTIVE NANs, as expected): ``` s.fillna(value=0, limit=3) #Fails to fill values at position 7 and forward ``` Desired output would fill NANs with 0 at positions 1,3,5,7, and 18. It would leave series of 4 NaNs in place in position 12-15. The documentation and other posts on SO have not resolved this issue (e.g. [here](https://stackoverflow.com/questions/45372816/how-to-fill-na-with-mean-only-for-2-or-less-consequective-values-of-na)). Documentation seems to imply that this limit will work on consecutive NANs, not the overall # in entire dataset that will be filled. Thanks!<issue_comment>username_1: We start with finding where the `nan` values are via `pd.Series.notna`. As we use `cumsum`, whenever we encounter a non-null value, we increment the cumulative sum this generating convenient groups for contiguous `nan` values. However, for all but the first group (and maybe the first group) we begin with a non-null value. So, I take the negation of `mask` and sum the total number of null values within each group. Now I `fillna` and use `pd.DataFrame.where` to mask the spots where the sum of `nan` values was too much. ``` mask = s.notna() c_na = (~mask).groupby(mask.cumsum()).transform('sum') filled = s.fillna(0).where(c_na.le(3)) s.fillna(filled) 0 1.418895 1 0.000000 2 -0.553732 3 0.000000 4 -0.101532 5 0.000000 6 -1.334803 7 0.000000 8 1.159115 9 0.309093 10 -0.047970 11 0.051567 12 NaN 13 NaN 14 NaN 15 NaN 16 0.623673 17 -0.786857 18 0.000000 19 0.310688 dtype: float64 ``` --- Here is a fancy Numpy/Pandas way using `np.bincount` and `pd.factorize` ``` v = s.values m = np.isnan(v) f, u = pd.factorize((~m).cumsum()) filled = np.where( ~m, v, np.where(np.bincount(f, weights=mask)[f] <= 3, 0, np.nan) ) pd.Series(filled, s.index) 0 1.418895 1 0.000000 2 -0.553732 3 0.000000 4 -0.101532 5 0.000000 6 -1.334803 7 0.000000 8 1.159115 9 0.309093 10 -0.047970 11 0.051567 12 NaN 13 NaN 14 NaN 15 NaN 16 0.623673 17 -0.786857 18 0.000000 19 0.310688 dtype: float64 ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: You can try it with `rolling` operator in the following fashion: 1) Create a function that returns 0 only if there are less than X values in a window ``` fillnaiflessthan(series, count): if series.isnull().sum() < count and series.center == pd.NaN: return 0 ``` 2) Then use it inside `rolling` ``` s.rolling(window=5, center=True, min_periods=0).apply(lambda x: fillnaiflessthan(x, 4)) ``` Upvotes: 1 <issue_comment>username_3: First, build a na cum\_count column. Consecutive nas will have same cum\_count. ``` df = s.to_frame('value').assign(na_ct=s.notna().cumsum()) ``` Then we can group by the na cum\_count, check the number of rows in each group and decide weather to fill the nas or not. ``` df.groupby(df.na_ct).apply(lambda x: x if len(x)>4 else x.fillna(0)).value Out[76]: 0 0.195634 1 0.000000 2 -0.818349 3 0.000000 4 -2.347686 5 0.000000 6 -0.464040 7 0.000000 8 0.179321 9 0.356661 10 0.471832 11 -1.217082 12 NaN 13 NaN 14 NaN 15 NaN 16 -0.112744 17 -2.630191 18 0.000000 19 -0.313592 Name: value, dtype: float64 ``` Upvotes: 2 <issue_comment>username_4: Maybe try this ? ``` t=s[s.isnull()]; v=pd.Series(t.index,index=t.index).diff().ne(1).cumsum(); z=v[v.isin(v.value_counts()[v.value_counts().gt(3)].index.values)]; s.fillna(0).mask(s.index.isin(z.index)) Out[348]: 0 -0.781728 1 0.000000 2 -1.114552 3 0.000000 4 1.242452 5 0.000000 6 0.599486 7 0.000000 8 0.757384 9 -1.559661 10 0.527451 11 -0.426890 12 NaN 13 NaN 14 NaN 15 NaN 16 -1.264962 17 0.703790 18 0.000000 19 0.953616 dtype: float64 ``` Upvotes: 2
2018/03/20
405
949
<issue_start>username_0: I have a list like this one: ``` l1 = [{'a': 123, 'b': 128}, {'a': 998, 'b': 345}] ``` I would like to create another list that contains only the `a` values: example: ``` [123,998] ``` I try this: ``` [x,i for x in l1[i]] ``` but I get an error. Then i try this: ``` [x for x in l1[x]] ``` and this: ``` [x[0] for x in l1] ``` but nothing. I can't create the expected final result.<issue_comment>username_1: You can iterate over `l1` and access `'a'` from each element: ``` l1 = [{'a': 123, 'b': 128}, {'a': 998, 'b': 345}] a_list = [i['a'] for i in l1] ``` Output: ``` [123, 998] ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: This is the explicit way of achieving your goal ``` l1 = [{'a': 123, 'b': 128}, {'a': 998, 'b': 345}] alist = [] for dic in l1: alist.append(dic['a']) print(alist) ``` iterate through the list of dictionaries and append key a to a new list Upvotes: 2
2018/03/20
509
1,891
<issue_start>username_0: I have a FormArray and need to iterate through each of its members. I see there is a `get` method in [the docs](https://angular.io/api/forms/FormControl), but I don't see where to get the keys, or even the length. How do I iterate a FormArray?<issue_comment>username_1: You have a property `controls` in `FormArray` which is an array of `AbstractControl` objects. Check the specific documentation for [FormArray](https://angular.io/api/forms/FormArray) and you will see they also inherit from `AbstractControl` like the `FormControl` you posted. Be aware that in the controls array you can have again inside `FormArray` or `FormGroup` objects besides `FormControl` objects because there can be nested groups or arrays. Here is simple example: ``` for (let control of formArray.controls) { if (control instanceof FormControl) { // is a FormControl } if (control instanceof FormGroup) { // is a FormGroup } if (control instanceof FormArray) { // is a FormArray } } ``` Upvotes: 7 [selected_answer]<issue_comment>username_2: I solved this problem by looping through `formArray.controls` : ``` formArray.controls.forEach((element, index) => { ... }); ``` Upvotes: 5 <issue_comment>username_3: If someone needs helps with iterating them in template (like I did), you can do this. In this case we have FormArray where each child is FormControl ``` get myRows(): FormControl[] { return (this..get('') as FormArray).controls as FormControl[]; } ``` And in template ``` *ngFor="let row of myRows" ``` Upvotes: 2 <issue_comment>username_4: So, I had same situation, in my case: ``` adjustmentAmountArray: FormArray; ``` And I need sum of `contingencyUsed` of every FormArray item. ``` adjustmentAmountArray.controls.reduce((acc, curr) => { return acc + curr.value.contingencyUsed; }); ``` Upvotes: 1
2018/03/20
577
2,337
<issue_start>username_0: I have two table views that contain a mutable array of objects that can be instantiated by the user with various properties. The class and its properties are within separate `.h` and `.m` files that the table views access. I would like the two table views to look identical so that when a user adds, deletes, or moves an object in one table view, the second table view is immediately updated. I understand that they will be sharing a mutable array, but I'm not sure where to put it so that changes in one table view occurs in the other table view. Additionally, is this a situation in which I would make one of the table views a subclass of the other?<issue_comment>username_1: First you should make a singleton class that contains that mutable array so you can edit/access it anywhere , whenever you update that array reload the visible tableView , if the other tableView is also visible reload it(either with delegate , observer , notificationCenter), otherwise it will be updated with the last edit when you open the VC that contains it , also you can make a use of `viewDidAppear` to reload the table inside it as another choice instead of delegates if it's the logic of your app **// .h** ``` #import @interface GlobalData : NSObject @property(nonatomic,retain)NSMutableArray\*masterArray; +(GlobalData\*)shared; @end ``` **// .m** ``` #import "GlobalData.h" @implementation GlobalData static GlobalData *instance = nil; +(GlobalData *)shared { @synchronized(self) { if(instance==nil) { instance = [GlobalData new]; instance.masterArray = [NSMutableArray new]; } } return instance; } @end ``` **Usage** ``` [GlobalData.shared.masterArray addObject:"strData"]; ``` Upvotes: -1 [selected_answer]<issue_comment>username_2: Suppose there is a controller owns the `NSMutableArray` object and the two table views. * Use the `KVO` feature, let the two table view retain (use `strong` as property) the `NSMutableArray` object. * Create a new delegates array property like `NSArray< id > \*delegates` for the `NSMutableArray` object's owner, implement the `MyArrayNotifier` protocol in two table view classes, add the table objects to `delegates` array. Now you could get notified when your focused message arrived. Upvotes: 0
2018/03/20
1,027
3,600
<issue_start>username_0: I wanted to create a context menu on my line graph. When the user hovers across a point, they can right click and will see a context menu so that they can trigger more action. Is this possible with chart.js? Thanks, Derek<issue_comment>username_1: AFAIK there is no native support for context menu from Chart.js, but you can create it using HTML and handle it. This is an example: ```js var timestamp = [], speed = [10, 100, 20, 30, 40, 100, 40, 60]; for (var k = speed.length; k--; k>0) { timestamp.push(new Date().getTime()-60*60*1000*k); } var canvas = document.getElementById('chart'); var BB = canvas.getBoundingClientRect(), offsetX = BB.left, offsetY = BB.top; var ctx = canvas.getContext("2d"); var data = { labels: timestamp, datasets: [{ data: speed, label: "speed", backgroundColor: ['rgba(0, 9, 132, 0.2)'], borderColor: ['rgba(0, 0, 192, 1)'], borderWidth: 1, } ] }; var options = { scales: { yAxes: [{ ticks: { beginAtZero: true, } }], xAxes: [{ type: 'time', }] } }; var chart = new Chart(ctx, { type: 'line', data: data, options: options }); var $menu = $('#contextMenu'); canvas.addEventListener('contextmenu', handleContextMenu, false); canvas.addEventListener('mousedown', handleMouseDown, false); function handleContextMenu(e){ e.preventDefault(); e.stopPropagation(); var x = parseInt(e.clientX-offsetX); var y = parseInt(e.clientY-offsetY); $menu.css({left:x,top:y}); $menu.show(); return(false); } function handleMouseDown(e){ $menu.hide(); } menu = function(n){ console.log("select menu "+n); $menu.hide(); } ``` ```css #chart { width: 100%; height: 100%; } #contextMenu{ position:absolute; border:1px solid red; background:white; list-style:none; padding:3px; } .menu-item:hover { background: #dddddd; text-decoration: underline; cursor: pointer; } ``` ```html * Menu 1 * Menu 2 ``` Upvotes: 2 <issue_comment>username_2: For anyone looking for this, @username_1's answer does not have access to the clicked item (data point), you can save the state in `onHover` and use it in `contextmenu`. ``` options: { events: ['click', 'mousemove'], onHover: function(e, fields){ const lx = e.layerX; const bars = fields.filter(({_view: {x,width}}) => (x - width/2) <= lx && lx <= (x + width/2)); const data = bars.map(({_index, _datasetIndex}) => this.data.datasets[_datasetIndex].data[_index]); this.hoveredItem = {bars, data, fields}; }, }, plugins: [ { afterInit: (chart) => { var menu = document.getElementById("contextMenu"); chart.canvas.addEventListener('contextmenu', handleContextMenu, false); chart.canvas.addEventListener('mousedown', handleMouseDown, false); function handleContextMenu(e){ e.preventDefault(); e.stopPropagation(); menu.style.left = e.clientX + "px"; menu.style.top = e.clientY + "px"; menu.style.display = "block"; console.log(chart.hoveredItem); return(false); } function handleMouseDown(e){ menu.style.display = "none"; } } } ], ``` <https://codepen.io/elizzk/pen/xxZjQvJ> Upvotes: 1
2018/03/20
219
700
<issue_start>username_0: I have a string `"[testid-1] is locked out / / Subject: / Account Domain: NM /"` and I need to extract `"testid-1"` within the square braces and domain `"NM"` out of the string using Lua script. I am trying to use the below code with no luck, I have also tried escaping `[`. `aname=string.match(a,'[(.*)]')`<issue_comment>username_1: Just figured that the escape character in lua is %. This code works fine: ``` aname=string.match(a,'%[(.*)%]') adomain=string.match(a,'.*Account Domain: (%a+)') ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You can do it in a single call: ``` aname, adomain = a:match('%[(.*)%].*Account Domain:%s*(.-)%s*/') ``` Upvotes: 2
2018/03/20
2,325
6,403
<issue_start>username_0: I have a squared 2D array that I would like to rotate clockwise and counter clockwise. I was following this answer here for rotating to the right: [Rotating a 2D pixel array by 90 degrees](https://stackoverflow.com/questions/16684856/rotating-a-2d-pixel-array-by-90-degrees?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) The code I developed: ``` void rotateRight() { for (int i = 0; i < m_width; i += 1) { for (int j = i + 1; j < m_height; j += 1) { std::swap(get(i, j), get(j, i)); } } } ``` However, the array did not rotate. I have a 10x10 array with 5's, and on the top-left corner is a 7. I expected the 7 to go to the top-right corner after rotating, but it's still at the top-left corner. The member function get() is my own, which just returns a reference to a cell. ``` T& get(const int x, const int y) { return m_array[y * m_width + x]; } ``` How can I get this to rotate? Does a new array have to be made? Would appreciate the help. Thanks! **Update:** Latest attempt. Okay, so the '7' rotated to the right finally from the top-left corner to the top-right corner. But when rotateRight() is called again, it fails. My 7 on the top-right corner is gone and no longer found. Looking into it. ``` for (int i = 0; i < m_width; i += 1) { for (int j = i + 1; j < m_height; j += 1) { get(j, i) = get(i, j); } } for (int i = 0; i < m_height; i++) { for (int j = 0, k = m_height - 1; j ``` Output: ``` Original: 700 000 000 Rotation #1: J: 1, I: 0 J: 2, I: 0 J: 2, I: 1 J: 0, I: 0, K: 2 Value: 7 J: 0 K: 2 J: 0, I: 1, K: 2 Value: 0 J: 0 K: 2 J: 0, I: 2, K: 2 Value: 0 J: 0 K: 2 007 000 000 Rotation #2: J: 1, I: 0 J: 2, I: 0 J: 2, I: 1 J: 0, I: 0, K: 2 Value: 0 J: 0 K: 2 J: 0, I: 1, K: 2 Value: 0 J: 0 K: 2 J: 0, I: 2, K: 2 Value: 0 J: 0 K: 2 000 000 000 ``` **Final code** ``` // Rotates a squared array clockwise. void rotateRight() { T temp; int halfwidth_floor = m_width / 2; int halfwidth_ceil = (m_width + 1) / 2; for (int j = 0; j < halfwidth_floor; j += 1) { for (int i = 0; i < halfwidth_ceil; i += 1) { std::swap(temp, get(i, j)); std::swap(get(i, j), get(j, m_width - i - 1)); std::swap(get(j, m_width - i - 1), get(m_width - i - 1, m_width - j - 1)); std::swap(get(m_width - i - 1, m_width - j - 1), get(m_width - j - 1, i)); std::swap(get(m_width - j - 1, i), temp); } } } // Rotates a squared array counter-clockwise. void rotateLeft() { T temp; int n = m_width; for (int i = 0; i < n / 2; i++) { for (int j = i; j < n - i - 1; j++) { std::swap(temp, get(i, j)); std::swap(get(i, j), get(n - j - 1, i)); std::swap(get(n - j - 1, i), get(n - i - 1, n - j - 1)); std::swap(get(n - i - 1, n - j - 1), get(j, n - i - 1)); std::swap(get(j, n - i - 1), temp); } } } ```<issue_comment>username_1: ~~Each iteration of your inner loop is swapping (i, j) with (j, i).~~ If (i == j), then it will do nothing. If (i != j), then that swap will be done twice - for example, the swap done when i == 3 and j == 4 will be done again when i == 4 and j == 3. Doing a swap twice of course results in nothing happening overall. That's why your code will finish with an array that's exactly the same as it started. What you may want to do instead is to write into a *different* array to the one you started with. edit: nevermind, I missed the `int j = i + 1` part of the question and thought both loops were iterating from 0 to the width or height. (The above might still be a useful insight for anyone looking to do the same thing though.) Your code will *transpose*, not rotate, the array. (Transpose means to reflect along the diagonal from top left to bottom right.) To rotate, you'd want to move each element (i, j) to (j, w-i-1) or to (h-j-1, i). (Though of course, to rotate by 90 degrees, your array needs to be a square, i.e. (w == h)). edit 2: If you want to rotate a square array in-place, by 90 degrees, std::swap won't work (because it swaps 2 elements), and raw assignment won't work (because it loses information). What you can do, though, is to iterate over a quarter of the array and rotate a sequence of 4 elements, like so: ``` void rotateRight() { int halfwidth_floor = m_width / 2; int halfwidth_ceil = (m_width + 1) / 2; for (int j = 0; j < halfwidth_floor; j += 1) { for (int i = 0; i < halfwidth_ceil; i += 1) { value_type temp = get(i, j); get(i, j) = get(j, m_width-i-1); get(j, m_width-i-1) = get(m_width-i-1, m_width-j-1); get(m_width-i-1, m_width-j-1) = get(m_width-j-1, i); get(m_width-j-1, i) = temp; } } } ``` Where `value_type` is the type of your array elements (and m\_width == m\_height). On the first iteration, this will move the bottom left to the top left, then the bottom right to the bottom left, then the top right to the bottom right, then the (temporarily saved) top left to the top right. Subsequent iterations will do the same for other points, getting closer towards the center. Note that one `for` loop iterates to half the size rounded down, and the other rounds up: this is so that in an array with an odd size (e.g. 5x5) it will look at a rectangle of 2x3 and its "rotations" around the square, to avoid rotating the middle elements twice (or not at all). Upvotes: 3 [selected_answer]<issue_comment>username_2: **What you are doing** Transposing the matrix. **What you should be doing** The algorithm to rotate a matrix consists of 2 steps 1. Transpose the matrix ( if rotating left) . Transpose and reverse the order of the columns if rotating right) 2. Reverse the columns Illustrated below ``` 1 2 3 1 4 7 3 6 9 4 5 6 => 2 5 8 => 2 5 8 7 8 9 3 6 9 1 4 7 ``` **Code** Like so, (initialize an aux array that will hold the rotated array, because the shape could be not square) ``` void rotate() { for (int i = 0; i < m_width; i += 1) { for (int j = i + 1; j < m_height; j += 1) { aux_array[j][i] = get(i, j) } } for (int i=0; i < m_height; i++) { for (int j=0, int k=m_height-1; j ``` Upvotes: 0
2018/03/20
872
3,163
<issue_start>username_0: My template parser looks like this (p/s the .'/'. is for readability): ``` $this->parser->parse($this->settings['theme'].'/'.'header', $data); $this->parser->parse($this->settings['theme'].'/'.'register', $data); $this->parser->parse($this->settings['theme'].'/'.'footer', $data); ``` I don't want to declare `$this->parser->parse($this->settings['theme'].'/'.'header', $data);` and `$this->parser->parse($this->settings['theme'].'/'.'footer', $data);` every time in my controller's functions. How can I extend the `MY_Parser.php` so that I could use it like this instead: `$this->parser->parse($this->settings['theme'].'/'.'register', $data);` will include the `register.php` between my `header.php` and `footer.php` automatically. The benefit of doing this is to save 2 lines and if I have 20 functions, I can save 40 lines.<issue_comment>username_1: Create class with the name of your prefix class name in application/core folder and follow below code. $this->input->is\_ajax\_request() will only load view other then header and footer if request is from ajax. and in each controller you need to extend YOUR-PREFIX\_Controller instead of CI\_Controller ``` php if (!defined('BASEPATH')) exit('No direct script access allowed'); class YOUR-PREFIX_Controller extends CI_Controller { protected $header_data; protected $footer_data; protected $header_view; protected $footer_view; public function __construct() { parent::__construct(); $this-header_view = 'path-to-header'; $this->footer_view = 'path-to-footer'; } public function _output($output) { if ($this->input->is_ajax_request()) { echo ($output); } else { echo $this->load->view($this->header_view, $this->header_data, true); echo ($output); echo $this->load->view($this->footer_view, $this->footer_data, true); } } } ?> ``` Upvotes: 0 <issue_comment>username_2: Just create a function (can be a helper, library extension or model): ``` function tpl($view, $data) { $this->parser->parse($this->settings['theme'].'/'.'header', $data); $this->parser->parse($this->settings['theme'].'/'.$view, $data); $this->parser->parse($this->settings['theme'].'/'.'footer', $data); } ``` If you want you can extend `Parser` and make a `MY_Parser` in the libraries folder and do: ``` class MY_Parser extends CI_Parser { function tpl($view, $data) { $this->parse($this->settings['theme'].'/'.'header', $data); $this->parse($this->settings['theme'].'/'.$view, $data); $this->parse($this->settings['theme'].'/'.'footer', $data); } } ``` Usage: ``` $this->parser->tpl($view, $data); ``` You could do this using `$this->parser->parse()` but that would require more code as you overwriting the default method and it's just as easy to introduce a new method. **UPDATE:** *Using the `MY_Parser` method you might have to access `$this->settings` via `$this->CI->settings` thereby referencing the CI instance in `CI_Parser` depending on where this variable is coming from.* Upvotes: 2 [selected_answer]
2018/03/20
1,040
3,355
<issue_start>username_0: When i open the html file on google chrome. It is just a blank page. Nothing is loading. If i take out the .js files it loads the content with the .css applied but never with the .js files. Whether I put the .js files in the or at the end of the it still does not show anything. I am using jquery btw and downloaded the file. all files are on the same folder. also tried both jquery-3.3.1.min.js and jquery-migrate-1.4.1.js if it makes a difference. Hoping someone can help. Thanks! HTML: ``` Title Blocks ====== * 10000$ * -10000$ * 10000$ * -10000$ * Bank * Loan Credit Side =========== 1. Add your items here Debit side ========== 1. Add your items here ``` .JS ``` $("#products li").draggable({ appendTo: "body", helper: "clone" }); $("#shoppingCart1 ol").droppable({ activeClass: "ui-state-default", hoverClass: "ui-state-hover", accept: ".credit", drop: function(event, ui) { var self = $(this); self.find(".placeholder").remove(); var productid = ui.draggable.attr("data-id"); if (self.find("[data-id=" + productid + "]").length) return; $("- ", { "text": ui.draggable.text(), "data-id": productid }).appendTo(this); // To remove item from other shopping cart do this var cartid = self.closest('.shoppingCart').attr('id'); $(".shoppingCart:not(#" + cartid + ") [data-id=" + productid + "]").remove(); } }).sortable({ items: "li:not(.placeholder)", sort: function() { $(this).removeClass("ui-state-default"); } }); // Second cart $("#shoppingCart2 ol").droppable({ activeClass: "ui-state-default", hoverClass: "ui-state-hover", accept: ".debit", drop: function(event, ui) { var self = $(this); self.find(".placeholder").remove(); var productid = ui.draggable.attr("data-id"); if (self.find("[data-id=" + productid + "]").length) return; $("- ", { "text": ui.draggable.text(), "data-id": productid }).appendTo(this); // To remove item from other shopping chart do this var cartid = self.closest('.shoppingCart').attr('id'); $(".shoppingCart:not(#" + cartid + ") [data-id=" + productid + "]").remove(); } }).sortable({ items: "li:not(.placeholder)", sort: function() { $(this).removeClass("ui-state-default"); } }); ``` .CSS ``` h1 { padding: .2em; margin: 0; } #products { float:left; width:200px; height: 600px; margin-right: 20px; } #products ul {list-style: disc; padding: 1em 0 1em 3em;} .shoppingCart{ width: 200px; margin: 20px; float: left; } .shoppingCart ol { margin: 0; padding: 1em 0 1em 3em; list-style-type: decimal; } ```<issue_comment>username_1: Use ``` ``` Because `jquery-migrate` not contains entire jquery code. Of course you can include script from local. Upvotes: 2 [selected_answer]<issue_comment>username_2: Issues: 1. Your HTML files do not have CDN links to jquery and jquery UI. They require in the same order. First, you need jquery CDN and second jquery UI cdn 2. You're using jquery in a testing.js file but you do not have document.ready function. Solution: 1. Add cdn links for jquery and jquery UI 2. Wrap your javascript code within document.ready function. Here is a [MDN document](https://learn.jquery.com/using-jquery-core/document-ready/) [Solution](https://github.com/username_2/StackOverflow-example) Upvotes: 0
2018/03/20
664
2,154
<issue_start>username_0: I want to create a suggestbox but the items in my "dropdown" wrap. I would like them to take as much space horizontally as they need. How can I tell the menu to take as much space as its children need horizontally? ```css .container { position: relative; width: 200px; } .container > input { box-sizing: border-box; width: 100%; } .menu { position: absolute; border: 1px solid blue; padding: 2px; } ``` ```html a very very very very long item ``` and a jsfiddle: <https://jsfiddle.net/89d2z95t/6/><issue_comment>username_1: On your `.container` you could specify `min-width: 200px;` instead of an absolute width, which will allow it to stretch horizontally with its children. Then also to prevent even larger spans you could enforce it to never wrap: ``` .item { white-space: nowrap; overflow: hidden; } ``` Upvotes: 1 <issue_comment>username_2: An absolutely positioned element has a bounding box which is set by the nearest positioned ancestor ([MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/position)). This out-of-flow element is confined by those boundaries. In your code, since the nearest positioned ancestor (`.container`) has a fixed width of 200px, the absolutely-positioned descendant (`.menu`) cannot exceed that limit. Therefore, the text wraps. You can force the element to overflow the bounding box with [**`white-space: nowrap`**](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space). ```css .container { position: relative; width: 200px; } .container>input { box-sizing: border-box; width: 100%; } .menu { position: absolute; border: 1px solid blue; padding: 2px; white-space: nowrap; /* NEW */ } ``` ```html a very very very very long item ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Update to your jsfiddle, set your input's `width:200px` ```css .container { position: relative; } .container > input { box-sizing: border-box; width:200px; } .menu { position: absolute; border: 1px solid blue; padding:2px; } ``` ```html a very very very very long item ``` Upvotes: 1
2018/03/20
1,068
4,078
<issue_start>username_0: I have some old code in CVS format ([RCS format](https://www.systutorials.com/docs/linux/man/5-rcsfile/)). I would like to avoid checking in a new revision only to fix the indentation, and not syntax. Often the original developer no longer has an account (they have left the company). If I were to fix that indentation, then that change is marked with my user account in `cvs annotate` output, which is undesirable. Since only indentation is changed, functionality is not changed. The net result is that, when the file is checked out again, its indentation is corrected, and a `cvs annotate` shows that line of the last "real" change and its associated author. So, is this even possible with directly editing of the `,v` RCS file (on a copy of the file on a locked down CVSROOT, for instance), or are there checksums that check for such editing ([RCS format](https://www.systutorials.com/docs/linux/man/5-rcsfile/) alludes to a "integrity" field but it is not clear if it is the thing that would invalidate this type of change)? Notice this is CVS-specific; other source code control systems such as Git have built-in mechanisms. (Migrating to those other systems is being considered but that is off-topic here). <https://stackoverflow.com/a/46713192/257924> seems to indicate there are tools readily available for parsing the underlying RCS format (,v files), so might be used for the basis of this in case it is actually true that there is some type of checksum in the file. But if I could just do the edits directly, that would be better.<issue_comment>username_1: It's certainly possible in theory to rewrite an RCS revision file in place. It's quite tricky to achieve in practice, though. As the answer you linked notes, the content of an RCS `,v` file is (are?): * the latest version in the trunk * with reverse deltas to produce each earlier trunk version * but with forward deltas to produce each branch version What this means is that to replace a particular version somewhere, you must: 1. Locate its position in the trunk or branch stream. 2. If it is in the trunk, rewrite the previous trunk delta while replacing this specific trunk version, which may mean rewriting this delta or rewriting the intact final version in place; 3. otherwise (it's a branch version), rewrite the subsequent delta while rewriting this version's predecessor's delta that leads to this version. This process is likely to be pretty error-prone. It's much simpler to just forge the user name. Produce an updated version of the file and commit it as the user you intend to get the credit/blame. [If you control the system, you control whether some credentials are accepted.](http://www.cvsnt.org/cvsclient/Connection-and-Authentication.html) If not, you can't rewrite the `,v` file anyway. Upvotes: 1 <issue_comment>username_2: I would avoid rewriting the raw `,v` file if you possibly can. Lots of things can go wrong in there, and the pool of people who can help dwindles each passing day. I would suggest "lying" to RCS instead. Something like this: ``` $ co -l file.ext $ prettyformat file.ext $ lastauthor=$(rlog file.ext | awk '$1=="date:"{print $5;exit}') $ ci -u -w"${lastauthor%;}" -m'formatting updates' file.ext ``` I don't know what your `prettyformat` command might be, but you can swap it in. The basic idea here is that we WILL do an update to each file, but we'll "fake" the author name with `-w`. This is fine, it's just a text string in the `,v` file, there's no magic associated with it. If you're also concerned about dates, you could also fake them with the `-d` option: ``` $ lastmod=$(rlog file.ext | awk '$1=="date:"{print $2,$3;exit}') $ co -l file.ext $ prettyformat file.ext $ lastauthor=$(rlog file.ext | awk '$1=="date:"{print $5;exit}') $ ci -u -w"${lastauthor%;}" -d"${lastmod%;}" -m'formatting updates' file.ext ``` This way, if you choose to migrate things to something other than CVS in the future, the age of each file will be recorded correctly irrespective of the formatting changes. Upvotes: 3 [selected_answer]
2018/03/20
1,231
4,427
<issue_start>username_0: Currently I have a function to return the first elements of each list (floats), within a list to a separate list. ``` let firstElements list = match list with | head::_ -> head | [] -> 0.00 ``` My question is, how do I expand this to return elements at the same index into different lists while I don't know how long this list is? For example ``` let biglist = [[1;2;3];[4;5;6];[7;8;9]] ``` If I did not know the length of this list, what is the most efficient and safest way to get ``` [[1;4;7];[2;5;8];[3;6;9]] ```<issue_comment>username_1: `List.transpose` has been added recently to FSharp.Core ``` let biglist = [[1;2;3];[4;5;6];[7;8;9]] let res = biglist |> List.transpose //val res : int list list = [[1; 4; 7]; [2; 5; 8]; [3; 6; 9]] ``` Upvotes: 2 <issue_comment>username_2: You can use the recent added `List.transpose` function. But it is always good to be good enough to create such functions yourself. If you want to solve the problem yourself, think of a general algorithm to solve your problem. One would be. 1. From the first element of each list you create a new list 2. You drop the first element of each list 3. If you end with empty lists you end, otherwise repeat at step 1) This could be the first attempt to solve the Problem. Function names are made up, at this point. ``` let transpose lst = if allEmpty lst then // Some Default value, we don't know yet else ... ``` The `else` branch looks like following. First we want to pick the first element of every element. We imagine a function `pickFirsts` that do this task. So we could write `pickFirsts lst`. The result is a list that itself is the first element of a new list. The new list is the result of the remaining list. First we imagine again a function that drops the first element of every sub-list `dropFirsts lst`. On that list we need to repeat step 1). We do that by a recursive call to `transpose`. Overall we get: ``` let rec transpose lst = if allEmpty lst then // Some Default value, we don't know yet else (pickFirsts lst) :: (transpose (dropFirsts lst)) ``` At this point we can think of the default value. `transpose` needs to return a value in the case it ends up with an empty list of empty lists. As we use the result of `transpose` to add an element to it. The results of it must be a `list`. And the best default value is an empty list. So we end up with. ``` let rec transpose lst = if allEmpty lst then [] else (pickFirsts lst) :: (transpose (dropFirsts lst)) ``` Next we need to implement the remaining functions `allEmpty`, `pickFirsts` and `dropFirsts`. `pickFirst` is easy. We need to iterate over each element, and must return the first value. We get the first value of a list by `List.head`, and iterating over it and turning every element into a new list is what `List.map` does. ``` let pickFirsts lst = List.map List.head lst ``` `dropFirsts` need to iterate ver each element, and just remove the first element, or in other words keeps the remaining/tail of a list. ``` let dropFirsts lst = List.map List.tail lst ``` The remaining `allEmpty` is a predicate that either return true/false if we have an empty list of lists or not. With a return value of `bool`, we need another function that allows to return another type is a list. This is usually the reason to use `List.fold`. An implementation could look like this: ``` let allEmpty lst = let folder acc x = match x with | [] -> acc | _ -> false List.fold folder true lst ``` It starts with `true` as the default value. As long it finds empty lists it returns the default value unchanged. As soon there is one element found, in any list, it will return `false` (Not Empty) as the new default value. The whole code: ``` let allEmpty lst = let folder acc x = match x with | [] -> acc | _ -> false List.fold folder true lst let pickFirsts lst = List.map List.head lst let dropFirsts lst = List.map List.tail lst let rec transpose lst = if allEmpty lst then [] else (pickFirsts lst) :: (transpose (dropFirsts lst)) transpose [[1;2;3];[4;5;6];[7;8;9]] ``` Another approach would be to turn it into a 2 dimensional mutable array. Also do length checkings. Do the transformation and return the mutable array again as an immutable list. Upvotes: 3 [selected_answer]
2018/03/20
745
2,530
<issue_start>username_0: I'm in a CS class and I'm trying to create a tic tac toe program. This is my first time using functions and I need help checking a 2d array to see if it is full with 'x' or 'o' s. I initialized to start off with all the elements to '\_' and I want a return value of true or false so I'm using `#include` . Here is the function: ``` bool check_table_full(char board[SIZE][SIZE]){ if(board[0][0] == '_'){ return false; }else if(board[1][0] == '_'){ return false; }else if(board[2][0] == '_'){ return false; }else if(board[0][1] == '_'){ return false; }else if(board[1][1] == '_'){ return false; }else if(board[2][1] == '_'){ return false; }else if(board[0][2] == '_'){ return false; }else if(board[1][2] == '_'){ return false; }else if(board[2][2] == '_'){ return false; }else{ return true; } ``` I know there is a better optimization then using if else statement but this is just is simple in my head. I use `printf("%s", check_table_full?"true":"false");` to check if it returns false as it should since all elements in the array are '\_'. No matter what I do it prints true, and if I change the "true" in the printf statement it prints whatever is inside the first quote. Everything else works like SIZE is defined, the array is defined, I just can't get this function to return false. Sorry if this is lengthy, this is my first time asking a question on here.<issue_comment>username_1: Your method of traversing the matrix is not scalable, you can easily introduce errors and is unnecessary complex. My 'check method' is 2 lines of code for any matrix size. ``` #include #include #define MXSIZE 3 bool is\_full(char \*block) { for (int l=0;l ``` Upvotes: -1 <issue_comment>username_2: **If** you do `printf("%s", check_table_full?"true":"false");`, you are *not* calling the function. `check_table_full` is the *address* of the function. You want `check_table_full()` Upvotes: 3 [selected_answer]<issue_comment>username_3: You may want to use nested for-loops. I have learned C++ syntax and not C syntax, so the syntax may be a little off. Example Code... ``` #include int main() { char board[2][2]; int outer\_count, inner\_count; //It will use nested for loops for (outer\_count = 0; outer\_count <= 2; count++) { for (inner\_count = 0; inner\_count <= 2; count ++) { if (board[outer\_count][inner\_count] == '\_'){ return false; } } } return True } ``` Upvotes: 0
2018/03/20
337
1,188
<issue_start>username_0: I hate css, I really do. I think this one will be trivial for most of you so please help me with this one. I would like to create a radiobutton which have to change the background color of the label it's in. Here's the code which obviously does not work: js: ``` ``` and css: ``` .check { background-color: green; display: inline-block; height: 34px; position: relative; width: 60px; cursor: pointer; } .check input { display:none; } input[type="radio"]:checked + .check { background-color: blue; } .container { margin: 0 auto; } ```<issue_comment>username_1: The `+` selector in CSS selects the next element in the HTML. Doing `input + label` is not going to work because your input is wrapped in the label. The easiest solution for this would be to apply a `checked` CSS class in react when the input is checked. The other option would be to place the label AFTER the input in your markup, but that will probably require you to apply more CSS to get the appearance you need. Upvotes: 2 [selected_answer]<issue_comment>username_2: I really love CSS, I really do! ;) Change your HTML to: ``` ``` and style the radio button individually. Upvotes: 0
2018/03/20
378
1,317
<issue_start>username_0: I'm doing some tests and I relate to the bands and albums tables with the foreign key. I tried deleting a row with a foreign key, but this returned parent row error My Code: ``` DELETE FROM BANDS WHERE idBand = '13 '; DELETE FROM albums WHERE albumId = '13 '; ``` > > albumId is the idBand foreign key > > > So, how to delete a foreign key row with condition?<issue_comment>username_1: you must delete from the albums table first. this is the parent table so all child rows must go first. just reverse the order of your delete. I am assuming your albums table is a child of the bands table delete all albums for this band ``` delete from albums where bandid = 13 ``` now delete the band ``` delete from bands where bandid = 13 ``` now you have a songs table which is a child of a child so how do you delete all of those? You have to remove all songs for all albums for that band. Now this will have to be done before you can delete the album ``` delete from Songs where albumid in (select albumid from albums where bandid = 13) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: I think the OP typed the wrong sql based on his comment? ``` DELETE FROM albums WHERE albumId='13' ``` should have been ``` DELETE FROM albums WHERE bandId='13' ``` ? Upvotes: 0
2018/03/20
780
2,496
<issue_start>username_0: I want the result of the math function into my css file, that the kind of blur is variable. But it doesn't work and I don't know how, because there are no errors. The variable number is between 1 and 5. This is the Javascript code I'm using: ``` var minNumber = 1; var maxNumber = 5; var result; var randomNumber = randomNumberFromRange(minNumber, maxNumber); function randomNumberFromRange(min, max) { result = Math.floor(Math.random() * (max - min + 1) + min); return; } document.getElementById("test").style.filter = blur(result + "px"); ```<issue_comment>username_1: Check your console. You should have an error saying `blur` is undefined. `blur` is not a function defined in JS, but rather a CSS filter function, and as such should be set as a string in your case. For example: ``` document.getElementById("test").style.filter = 'blur('+result+'px)'; ``` If ES6 is possible in your case, you can also use a [template string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) and plug the value as an embedded expression: ``` document.getElementById("test").style.filter = `blur(${result}px)`; ``` Upvotes: 1 <issue_comment>username_2: You need to pass blur as a text value to the CSS filter property: ```js var minNumber = 1; var maxNumber = 5; var result; var randomNumber = randomNumberFromRange(minNumber, maxNumber); function randomNumberFromRange(min, max) { result = Math.floor(Math.random() * (max - min + 1) + min); return; } console.log('random value for blur: ', result); document.getElementById("test").style.filter = 'blur('+ result +'px)'; ``` ```html test ``` Upvotes: 1 <issue_comment>username_3: **Set that style as a string:** ``` document.getElementById("test").style.filter = "blur(" + result + "px)"; ``` ```js var minNumber = 1; var maxNumber = 5; var result; var randomNumber = randomNumberFromRange(minNumber, maxNumber); function randomNumberFromRange(min, max) { result = Math.floor(Math.random() * (max - min + 1) + min); } document.getElementById("test").style.filter = "blur(" + result + "px)"; ``` ```css #test { position: absolute left: 10px; top: 10px; background-color: lightgreen; width: 200px; height: 200px; z-index: 9999; opacity: .9; } #test2 { position: absolute; left: 30px; top: 40px; background-color: black; width: 100px; height: 100px; } ``` ```html ``` Upvotes: 3 [selected_answer]
2018/03/20
629
2,046
<issue_start>username_0: I am using semantic ui react and I am using NavLink with Menu.Item for routing. Below is my navbar component: ``` const Navbar = () => ( ![header]({Logo}) Home Dashboard User ); ``` Now here is where the issue resides. The routing works fine but for some reason the 'Home' Menu Item is **always active**. However the other two routes work fine (i.e. are only set 'active' when route is correct) [Here is what it looks like with /dashboard route active](https://i.stack.imgur.com/fcnVK.png) The code for the routes in my App.jsx: ``` ``` The photo above should give you a clear indication of the issue! Any input would be appreciated!!<issue_comment>username_1: Can confirm as from AngelSalazar above, this fixes it. Thank you! ``` ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Here is the setup that I have that helped fix the issue. I was getting the following error: ``` Warning: validateDOMNesting(...): cannot appear as a descendant of . in a (created by Link) in Link (created by Route) in Route (created by NavLink) in NavLink (created by MenuItem) in MenuItem (at NavBar.js:47) in a (created by Link) in Link (created by Route) in Route (created by NavLink) in NavLink (at NavBar.js:46) in div (created by Menu) in Menu (at NavBar.js:20) in NavBar (at App.js:26) in div (at App.js:25) in Router (created by BrowserRouter) in BrowserRouter (at App.js:24) in div (at App.js:22) in App (at index.js:6) ``` The main component setup was in App.js where I was doing my routing ``` ``` Here I have my NavBar component which holds the and where I was having the issue. ``` class NavBar extends Component{ constructor(){ super(); this.state={ activeItem: "home" } } handleItemClick = (e, { name }) => this.setState({ activeItem: name }) render() { const { activeItem } = this.state return ( Bills ``` I removed the NavLink tags and within the Menu.Item tags I added: ``` as={NavLink} to="bills" ``` After update: ``` Login ``` Upvotes: 0
2018/03/20
793
2,677
<issue_start>username_0: *Please do not vote to close. This is about the technical reason on why this is not working. I already have a working solution and I'm not asking for it.* Simple example where I need to make `.wrapper` height, at least, the browser height. The following works in IE10-11, Edge, Firefox, Chrome ([working fiddle](https://jsfiddle.net/nhhqw15y/)): ``` Demo body { margin: 0; height: 100vh; background-color: red; } .wrapper { min-height: 100%; background-color: green; } ``` But if I set `body` to `min-height` instead of `height` (which is, IMHO, reasonable), it doesn't work anymore ([not working fiddle](https://jsfiddle.net/nhhqw15y/2/)). Why? What's the technical reason behind it? **EDIT 1** [Another **working** fiddle](https://jsfiddle.net/nhhqw15y/9/) where `body` has `min-height: 100vh` and `.wrapper` has `min-height: inherit`. [Another **working** fiddle](https://jsfiddle.net/nhhqw15y/11/) where only `.wrapper` has `min-height: 100vh`.<issue_comment>username_1: And here we go:D I think i find a issue. [fiddle](https://jsfiddle.net/PiotrCodeReaper/9hhxLk1w/3/) ``` .wrapper { min-height: 100vh; background-color: green; } ``` In my point of view min-height of some VH - Viewport Height can't be overlapped, with %. **vh !=%.** ----------- So only think to do it's change the wrapped min-height from % to vh. Hope i helped. Upvotes: 2 <issue_comment>username_2: The [CSS 2.2 spec says](https://www.w3.org/TR/CSS22/visudet.html#min-max-widths): > > The percentage is calculated with respect to the height of the > generated box's containing block. **If the height of the containing > block is not specified explicitly** (i.e., it depends on content > height), and this element is not absolutely positioned, **the percentage > value is treated as '0'** (for 'min-height') or 'none' (for > 'max-height'). > > > So that's the rule. The reasoning behind the rule is pretty simple, and follows similar rules in CSS 2, circular dependencies must be avoided. When the container's height is specified, it has no dependency on the height of its content, so its content height can be safely specified as a percentage of that without creating a circular dependency. But that doesn't apply to when only the container's min-height is specified. If the content's height is greater than the min-height, then the container's height depends on the content's height, and if that's a percentage, then the content's height depends on the container's height, and you have a circular dependency. So it intentionally "doesn't work", to stop that situation arising. Upvotes: 3
2018/03/20
1,137
3,873
<issue_start>username_0: I first installed cuda 9.0 and cudnn for cuda 9.0 and the latest tensorflow-gpu 1.6. But I noticed my nvidia-driver 384.111 doesn't support cuda 9.0. SO I uninstalled cuda 9.0, cudnn and tensorflow-gpu 1.5 and reinstalled tensorflow-gpu 1.5, cuda8.0 and cudnn v7.1 for cuda 8.0. But when I import tensorflow, it always shows: ``` Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.7/dist-packages/tensorflow/\_\_init\_\_.py", line 24, in from tensorflow.python import \* File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/\_\_init\_\_.py", line 49, in from tensorflow.python import pywrap\_tensorflow File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/pywrap\_tensorflow.py", line 74, in raise ImportError(msg) ImportError: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/pywrap\_tensorflow.py", line 58, in from tensorflow.python.pywrap\_tensorflow\_internal import \* File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/pywrap\_tensorflow\_internal.py", line 28, in \_pywrap\_tensorflow\_internal = swig\_import\_helper() File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/pywrap\_tensorflow\_internal.py", line 24, in swig\_import\_helper \_mod = imp.load\_module('\_pywrap\_tensorflow\_internal', fp, pathname, description) ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory Failed to load the native TensorFlow runtime. ``` Seems like tensorflow is trying to find libcublas.so.9.0 however I only have cuda 8.0 installed. It's clear that I can use tensorflow 1.5 with cuda 8.0. Does anyone know how to solve this? Update: Looks like tensorflow officially doesn't provide binaries compiled with cuda 8.0 and cudnn v7.1 after tensorflow 1.4. Does any one know where to download those binaries?<issue_comment>username_1: I assume that you are installing TF using **pip install**. [Tensorflow install page](https://www.tensorflow.org/install/install_linux) (currently, version 1.6) mentions than that CUDA® Toolkit 9.0 along with cuDNN v7.0 are the requirements for your installation. Since TF version 1.5 CUDA9+CUDNN7 are among new requirements. Since CUDA9 relies on NVIDIA driver 384+ it causes a chain of updates of software: driver, CUDA, CUDNN, TF, etc. CUDA 9.1 would require nvidia driver 390 or later. Ways to solve the issue you can follow one of following paths: * Update nvidia driver and switch back to CUDA 9.0 and cuDNN 7.0. You can have multiple versions of CUDA and CUDNN coexisting on your system. * Install TF 1.4 which requires exactly CUDA 8.0 and cuDNN v6.0 * Compile [TF from source](https://www.tensorflow.org/install/install_sources). It requires investing some time and installing additional software. In my experience can easily take hours even if it is not your first time. * Find a wheel of TF compiled for your system configuration. Upvotes: 1 <issue_comment>username_2: I have had the same problem when installing tensorflow-gpu-1.6, i have resolved my problem like this : step(1): for tensorflow-gpu-1.6 we can use cuda9.0 and cudnn7 so download cuda9.0 debian if you are using Ubuntu, you can download cuda9.0 from here <https://developer.nvidia.com/cuda-90-download-archive> step(2): enter the following command ``` sudo apt-get --purge remove cuda ``` step(3): ``` sudo apt autoremove ``` step(4): and now install the downloaded cuda9.0 file step(5): and nvidia driver 384 is ok for cuda9.0, so no worries step(6): edit the path for cuda9.0 in bashrc ``` gedit ~/.bashrc ``` I have done the same procedure like i removed every thing related to cuda from my pc, and then tried installing cuda9.0 and it did worked for me. Let me know whether problem is resolved or not, Thank You. Upvotes: 0
2018/03/20
769
2,798
<issue_start>username_0: ``` def write(self, range, data): ''' clears the spreadsheet, then given a range of data will write that data into the google sheets with the id self.spreadsheet_id ''' self.ensure_service_exists() self.service.spreadsheets().values().clear(spreadsheetId=self.spreadsheet_id, range='A1:Z4000', body={}).execute() value_range_body = {'values': data} result = self.service.spreadsheets().values().update(spreadsheetId=self.spreadsheet_id, range=f'{self.sheet_label}!{range}', valueInputOption=self.value_input_option, body=value_range_body).execute() return result ``` For some reason, all of my data is being aggregated, and then cleared. When I want the opposite to happen. Also, does anyone know how to undo a border color change on the API as well?<issue_comment>username_1: I assume that you are installing TF using **pip install**. [Tensorflow install page](https://www.tensorflow.org/install/install_linux) (currently, version 1.6) mentions than that CUDA® Toolkit 9.0 along with cuDNN v7.0 are the requirements for your installation. Since TF version 1.5 CUDA9+CUDNN7 are among new requirements. Since CUDA9 relies on NVIDIA driver 384+ it causes a chain of updates of software: driver, CUDA, CUDNN, TF, etc. CUDA 9.1 would require nvidia driver 390 or later. Ways to solve the issue you can follow one of following paths: * Update nvidia driver and switch back to CUDA 9.0 and cuDNN 7.0. You can have multiple versions of CUDA and CUDNN coexisting on your system. * Install TF 1.4 which requires exactly CUDA 8.0 and cuDNN v6.0 * Compile [TF from source](https://www.tensorflow.org/install/install_sources). It requires investing some time and installing additional software. In my experience can easily take hours even if it is not your first time. * Find a wheel of TF compiled for your system configuration. Upvotes: 1 <issue_comment>username_2: I have had the same problem when installing tensorflow-gpu-1.6, i have resolved my problem like this : step(1): for tensorflow-gpu-1.6 we can use cuda9.0 and cudnn7 so download cuda9.0 debian if you are using Ubuntu, you can download cuda9.0 from here <https://developer.nvidia.com/cuda-90-download-archive> step(2): enter the following command ``` sudo apt-get --purge remove cuda ``` step(3): ``` sudo apt autoremove ``` step(4): and now install the downloaded cuda9.0 file step(5): and nvidia driver 384 is ok for cuda9.0, so no worries step(6): edit the path for cuda9.0 in bashrc ``` gedit ~/.bashrc ``` I have done the same procedure like i removed every thing related to cuda from my pc, and then tried installing cuda9.0 and it did worked for me. Let me know whether problem is resolved or not, Thank You. Upvotes: 0
2018/03/20
548
1,813
<issue_start>username_0: I've tried different ways to scrape `Answer1` and `Answer2` from a website through BeautifulSoup, urllib and Selenium, but without success. Here's the simplified version: ``` Question1 **Answer1** Question2 **Answer2** ``` In selenium, I try to find `Question1`, then go to its parent and scrape `Answer1`. Below is the code I use, although it's not correct. ``` browser.find_elements_by_xpath("//span[contains(text(), 'Question1')]/parent::p/following::strong") ``` I believe bs is more efficient than selenium in this case. How would you do this in bs? Thanks! **Edit:** @Juan's solution is perfect for my example. However, I realized it's inapplicable to the website <https://finance.yahoo.com/quote/AAPL?p=AAPL> . Can anyone shed some light on parsing `Consumer Goods` and `Electronic Equipment` from there? And would it be better to use urllib.requests instead? Thank you.<issue_comment>username_1: This is how I would do it. I modified your html closing the tags p and div: ``` from bs4 import BeautifulSoup as BS html = """ Question1 **Answer1** Question2 **Answer2** """ soup = BS(html,'lxml') QA = {x.text:y.text for x,y in zip(soup.select('span'),soup.select('strong'))} print(QA) ``` Upvotes: 1 <issue_comment>username_2: > > div class="div1"> > > > Question1 **Answer1** > > Question2 **Answer2** > > You only have to import and do it that with requests and beautifulsoup ``` Import request From bs4 import BeautifulSoup Url ="google.com" R = requests.get(url) Soup = BeautifulSoup(url, "lxml") For link in links: Soup.find_all("span") Print(link.text()) For answers in answer: Soup.find_all("strong") Print(answes.text) ``` And that my friend doing a membership check and a tuple that how you can do it. Upvotes: -1
2018/03/20
648
2,520
<issue_start>username_0: I have two functions which are almost the same. Is there a good way to remove duplicates? I think about moving duplicated code in the separate function and pass a function as the argument. ``` private object GetValue(object key) { var index = GetHash(key); var node = _table[index]; while (node != null) { if (Equals(node.Key, key)) return node.Value; node = node.Next; } throw new KeyNotFoundException("Such key doesn't exist"); } private void SetValue(object key, object value) { var index = GetHash(key); var node = _table[index]; if(value == null) RemoveValue(key); while (node != null) { if (Equals(node.Key, key)) { node.Value = value; return; } node = node.Next; } throw new KeyNotFoundException("Such key doesn't exist"); } ```<issue_comment>username_1: Split each of your methods in two parts: * Finding the target node (private helper), and * Doing something to the target node if it exists Finding the target node should have this signature: ``` private Node FindNodeByKey(object key) { ... } ``` This method would be in charge of throwing `KeyNotFoundException`, so both getter and setter could assume that when `FindNodeByKey` returns a value, it is not `null`. This assumption lets you reduce the getter to a single line: ``` private object GetValue(object key) { return FindNodeByKey(key).Value; } private void SetValue(object key, object value) { if (value == null) { RemoveValue(key); } else { FindNodeByKey(key).Value = value; } } ``` Upvotes: 2 <issue_comment>username_2: Sure, seems reasonable. ``` private Node GetNode(object key) { var index = GetHash(key); var node = _table[index]; while (true) { if (node == null) throw ... if (Equals(node.Key, key)) return node; node = node.Next; } } private object GetValue(object key) => GetNode(key).Value; private void SetValue(object key, object value) { if (value == null) RemoveValue(key); else GetNode(key).Value = value; } ``` Now, always ask yourself "how can I improve this further?" Some thoughts: * Why are these methods private? Are they implementation details of a nice public API, with a proper indexer? * Object, in 2018? Use generics! * And so on. Upvotes: 4 [selected_answer]
2018/03/20
599
2,181
<issue_start>username_0: I am trying to select data from our main database (postgres) and insert it into a temporary sqlite database for some comparision, analytics and reporting. Is there an easy way to do this in Python? I am trying to do something like this: Get data from the main Postgres db: ``` import psycopg2 postgres_conn = psycopg2.connect(connection_string) from_cursor = postgres_conn.cursor() from_cursor.execute("SELECT email, firstname, lastname FROM schemaname.tablename") ``` Insert into SQLite table: ``` import sqlite3 sqlite_conn = sqlite3.connect(db_file) to_cursor = sqlite_conn.cursor() insert_query = "INSERT INTO sqlite_tablename (email, firstname, lastname) values %s" to_cursor.some_insert_function(insert_query, from_cursor) ``` So the question is: is there a `some_insert_function` that would work for this scenario (either using pyodbc or using sqlite3)? If yes, how to use it? Would the `insert_query` above work? or should it be modified? Any other suggestions/approaches would also be appreciated in case a function like this doesn't exist in Python. Thanks in advance!<issue_comment>username_1: You can look at executemany from pyodbc or sqlite. If you can build a list of parameters from your select, you can pass the list to executemany. Depending on the number of records you plan to insert, performance can be a problem as referenced in this open issue. <https://github.com/mkleehammer/pyodbc/issues/120> Upvotes: 1 <issue_comment>username_2: You should pass the result of your select query to `execute_many`. ``` insert_query = "INSERT INTO smallUsers values (?,?,?)" to_cursor.executemany(insert_query, from_cursor.fetchall()) ``` You should also use a parameterized query (? marks), as explained here: <https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.execute> If you want to avoid loading the entire source database into memory, you can use the following code to process 100 rows at a time: ``` while True: current_data = from_cursor.fetchmany(100) if not current_data: break to_cursor.exectutemany(insert_query, current_data) sqlite_conn.commit() sqlite_conn.commit() ``` Upvotes: 2
2018/03/20
1,037
3,695
<issue_start>username_0: I would like to achieve something like ``` { _id: "A", count: 2 } { _id: "B", count: 1 } ``` from ``` { userId: "A", timeStamp: "12:30PM" } <- start of 5 min interval A: 1 { userId: "B", timeStamp: "12:30PM" } <- start of 5 min interval B: 1 { userId: "B", timeStamp: "12:31PM" } <- ignored { userId: "A", timeStamp: "12:32PM" } <- ignored { userId: "B", timeStamp: "12:33PM" } <- ignored { userId: "A", timeStamp: "12:37PM" } <- start of next 5 min A : 2 ``` where it groups based on userId and then after userId is group, the count is triggered every 5 mins. For example: Within any 5 min period, starting at say midnight, an unlimited number of collections can have a timeStamp from 00:00 to 00:05 but would only be counted as 1 hit. Hopefully I am explaining this clearly. I'm able to group by userId and get the count in general but setting a condition of the count seems to be tricky.<issue_comment>username_1: You can try [$bucket](https://docs.mongodb.com/manual/reference/operator/aggregation/bucket/) and `$addToSet` - the drawback is that you have to specify all the ranges manually: ``` db.col.aggregate([ { $bucket: { groupBy: "$timeStamp", boundaries: [ "12:30PM", "12:35PM", "12:40PM", "12:45PM", "12:50PM", "12:55PM", "13:00PM" ], output: { "users" : { $addToSet: "$userId" } } } }, { $unwind: "$users" }, { $group: { _id: "$users", count: { $sum: 1 } } } ]) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Micki's solution is better if you have mongo 3.6. If you have mongo 3.4 you can use $switch. Obviously you would need to add all the cases in the day. ``` db.getCollection('user_timestamps').aggregate( { $group: { _id: '$userId', timeStamp: {$push: '$timeStamp'} } }, { $project: { timeStamps: { $map: { input: '$timeStamp', as: 'timeStamp', in: { $switch: { branches: [ { case: { $and: [ {$gte: ['$$timeStamp', '12:30PM']}, {$lt: ['$$timeStamp', '12:35PM']} ] }, then: 1 }, { case: { $and: [ {$gte: ['$$timeStamp', '12:35PM']}, {$lt: ['$$timeStamp', '12:40PM']} ] }, then: 2 } ], default: 0 } } } } } }, { $unwind: '$timeStamps' }, { $group: { _id: '$_id', count: { $addToSet: '$timeStamps' } } }, { $project: { _id: true, count: {$size: '$count'} } } ) ``` If you don't have mongo 3.4 you can replace the $switch with ``` cond: [ { $and: [ {$gte: ['$$timeStamp', '12:30PM']}, {$lt: ['$$timeStamp', '12:35PM']} ] }, 1, { cond: [ { $and: [ {$gte: ['$$timeStamp', '12:35PM']}, {$lt: ['$$timeStamp', '12:40PM']} ] }, 2, 0 ] } ] ``` Upvotes: 1
2018/03/20
1,443
4,550
<issue_start>username_0: ``` declare @test varchar(50) = 'F-1084-002-04-009' ``` I need to replace the value inside the last two dashes to "00" So it should be this: ``` F-1084-002-00-009 ``` I'm struggling to find the easiest way to do this.<issue_comment>username_1: If the format is always the same you could do this: ``` select stuff('F-1084-002-04-009', 12, 2, '00') ``` Upvotes: 1 <issue_comment>username_2: Something like this: ``` select *, charindex('-', reverse(v), 0) Last, charindex('-', reverse(v), charindex('-', reverse(v), 0)+1) Second_Last, left(v, len(v)-(charindex('-', reverse(v), charindex('-', reverse(v), 0)+1))) + '-00' +right(v, charindex('-', reverse(v), 0)) from t ``` Upvotes: 0 <issue_comment>username_1: I'm posting this as a separate answer because while I'm pretty happy with it, it's a little bit unconventional. However it is quite robust even if you make absolutely no assumptions about how many groups there are or how many characters are in each group. The first two table variables are just setup data. I used your test examples and added a third of my own. I also created a small auto-incrementing tally table. Id recommend having one of these persisted on your DB somewhere if you don't already. ``` declare @src table (val) insert into @src (Val) values ('F-0-001-99-003'), ('F-1084-002-04-009'), ('FF-1-02-345-9') declare @tally table (idx) insert into @tally (idx) select top 100 row_number() over (order by (select null)) - 1 -- 0 based from sys.all_objects ``` Now we begin work in earnest. I used a trick I learned from writing SQL comma-delimited-string splitters to quickly get the indexes of all the hyphens in the string. What I'm interested in here is the second to last hyphen (which starts the section we want to replace) and the last hyphen (which denotes its end). I add 1 to it because computers are just like that. Now I need to get the row with the highest index, and the second highest index. I went about this with a row\_number and a group by, but I suspect there are other ways to get at it as well. So for the final select, we have the starting index of the slug we want to replace, the ending index, as well as its length (which I just saved off as an additional column for brevity. And at *this* point, my original solution using `stuff` works. ``` ;with hyphenIndexes as ( select RID = row_number() over (partition by s.Val order by idx desc), Val, Idx = Idx + 1 from @src s inner join @tally t on t.idx <= len(val) where substring(val, idx, 1) = '-' ), almostDone as ( select Val, StartIndex = max(iif(RID = 2, idx, null)), EndIndex = max(Idx), SlugLength = max(Idx) - max(iif(RID = 2, idx, null)) - 1 from hyphenIndexes group by Val ) select OriginalString = val, ReplacedString = stuff ( Val, StartIndex, SlugLength, replicate('0', SlugLength) ) from almostDone ``` I should note that it's late in the day and my brain is pretty fried, so there might be ways to make this more succinct. I also broke things out quite a bit for clarity. I also approached it from the standpoint that the strings could be all mannar of whackness, and it would still work. However if you're able to make any assumption about the number of groups or the number of characters per group, I suspect you could skip several steps I've done in here. Upvotes: 0 <issue_comment>username_3: ``` - Simple way is to Use Substring to find what you want to Replace.And use Replace Function to Replace it. DECLARE @test NVARCHAR(50) = 'F-1084-002-04-009', @Replce NVARCHAR(3), @Value NVARCHAR(10)='00' SELECT @Replce=SUBSTRING(@test,12,2) SELECT REPLACE(@test,@Replce,@Value) ``` Upvotes: 0 <issue_comment>username_2: This works for variable length strings in the second-last element: ``` use tempdb create table t ( v varchar(90) ) insert t (v) values ('F-1084-002-04-009'), ('g-68236-6514652145-99-8127638176321637'), ('F-1084-002-0456-009') select *, stuff( v, len(v) - (charindex('-', reverse(v), charindex('-', reverse(v), 0)+1) - 2), (charindex('-', reverse(v), charindex('-', reverse(v), 0)+1) - charindex('-', reverse(v), 0))-1, replicate('0', charindex('-', reverse(v), charindex('-', reverse(v), 0)+1) - charindex('-', reverse(v), 0) - 1) ) [Stuff] from t ``` Upvotes: 0
2018/03/20
1,119
4,325
<issue_start>username_0: I am using selenium 3.9.1 and java to automate testing of a web application. The web application has some dynamic content based on pressing of a button for example. The page refreshes whenever this button is clicked. A java script runs on button click and updates the DOM I think. At this time, when I try to access the button (which is visible on the page), I get a staleElementReferenceException. Does Selenium automatically reload the DOM once it is changed? I am relatively new to selenium. I have researched into this and I have tried to refresh the page using driver.navigate().Refresh() to try to see whether this will solve the problem. It does not solve the issue. Any pointers will be deeply appreciated.<issue_comment>username_1: Since the page has been refreshed, the button reference you have is to the button on the old page that no longer exists. I'd say you need to get a new reference to the button on the refreshed page (eg call FindElementById). Upvotes: 1 <issue_comment>username_2: If the page is refreshed all the items in the DOM are now stale. What this means is that all items found before the button press will have to be found again. Any attempts to use those items will more than likely be treated with a stale element exception. However, if the button click mearilly affects items on the page without having to ask the webserver to give you a new page you could interact with the old items. Upvotes: 1 <issue_comment>username_3: You could do something like this: ``` public void SaveAndAgainClick() throws Exception{ try{ clicksaveButton(); //method to click save button WebElement someValue = driver.findElement(By.xpath("(//input[@name='someValue'])[1]")); someValue.click(); }catch (StaleElementException e){ WebElement someValue = driver.findElement(By.xpath("(//input[@name='someValue'])[1]"); someValue.click(); } } ``` If findElement gets staleElementError while looking for `(//input[@name='someValue'])[1]` then it will again try one more time in the catch block and most certainly find the element and clicks on it. Your test will pass if you follow this approach. Upvotes: 1 <issue_comment>username_4: Here are the answers to your questions : * *A java script runs on button click and updates the DOM I think* : If you inspect the *HTML* of the element through **Development Tools** / **Inspect Element** the element *attributes* will reveal it all. * Consider the following *HTML* : ``` ``` * In the given *HTML* as per the `onclick` attribute of this element, if you invoke `click()` method on the *WebElement*, an *alert* would be generated. Similarly the `onclick` attribute may invoke a **JavaScript** or **Ajax** which may bring-in/phase-out new/old elements from the [HTML DOM](https://www.w3schools.com/js/js_htmldom.asp) * *At this time, when I try to access the button I get a staleElementReferenceException* : In this case you should induce [WebDriverWait](http://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/WebDriverWait.html) for the *WebElement* to be *interactive* before attempting to interact with the element. Else you may face either of the following *exceptions* : + [**`StaleElementReferenceException`**](https://stackoverflow.com/questions/44838538/staleelementreference-exception-in-pagefactory/44844879#44844879) + [**`WebDriverException`**](https://stackoverflow.com/questions/44724185/element-myelement-is-not-clickable-at-point-x-y-other-element-would-receiv/44724688#44724688) + [**`ElementNotInteractableException`**](https://stackoverflow.com/questions/44690971/selenium-webdriver-throws-exception-in-thread-main-org-openqa-selenium-element/44691041#44691041) + [**`InvalidElementStateException`**](http://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/InvalidElementStateException.html) * *Does Selenium automatically reload the DOM once it is changed?* Short answer, **Yes** it does. * *Refresh the page using driver.navigate().refresh()* : **No** invoking `driver.navigate().refresh()` wouldn't be a optimum solution as it may not invoke the intended *JavaScript* or *Ajax* properly. Hence the intended *WebElement* may not be interactive in a optimum way. Upvotes: 0
2018/03/20
772
2,509
<issue_start>username_0: I would like to have a colored underline that looks like this when it breaks: [![Heading with colored underline in one and two lines](https://i.stack.imgur.com/ZjpsL.jpg)](https://i.stack.imgur.com/ZjpsL.jpg) `text-decoration-color` seems to be not supported widely enough. I tried this: ```css .underline { position: relative; } .underline:after { position: absolute; content: ''; height: 1px; background-color: #ffc04d; bottom: .1rem; right: 0; left: 0; z-index: -1; } ``` ```html Sprouted Bread ============== ``` [![and this is what it looks like when it breaks.](https://i.stack.imgur.com/jSkvC.jpg)](https://i.stack.imgur.com/jSkvC.jpg)<issue_comment>username_1: What about a linear-gradient where it will be easy to control color, size and distance within a single element: ```css .underline { position: relative; font-size:28px; background: linear-gradient(yellow,yellow) /* Color */ left 0 bottom 2px/ /* Position */ 100% 2px /* Size (width height)*/ no-repeat; } ``` ```html Sprouted Bread ``` As a side note, border-bottom works fine used with **inline element** but of course you cannot easily control the distance to make it behave as a text-decoration: ```css .underline { position: relative; font-size:28px; border-bottom:2px solid yellow; } ``` ```html Sprouted Bread ``` Upvotes: 2 <issue_comment>username_2: [Try this JSFiddle](https://jsfiddle.net/fgz9ndme/1/) By wrapping the elements like you have in a span. You can put the text decoration on the parent element and the text color on the span. **HTML:** ``` Some Text ========= ``` **CSS:** ``` h1 { text-decoration: underline; color: red; } .underline { color: blue; } ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Just add a border! ================== Using `display: inline`, add a bottom border and space it with padding. You could also use `line-height` and then place negative margins to increase the space in between the lines. And...you could also animate it! ```css .underline { position: relative; padding-bottom: 1px; border-bottom: 1px solid #ffc04d; } ``` ```html Sprouted Bread ================ ``` As mentioned by @chriskirknielsen, you could use [box-decoration-break](https://developer.mozilla.org/en-US/docs/Web/CSS/box-decoration-break), although not supported by [IE or Edge](https://caniuse.com/#search=box-decoration-break). Credits: @username_1 Upvotes: 1
2018/03/20
1,557
4,371
<issue_start>username_0: ``` def make_Ab(A,b): n = len(A) Ab = list(A) for index in range(0,n): Ab[index].append(b[index][0]) print(A) return Ab.copy() A = [[0.0, 1.0, 1.0, 2.0], [1.0, 3.0, 1.0, 5.0], [2.0, 0.0, 2.0, 4.0]] b = [[1],[2],[3]] print(A) ``` `[[0.0, 1.0, 1.0, 2.0], [1.0, 3.0, 1.0, 5.0], [2.0, 0.0, 2.0, 4.0]]` ``` Ab = make_Ab(A,b) print(A) ``` `[[0.0, 1.0, 1.0, 2.0, 1], [1.0, 3.0, 1.0, 5.0, 2], [2.0, 0.0, 2.0, 4.0, 3]]` I don't get why does my function modify my original list. I didn't specify`A` as global in function (I've even tried to declare it in a different function so it won't be global), I didn't pass it through reference (like `Ab = A`). What's the problem?<issue_comment>username_1: The issue here is that, while you're not modifying the *variable* (which you can't do without `global`), you *are* modifying the *value*. This can be a bit confusing at first. These two look like they do the same thing: ``` >>> a = [1, 2, 3] >>> a = a + [1] >>> a [1, 2, 3, 1] >>> a = [1, 2, 3] >>> a.append(1) >>> a [1, 2, 3, 1] ``` But they're not. The first one is making a new list out of `a` and `[1]` and then binding that new list back to the name `a`. If there was some other reference to that same list, it would be unchanged. The second one, on the other hand, is changing the actual list object that `a` names. If there was some other reference to that same list, it would change. ``` >>> a = [1, 2, 3] >>> b = a >>> a = a + [1] >>> b [1, 2, 3] >>> a = [1, 2, 3] >>> b = a >>> a.append(1) >>> b [1, 2, 3, 1] ``` What you're doing in your code is the second one, changing the value of the list object. Which means that every reference to that list object, even a name you don't have access to, will see the change. But you're not modifying `A` itself, you're modifying `list(A)`. Shouldn't that be a new copy of the list? Yes, it is—but, even if `Ab` is a different list from `A`, `Ab[0]` is still the same list as `A[0]`. You've made a new list that references the same sublists as the original one. So when you mutate those sublists… same problem. If you want to change this, you can do one of two things: * Copy all of the sublists, as well as the list, at the top of the function, so you mutate the copy instead of the original. * Don't use any mutating operations on the lists; build a new one. The first one is a simple change: instead of `Ab = list(A)`, do `Ab = copy.deepcopy(A)` or `Ab = [list(sub) for sub in Ab]`. The second one requires rewriting your code a bit: ``` def make_Ab(A,b): n = len(A) Ab = [] for index in range(0,n): Ab.append(A[n] + [b[index][0]]) return Ab ``` (Or, of course, you can rewrite that as a list comprehension.) Upvotes: 3 [selected_answer]<issue_comment>username_2: Passing Arguments to Function - Python ====================================== > > Python uses a mechanism, which is known as "Call-by-Object", sometimes > also called "Call by Object Reference" or "Call by Sharing". > > > Call by Value - Immutable Arguments ----------------------------------- If we pass immutable arguments like integers, strings or tuples to a function, the passing acts like call-by-value. Call by Object or Call by Object Reference - Mutable Arguments -------------------------------------------------------------- If we pass mutable arguments like lists and dictionaries to a function, they are passed by object reference. Solution ======== The solution to your problem is to use ***deepcopy***. 1. Add ***from copy import deepcopy*** 2. Replace ***Ab = list(A)*** with ***Ab = deepcopy(A)*** 3. Replace ***return Ab.copy()*** with ***return Ab*** main.py ------- ``` from copy import deepcopy def make_Ab(A, b): n = len(A) Ab = deepcopy(A) print("\nmake_Ab-before append: \n A=", A) for index in range(0, n): Ab[index].append(b[index][0]) print("\nmake_Ab-after append: \n A=", A) return Ab A = [[0.0, 1.0, 1.0, 2.0], [1.0, 3.0, 1.0, 5.0], [2.0, 0.0, 2.0, 4.0]] b = [[1], [2], [3]] print("Before: make_Ab call, \n A=", A) Ab = make_Ab(A, b) print("\nAfter: make_Ab call, \n A=", A) print("\nAfter: make_Ab call, \n Ab=", Ab) ``` Output ====== [![enter image description here](https://i.stack.imgur.com/eF0Dq.png)](https://i.stack.imgur.com/eF0Dq.png) Upvotes: 0
2018/03/20
1,257
4,347
<issue_start>username_0: Using test config with Ignite 2.4 and k8s 1.9: ``` xml version="1.0" encoding="UTF-8"? ``` Unable to find Kubernetes API Server at <https://kubernetes.default.svc.cluster.local:443> Can I set the API Server URL in the XML config file? How?<issue_comment>username_1: Take a look at this thread: <http://apache-ignite-users.70518.x6.nabble.com/Unable-to-connect-ignite-pods-in-Kubernetes-using-Ip-finder-td18009.html> The problem of 403 error can be solved by granting more permissions to the service account. Upvotes: 2 [selected_answer]<issue_comment>username_2: @username_1 was right. Kubernetes using RBAC access controlling system and you need to authorize your pod to access to API. For that, you need to add a [Service Account](https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/) to your pod. So, for do that you need: 1. Create a service account and set role for it: ``` apiVersion: v1 kind: ServiceAccount metadata: name: ignite namespace: ``` 2. I am not sure that permissions to access only pods will be enough for Ignite, but if not - you can add as more permissions as you want. [Here](https://github.com/kubernetes/kubernetes/blob/master/plugin/pkg/auth/authorizer/rbac/bootstrappolicy/testdata/cluster-roles.yaml) is example of different kind of roles with large list of permissions. So, now we create Cluster Role for your app: ``` apiVersion: rbac.authorization.k8s.io/v1beta1 kind: ClusterRole metadata: name: ignite namespace: rules: - apiGroups: - "" resources: - pods # Here is resources you can access verbs: # That is what you can do with them - get - list - watch ``` 3. Create binding for that role: ``` kind: ClusterRoleBinding apiVersion: rbac.authorization.k8s.io/v1beta1 metadata: name: ignite roleRef: kind: ClusterRole name: ignite apiGroup: rbac.authorization.k8s.io subjects: - kind: ServiceAccount name: ignite namespace: ``` 4. Now, you need to associate ServiceAccount to pods with your application: ``` apiVersion: extensions/v1beta1 kind: DaemonSet metadata: .... spec: template: spec: serviceAccountName: ignite ``` After that, your application will have an access to K8s API. P.S. Do not forget to change to namespace where you running Ignition. Upvotes: 3 <issue_comment>username_3: ### Platform versions * Kubernetes: v1.8 * Ignite: v2.4 @username_2 design is mostly right, but here's a refined suggestion that works and grants *least access privileges* to Ignite. 1. If you're using a `Deployment` to manage Ignite, then all of your Pods will launch within a single namespace. Therefore, you should really use a `Role` and a `RoleBinding` to grant API access to the service account associated with your deployment. 2. The `TcpDiscoveryKubernetesIpFinder` only needs access to the endpoints for the headless service that selects your Ignite pods. The following 2 manifests will grant that access. ``` apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: ignite-endpoint-access namespace: labels: app: ignite rules: - apiGroups: [""] resources: ["endpoints"] resourceNames: [""] verbs: ["get"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: ignite-role-binding labels: app: ignite subjects: - kind: ServiceAccount name: roleRef: kind: Role name: ignite-endpoint-access apiGroup: rbac.authorization.k8s.io ``` Upvotes: 2 <issue_comment>username_4: **Tested Version:** Kubernetes: v1.8 Ignite: v2.4 This is going to be little bit more permissive. ``` apiVersion: rbac.authorization.k8s.io/v1beta1 kind: ClusterRoleBinding metadata: name: ignite-rbac subjects: - kind: ServiceAccount name: default namespace: roleRef: kind: ClusterRole name: cluster-admin apiGroup: rbac.authorization.k8s.io ``` Upvotes: 1 <issue_comment>username_5: If you're getting 403 unauthorized then your service account that made your resources may not have good enough permissions. you should update your permissions after you ensure that your namespace and service account and deployments/ replica sets are exactly the way you want it to be. This link is very helpful to setting permissions for service accounts: <https://kubernetes.io/docs/reference/access-authn-authz/rbac/#service-account-permissions> Upvotes: 0
2018/03/20
1,101
3,654
<issue_start>username_0: I’m working on an app which dynamically renders a set of UI elements (currently sliders) into three columns based on the user selecting which metrics they’d like to filter a particular dataset on. The issue I’m running into is that the different metrics have wildly variable ranges (i.e. gross merchandise sales vs. customer return rate) meaning sliders aren’t the best to work with. I’m wondering if any of you are aware of a numeric range input that can take two numeric inputs (a min and max) similar to the ends of a range slider? I haven’t been able to find something built into Shiny with this capability, but am hoping one of you may have some experience with customizing input elements. Any help will be greatly appreciated. See below for a snippet demonstrating the dynamic slider generation. Thanks! ``` output$filters <- renderUI({ if (input$geoselect == "US") { atts <- tolower(input$ucolselect) if(length(input$ucolselect) >= 3) { fluidRow(column(width = 4, lapply(1:round( 1 / 3 * length(atts) ), function(i) { sliderInput( inputId = atts[i], label = atts[i], min = min(us[, tolower(colnames(us)) %in% atts[i]], na.rm = TRUE), max = max(us[, tolower(colnames(us)) %in% atts[i]], na.rm = TRUE) , value = c(min(us[, tolower(colnames(us)) %in% atts[i]], na.rm = TRUE), max(us[, tolower(colnames(us)) %in% atts[i]], na.rm = TRUE)), step = NULL ) })), column(width = 4, lapply((1 + round(1 / 3 * length(atts))):round(2 / 3 * length(atts)), function(i) { sliderInput( inputId = atts[i], label = atts[i], min = min(us[, tolower(colnames(us)) %in% atts[i]], na.rm = TRUE), max = max(us[, tolower(colnames(us)) %in% atts[i]], na.rm = TRUE) , value = c(min(us[, tolower(colnames(us)) %in% atts[i]], na.rm = TRUE), max(us[, tolower(colnames(us)) %in% atts[i]], na.rm = TRUE)), step = NULL ) })), ..... ```<issue_comment>username_1: Why not `numericInput`? This also include min, max and step values. But as i know, you can type in value that greater than max or lower than min, so better to manage it on server with `updateNumericInput()` and back values in min:max range in code. Hope i understand you rigth and this will help. Upvotes: 0 <issue_comment>username_2: A feature like this called `numericRangeInput()` was just added to `shinyWidgets` (<https://github.com/dreamRs/shinyWidgets/pull/150>). It's not on CRAN yet but you can install the development version from GitHub. ``` devtools::install_github("dreamRs/shinyWidgets") output$filters <- renderUI({ if (input$geoselect == "US") { atts <- tolower(input$ucolselect) if (length(input$ucolselect) >= 3) { fluidRow(column(width = 4, lapply(1:round( 1 / 3 * length(atts) ), function(i) { numericRangeInput( inputId = atts[i], label = atts[i], value = c(min(us[, tolower(colnames(us)) %in% atts[i]], na.rm = TRUE), max(us[, tolower(colnames(us)) %in% atts[i]], na.rm = TRUE)) ) })), column(width = 4, lapply((1 + round(1 / 3 * length(atts))):round(2 / 3 * length(atts)), function(i) { numericRangeInput( inputId = atts[i], label = atts[i], value = c(min(us[, tolower(colnames(us)) %in% atts[i]], na.rm = TRUE), max(us[, tolower(colnames(us)) %in% atts[i]], na.rm = TRUE)) ) })), ``` UPDATE: `numericRangeInput()` is now on CRAN in `shinyWidgets` 0.4.5 Upvotes: 2
2018/03/20
835
2,614
<issue_start>username_0: Haven't been able to find this in docs. Can I just pause an ECS service so it stopped creating new tasks? Or do I have to delete it to stop that behavior? I just want to temporarily suspend it from creating new tasks on the cluster<issue_comment>username_1: You can accomplish a "pause" by adjusting your service configuration to match your current number of running tasks. For example, if you currently have 3 running tasks in your service, you'd configure the service as below: [![.](https://i.stack.imgur.com/HyP1U.png)](https://i.stack.imgur.com/HyP1U.png) This tells the service: * *The number of tasks I want is `[current-count]`* * *I want you to maintain **at least** `[current-count]`* * *I don't want **more than** `[current-count`* These combined effectively halt your service from making any changes. Upvotes: 5 [selected_answer]<issue_comment>username_2: The accepted answer is incorrect. If you set both "Minimum healthy percent" and "Maximum healthy percent" to 100, AWS will give you an error similar to following: [![enter image description here](https://i.stack.imgur.com/idpj5.png)](https://i.stack.imgur.com/idpj5.png) To stop service from creating new tasks, you have to update service by updating task definition and setting desired number of tasks to 0. After that you can use AWS CLI (fastest option) to stop existing running tasks , for example: ``` aws ecs list-services --cluster "ecs-my-ClusterName" aws ecs list-tasks --cluster "ecs-my-ClusterName" --service "service-my-ServiceName-117U7OHVC5NJP" ``` After that you will get the list of the running tasks for the service, such as: ``` { "taskArns": [ "arn:aws:ecs:us-east-1:XXXXXXXXXXX:task/12e13d93-1e75-4088-a7ab-08546d69dc2c", "arn:aws:ecs:us-east-1:XXXXXXXXXXX:task/35ed484a-cc8f-4b5f-8400-71e40a185806" ] } ``` Finally use below to stop each task: ``` aws ecs stop-task --cluster "ecs-my-ClusterName" --task 12e13d93-1e75-4088-a7ab-08546d69dc2c aws ecs stop-task --cluster "ecs-my-ClusterName" --task 35ed484a-cc8f-4b5f-8400-71e40a185806 ``` **UPDATE:** *By setting the desired number of running tasks to 0, ECS will stop and drain all running tasks in that service. There is no need to stop them individually afterwards using CLI commands originally posted above.* Upvotes: 4 <issue_comment>username_3: It is enough to set the desired number of tasks for a service to 0. ECS will automatically remove all running tasks. ``` aws ecs update-service --desired-count 0 --cluster "ecs-my-ClusterName" --service "service-my-ServiceName-117U7OHVC5NJP" ``` Upvotes: 6
2018/03/20
263
760
<issue_start>username_0: In a SharePoint calculated field how do I check two things? I have the following which checks field Est OpMargin and if less than 20 sets field to BG but I would also if less than 17 set it to RG =IF([Est OpMargin]<20,"BG","")<issue_comment>username_1: Nest the IFs: ``` =IF([Est OpMargin]<17, "RG", IF([Est OpMargin]<20,"RG","") ) ``` In SharePoint 2007 and 2010 you can nest 7 levels deep, and 2013 and later you can next 19 levels. Upvotes: 1 <issue_comment>username_2: The Formula below for your reference: ``` =IF(And([Est OpMargin]>=17,[Est OpMargin]<20),"BG",IF([Est OpMargin]<17, "RG","")) ``` [![enter image description here](https://i.stack.imgur.com/tyUvW.jpg)](https://i.stack.imgur.com/tyUvW.jpg) Upvotes: 0
2018/03/20
446
1,537
<issue_start>username_0: I have few questions related to NetSuite: 1. On the [NetSuite help page](https://system.netsuite.com/app/help/helpcenter.nl?fid=chapter_4387172495.html&whence=), the User Event scripts are stated to execute on servers. In that case if a record is updated in NetSuite indirectly\*, it should still trigger the User Event script associated with it, right? \*By indirectly I mean a user does not navigate to the record in a browser and clicks on Edit and Save. An example usecase would be, when a customer payment is made against an Invoice, it updates the Amount due on the Invoice automatically. But it does not trigger the UserEvent Script deployed on the Invoice. Please let me know if my understanding is correct. Also, could you please give me a way to execute a script when a record is updated both directly and indirectly. 2. Is there a way to execute a script (make a REST call) when a File is uploaded. I am not able to see it under script deployments for User Event scripts. Thanks in advance!<issue_comment>username_1: Nest the IFs: ``` =IF([Est OpMargin]<17, "RG", IF([Est OpMargin]<20,"RG","") ) ``` In SharePoint 2007 and 2010 you can nest 7 levels deep, and 2013 and later you can next 19 levels. Upvotes: 1 <issue_comment>username_2: The Formula below for your reference: ``` =IF(And([Est OpMargin]>=17,[Est OpMargin]<20),"BG",IF([Est OpMargin]<17, "RG","")) ``` [![enter image description here](https://i.stack.imgur.com/tyUvW.jpg)](https://i.stack.imgur.com/tyUvW.jpg) Upvotes: 0
2018/03/20
583
2,273
<issue_start>username_0: I have this problem and i keep thinking about it. I'm trying to figure how this actually works and WHY? So, I have this Base class: ``` public class Shape { private float width; private float height; public Shape(float width, float height) { this.width = width; this.height = height; } public void setWidth(float x){ this.width = x; } public float getWidth() { return width; } public float getHeight() { return height; } } ``` and this derived class: ``` public class Rectangle extends Shape { public Rectangle(float width, float height) { super(width, height); } public float area (){ float x = getHeight(); float y = getWidth(); return x*y; } } ``` Why is the derived class using `width` and `height`? I mean, I can instantiate objects like: ``` Shape s = new Shape(1,1); Rectangle rect = new Rectangle(3,5); ``` and `Rectangle` has the variables `width` and `height`. I'm using the base class constructor, but when it passes `super(width, height)` it gets to `this.width = width` and the same for `height`. What is `this.width`?. Is it just a kind of copy for the base class or how does it work?<issue_comment>username_1: The key to understanding here is to notice that inside the base class constructor we have two variants of both the 'width' and the 'height' variable: one are members in the class object as such, the other are the parameters passed to the constructor, each using the same name as the other `this.height = height;` takes the value of the constructor *parameter* and assigns it to the class *member*. It is a bit of an odd convention, but makes it easy to visually check that the constructor parameters are assigned to the correct class members during construction. Upvotes: 2 [selected_answer]<issue_comment>username_2: ``` private float width; private float height; public Shape(float width, float height) { this.width = width; this.height = height; } ``` In the above code, the global variables are width, height. Similarly the local variables are also width, height present in the Shape Constructor. So we use this keyword for differentiating the local variable and global variable , as they both have the same name. Upvotes: 0
2018/03/20
427
1,651
<issue_start>username_0: I'm processing some semi-structured documents in Python and I have some code that reads the file into a tuple and loops through each line and performs a function. Is there a way of finding the exact line in the processed file where an error is encountered? ``` c = tuple(open("file", 'r')) for element in c: if (condition is met): do something else: do something else ``` The result should be: ```none Error: in line # of "file" ```<issue_comment>username_1: [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate) should help: ``` for line, element in enumerate(c): try: if (condition is met): do something else: do something else except Exception as e: print('got error {!r} on line {}'.format(e, line)) ``` The above would give an error like: ``` got error OSError('oops!',) on line 4 ``` Although as good practice you'd generally replace `Exception` with whatever error you're expecting to catch. Upvotes: 3 [selected_answer]<issue_comment>username_2: In general, it is good practice to use the `with` keyword when you are reading from a file, especially if you expect an Exception to occur. You can also `enumerate` to count the lines: `with open(filename) as f: for line_num, line in enumerate(f): try: if (condition is met): do something else: do something else except Exception: print('Error: in line {:d} of file'.format(line_num))` It's best to not use `Exception` if you know the specific Exception you are expecting because it will catch all Exceptions, even those you don't expect. Upvotes: 1
2018/03/20
690
2,419
<issue_start>username_0: Trying to write an efficient algorithm to scale down YUV 4:2:2 by a factor of 2 - and which doesn't require a conversion to RGB (which is CPU intensive). I've seen plenty of code on stack overflow for YUV to RGB conversion - but only an example of scaling for YUV 4:2:0 here which I have started based my code on. However, this produces an image which is effectively 3 columns of the same image with corrupt colours, so something is wrong with the algo when applied to 4:2:2. Can anybody see what is wrong with this code? ``` public static byte[] HalveYuv(byte[] data, int imageWidth, int imageHeight) { byte[] yuv = new byte[imageWidth / 2 * imageHeight / 2 * 3 / 2]; int i = 0; for (int y = 0; y < imageHeight; y += 2) { for (int x = 0; x < imageWidth; x += 2) { yuv[i] = data[y * imageWidth + x]; i++; } } for (int y = 0; y < imageHeight / 2; y += 2) { for (int x = 0; x < imageWidth; x += 4) { yuv[i] = data[(imageWidth * imageHeight) + (y * imageWidth) + x]; i++; yuv[i] = data[(imageWidth * imageHeight) + (y * imageWidth) + (x + 1)]; i++; } } return yuv; } ```<issue_comment>username_1: [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate) should help: ``` for line, element in enumerate(c): try: if (condition is met): do something else: do something else except Exception as e: print('got error {!r} on line {}'.format(e, line)) ``` The above would give an error like: ``` got error OSError('oops!',) on line 4 ``` Although as good practice you'd generally replace `Exception` with whatever error you're expecting to catch. Upvotes: 3 [selected_answer]<issue_comment>username_2: In general, it is good practice to use the `with` keyword when you are reading from a file, especially if you expect an Exception to occur. You can also `enumerate` to count the lines: `with open(filename) as f: for line_num, line in enumerate(f): try: if (condition is met): do something else: do something else except Exception: print('Error: in line {:d} of file'.format(line_num))` It's best to not use `Exception` if you know the specific Exception you are expecting because it will catch all Exceptions, even those you don't expect. Upvotes: 1
2018/03/20
903
3,411
<issue_start>username_0: In VB6 on a UserControl, I must use `UserControl.MousePointer = vbDefault` instead of `Me.MousePointer = vbDefault`. I can use `Me.MousePointer` on a Form (and `Form.MousePointer` doesn't work). Why must I use `UserControl.MousePointer` instead of `Me.MousePointer`? I mean literally the text "UserControl", not `UserControl` as the placeholder for another control name.<issue_comment>username_1: `Me` isn't what you seem to think it is. It is a reference to the current instance of the module you use it in, not "magic." To get what you want you must add this property to the default interface of your UserControl, e.g.: ``` Option Explicit Public Property Get MousePointer() As MousePointerConstants MousePointer = UserControl.MousePointer End Property Public Sub Test() MsgBox Me.MousePointer End Sub ``` In VB6 Forms are a little different, probably as a holdover from 16-bit VB to make porting old code easier. These always seem to inherit from a hidden interface. This is defined in a type library you don't have access to since Microsoft did not release it as part of VB6. Attempting to query it typically comes up with an error like: > > Cannot jump to 'MousePointer' because it is in the library 'Unknown10' which is not currently referenced > > > From this alone it seems likely that using `Me` always carries a small performance penalty. Instead of going directly to the module's procedures it appears to me that you are going through its default COM interface. You'd have to inspect the compiled code to determine whether there is a performance penalty, and if so how much. I don't see this documented so otherwise we are just guessing about it. In any case there is little reason to *ever* use `Me` unless you must in order to qualify something. Crummy example but: ``` Option Explicit Private mCharm As Long Public Property Get Charm() As Long Charm = mCharm End Property Public Property Let Charm(ByVal RHS As Long) mCharm = RHS 'Maybe we do more here such as update the user interface or some 'other things. End Property Public Sub GetLucky(ByVal Charm As Long) 'Do some stuff. Charm = Charm + Int(Rnd() * 50000) 'etc. Me.Charm = Charm 'Here we use Me so we can assign to the property Charm. End Sub ``` That's really about the only legitimate use for `Me` anyway: scoping to the desired namespace. Relying on it because in typing it brings up IntelliSense is just lazy. If anything *Forms* are "broken" not UserControls. Upvotes: 2 <issue_comment>username_2: Figured it out. It turns out that since a UserControl is an ActiveX control, VB6 does some magic for you. With a Form control, it's not an ActiveX control which is why the MousePointer property is accessible via Me, like you'd expect. For UserControl's, the UserControl control you create in VB6 sits on another control - the ActiveX control. That ActiveX control is accessible via UserControl. Something like this: ``` class ActiveXControl { int MousePointer; VBUserControl control; } class VBUserControl { } class YourUserControl : VBUserControl { ActiveXControl UserControl; // we must use UserControl.MousePointer } ``` but for a Form, it's more like this: ``` class Form { int MousePointer; } class YourForm : Form { // we actually inherit from Form so we use Me.MousePointer } ``` Upvotes: 2 [selected_answer]
2018/03/20
439
1,378
<issue_start>username_0: I get this error when running anaconda-navigator on Linux Mint 18.1: ``` QApplication: invalid style override passed, ignoring it. 2018-03-20 19:54:36,039 - ERROR anaconda_api.is_vscode_available:871 '' Traceback (most recent call last): File "/home/daniel/anaconda3/lib/python3.5/site-packages/anaconda_navigator/ api/anaconda_api.py", line 368, in _conda_info_processed processed_info = self._process_conda_info(info) File "/home/daniel/anaconda3/lib/python3.5/site-packages/anaconda_navigator/ api/anaconda_api.py", line 479, in _process_conda_info processed_info = info.copy() AttributeError: 'bytes' object has no attribute 'copy' ... ``` I updated using: ``` conda update conda conda update anaconda-navigator conda update navigator-updater ``` The versions are: ``` conda 4.5.0 anaconda Command line client (version 1.6.14) ```<issue_comment>username_1: I have no idea *how* or *why* this works, but if you delete the `.condarc` file in your user folder, it starts to work fine. At least for me and some users here: <https://github.com/ContinuumIO/anaconda-issues/issues/11734#issuecomment-638591004> Putting this here in case anyone else runs into the same problem. Upvotes: 1 <issue_comment>username_2: For me, It was only the fact that I modified too much my file .condarc. I restored back and solved my issue Upvotes: 0
2018/03/20
631
2,184
<issue_start>username_0: I am running Django on localhost (development machine), and I came across this in my debug console: ``` Not Found: /robots.txt 2018-03-20 22:58:03,173 WARNING Not Found: /robots.txt [20/Mar/2018 22:58:03] "GET /robots.txt HTTP/1.1" 404 18566 ``` What is the meaning of this and if there is any recommendation to handle this right. Also on production server.<issue_comment>username_1: `robots.txt` is a file that is used to manage behavior of crawling robots (such as search index bots like google). It determines which paths/files the bots should include in it's results. If things like search engine optimization are not relevant to you, don't worry about it. If you do care, you might want to use a django native implementation of robots.txt file management like [this](https://github.com/jazzband/django-robots). Upvotes: 0 <issue_comment>username_2: robots.txt is a standard for web crawlers, such as those used by search engines, that tells them which pages they should index. To resolve the issue, you can either host your own version of robots.txt statically, or use a package like [django-robots](https://github.com/jazzband/django-robots). It's odd that you're seeing the error in development unless you or your browser is trying to explicitly access it. In production, if you're concerned with SEO, you'll likely also want to set up the webmaster tools with each search engine , example: [Google Webmaster Tools](https://www.google.com/webmasters/tools/home?hl=en) <https://en.wikipedia.org/wiki/Robots_exclusion_standard> <https://support.google.com/webmasters/answer/6062608?hl=en> Upvotes: 4 [selected_answer]<issue_comment>username_3: the **robots.txt** file is a *Robots exclusion standard*, please see **[THIS](https://en.wikipedia.org/wiki/Robots_exclusion_standard)** for more informtion. Here is an example of Google's robots.txt: <https://www.google.com/robots.txt> For a good example of how to set one up, use [What are recommended directives for robots.txt in a Django application?](https://stackoverflow.com/questions/42594231/what-are-recommended-directives-for-robots-txt-in-a-django-application), as reference. Upvotes: 0
2018/03/20
714
2,496
<issue_start>username_0: Im running Matlab on linux (Elementary OS) The problem im facing is that Matlab isnt compatible with the gcc compiler higher than 4.9. Same question as: <https://www.mathworks.com/matlabcentral/answers/348906-downgrading-gcc-g-for-use-with-mex> When I use "sudo apt get install gcc" 5.4 is automatically installed. When I remove 5.4, Matlab will not recognize 4.9 which I've installed. How do I get Matlab to recognize gcc/g++ 4.9 as my compiler? I've also followed this but it didnt resolve the problem: <https://www.mathworks.com/matlabcentral/answers/137228-setup-mex-compiler-for-r2014a-for-linux#answer_263109> Any help would be greatly appreciated.<issue_comment>username_1: `robots.txt` is a file that is used to manage behavior of crawling robots (such as search index bots like google). It determines which paths/files the bots should include in it's results. If things like search engine optimization are not relevant to you, don't worry about it. If you do care, you might want to use a django native implementation of robots.txt file management like [this](https://github.com/jazzband/django-robots). Upvotes: 0 <issue_comment>username_2: robots.txt is a standard for web crawlers, such as those used by search engines, that tells them which pages they should index. To resolve the issue, you can either host your own version of robots.txt statically, or use a package like [django-robots](https://github.com/jazzband/django-robots). It's odd that you're seeing the error in development unless you or your browser is trying to explicitly access it. In production, if you're concerned with SEO, you'll likely also want to set up the webmaster tools with each search engine , example: [Google Webmaster Tools](https://www.google.com/webmasters/tools/home?hl=en) <https://en.wikipedia.org/wiki/Robots_exclusion_standard> <https://support.google.com/webmasters/answer/6062608?hl=en> Upvotes: 4 [selected_answer]<issue_comment>username_3: the **robots.txt** file is a *Robots exclusion standard*, please see **[THIS](https://en.wikipedia.org/wiki/Robots_exclusion_standard)** for more informtion. Here is an example of Google's robots.txt: <https://www.google.com/robots.txt> For a good example of how to set one up, use [What are recommended directives for robots.txt in a Django application?](https://stackoverflow.com/questions/42594231/what-are-recommended-directives-for-robots-txt-in-a-django-application), as reference. Upvotes: 0
2018/03/20
264
828
<issue_start>username_0: Does anyone know of an expression for reporting services to return the first day of 3 years ago? Example: Today's Date = 3/20/2018 Return date: 1/1/2015 I would like to always return 1/1/2015 regardless of what date it is during the current year. Thank you<issue_comment>username_1: Not sure if this is the best way to go about it.. but a hack way would be to do this in SSRS is : ``` =CDate("1/1/" & Str(Year(Today())-3)) ``` This is assuming you always want 3 years ago of course.. adjust to suit Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` =dateadd(dateinterval.year, -3, DateAdd("d", -1, Today)) ``` This will give you date 3 year exactly from yesterday. If you want today and then 3 year back then change it to ``` =dateadd(dateinterval.year, -3, Today) ``` Upvotes: 0
2018/03/20
628
2,431
<issue_start>username_0: I'm trying to customise the way in which Google Home handles no user input - ie. if the user just says nothing and doesn't respond, I want to handle that in my fulfilment, but currently, no matter what combination of things I try, Google Home will always say "Sorry, I didn't hear that", and then after two attempts, will exit. My fulfilment is returning a response after she's said "Sorry".. but i want to use a more graceful message than the default. I just cannot figure out how to override that message, and get my fulfilment to respond, rather than the seemingly inbuilt response. I'm assuming the correct action is "actions\_intent\_NO\_INPUT", but it doesn't seem to work. Has anyone managed to do this, or is it an inbuilt security mechanism?<issue_comment>username_1: I usually find that it takes two Intents to make sure it works correctly. Sometimes I get it to work with the first one by itself, and the documentation says you should only need that, but the second seems to work when the first one (occasionally) doesn't. I have them set to call the same action in fulfillment. While `actions_intent_NO_INPUT` is correct, you need to set this as the *Event* in Dialogflow. It also corresponds to a context named `actions_intent_no_input`. Between these two, we can create the following Intents: The first is a regular Intent that handles the event, sets an action, and calls the webhook fulfillment: [![enter image description here](https://i.stack.imgur.com/yuYyS.png)](https://i.stack.imgur.com/yuYyS.png) The second is a Fallback Intent that only triggers if the `actions_intent_no_input` context is set: [![enter image description here](https://i.stack.imgur.com/o67jg.png)](https://i.stack.imgur.com/o67jg.png) Upvotes: 2 <issue_comment>username_2: No input intents are only available for speaker surfaces currently. For devices with screens (say, smartphones), the mic is just closed after a while. This can be verified by hovering over to the "no input" icon in the actions console. Guess you are testing it for the mobile devices and hence aren't able to test it. In case, your action works for the speaker surface too, just try testing your code for the same and you should be good to go! [![hovering over to the no input icon in the actions console shows support for only Speaker Surface](https://i.stack.imgur.com/MKTCD.png)](https://i.stack.imgur.com/MKTCD.png) Upvotes: 2
2018/03/20
1,039
3,125
<issue_start>username_0: My problem is something like I want to append some string in front of a iostream. You can say in front of std::cin. ``` #include #include void print(std::istream & in){// function not to be modified std::string str; in >> str; std::cout<< str << std::endl; in >> str; std::cout<< str << std::endl; } int main() { std::string header = "hello "; //boost::iostream::filtering\_istream in(std::cin); std::istream & in = std::cin; //you may do someting here //something like inserting characters into cin or something with buffers print(in); } ``` I want the implementation of the fuction such that if I provide input like ``` $ cat file.txt help me to solve this. $ $ ./a.out < file hello help $ ``` any kind of help is welcome. you may use boost::iostream to implement it.<issue_comment>username_1: A stream is not a container. It is a flow of data. You cannot change data that has already floated away. The only exception is streams tied to block devices, in which you can seek around, e.g. `fstream` - but even then you can only overwrite. Instead, structure your code so that `header` is consumed before the stream is consulted at all. Upvotes: 2 <issue_comment>username_2: You should avoid the issue. Just don't parse it all from the same stream if it isn't the same stream. ### Low-Tech A low-tech "solution" is to copy the stream to a stringstream, putting your "prefix" in the buffer first: **`[Live On Coliru](http://coliru.stacked-crooked.com/a/3c4b63ed190d82c0)`** ``` #include #include #include void print(std::istream ∈) { // function not to be modified std::string str; while (in >> str) std::cout << str << std::endl; } int main() { std::string header = "hello "; std::stringstream in; in << header << std::cin.rdbuf(); print(in); } ``` Given the input `foo bar qux` prints: ``` hello foo bar qux ``` ### High-Tech You can always create a custom stream buffer that implements the behaviour you desire: **[Live On Coliru](http://coliru.stacked-crooked.com/a/ad713db2462b6ffa)** ``` #include #include #include template class cat\_streambuf : public std::streambuf { B1\* \_sb1; B2\* \_sb2; std::vector \_buf; bool \_insb1 = true; public: cat\_streambuf(B1\* sb1, B2\* sb2) : \_sb1(sb1), \_sb2(sb2), \_buf(1024) {} int underflow() { if (gptr() == egptr()) { auto size = [this] { if (\_insb1) { if (auto size = \_sb1->sgetn(\_buf.data(), \_buf.size())) return size; \_insb1 = false; } return \_sb2->sgetn(\_buf.data(), \_buf.size()); }(); setg(\_buf.data(), \_buf.data(), \_buf.data() + size); } return gptr() == egptr() ? std::char\_traits::eof() : std::char\_traits::to\_int\_type(\*gptr()); } }; void print(std::istream ∈) { // function not to be modified std::string str; while (in >> str) std::cout << str << std::endl; } int main() { std::stringbuf header("hello "); cat\_streambuf both(&header, std::cin.rdbuf()); std::istream is(&both); print(is); } ``` Which also prints ``` hello foo bar qux ``` for the same input. This will definitely scale better for (very) large streams. Upvotes: 0
2018/03/20
2,300
7,808
<issue_start>username_0: I'm using the Django-Python Social Auth app and i'm trying to extend my pipeline so that when a user signs up using Facebook, they are simultaneously signed up to my Mailchimp mailing list (and sent an email to verify). This works fine if a user signs up using traditional input methods--but not via Social auth.and is returning this error: `ValueError at /oauth/complete/facebook/ not enough values to unpack (expected 2, got 1)` here is full stack trace: ``` File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_django\utils.py" in wrapper 49. return func(request, backend, *args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_django\views.py" in complete 33. *args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_core\actions.py" in do_complete 41. user = backend.complete(user=user, *args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_core\backends\base.py" in complete 40. return self.auth_complete(*args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_core\utils.py" in wrapper 252. return func(*args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_core\backends\facebook.py" in auth_complete 111. return self.do_auth(access_token, response, *args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_core\backends\facebook.py" in do_auth 153. return self.strategy.authenticate(*args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_django\strategy.py" in authenticate 107. return authenticate(*args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\__init__.py" in authenticate 70. user = _authenticate_with_backend(backend, backend_path, request, credentials) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\__init__.py" in _authenticate_with_backend 116. return backend.authenticate(*args, **credentials) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_core\backends\base.py" in authenticate 80. return self.pipeline(pipeline, *args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_core\backends\base.py" in pipeline 83. out = self.run_pipeline(pipeline, pipeline_index, *args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_core\backends\base.py" in run_pipeline 112. func = module_member(name) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\social_core\utils.py" in module_member 57. mod, member = name.rsplit('.', 1) Exception Type: ValueError at /oauth/complete/facebook/ Exception Value: not enough values to unpack (expected 2, got 1) ``` My pipeline looks like so: ``` SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', # <--- enable this one 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'sendsub', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) ``` you can see that I've added a `sendsub` function which is based on this function---and somewhat modeled [off this page here](http://python-social-auth.readthedocs.io/en/latest/pipeline.html#extending-the-pipeline) ``` def sendsub(backend, user, response, *args, **kwargs): profile = user.get_profile() email = profile.email thread = threading.Thread(target=self.run, args=()) thread.daemon = True thread.start() def run(self): API_KEY = settings.MAILCHIMP_API_KEY LIST_ID = settings.MAILCHIMP_SUBSCRIBE_LIST_ID api = mailchimp.Mailchimp(API_KEY) try: api.lists.subscribe(LIST_ID, {'email': self.email}) except: return False ``` again this `sendsub` function is working correctly when applied to my regular registration page an user model..here is the function (slight difference). ``` class SendSubscribeMail(object): def __init__(self, email): self.email = email thread = threading.Thread(target=self.run, args=()) thread.daemon = True thread.start() def run(self): API_KEY = settings.MAILCHIMP_API_KEY LIST_ID = settings.MAILCHIMP_SUBSCRIBE_LIST_ID api = mailchimp.Mailchimp(API_KEY) try: api.lists.subscribe(LIST_ID, {'email': self.email}) except: return False ```<issue_comment>username_1: Ok, the error itself comes from social auth. But that's because you are not giving it the right data. ``` mod, member = name.rsplit('.', 1) ``` It's trying to split the name into two, there isn't a dot in the name so you cannot get two parts out of it. So it's impossible to assign to mod and member. Now we know the problem, but we still have a long way to goto solve it. The first step is to identify the culprit. I would say it's right here. ``` thread = threading.Thread(target=self.run, args=()) thread.daemon = True thread.start() ``` Creating your own threads in a web app is a very dangerous thing to do. You should either do this task synchronously, or you should delegate to a task queue and let it happen completely asynchronously. Upvotes: 2 [selected_answer]<issue_comment>username_2: Entries in `SOCIAL_AUTH_PIPELINE` should be in the form of an import path, in this case the error is caused becuase `sendsub` is not a proper import path, you need to specify the module it's defined like `module.sendsub`. In order to verify that the import path is correct, you should be able to run the same in a django shell in the form `import module.sendsub` and it should successfully import it. Upvotes: 2 <issue_comment>username_3: Hope this isn't too late. But in `settings.py`, make sure that `AUTHENTICATION_BACKENDS` have a comma behind it, otherwise it's taken as a string, and hence causes the error. Upvotes: 2
2018/03/20
851
2,384
<issue_start>username_0: If you can explain to me, not only solve it, it will really be incredible. FIRST: It's an exercise that my teacher gave me, it really does not have any value in my grades, but I'm trying to solve it, and I can't when I do the tests says Input: n: 3 Output: 10 Expected Output: 13 Console Output: Empty Here is the question: Below we will define an n-interesting polygon. Your task is to find the area of a polygon for a given n. A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the n - 1-interesting polygon and appending 1-interesting polygons to its rim, side by side. You can see the 1-, 2-, 3- and 4-interesting polygons in the picture below.[![enter image description here](https://i.stack.imgur.com/eT6c6.png)](https://i.stack.imgur.com/eT6c6.png)<issue_comment>username_1: Firstly you have to find a mathematical way to find the area of your n-interesting polygon, than traspose to code. One way is to consider the Area function of a given n-polygon, such as `Area(n)= (2n-1)^2-2*(n-1)(n)` where (2n-1)^2 is the area of the square built over the n-int polygon with side=n+n-1(blue squares plus white squares), than I subtract only the area of white squares (one of this area is (n-1)n/2, I have to mul this with 4 sides so finally we have 2\*(n-1)n ) Upvotes: 3 [selected_answer]<issue_comment>username_2: You can do it in the simplest way. I set down calculations and found that for: * n = 1 => 1 * n = 2 => 5 * n = 3 => 13 * n = 4 => 25 * n = 5 => 41 * n = 6 => 61 So when I did a calculation of the square of each number: * n = 1 => 1 -> 1\*1 = 1 * n = 2 => 5 -> 2\*2 = 4, 5-4 = 1 * n = 3 => 13 -> 3\*3 = 9, 13-9=4 * n = 4 => 25 -> 4\*4 = 16, 25-16=9 * n = 5 => 41 -> 5\*5 = 25, 41-25=16 * n = 6 => 61 -> 6\*6 = 36, 61-36=25 Then I figured out formula : n^2 + (n-1)\*(n-1) Upvotes: 2 <issue_comment>username_3: I did it a little more of a rudimentary way than others here. I saw that lines above/below the middle follow the same formula (2n - 1) for the area. The top and the bottom are mirrored. So, I looped only half of the height. Each time it looped I added (2n-1) to the total area then I subtracted 1 from n. After the loop is finished I multiplied the area by 2 to get the bottom/top area. I then combined that with the middle area. Hope that helps! Upvotes: 0
2018/03/20
833
2,401
<issue_start>username_0: I'm trying to center a label inside a custom drawing node in Godot. The label is attached to the node. The parent node is an hexagon, which (0,0) position is in the center of the hexagon (that means, there are negative coordinates in the node). When I add the label it seems to take the center of the hexagon as its top-left corner. ![Imgur](https://i.stack.imgur.com/AK3Rq.png) However, I would like to have the center of the label in the center of the hexagon. That means, some parts of the label must have negative coordinates, but I can't find any solution to center the label the right way. Labels don't have size on Godot so I can't center it manually. Code of Label: ``` var label = new Label(); tile.AddChild(label); label.SetText("1"); label.SetScale(new Vector2(1.5f,1.5f)); label.SetAlign(Godot.Label.AlignEnum.Center); ```<issue_comment>username_1: Firstly you have to find a mathematical way to find the area of your n-interesting polygon, than traspose to code. One way is to consider the Area function of a given n-polygon, such as `Area(n)= (2n-1)^2-2*(n-1)(n)` where (2n-1)^2 is the area of the square built over the n-int polygon with side=n+n-1(blue squares plus white squares), than I subtract only the area of white squares (one of this area is (n-1)n/2, I have to mul this with 4 sides so finally we have 2\*(n-1)n ) Upvotes: 3 [selected_answer]<issue_comment>username_2: You can do it in the simplest way. I set down calculations and found that for: * n = 1 => 1 * n = 2 => 5 * n = 3 => 13 * n = 4 => 25 * n = 5 => 41 * n = 6 => 61 So when I did a calculation of the square of each number: * n = 1 => 1 -> 1\*1 = 1 * n = 2 => 5 -> 2\*2 = 4, 5-4 = 1 * n = 3 => 13 -> 3\*3 = 9, 13-9=4 * n = 4 => 25 -> 4\*4 = 16, 25-16=9 * n = 5 => 41 -> 5\*5 = 25, 41-25=16 * n = 6 => 61 -> 6\*6 = 36, 61-36=25 Then I figured out formula : n^2 + (n-1)\*(n-1) Upvotes: 2 <issue_comment>username_3: I did it a little more of a rudimentary way than others here. I saw that lines above/below the middle follow the same formula (2n - 1) for the area. The top and the bottom are mirrored. So, I looped only half of the height. Each time it looped I added (2n-1) to the total area then I subtracted 1 from n. After the loop is finished I multiplied the area by 2 to get the bottom/top area. I then combined that with the middle area. Hope that helps! Upvotes: 0
2018/03/20
378
1,510
<issue_start>username_0: I have a webform with a submit button like this ``` ``` The javascript function it calls is like this ``` function processSub(){ var btnId = '<%= btnSub.ClientID %>' var userSelection = confirm('Are you sure you wish to submit'); if (userSelection){ document.getElementById(btnId).setAttribute("disabled","disabled"); return true; } else { return false; } } ``` Now I want to disable the submit button when the user clicks submit. But when I call the code to set the attribute to disabled the submit doesn't happen. When I comment this line `document.getElementById(btnId).setAttribute("disabled","disabled");` in the IF block, it works and continues with the submit. Why is this so and how do I get it to work? I am not using any JavaScript library and don't want to as well. Thanks.<issue_comment>username_1: submit the form by js before return in if statement ``` document.forms[0].submit(); ``` Upvotes: -1 <issue_comment>username_2: Even though there is no `OnClick` specified on the button, it will still do a form post (PostBack) when it is clicked. You set the `disabled` state with javascript, but immediately after a PostBack occurs therefore resetting the Button to it's original state. if you want to disable the button you can set it in code begind after the user confirmes. ``` protected void btnSub_Click(object sender, EventArgs e) { //disable the button btnSub.Enabled = false; } ``` Upvotes: 0
2018/03/20
1,012
3,258
<issue_start>username_0: I'm aware that the following code ``` #include #include int main() { std::string s; s[0] = 'a'; s[1] = 'b'; } ``` says "string subscript out of range" even though std::string's size is 28 bytes. From previous posts, I read to dynamically make the string bigger as you need. What's the best way to do that? I did the following but it's too ugly. ``` #include #include int main() { std::string s; char c; unsigned x = 0; std::cout << "char to append: "; s += " "; // what to do here std::cin >> c; s[x++] = c; //for future appends, x is already 1 position to the right std::cout << s; std::cin.get(); std::cin.get(); } ```<issue_comment>username_1: EDITED You might want to use the fact that string can behave as a `vector` in some way, so adding a character to the end of the string could be implemented as `s.push_back(c)`, and deleting the last character could also be implemented as `s.pop_back()`. Upvotes: 1 <issue_comment>username_2: > > says "string subscript out of range" even though std::string's size is 28 bytes > > > No, the logical size of this string is "zero characters". The bytes making up the container itself are irrelevant. If you want to add characters, use [`push_back`](http://en.cppreference.com/w/cpp/string/basic_string/push_back) or [the `+=` operator](http://en.cppreference.com/w/cpp/string/basic_string/operator%2B%3D): ``` s.push_back('a'); s += 'b'; ``` Upvotes: 2 <issue_comment>username_3: The size of the string object does not indicate the nominal length of the string. Twenty-eight bytes is just the amount of memory that the implementation uses. On a different system it might be more or less. The way you allocated the string, its length is zero. To expand it, use `push_back`. You can also initialize it with "ab". ``` #include #include int main() { std::string s; std::cout << s.length() << '\n'; s.push\_back('a'); // not s[0] = 'a'; s.push\_back ('b'); // not s[1] = 'b'; std::cout << s.length() << '\n'; // or initialize it with 'ab'... std::string s2 {"ab"}; std::cout << s2 << std::endl; } ``` There are a couple of dozen [member-functions of std::string](http://en.cppreference.com/w/cpp/string/basic_string) that you should familiarize yourself with. `resize()` is one of them. Upvotes: 2 <issue_comment>username_4: Resizing a `std::string` ======================== ``` std::string str; str.resize(2); str[0] = 'a'; str[1] = 'b'; ``` The `std::string` is basically a container of bytes. It has a "length/size" attribute which can be accessed with the `length()` and `size()` [methods](http://en.cppreference.com/w/cpp/string/basic_string/size). You can modify this field and ask for a larger memory buffer by calling the `resize()` method. Appending to a `std::string` ============================ If you'd like to append to an `std::string`, the cleanest way is by using the `std::ostringstream`, as mentioned in another answer. `std::push_back()` was also discussed. Another way is by using the `std::string`'s `operator+` and `operator+=`. Both take a std::string or char. ``` std::string str; str += 'a'; str = str + "b"; ``` These methods automatically resize as well as append to the `std::string`. Upvotes: 1 [selected_answer]
2018/03/20
1,465
5,877
<issue_start>username_0: I want to setup a cognito user pool and configure my google identity provider automatically with a cloudformation yml file. I checked all the documentation but could not find anything even close to doing this. Any idea on how to do it? [![enter image description here](https://i.stack.imgur.com/OVB31.png)](https://i.stack.imgur.com/OVB31.png)<issue_comment>username_1: It seems a lot of Cognito details are not supported within Cloudformation as of right now, but there are ways to achieve what you want after the stack spins up, e.g. using Lambdas. See the following answers: [Cannot set a property of cognito userpool client via cloudformation](https://stackoverflow.com/questions/51410345/cannot-set-a-property-of-cognito-userpool-client-via-cloudformation?rq=1) [Cloudformation Cognito - how to setup App Client Settings, Domain, and Federated Identities via SAM template](https://stackoverflow.com/questions/49524493/cloudformation-cognito-how-to-setup-app-client-settings-domain-and-federated?rq=1) Upvotes: 2 <issue_comment>username_2: You can achieve this using Lambda function as custom Cloudformation resources. I have made custom resources to allow creation of user pool domain, client settings and Identity providers on [this repo](https://github.com/qalshakhoori/sls-custom-cognito) You will have somethings like this for creating identity provider, for example Facebook ``` FacebookIdp: Type: 'Custom::${self:service}-${self:provider.stage}-CUPIdentityProvider' DependsOn: - CFNSendResponseLambdaFunction - CUPIdentityProviderLambdaFunction Properties: ServiceToken: Fn::GetAtt: [CUPIdentityProviderLambdaFunction, Arn] UserPoolId: Ref: AppUserPool ProviderName: Facebook ProviderType: Facebook Client_id: 'YourFacebookAppID' Client_secret: 'YourFacebookAppSecert' Authorize_scopes: 'public_profile,email' ``` And then enable that identity provider on the user pool client settings ``` AppUserPoolClientSettings: Type: 'Custom::${self:service}-${self:provider.stage}-CUPClientSettings' DependsOn: - CFNSendResponseLambdaFunction - CUPClientSettingsLambdaFunction - FacebookIdp Properties: ServiceToken: Fn::GetAtt: [ CUPClientSettingsLambdaFunction, Arn] UserPoolId: Ref: AppUserPool UserPoolClientId: Ref: AppUserPoolClient SupportedIdentityProviders: - COGNITO - Facebook CallbackURL: 'https://www.yourdomain.com/callback' ##Replace this with your app callback url LogoutURL: 'https://www.yourdomain.com/logout' ##Replace this with your app logout url AllowedOAuthFlowsUserPoolClient: true AllowedOAuthFlows: - code AllowedOAuthScopes: - openid ``` Note that this repo is built using [Serverless framework](https://serverless.com/), if you wish to build this with pure cloudformation stacks, use the code on file [CUPIdentityProvider.js](https://github.com/qalshakhoori/sls-custom-cognito/blob/master/CUPIdentityProvider.js) to make your own custom resource. Upvotes: 2 <issue_comment>username_3: Using a [generic custom resource provider](https://github.com/username_3/cfn-generic-custom-resource/blob/master/cognito-template.yaml), you can create all the resource CFN doesn't support. The example given [here](https://github.com/username_3/cfn-generic-custom-resource#cognito-demo) specifically creates and configures Cognito for Google SAML auth. It should be easy enough to change it to use Google oAuth instead of SAML by changing the parameters passed to the custom resource handler, for example. ``` UserPoolIdentityProvider: Type: 'Custom::CognitoUserPoolIdentityProvider' Condition: HasMetadata DependsOn: UserPool Properties: ServiceToken: !Sub '${CustomResourceLambdaArn}' AgentService: cognito-idp AgentType: client # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cognito-idp.html#CognitoIdentityProvider.Client.create_user_pool_domain AgentCreateMethod: create_identity_provider AgentUpdateMethod: update_identity_provider AgentDeleteMethod: delete_identity_provider AgentResourceId: ProviderName AgentCreateArgs: UserPoolId: !Sub '${UserPool}' ProviderName: google-provider AttributeMapping: email: emailAddress ProviderDetails: google_app_id: some_value google_app_secret: some_value google_authorize_scope: some_value ProviderType: Google AgentUpdateArgs: UserPoolId: !Sub '${UserPool}' ProviderName: google-provider AttributeMapping: email: emailAddress ProviderDetails: google_app_id: some_value google_app_secret: some_value google_authorize_scope: some_value ProviderType: Google AgentDeleteArgs: UserPoolId: !Sub '${UserPool}' ProviderName: google-provider ``` > > you'll need to create a test provider in the console to get the correct names for parameters under `ProviderDetails`, namely `Google app ID`, `App secret` and `Authorize scope`. Also the `AttributeMapping` might need to be set to something else. > > > Upvotes: 1 <issue_comment>username_4: `UserPoolIdentityProvider` was added in Oct 2019, [official docs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolidentityprovider.html). Your CloudFormation would then look something like ``` CognitoUserPoolIdentityProvider: Type: AWS::Cognito::UserPoolIdentityProvider Properties: ProviderName: Google AttributeMapping: email: emailAddress ProviderDetails: client_id: .apps.googleusercontent.com client\_secret: authorize\_scopes: email openid ProviderType: Google UserPoolId: Ref: CognitoUserPool ``` Upvotes: 4