text:
Q: NoClassDefFoundError: NameCoder at Spring Cloud Brixton.SR7 and Spring Cloud Camden.SR3 For all the Camden releases and now on the Brixton.SR7 as well, the following issue related to the Eureka Client occurs when starting the Spring Boot app:
java.lang.NoClassDefFoundError: com/thoughtworks/xstream/io/naming/NameCoder
For an instance I have a Spring Boot app having the @EnableDiscoveryClient annotation...
Lately I've been changing the Spring Cloud dependencies back to Brixton.SR6 in order to get rid of this error. Certainly, I want to use the latest versions of the Spring Cloud but how could I fix this error the right way?
Thanks
The console output is the following:
2016-11-30 13:09:50.166  INFO 9248 --- [           main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2016-11-30 13:09:50.177 ERROR 9248 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.context.ApplicationContextException: Failed to start bean 'org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.eurekaClient' defined in class path resource [org/springframework/cloud/netflix/eureka/EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.netflix.discovery.EurekaClient]: Factory method 'eurekaClient' threw exception; nested exception is java.lang.RuntimeException: Failed to initialize DiscoveryClient!
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:176) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:51) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:346) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:149) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:112) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:879) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:144) ~[spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
    at com.citifintech.ReferenceZipkinServiceApplication.main(ReferenceZipkinServiceApplication.java:15) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.eurekaClient' defined in class path resource [org/springframework/cloud/netflix/eureka/EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.netflix.discovery.EurekaClient]: Factory method 'eurekaClient' threw exception; nested exception is java.lang.RuntimeException: Failed to initialize DiscoveryClient!
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1128) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1022) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:345) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.cloud.context.scope.GenericScope$BeanLifecycleWrapper.getBean(GenericScope.java:359) ~[spring-cloud-context-1.1.6.RELEASE.jar:1.1.6.RELEASE]
    at org.springframework.cloud.context.scope.GenericScope.get(GenericScope.java:176) ~[spring-cloud-context-1.1.6.RELEASE.jar:1.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:340) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:192) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at com.sun.proxy.$Proxy82.getApplications(Unknown Source) ~[na:na]
    at org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration.maybeInitializeClient(EurekaDiscoveryClientConfiguration.java:120) ~[spring-cloud-netflix-eureka-client-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration.start(EurekaDiscoveryClientConfiguration.java:97) ~[spring-cloud-netflix-eureka-client-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:173) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    ... 14 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.netflix.discovery.EurekaClient]: Factory method 'eurekaClient' threw exception; nested exception is java.lang.RuntimeException: Failed to initialize DiscoveryClient!
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    ... 29 common frames omitted
Caused by: java.lang.RuntimeException: Failed to initialize DiscoveryClient!
    at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:441) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:304) ~[eureka-client-1.4.12.jar:1.4.12]
    at org.springframework.cloud.netflix.eureka.CloudEurekaClient.<init>(CloudEurekaClient.java:51) ~[spring-cloud-netflix-eureka-client-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration.eurekaClient(EurekaClientAutoConfiguration.java:192) ~[spring-cloud-netflix-eureka-client-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration$$EnhancerBySpringCGLIB$$c1700a5f.CGLIB$eurekaClient$1(<generated>) ~[spring-cloud-netflix-eureka-client-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration$$EnhancerBySpringCGLIB$$c1700a5f$$FastClassBySpringCGLIB$$3759430b.invoke(<generated>) ~[spring-cloud-netflix-eureka-client-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    at org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration$$EnhancerBySpringCGLIB$$c1700a5f.eurekaClient(<generated>) ~[spring-cloud-netflix-eureka-client-1.2.3.RELEASE.jar:1.2.3.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_111]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_111]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_111]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_111]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
    ... 30 common frames omitted
Caused by: java.lang.NoClassDefFoundError: com/thoughtworks/xstream/io/naming/NameCoder
    at com.netflix.discovery.converters.wrappers.CodecWrappers$XStreamXml.<init>(CodecWrappers.java:358) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.converters.wrappers.CodecWrappers.create(CodecWrappers.java:133) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.converters.wrappers.CodecWrappers.getEncoder(CodecWrappers.java:75) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.converters.wrappers.CodecWrappers.getEncoder(CodecWrappers.java:66) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.provider.DiscoveryJerseyProvider.<init>(DiscoveryJerseyProvider.java:77) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.shared.transport.jersey.EurekaJerseyClientImpl$EurekaJerseyClientBuilder$MyDefaultApacheHttpClient4Config.<init>(EurekaJerseyClientImpl.java:194) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.shared.transport.jersey.EurekaJerseyClientImpl$EurekaJerseyClientBuilder.build(EurekaJerseyClientImpl.java:170) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.shared.transport.jersey.JerseyEurekaHttpClientFactory$JerseyEurekaHttpClientFactoryBuilder.buildLegacy(JerseyEurekaHttpClientFactory.java:205) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.shared.transport.jersey.JerseyEurekaHttpClientFactory$JerseyEurekaHttpClientFactoryBuilder.build(JerseyEurekaHttpClientFactory.java:186) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.shared.transport.jersey.JerseyEurekaHttpClientFactory.create(JerseyEurekaHttpClientFactory.java:143) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.shared.transport.jersey.TransportClientFactories.newTransportClientFactory(TransportClientFactories.java:49) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.DiscoveryClient.scheduleServerEndpointTask(DiscoveryClient.java:477) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.DiscoveryClient.<init>(DiscoveryClient.java:428) ~[eureka-client-1.4.12.jar:1.4.12]
    ... 43 common frames omitted
Caused by: java.lang.ClassNotFoundException: com.thoughtworks.xstream.io.naming.NameCoder
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_111]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_111]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_111]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_111]
    ... 56 common frames omitted

Here is the pom.xml :
`
http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0
<groupId>com.financial</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>client-service</name>
<description>Reference application</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.2.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Camden.SR3</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

`
Here is the main class of the application:
package com.financial;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient
@SpringBootApplication
public class ClientServiceApplication {

public static void main(String[] args) {
    SpringApplication.run(ClientServiceApplication.class, args);
 }
}

Finally the bootstrap.properties
spring.application.name=client-service
spring.cloud.config.uri=http://localhost:8888

A: I had the same issue. This is related to an old inclusion of xstream (xstream:xstream:jar:1.1.3:compile).
The xstream library change groupId and Spring cloud use a new version (com.thoughtworks.xstream:xstream:jar:1.4.9:compile).
Use mvn dependency:tree command to check if you have the two library in your classpath. Then you can use maven exclusions to remove the old one from your classpath.
<dependency>
    <groupId>GROUPID</groupId>
    <artifactId>ARTIFACTID</artifactId>
    <version>X.Y.Z</version>
    <exclusions>
        <exclusion>
            <groupId>xstream</groupId>
            <artifactId>xstream</artifactId>
        </exclusion>
    </exclusions>
</dependency>

A: I had some time to take a closer look into this issue… so the exception is caused by the absence of the NameCoder class in the xstream library. This library is used by Eureka implementation.
Now then, xstream latest version to this date is 1.4.9 which is the one that is included on the managed dependencies for Camden.SR3 and Brixton.SR7.
The latest version that includes the NameCoder class is the xstream-1.4.8 so I had to modify the pom.xml right where the eureka dependency is stated, for all of my projects have eureka server or client to use the dependency xstream version 1.4.8 instead of the provided by the Camden.SR3 managed dependencies. For sure in maven there are several alternatives to accomplish this depending of the structure of the project, but the most straight forward way is as follows:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
    <exclusions>
        <exclusion>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
        </exclusion>
     </exclusions>
</dependency>

<dependency>
    <groupId>com.thoughtworks.xstream</groupId>
    <artifactId>xstream</artifactId>
    <version>1.4.8</version><!--$NO-MVN-MAN-VER$-->
</dependency>

Now then, the point to notice is that how the Eureka current implementations  use the NameCoder class being that the version of the xstream library provided by the Spring Cloud Camden.SR3 and Brixton.SR7 releases is xstream-1.4.9 which doesn't have precisely this class?  Possibly this issue went under the radar during the testing bundle because of some multiple dependencies that maven ended up solving automatically, however when implementing Eureka service with the latest release of Spring Cloud it will be necessary to do this change, at least for the time being.


text:
Q: Close browser tab after executing a post I have a wsgi python-2 web server and I would like that after pressing a button, executing some code on server side, the browser page would close.
At the moment the post redirects the browser tab to a hostname/foo page and I would like to not do that but just receive the post and close the page on client side.
This page is a legacy one and the less code is touched the better (it has already been reworked from scratch but I have to keep it as simple as possible for compatibility issues).
So for example the execution flow would be like this:
user clicks on "foo" button -> a post arrives to the web server -> the server does something on its side
-> page closes

From what I know an html page can be closed with a window.close(); command but I have no idea how to insert this command in the current page.
I have tried creating a javascript function bounded to the onclick and onsubmit listeners but I was not able to solve the issue as the /foo page is always printed.
The existing code is like that:
<form method="post" action="foo">
    <input type="submit" value="Submit and foo!"/>
</form>

The foo function calls a foo function in python-webserver as per wsgi programming model.
What I would like to do is to automatically close the page after pressing the Submit and Foo form submission button

A: Consider using JavaScript FormData object combined with XMLHttpRequest and thus do on submit event
var formElement = document.querySelector("form");
var request = new XMLHttpRequest();
request.open("POST", "foo", true);
request.onreadystatechange = function() {
    if (this.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
        window.close();
    }
}
request.send(new FormData(formElement));

Note that this assume you have single form on your page. If you prefer to close at another moment, replace HEADERS_RECEIVED with one of other readyState value. Disclaimer: this code was not tested.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need help with PHP socket server! Hi i am writing a socket server , At the moment i have 2 options

*

*Go with PHP

*Go with C++

The thing i need to know is that which of them is more reliable and scalable.After searching google a lot i found out that pretty much C++ can take care of my Scale needs but the thing is C++ requires much more coding then PHP moreover deployment is a bit harder on C++ .
PHP sounds promising (because of native API's for SQL & SOCKETS also its easier to deploy on cross platforms ) but I have no clue on how scalable the PHP based server can be.At the moment i want to support atleast 1k - 2k concurrent connections . Can PHP take this load ?
Also is there any way to implement Multithreading in PHP (so that i can part the workload on 2 or more threads rather then 1 overloaded thread holding all users and there requests).

Incase needed My server is a basic machine.
Processor : AMD Sempron 3000+
RAM       : 2 GB
HDD       : 80 Gigs
I plan to move to a faster server after some time .
Thanks in advance.

A: I wouldn't use PHP for that. PHP has no built-in support for multithreading. Go with C++ or maybe Java.

A: PHP has no multithreading and 2k clients will "kill" a single script.
C++ is fine, for a lot of (lightweight) tasks a single thread with epoll demultiplexing is the fastest way, if not, there is prethread(like prefork buth with threads), fork is only needed if one processor core is not able to serve all the requests. Write the socket code with a state machine so you can play with different implementations and switch between single and multithreaded behavior.

A: on Java you have Netty and Mina

A: PHP is definitely a bad choice - no threads - your basic architecture would be to fork() a process for every connection.  Not fun.
C++ is probably the way to go, though you might other interpreted languages and evaluate them.
Before committing to writing something in C++, I'd certainly consider an event-driven server-side-javascript approach (see http://nodejs.org), or possibly something python (twisted?) or ruby-based.


text:
Q: Does Alfresco support monitoring entire folder tree for changes? I am interested in triggering code to run when any changes are made to any documents or folders under a specific folder in alfresco. I am sure alfresco has to support this some how but I am not entirely sure what the feature/api/service is called or what to google for. What has this ability in alfresco and what is it called?
I am aware that its possible to create custom content rules in javascript and then add them to a folder to be triggered by some action. I did that a couple years back for auto filing documents that were dropped into a specific folder. Problem is that requires adding that action to each folder you want to monitor. I want to monitory an entire directory tree basically.
EDIT:
Correct me if I am wrong, but it appears that Events API may do what I need to do. I found this right after posting my question.

A: You probably just want to create a Rule on the top folder, and set it to apply to subfolders. If you're interested in changes, then set a When of "Items are updated". Depending on your needs, you could also restrict it to only items of a given type or aspect (eg to pick up document changes, but not folder changes)
Finally, you can either have your Rule run a JavaScript file (Execute script) to perform the business logic, or you can register a Java Custom Action and have that triggered

A: @Gragravarr answer is the best for handling events over a subtree of the repository.
In case what you need to monitor is only a subset of all the content of the subree (e.g. watch all the incoming documents, but only if they are PDF) and possibly scattered across the whole repository, then creating a specific content type and handle events using Policies is probably a better option.


text:
Q: Retrieval of Azure Runbook schedules list having a particular schedule triggered on a weekly basis generates an error I've recently created a runbook schedule which is executed periodically - every 1 week on Monday without expiry date.
The creation of schedule was flawless.
However when i want to retrieve a list of all runbook schedules using the powershell cmdlet
Get-AzureAutomationSchedule -AutomationAccountName $automationAccountName
i get an error message:
Get-AzureAutomationSchedule : Nie można znaleźć żądanej wartości 'Week'. (The value 'Week' could not be found)
+  Get-AzureAutomationSchedule -AutomationAccountName $automationAccoun ...
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Get-AzureAutomationSchedule], ArgumentException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Automation.Cmdlet.GetAzureAutomationSchedule

When i remove this particular schedule the full list of available schedules appears.
I've got also schedules than run on hourly/daily basis and they do not generate such problems.
Any help would be much appreciated.
After running the command Get-AzureRmAutomationSchedule -Name name_of_the_failing_schedule as suggested by @4c74356b41 i get the same error message.
Below u can see the body of http response after running the cmdlet in debug mode
{
  "id": "/subscriptions/XXXXXXXXX",
  "name": "orphaned objects",
  "properties": {
    "description": "",
    "startTime": "2016-11-28T09:00:00+01:00",
    "startTimeOffsetMinutes": 0.0,
    "expiryTime": "9999-12-31T23:59:59.9999999+01:00",
    "expiryTimeOffsetMinutes": 0.0,
    "isEnabled": true,
    "nextRun": "2016-11-28T09:00:00+01:00",
    "nextRunOffsetMinutes": 0.0,
    "interval": 1,
    "frequency": "Week",
    "creationTime": "2016-11-22T10:41:49.433+01:00",
    "lastModifiedTime": "2016-11-22T10:41:49.433+01:00",
    "timeZone": "UTC",
    "advancedSchedule": {
      "monthDays": null,
      "monthlyOccurrences": null,
      "weekDays": [
        "Monday"
      ]
    }
  }

A: I get the same error on older versions of the AzureRM.Automation PowerShell module:
PS C:\Users\Joe> Get-AzureRmAutomationSchedule -Name Every1WeekOnMonday -AutomationAccountName DemoAccount -ResourceGroupName DemoGroup
Get-AzureRmAutomationSchedule : Requested value 'Week' was not found.
At line:1 char:1
+ Get-AzureRmAutomationSchedule -Name Every1WeekOnMonday -AutomationAcc ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Get-AzureRmAutomationSchedule], ArgumentException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Automation.Cmdlet.GetAzureAutomationSchedule

PS C:\Users\Joe> Get-Module -Name AzureRM.Automation

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   1.0.4      AzureRM.Automation                  {Export-AzureRmAutomationDscConfiguration, Export-AzureRmAutomationD...

Upgrading to the latest version of the AzureRM PowerShell cmdlets fixes this:
PS C:\Users\Joe> Get-AzureRmAutomationSchedule -Name Every1WeekOnMonday -AutomationAccountName DemoAccount -ResourceGroupName DemoGroup

StartTime              : 11/22/2016 6:44:00 PM -08:00
ExpiryTime             : 12/31/9999 3:59:00 PM -08:00
IsEnabled              : True
NextRun                : 11/28/2016 6:44:00 PM -08:00
Interval               : 1
Frequency              : Week
MonthlyScheduleOptions : Microsoft.Azure.Commands.Automation.Model.MonthlyScheduleOptions
WeeklyScheduleOptions  : Microsoft.Azure.Commands.Automation.Model.WeeklyScheduleOptions
TimeZone               : America/Los_Angeles
ResourceGroupName      : DemoGroup
AutomationAccountName  : DemoAccount
Name                   : Every1WeekOnMonday
CreationTime           : 11/22/2016 6:15:08 PM -08:00
LastModifiedTime       : 11/22/2016 6:15:08 PM -08:00
Description            :

PS C:\Users\Joe>  Get-Module -Name AzureRM.Automation

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   2.3.0      AzureRM.Automation                  {Export-AzureRmAutomationDscConfiguration, Export-AzureRmAutomationD...

So you can resolve this issue by upgrading to the latest version of the AzureRM PowerShell cmdlets.


text:
Q: to_date(to_char(EVT_COMPLETED, 'dd/mm/yyyy'),'dd/mm/yyyy')as "Corrected Completion Date" I currently have to convert below statement from oracle to TSQL
to_date(to_char(EVT_COMPLETED, 'dd/mm/yyyy'),'dd/mm/yyyy') as "Corrected Completion Date"

Can anyone help me on this please

A: Hope this helps:
DECLARE @date datetime = '2009-05-11 09:40:00.0'

SELECT @date , CONVERT(varchar,@date,110 ) , CONVERT(varchar,@date,101 ) , CONVERT(date,@date,110 ) , CONVERT(date,@date,101 ), CONVERT(date,CONVERT(varchar,@date,110 ),110 ) , CONVERT(date,CONVERT(varchar,@date,101 ),101 )

Results:

However the data type date will show differently as shown in the above query. So you will need to convert to varchar when showing the data to the user. More info here

A: Try this...
DECLARE @date datetime = '2009-05-11 09:40:00.0'
DECLARE @date2 date = '2009-06-11'

select CONVERT(varchar(10), @date,105) where @date2>cast(@date as date)


text:
Q: Can I validate the length of something by middy? const baseHandler: APIGatewayProxyHandlerV2 = async (event) => {
  return service.create(event.body);
}

const inputSchema = {
  type: "object",
  properties: {
    body: {
      type: "object",
      properties: {
        year: { type: "number" },
        questionId: { type: "string" },
        propSeq: { type: "number" },
        questionTitle: { type: "string" },
        propContent: { type: "string" },
        isTrue: { type: "boolean" },
        chapter: { type: "number" }
      },
      required: ["year", "questionId", "propSeq", "questionTitle", "propContent", "isTrue", "chapter"],
    },
  },
};

export const handler = middy(baseHandler)
  .use(jsonBodyParser())
  .use(validator({inputSchema}))
  .use(httpErrorHandler())

I'm writing AWS Lambda code on Serverless Framework.
I wanted request body validator like express-validator, so I found middy.
But it looks impossible to validate the length of something.
I want to force the length of year to 4.
for example, 2023(o), 23(x)
properties: {
  year: { type: "number", length: 4 }
}

As you guess, length property cannot be understood.
I don't want to add some codes to baseHandler function to validate the length.
Thank you in advance.

A: Middy uses JSONSchema, so you can use anything that is compatible with JSONSchema there. You could use length, but then you'd need to switch the type to string from number, as length is not supported for number (rightfully so in my opinion). If you want to keep it as number, then probably using range-based validation is your best bet: https://json-schema.org/understanding-json-schema/reference/numeric.html#range


text:
Q: C# UWP displaying Image I have a little problem. I have to display Images from PicturesLibrary.
I have this code:
    info = new ImageFileInfo() { ImageTitle = file.Path, ImageType = file.DisplayType, Image = file.Path };

I tried using converter:
  return new Uri("ms-appx:///" + imagename, UriKind.Absolute);

But my images dont show up.
I know that there is a way to display images from outside of projects, cause I have been using it some time ago, but I forgot how it was done, and I can't find it anywhere.

A: The Uri schemes of ms-appx are only used for the files in the project, and the files in the picture library cannot be obtained through it.
In UWP, we do not recommend using the file path to get file. Because UWP has strict restrictions on accessing files from the path.
If you want to access files from the picture library, first you need to check Picture Library in the Capability tab in package.appxmenifest.
Then you can access it by file name:
var img = await KnownFolders.PicturesLibrary.TryGetItemAsync("test.png");

But there are other more recommended way, like use Token to access files:
After obtaining the file, we store it in the future access list and obtain a Token
Save
string faToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
info = new ImageFileInfo() { ImageTitle = file.Path, ImageType = file.DisplayType, Image = faToken };

Get
var image = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFileAsync(info.Image);


text:
Q: Set React-Toastify toast limit programmatically to show and hide number of toast on the UI I have a use case where max number of toast that can be displayed at a time is 2. If there are more than 2 toast then the total Number of toast is also displayed
within the currently displayed 2 toasts.
User Action 1 - The user can click on the total number to expand and view all toasts there is. Up to this part I've everything working for me.
User Action 2 - If the user clicks on the total number of toast again then hide the rest of the toast and go back to only display 2 toast at a time. This is what is
not working for me. Once I can achieve this then ofcourse I would also like to show back again all toast there is as mentioned in User Action 1.
On the NotificationManager component, I set default maxToast as 2. Then onClick handleMaxNotification() will change the the max toast value to null - which displays all toast there is (this is working).
handleMaxNotification() will also toggle back the maxToast to 2 and on the local state it does set the values correctly, however react-toastify doesn't reflect that in the UI.
for e.g. displayed 4 toast doesn't go back 2. Help is much appreciated!
export default function NotificationManager() {
    const [maxToast, setMaxToast] = useState(2); // default
    const [displayAllNotification, setDisplayAllNotification] = useState(false);

    const handleMaxNotification = () => {
        setDisplayAllNotification(v => !v);
    };

    useEffect(() => {
        if (displayAllNotification)
            setMaxToast(null);
        else
            setMaxToast(2);
    }, [displayAllNotification]);

    return (<>
        <ToastContainer
            newestOnTop={true}
            limit={maxToast}
        />
        <Notification
            maxToast={maxToast}
            handleMaxNotification={handleMaxNotification}
            displayAllNotification={displayAllNotification}
        />
    </>);
}

This is the component that display toast.
import { displayToast } from '../components/toast/displayToast';

const Notification = ({handleMaxNotification, maxToast, displayAllNotification}) => {

    const notifications = useSelector(state => state.notifications);
    const totalNotification = notifications.length > 2 ? notifications.length : '';

    const Toast = () => (

             handleMaxNotification()}>{totalNotification}
            <Icon name='circle' />Notification

    );

    const showNotification = (id) => {
        const toastOptions = { toastId: id };
        displayToast(Toast, toastOptions);
    };

    const handleNotification = () => {
        notifications.forEach(({ id }) => showNotification(id));
    };

    useEffect(() => {
        handleNotification();
    }, [notifications, maxToast, displayAllNotification]);

    return ();
};

export default Notification;


text:
Q: Sum of functions in Lp spaces for $p<1$ For $p \in (0,1)$, I know that the Minkowski inequality does not hold. But do we still have that $f+g \in L^p$ for $f,g \in L^p$ if $p \in (0,1)$?

A: Yes. If $p\in(0,1)$ and $s,t\ge0$ then $(s+t)^p\le s^p+t^p$, hence $||f+g||_p^p\le||f||_p^p+||g||_p^p$.
One can give a proof of that inequality that's so simple it seems like cheating: Fix $s\ge0$ and define $f:[0,\infty)\to\Bbb R$ by$$f(t)=s^p+t^p-(s+t)^p.$$Then $f(0)=0$, and for $t>0$ we have $$f'(t)=p(t^{p-1}-(s+t)^{p-1})\ge0,$$ since $s+t\ge t>0$ and $p-1<0$; hence $f(t)\ge0$.


text:
Q: calling a secure service using a service reference There is an external secure service that I am consuming in my .net class by making a web reference to it and passing it the username token like so:
MyWebService objWS = new MyWebService();
UsernameToken token = new UsernameToken("User","Password", PasswordOption.SendPlainText);
objWS.RequestSoapContext.Security.Timestamp.TtlInSeconds = 60;
objWS.RequestSoapContext.Security.Tokens.Add(token);
objWS.RequestSoapContext.Security.MustUnderstand = false;

when I make service reference to the same service url and try to pass in the username and password using ClientCredentials it fails.
I have no idea about the external service. Any idea what could be wrong?
Thanks for your time...

A: Are you calling the service over https?  The server may require a client certificate.
I found this example usage of.  UsernameToken

A: The solution was to install WSE3 and in the proxy generated inherit from Microsoft.Web.Services3.WebServicesClientProtocol instead of the default System.Web.Services.Protocols.SoapHttpClientProtocol.
Then the service proxy object would get the Security property.
objWS.RequestSoapContext.Security

which I can then use to pass in the UsernameToken.
This is a hack and I have not found a better way to do it yet. Regenerating the proxy will always involve that extra step of having to manually edit the proxy again, as above.


text:
Q: Cannot find my downloaded file in the document folder via fileExistsAtPath I'm facing an issue when trying to read my downloaded audio file from the document folder. The file '032000.mp3' really exists on the download folder(see illustration)
  F501141C-4D7B-42D9-83DE-83DE0C04AA66
  |- Documents
  |-- audios
  |--- 0
  |---- 032
  |------ 032000.mp3

  var path: String = "/Users/abm/Library/Developer/CoreSimulator/Devices/52FDA0EC-1A3F-4A69-9359-96511E21E172/data/Containers/Data/Application/F501141C-4D7B-42D9-83DE-83DE0C04AA66/Documents/audios/0/032/032000.mp3"
  println("fileExistsAtPath= \(NSFileManager.defaultManager().fileExistsAtPath(path))") // --> false

Note: Opening the downloaded file via terminal just works.
Thanks in advance

A: You need to get path for documents folder dynamically. Every times, when you start application in simulator, application folder name changed. See this answer How to find NSDocumentDirectory in swift?


text:
Q: Prepare histogram from ASCII or XYZ file and save it to image I found many examples of creating histogram in Python using the matplotlib module
(for example here).
I have also found a command which I can use to save an image to file
print('-f1','-dtiff','file_name')

Unfortunately I can't find information how to load data from both ASCII or XYZ files (containing coordinates and values). For XYZ files, I thought about reading them as CSV files, but maybe there is easier way of accomplishing this task?


text:
Q: PostgreSQL - Create Role - Permission Matrix I have three tables, Roles, Permissions, and Role_ Permissions
Table Roles has the following: id, role_name
Data:   id, role_name
         1, Accounting
         2, Order_Entry
         3, Shipping

Table Permission has: id, permission _name
Data:   id, permission _name
         1, Admin
         2, Super_User
         3, Read_Write
         4, Read_Only

Table Role_ Permissions has:
     role_id (FK from Roles),
     permission_id (FK from Permissions)

I need to create a matrix that looks like this:
Heading:       Roles        Admin Super_User Read_Write Read_Only
Columns/Rows:  Accounting     X        X
               Order_Entry    X                  X
               Shipping       X                             X

The 'X' represent that there is a permission for that role. Blanks, of course, mean there is no permission for that role
Can this be done in SQL


text:
Q: Вопрос по коллайдерам Как сделать так, чтобы в блок коллайдера вообще нельзя было даже на пару пикселей попасть? Коллайдеры настроены верно, но танк все равно на чуть-чуть, но заезжает в текстуры.

Коллайдер выталкивает объект, но если целеноправленно жать кнопку
  вперед, то модель заезжает в текстуры.

КАК сделать полностью жесткий коллайдер?

A: Столкновения между коллайдерами обсчитывает физический движок для него transform.Translate() это телепортация.
Чтобы физика работала Вам необходимо добавлять силы, которые воздействуют на объект, толкая его в направлении движения.
using UnityEngine;

public class ExampleMoveForward : MonoBehaviour
{
    public float thrust;
    public Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        rb.AddForce(transform.forward * thrust);
    }
}

Обратите внимание что обработка физики происходит не в методе Update а в методе FixedUpdate. Он в отличие от Update срабатывает в четко определенные моменты времени, а когда будет вызван Update зависит он некоторых факторов, которые сложно предсказать. Например он может вызываться очень редко или не вызываться вообще для свернутых или не активных окон. Update - для графики, FixedUpdate- для физики.

Есть грязный способ - поставить у rigidbody collision detection - continous dynamic, он порождает дополнительную нагрузку на процессор

A: Я просто займусь критикой кода
using System.Collections;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float moveSpeedup;
    public float moveSpeeddown;
    public float rotateSpeed;
    public bool moveup;
    public bool movedown;
    public bool rotateleft;
    public bool rotateright;
    void Update()
    {
        if ((Input.GetKey(KeyCode.UpArrow)) || moveup)
        {
            transform.Translate(Vector3.right * moveSpeedup * Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.DownArrow) || movedown)
        {
            transform.Translate(-Vector3.right * moveSpeeddown * Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.RightArrow) || rotateleft)
        {
            transform.Rotate(Vector3.forward * rotateSpeed * Time.deltaTime);
        }
        if (Input.GetKey(KeyCode.LeftArrow) || rotateright)
        {
            transform.Rotate(Vector3.forward * -rotateSpeed * Time.deltaTime);
        }
    }
}

В следующий раз, пожалуста, вставляй код в сам вопрос SO, а не в левые сервисы.

*

*Убери всю логику в стиле
 if ((Input.GetKey(KeyCode.UpArrow)) || moveup)

Это должно реализоватся через
 Input.GetAxis

весь список нужных команд ты найдешь в Edit -> Project Settings -> Input

*У тебя много лишних переменных. Достаточно обойтись:
 public float moveSpeed;
 public float rotateSpeed;

остальные тебе не нужны.
Если тебе хочется что бы скорость была разной, можно или ввести коэфициэнтное соотношение скорости вперед или назад, или же добавить переменные как у тебя были. (за исключением неиспользуемых)
Если это движение вперед-назад то это значение берется с плюсом или минусом. С ротейтом - идентично.

*

*Для даного случая оптимальным было бы решение движения через AddForce. Танк должен плавно останавливатся, а не резко.
Возможно, нужно будет донастроить физический материал танка что бы получилось то что нужно тебе лично (длинна скольжения при остановке).

*Множитель Time.deltaTime при использовании Translate() - лишний. Но в даном контексте, вероятно, лучше будет вызывать его из FixedUpdate().
Если же очень хочется что бы движение было нефизическим, но плавность, все же, была -- нужно ее эмулировать, например, через библиотеку LeanTween -- искать по ключевику SetEase.
Но я, все же, советую, использовать перемещение через AddForce.

*Как нежелательная альтернатива решения проблемы в самом вопросе - можно выставить Continius CollisionDetect в настройках RigitBody.

И в любом случае я настоятельно рекомендую перейти на физическое движение. Правильная реализация передвижения персонажа


text:
Q: Maven: different java compiler versions for project and plugin We have a Java 7 project which uses a plugin built with Java 8. Is it possible to use the Java 8 plugin in Java 7 pom by setting the compiler version to use only for the plugin?

A: I just found that on the internet :
http://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html
You should just add a configuration section specifying the jdk wanted as
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.3</version>
    <configuration>
      <source>1.4</source>
      <target>1.4</target>
    </configuration>
</plugin>

I hope it helps !

A: It is only possible, if the plugin forks into a new JVM process and allows you to configure the JVM which it uses to execute. Otherwise it will use the JVM, which the whole build uses. You would then have to run the build with a JRE/JDK 8 (which shouldn't be a problem when you set the source and target version appropriately, like in the answer from Juan Wolf (just set 1.7 instead of 1.4)


text:
Q: kprobes, backtrace, same symbol adjacent to itself I'm trying to understand the output from the backtrace I captured using kprobes.  If you'd like to see the full stack trace, that's fine, but it's not necessary for the question.  Below is an excerpt:
Jul 24 16:31:34 scilinx kernel: [<ffffffff813a2b2e>] ? ata_scsi_port_error_handler+0x4be/0x710
Jul 24 16:31:34 scilinx kernel: [<ffffffff813a2ea8>] ? ata_scsi_cmd_error_handler+0x128/0x180
Jul 24 16:31:34 scilinx kernel: [<ffffffff813a2f98>] ? ata_scsi_error+0x98/0xd0
Jul 24 16:31:34 scilinx kernel: [<ffffffff81386cfa>] ? scsi_error_handler+0x12a/0x810
Jul 24 16:31:34 scilinx kernel: [<ffffffff81386bd0>] ? scsi_error_handler+0x0/0x810
Jul 24 16:31:34 scilinx kernel: [<ffffffff8109aef6>] ? kthread+0x96/0xa0

You'll notice that scsi_error_handler is adjacent to itself in the call stack but I cannot find why this is.  Here is the  scsi_error_handler function for this kernel.  As you can see, it does not call itself.  So why does the stacktrace show it adjacent to itself like this?
Thanks.


text:
Q: .conf changes have no effect on reboot in WSL? I've tried making some changes in various .conf files in my Ubuntu WSL2 install, such as editing /etc/sysctl.conf with nano, adding vm.max_map_count=262144 at the end of it, saving, then rebooting Windows, and finally checking if vm.max_map_count still = 262144 ...
When I do a sysctl vm.max_map_count it still ends up showing the default 65530.
However, if I do a cat /etc/sysctl.conf I'm still seeing that new line that I added to it, with 262144?

A: I have the same problem. That doesn't work because /etc/sysctl.conf is not read when WSL2 starts up.
There's a workaround for that:
https://github.com/shayne/wsl2-hacks

A: This github issue appears to be the same problem and has just been elevated to a feature:
https://github.com/microsoft/WSL/issues/4232


text:
Q: Django Allauth Prevent Email Verification & Password Reset Email Abuse/Spam I need to stop users from abusing allauth's ability to send users verification & password reset emails so that my email provider does not temporarily suspend my email address for sending too many emails.
On the /accounts/email/ page, a user could click the re-send verification all they want and an email gets sent every click.
I noticed an ACCOUNT_EMAIL_CONFIRMATION_COOLDOWN setting but am not entirely sure how it works. I tried testing it and am still able to spam click and have the emails get sent every click.
On the /accounts/password/reset/ page, this issue occurs:
https://github.com/pennersr/django-allauth/issues/2167
The creator mentions doing something like this to alleviate it:
https://github.com/pennersr/django-allauth/issues/1008
Maybe this can be used to solve both problems? How would you implement it with the allauth code?
https://stackoverflow.com/a/2157688/13955916
Would rate limiting or throttling solve this? If so, what would a code example be for this?
I have recaptcha v3 on both pages. But that doesn't stop human spam farms.
I came up with a client side javascript cookie solution but am afraid it will not be effective to stop these problems since it is not a server side solution:
button.disabled,
button[disabled] {
    box-shadow: none;
    cursor: not-allowed;
    opacity: 0.5;
    pointer-events: none;
}

<button id="re-send" class="secondaryAction" type="submit" name="action_send" >{% trans 'Re-send Verification' %}</button>

<script>
  const resendBtn = document.getElementById("re-send");
  resendBtn.addEventListener("click", disable);

var cookieString = getCookie("cookieName");
if(cookieString == "mysite"){
    var btn = document.querySelector('#re-send');
    btn.classList.add('disabled');
}

function setCookie(){
   days=1;
   myDate = new Date();
   myDate.setTime(myDate.getTime()+(days*24*60*60*1000));
   document.cookie = 'cookieName=mysite; expires=' + myDate.toGMTString();
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

  function disable() {
    var btn = document.querySelector('#re-send');
    btn.classList.add('disabled');
    setCookie();
  };

function runFunction(){
    var testElement = document.getElementById('re-send');
if (!testElement.classList.contains('disabled') && (getCookie("cookieName") == "mysite")) {
    var btn = document.querySelector('#re-send');
    btn.classList.add('disabled');
}
};

setInterval(runFunction,1000);

</script>


text:
Q: Azure App Service vs Azure Service Fabric Can anyone direct me to something that will explain when I should create an Azure Service Fabric application vs an Azure App Service application?  I have an application I want to build but can not determine whether I should build it using the Azure Service Fabric or the Azure App Service.

A: Unfortunately there isn't any official guidance about when to use what. They're two separate platforms, following different development paradigms.
The App Service will give you functionality that Service Fabric doesn't provide out of the box. Stuff like auto-scale, authentication, rate limiting, integration with SaaS applications, etc. Some or all these things may come to Service Fabric gradually, but I'd say that, at the minute, they're targeted at different audiences - a less experienced team might find it easier to work with the App Service.
Service Fabric on the other hand makes composition of parts easier. For example, in the "traditional" approach, if you had an API that speaks to a data store and a cache to avoid hammering the data store, you'd have to handle the various fault tolerance scenarios. With Service Fabric your cache can sit within the API process in a reliable collection and you won't have to deal with having an external cache component. The data is co-located with the service (faster to retrieve/edit!) and is reliable as it's distributed across all the nodes the service is deployed into. Similar thing with queues. If you think of a workflow type system, where there is an API, a job service, and a queue that sits between them and allows them to communicate, you'd have to manage 3 different components and the communication between them. With Service Fabric the queue comes into the application. And that's just half of it :) you also get the power of using the actor model for distributed computation without the usual concurrency headaches. Finally, with Service Fabric you get the benefit of having a more complete development environment on your local box - you don't have to deal with creating queues, etc. on an Azure dev account or anything like that.
Also worth noting that there's nothing stopping you from using both paradigms - imagine two apps with at least one of them being a service fabric app, that expose APIs and a logic app that sits on top of those.
Your decision should be based on what you're trying to build, in how much time, when you want to release (Service Fabric is currently only in private preview so it'll be a while until they get to GA) and what kind of team you have. I imagine that with the App Service it'll be easy to hit the ground running even if you don't have a massively experienced team, but Service Fabric will give you more power, flexibility and control.

A: App service is a more managed service , SF is more you manage your own and you can run on your own premises as well. SF has better support for non MS stack dev eg native apps etc.
As that document states "Service Fabric is a good choice if you're creating a new app or re-writing an existing app to use a microservice architecture. "
If your hosting a few apps you should not be looking at SF , On the other hand if your deploying more than 10 services than it becomes a better solution.
Also note SF has a data storage mechanism that is included with the services . It is good at 3 things
1) Massive clusters of data
2) Simple data,  often in Micros services DBs become a heavy burden since each service should have its own data and things like SQL are bit overkill when you only have 1-3 tables.
3) State storage for the Actor programming model.
I think SF and Web apps will slice the "Cloud Service"  user base in the future.

A: Microsoft has created the document with a comparison for Azure App Service, Virtual Machines, Service Fabric, and Cloud Services. Also, you might find helpful this decision tree.

A: If (App may required to scale up in future || want to build App with micro service architecture)
 go for Azure Service Fabric
else
 Azure App Service is ok

A: Use Service Fabric when you need more control over, or direct access to, the underlying infrastructure.
Use App Service when you need a fully managed hosting platform for your web apps.
-as per documentation


text:
Q: AppLaunchChecker, where is the data stored? As Android Support Library, revision 23.3.0 (April 2016) google announced the new Api AppLaunchChecker.
I just wanted to know how and where does the system store the data. Does it store it as a shared preference, or does it store somewhere else ...
I already read the docs but I got nothing.

A: According to the official documentation: AppLaunchChecker https://developer.android.com/reference/android/support/v4/app/AppLaunchChecker.html

To help track how your app has been launched by the user in the past. This can be useful if you want to confirm that a user has launched your app through its front door activity from their launcher/home screen, rather than just if the app has been opened in the past in order to view a link, open a document or perform some other service for other apps on the device.

Thus, this new utility class is nothing more than the typical "workaround" based on SharedPreferences already used by many developers: when the launcher Activity is created, a boolean shared preference is set to true, then later in the lifecycle of the application, calling hasStartedFromLauncher, we simply get its value.
This utility class is only useful to know if the application has been launched from the home screen at least once in the past but not every time it's launched: in fact, after the fist time, you will always get true from hasStartedFromLauncher.
To answer your question: The data is kept in SharedPreferences.


text:
Q: Display a php function in jquery onblur I have html code:
<input type="text" id="email" onblur="<?php validate_email_input($email); ?>" />

And now I want to display while onblur:
function validate_email_input($email)
{
    if(!prawidlowy_email($email)) {
        throw new exception('

Kombinacja znaków w polu e-mail jest niepoprawna!

');
    }
    elseif(strlen($email) > 44) {
        throw new exception('

Pole email musi zawierać maksymalnie 44 znaki!

');
    }
    elseif(strlen($email) < 6) {
        throw new exception('

Pole email musi zawierać minimum 6 znaków!

');
    }
}

And for displaying it on the same page, but in div named okno_bledu_rejestracji I use this HTML code:

validate error box

And this JQ code, which is displaying after click form's submit button, which its name is #zarejestruj_sie:
$(document).ready( function() {
    $("#zarejestruj_sie").click( function() {

            $.post( $("#formularz_rejestracji").attr("action"), $("#formularz_rejestracji :input").serializeArray(), function(info) {
                $("#okno_bledu_rejestracji").empty();
                $("#okno_bledu_rejestracji").html(info);
            });

            $("#formularz_rejestracji").submit( function() {
                return false;
            });
    });
});

Now I want to display a php function:
function validate_email_input($email)
    {
        if(!prawidlowy_email($email)) {
            throw new exception('

Kombinacja znaków w polu e-mail jest niepoprawna!

');
        }
        elseif(strlen($email) > 44) {
            throw new exception('

Pole email musi zawierać maksymalnie 44 znaki!

');
        }
        elseif(strlen($email) < 6) {
            throw new exception('

Pole email musi zawierać minimum 6 znaków!

');
        }
    }

In div named okno_bledu_rejestracji after onblur input, which id is email.
I give thumbs for help. thanks.

A: This isn't "normally" possible.  PHP is executed by the server before the page is served to the client.  The client doesn't understand your PHP code.
That being said, there is a way to achieve this with PHP.  Using Ajax, it's possible to query the server with the email and get a response back from the server.  Typically you'll get a response back in JSON.
With jQuery, the following code would do just that:
$(document).ready( function() {
    $("#email").mouseup(function() {
        var email = $(this).val(),
            url = "api/myfunction?email=" + email;

        $.get(url, function(data) {
            // We succeeded!  data contains your response.
        });
    });
});

A: You will need to learn about Client-Side and Server-side.
The distinction between these two will be really important in your web programming.
I recommend you learn a bit about Ajax.
On the server-side you want a file, like ajax.php, that will take a email as GET parameter and will return a JSON with the response.
On mouse up, jquery will call that ajax page and take his answer and put it in a DOM element, lets say a Div.
http://learn.jquery.com/ajax/
Good luck!
Also:  If you are checking for email length and format, you might look forward a javascript translation of your code.


text:
Q: Have professional dreamers been explored in the Alien franchise? In the Alan Dean Foster novelisation of the film Alien, the book starts off with:

Seven dreamers.
You must understand that they were not professional dreamers.
Professional dreamers are highly paid, respected, much sought-after talents.
Like the majority of us, these seven dreamt without effort or discipline. Dreaming professionally, so that one's dreams can be recorded and played
back for the entertainment of others, is a much more demanding
proposition.

Has the concept of professional dreamers been explored further in the Alien franchise?
The nearest that supports this possibility I have found is from Prometheus, where, near the beginning, David was observing Elizabeth Shaw's dreams.


text:
Q: Append .html extension with php I am creating a search function that returns entries in my database.
I want to dynamically create a HTML page with the name of the entry in the database. I create the name; however, I can't append the .html extension to it.
Here is what I have tried so far:
  echo "
" . " "   .$filmName . "
\n";

A: Need to get your escaped "'s in order
    echo "
" . " " . $filmName . "
\n";

I've added an \" after the href


text:
Q: Where is this Virasoro null from? Let's consider the Virasoro algebra with a generic $c$. Take a primary $|h\rangle$ and I try to look for its level-9 nulls: Mathematica spits out 3 solutions
$$
h = \frac{1-c}{3}, \quad \frac{1}{3}(53-5c \pm 5\sqrt{(25-c)(1-c)}) \ , \quad (*)
$$
corresponding to $h_{3,3}(c), h_{1,9}(c), h_{9,1}(c)$.
Now I consider the minimal model central charge $c = c_{p=5, p'=2} = - 22/5$ and primary $|h_{1,2}\rangle$, where as usual
$$
h_{r,s} \equiv \frac{(pr - p's)^2 - (p - p')^2}{4pp'}\ .
$$

*

*$|h_{1,2}\rangle$-module contains a null $\chi^{(1)}$ at level-$rs = 2$, with conformal weight $h(\chi^{(1)}) = h_{3,3} = h_{1,7} = \frac{ 9 }{ 5 }$, which means the $\chi^{(1)}$-submodule contains nulls at level 7 (and level 9) called $\chi^{(1,1)}$ (and $\chi^{(1,2)}$).

*I want to view $\chi^{(1,1)}$ as a level-9 null of $|h_{1,2}\rangle$-module, but this seems to fail: $h_{1,2}$ is not in the three null solutions in eq. $(*)$.

*However, if I specify $c = -22/5$ before solving the level-9 null equations, I will find the extra solution $h = -22/5$.
So my question is: what is happening as $c \to - 22/5$? Where was this extra null before setting $c=-22/5$?

A: The Kac determinant formula tells you that a Verma module of dimension $h$ has a null vector at level $rs$ if $h=h_{r,s}(c)$. If $c$ is generic, all null vectors are of this type. However, if $c$ is rational and in particular in minimal models, some null vectors are not of this type. A null vector of a null vector is a null vector, but it is not always of this type. You have provided an example of this phenomenon.
In a minimal model, the Kac formula already gives infinitely many null vectors in each representation, since $h_{r+kp',s+kp}=h_{r,s}$ for any $k=1, 2, 3, \dots$. But to get all null vectors, you need to add the null vectors of null vectors.
See also Exercise 2.5 of my review article https://arxiv.org/abs/1406.4290 .

A: Ok it turns out the rough answer is mostly simple.

*

*The additional null was of course hidden among all the level-7 nulls of $\chi^{(1)}$. It contributes to $det M^{(9)}$ inside the factor
$$
(-5 + \sqrt{(1-c)(c-25)} + c + 16 h)^{15} \xrightarrow{c \to -22/5} (h + 1/5)^{15}
$$
where $15 = \mathfrak{p}(9-2)$, the number of descendants of $\chi^{(1)}$ at this level.

*As $c \to -22/5$, one of the descendant becomes primary. The detail behavior of $c \to -cc/5$ of the null equations remain unclear (and probably not important), but I suspect it's similar to what happens to the following set of equations in the limit,
$$
  a x_1 + b x_3 = \alpha, \quad a'x_1 + b'x_3 = \beta, \\
  h x_2 + (c + \frac{ 22 }{ 5 }) x_3 = \gamma \ ,
  \quad
  h x_2 - (c + \frac{ 22 }{ 5 }) x_3 = \gamma\ ,
$$
where at $c = - 22/5$ a solution appears while in general there is no solution.


text:
Q: How to pass a currency formatted string from the controller to the view? I have a formatted string variable to which passing to a ViewData Variable.
My Controller basically looks like this:
if(ModelState.IsValid)
{
    string total = "$2.00";
    ViewData["totalSales"] = total;
    return View();
}

I have an html helper function in my view like this:
<%: Html.Label(ViewData["totalSales"].Tostring()) %>

however the asp.net mvc engine is generating this :
00

I just wanna pass the money value to the view and display it.
It appears that the decimal is breaking the value. However there has got to be a way around this.
Am I making a noob mistake here ?

Well I was able to bypass this by doing this:

<%: ViewData["totalSales"].ToString() %>

But this does not explain why a decimal in a string is causing data loss.
Any ideas ?

A: pass your total variable as a decimal:
decimal total = 2.0;
ViewData["totalSales"] = total;
return View();

then in your view, render the label like this:
<%: Html.Label(string.Format("{0:C2}", ViewData["totalSales"])) %>

A: Use String.Format() with currency
Your mistake is that the framework will automatically escape/transform special characters (such as the ".") when they're turned into HTML attributes. That's by design.
Also, why are you passing a hard coded string via ViewData? Is that computed from your models? You may not be using Label correctly.


text:
Q: GitHub Navigating from a repository to my fork of the repository If I am in one of my organization's repository and I want to navigate to my fork of that repository, the only way I know how to do that is:
click my avatar -> profile -> Repositories -> search for repository
I feel like there HAS to be an easier way.
I thought I was the only one to experience this problem until my whole team expressed the same frustration by a very simple thing on GitHub.
This question is relevant here because it discusses a programming tool.

A: You can just click on Fork (the symbol, not the number), this should appear:

Only 2 clicks in total.


text:
Q: trying to send data from thingworx composer to Postgres database ]4[]5
I created one thing which access my database table name is sensordata from PostgreSQL. Now I have to send data to these table how. How can I do this?

I did the connection part of thingworx composer and PostgreSQL db on local setup.
I am trying to send sensor data from thingworx to PostgreSQL db but i am not able to sent it

A: You must to do two things:
1 Create a service to insert row in postgresql_conn thing;

*

*Select 'SQL (Command)' as script type.

*Put somthing like this into script area
INSERT INTO sensordata
(Temperature, Humidity, Vibration)
VALUES ([[TemperatureField]], [[HumidityField]], [[VibrationField]]);

TemperatureField, HumidityField, VibrationField are input fields of the service.
2  Create  Subscriptions to sensordata thing.

*

*As event set AnyDataChange;

*Put something like this in the script area:
var params = {
    TemperatureField: me.Temperature,
    HumidityField: me.Humidity,
    VibrationField: me.Vibration
};

var result = Things["postgresql_conn"].InsertRecord(params);

Now when data of sensordata change one row is add to the postgress table.
Sorry for my english


text:
Q: how to apply mulpiple popovers backgrpund color I have a working code that displays a lot of features, and when I click on each feature, it'll show a popover, but I'd like to show it in different background colors, ex. there are three popovers displayed and each one with a different background color.
// display popup on click
map.on('click', function(evt) {
  var feature = map.forEachFeatureAtPixel(evt.pixel,
    function(feature) {
      return feature;
    });
  if (feature) {
    var element = document.getElementById(feature.get('name'));
    var popup = new Overlay({
      element: element,
      positioning: 'bottom-center',
      stopEvent: false,
      offset: [0, -15]
    });
    map.addOverlay(popup);

    var coordinates = feature.getGeometry().getCoordinates();
    popup.setPosition(coordinates);
    $(element).popover({
      placement: 'top',
      html: true,
      content: feature.get('name')
    });
    $(element).popover('toggle');
    //$(".popover").css("background", "#C71F1F");
  }
});

it is only using the ".popover", but I'd like to use the ".popover1" and ".popover2" using the JS code.
//CSS
.popover{
   background: #ebd997;
}
.popover1{
   background: #C71F1F;
}
.popover2{
   background: #FFE600;
}

A: I just solved, I created an new  and a new CSS Style, like this
var iDiv = document.createElement("div");
iDiv.id = "mydiv"+index;
document.getElementsByTagName('body')[0].appendChild(iDiv);

CSS
var css = '#' + iDiv.id + ' + .popover {background:#FFFFFF;}';
var head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');

head.appendChild(style);

style.type = 'text/css';
if (style.styleSheet){
// This is required for IE8 and below.
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}


text:
Q: How To Merge Concatenate Two PDF Files In Salesforce I was wondering if there's a possibility to meet this requirement using any PDF tool (maybe Conga) in a Salesforce Org.
I'm making a LWC that must merge or conc a group of PDF files related with a Salesforce record. These documents are stored as attachments to the record and we want to append them one behind the other to create one single pdf that is the joining of the others.
I can do this without problems using an external API called Api2Pdf but the problem is that the documents has very sensitive data and we don't want to share this info sending it to the Api2Pdf external servers to be processed
(Althought they say they comply with a privacy law the client dont want it)
Is there a way to merge this pdf attachments using some other tool like Conga? have you guys done this before? Thanks!
(link to Api2Pdf for Salesforce in github (https://github.com/Api2Pdf/api2pdf.salesforce/))

A: As I understood, you want to merge documents locally (on a client's browser side) to achieve sensitive data rules compliance.
Perhaps you can use any Javascript (ES7, ES5) library that you can include in your LWC code. For example this open-source library:
https://github.com/foliojs/pdfkit
From my experience, most of such libraries respect Locker Service rules, therefore you shouldn't face with any major issues.
Cheers,
Paul


text:
Q: How to read MANIFEST.MF inside WAR application? I would like to read MANIFEST.MF of my WAR application. How can I find its file name?

A:
How can I find its file name?

You already have it. Maybe you meant to find the absolute file location? You can use ServletContext#getRealPath() for this.
String relativeWARPath = "/META-INF/MANIFEST.MF";
String absoluteDiskPath = getServletContext().getRealPath(relativeWARPath);
File file = new File(absoluteDiskPath);
// ...

Or if you want to get it as InputStream directly, use ServletContext#getResourceAsStream().
InputStream input = getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF");
// ...

A: I had the same problem in every application and decided to create a component with a utility class in it: jcabi-manifests. Now it's easy to load any attribute from one of available MANIFEST.MF in classpath:
import com.jcabi.manifests.Manifests;
String value = Manifests.read("My-Version");

Also, check this out: http://www.yegor256.com/2014/07/03/how-to-read-manifest-mf.html

A: I did some researches to find the right solution for me.
Mainly thanks to BalusC but also others I cannot remember now because I went deeply in many sources.
I have a web application running on Weblogic 12c (12.2.1.4) version.
First I had to say maven to add information in MANIFEST.MF, adding the following in plugins section of POM file
 <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.2</version>
    <configuration>
      <archive>
        <manifest>
         <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
          <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
        </manifest>
      </archive>
    </configuration>
  </plugin>

You can find the version of maven plugin looking at the console in the package goal.
Then I've mainly followed the BalusC direction in the post Using special auto start servlet to initialize on startup and share application data
Before registering the class in the servlet context in the contextInitialized method
 @Override public void contextInitialized(ServletContextEvent servletContextEvent)

I've put my business logic to retrieve information from the manifest, like the following
    @Override public void contextInitialized(ServletContextEvent servletContextEvent) {
        logger.info("context initialized - reading MANIFEST.MF infos");
        StringBuilder welcomeStrBuild;
        welcomeStrBuild = new StringBuilder("version");
        try (InputStream inputStream = servletContextEvent.getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF")) {
            Properties prop = new Properties();
            prop.load(inputStream);
            welcomeStrBuild.append(prop.getProperty("Implementation-Version", "n/a"));
        } catch (Exception e) {
            logger.info("Unable to extract info from MANIFEST.MF");
            welcomeStrBuild.append("Unable to extract info from MANIFEST.MF");
        }
        infoProject = welcomeStrBuild.toString();
        servletContextEvent.getServletContext().setAttribute("config", this);
}

You can of course read the content of the manifest using the Java Manifest class, instead of using Properties class.
The main points of the solution are the two:

*

*add the information to the manifest using the maven war goal

*read the information at right moment and from the right WAR, because if you are not using the correct approach you end in reading the manifest from the classloader or other jars

A: There are a few ways to do it, and the chosen answer is only works when you want to read Manifiest files on Servlet/SpringMVC layer or whatever layer you can access to ServletContext.
However, if you want to read a value like "version" even before Servlet starts up, like during logback configuration or something else, you might need to do some old-way classloading or Manifest file manipulation.
I found this github repository(not mine) and it includes 4 different way to read information from Manifest file. If your situation is not accessible to ServletContext, check these out.
https://github.com/khmarbaise/version-examples


text:
Q: How do I run a jar file in multiple threads? I need to run an executable JAR file in multiple threads/cores. The JAR file does not implement Runnable. I've been looking for a way to do that and haven't found one. Is it possible to make a JAR file use multiple threads/cores without having access to the source code?
Currently. if I just run the JAR file normally, it only uses a single core.

A: There is no way to magically make a program (doesn't matter if it's packaged in a Java JAR file or some other way) automatically use multiple cores. The program must have been written to make use of multiple cores - there's no other way.

A: No, you can't. You can run several java processes running the same JAR in different threads, but this might not be what you want.

A: If the jar is an executable jar, then it has a main method (the main class is listed in the manifest of the jar file).  you can invoke this main method in your own Runnable instance.
however, if the classes in this jar make use of static resources without appropriate synchronization, then this strategy won't work.  if this is the case, you could setup a separate ClassLoader per Runnable and run each instance of the jar in its own isolated ClassLoader (you would then need to invoke the main method using reflection).


text:
Q: Where does the Toolbar Metadata live in Visual Studio on the Filesystem My IDE crashes any time I try add a new component to the toolbar.  I've already tried Resetting the toolbar.
Where does the the information about the toolbar exist on the filesystem to see what may be the offending control?

A: Found the location:
C:\users\\AppData\Local\Microsoft\VisualStudio\9.0
The 4 files: toolbox.tbd, toolbox_reset.tbd, toolboxIndex.tbd, toolboxIndex_reset.tbd


text:
Q: List of Base64 images embedded in Thymeleaf will not display I ended up making a List of images received from my database where they are stored as LongBlob. After receiving them, I then create a new list of base64 and encode those values into the Base64 list. The issue is that when I go to insert this into Thymeleaf it doesn't display any images.
User.java
@Entity
public class User {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  private String firstName;

  private String lastName;

  private String username;

  private String email;

  private String phoneNumber;

  @OneToOne
  private Demographic demographic;

  @OneToOne
  private Resume resume;

  @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  @JsonIgnore
  private List<Skills> userSkills;

  public User() {
  }
  ... getters/setters
}

Skills.java
@Entity
public class Skills {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  private String techName;
  private byte[] logo;

  @ManyToOne
  @JoinColumn(name = "user_id")
  private User user   ;

  public Skills() {
  }
  ... getters/setters
}

HomeController
@Controller
@RequestMapping("/")
public class HomeController {

  @Autowired
  private UserService userService;

  @Autowired
  private SkillsService skillsService;

  @RequestMapping("/home")
  public String showHome() {
      return "index";
  }

  @RequestMapping("/portfolio")
  public String showPortfolio() {
      return "portfolio";
  }

  GetMapping(value = "/technology")
public String technologyList(Model theModel) throws IOException {
    User user = userService.findByUsername("wmangram");
    List<Skills> userSkillsList = skillsService.findSkillList("wmangram");

    List<byte[]> logo = skillsService.findLogos();
    List<String> base64List = new ArrayList<>();

    for (int i = 0; i < logo.size(); i++) {
        byte[] encodeBase64 = Base64.encodeBase64(logo.get(i));
        String base64Encoded = new String(encodeBase64, "UTF-8");
        base64List.add(base64Encoded);
    }
    theModel.addAttribute("userSkills", userSkillsList);
    theModel.addAttribute("userImages", base64List);

    /*for (int j = 0; j < base64List.size(); j++) {
        theModel.addAttribute("userImage", base64List.get(j));
        System.out.println("\\\nThis is the base64 called for: " + base64List.get(j));
    }*/
    /*for (int j = 0; j < logo.size(); j++) {
        theModel.addAttribute("logo", logo.get(j));
        System.out.println("\\\nThis is the logo called for: " + logo.get(j));
    }
    theModel.addAttribute("logo", logo);
    */

    return "technology";
}

skills.html

      No Skills Available

A: It should probably look something like this:

Based on your comments, you should have all the tools you need to debug this.  You said this is what when you view the source:

Therefore you know that the Thymeleaf variable wasn't being evaluated.  Also, userImages is an array, so you need to index into it.  You'll have to figure out the correct index though, since you aren't looping over the array I'm not sure how to write that part of the code.


text:
Q: Mono xbuild error CS1548 - key file has incorrect format So I'm trying to get a VS2010 C# project to go cross-platform. First goal is build it in Mono 2.10.5 for Windows.  I have not touched any code yet - I'm starting with xbuild's recent ability to build sln files.  (Incidentally I use Jenkins to trigger builds, not that it matters as I get the same result at the command-line.)
I get "error CS1548: Error during assembly signing. The specified key file `AlphaBeta.pfx' has incorrect format".  There's not much google juice on this error.  Does anyone know what would cause this? Thanks in advance!
Full output below:
C:\Program Files\Jenkins\jobs\AlphaBeta\...\AlphaSolution>"C:\Program Files\Mono-2.10.5\bin\xbuild" AlphaSolution.sln
XBuild Engine Version 2.10.5.0
Mono, Version 2.10.5.0
Copyright (C) Marek Sieradzki 2005-2008, Novell 2008-2011.

Build started 9/20/2011 3:54:14 PM.

C:\Program Files\Jenkins\jobs\AlphaBeta\...\AlphaSolution\AlphaSolution.sln:  warning : Ignoring vcproj 'ZBM'.
C:\Program Files\Jenkins\jobs\AlphaBeta\...\AlphaSolution\AlphaSolution.sln:  warning : Don't know how to handle GlobalSection TestCaseManagementSettings, Ignoring.
C:\Program Files\Jenkins\jobs\AlphaBeta\...\AlphaSolution\AlphaSolution.sln:  warning : Failed to find project d393406d-3397-4907-a536-2a4b77512bc6
Project "C:\Program Files\Jenkins\jobs\AlphaBeta\...\AlphaSolution\AlphaSolution.sln" (default target(s)):
    Target ValidateSolutionConfiguration:
        Building solution configuration "Debug|Mixed Platforms".
    Target Build:
        Project "C:\Program Files\Jenkins\jobs\AlphaBeta\...\AlphaSolution\AlphaCommon\AlphaCommon.csproj" (default target(s)):
            Target PrepareForBuild:
                Configuration: Debug Platform: AnyCPU
            Target GenerateSatelliteAssemblies:
            No input files were specified for target GenerateSatelliteAssemblies, skipping.
            Target CoreCompile:
                Tool C:\PROGRA~1\MONO-2~1.5\bin\dmcs.bat execution started with arguments: /noconfig /debug:full /debug+ /keyfile:AlphaBeta.pfx /optimize- /out:obj\Debug\AlphaCommon.dll AlphaCommon.cs Properties\AssemblyInfo.cs /target:library /define:"DEBUG;TRACE" /reference:C:\PROGRA~1\MONO-2~1.5\lib\mono\xbuild-frameworks\.NETFramework\v4.0\RedistList\..\..\..\..\4.0\System.dll /reference:C:\PROGRA~1\MONO-2~1.5\lib\mono\xbuild-frameworks\.NETFramework\v4.0\RedistList\..\..\..\..\4.0\System.Xml.Linq.dll /reference:C:\PROGRA~1\MONO-2~1.5\lib\mono\xbuild-frameworks\.NETFramework\v4.0\RedistList\..\..\..\..\4.0\System.Data.DataSetExtensions.dll /reference:C:\PROGRA~1\MONO-2~1.5\lib\mono\xbuild-frameworks\.NETFramework\v4.0\RedistList\..\..\..\..\4.0\Microsoft.CSharp.dll /reference:C:\PROGRA~1\MONO-2~1.5\lib\mono\xbuild-frameworks\.NETFramework\v4.0\RedistList\..\..\..\..\4.0\System.Data.dll /reference:C:\PROGRA~1\MONO-2~1.5\lib\mono\xbuild-frameworks\.NETFramework\v4.0\RedistList\..\..\..\..\4.0\System.Xml.dll /reference:C:\PROGRA~1\MONO-2~1.5\lib\mono\xbuild-frameworks\.NETFramework\v4.0\RedistList\..\..\..\..\4.0\System.Core.dll /warn:4
: error CS1548: Error during assembly signing. The specified key file `AlphaBeta.pfx' has incorrect format
            Task "Csc" execution -- FAILED
            Done building target "CoreCompile" in project "C:\Program Files\Jenkins\jobs\AlphaBeta\...\AlphaSolution\AlphaCommon\AlphaCommon.csproj".-- FAILED

A: Mono does not support using PKCS#12 (.pfx) files to store keys used for strongnaming assemblies. This is a known issue and tracked on Xamarin's bugzilla #725.
A workaround is to export your key into a .snk file and use this when building your project.
The answers here provide examples of how to generate an .snk from a .pfx.


text: Q: Screen off to trigger shut down on Android When an Android device's screen turns off, I would like to shut down the device after 6 hours. I have a customized Android OS and I want to make changes to the Android source code to make this happen. Do you know which framework or module has the logic for 'screen off' and 'power off/shut down' in the Android source code? Thanks a lot!


text:
Q: How to interpret OR confidence intervals for interaction or confounding? This is a textbook problem I've been trying to understand I wanted to check if my thinking is correct (unfortunately there is no solution manual) I have a case-control study where I'm looking at exposure and a disease stratified by a confounder.
My ORs and associated CIs are:
Overall Pooled: OR =1.05, 95% CI:(0.65,1.75)
Stratified on the confounder:
With confounder: OR = 2.08, 95% CI: (0.84,3.60)
Without confounder: OR = 2.00, 95% CI:(1.60,2.16)
How would I decide if there is confounding or interaction/effect measure modification?
It looks to me that since the pooled is different from the stratum, which are similar to each other, that would mean there is confounding but no interaction/EMM. Is my thinking correct? How do the confidence intervals affect the interpretation? Since the stratum-specific CIs overlap does that mean they are not significantly different?

A: Generally speaking, you would make the most informed decision based on the variables on hand to see whether the confounding variable falls in the causal pathway of the disease or not. Since your question is to try and verify what the variable could be based on just the Odds Ratios, I found a source that might be useful:
"This is an example of confounding - the stratified results are both on the same side of the crude odds ratio. This is positive confounding because the unstratified estimate is biased away from the null hypothesis." - Source (STAT 507, PSU)

A: The noncollapsibility effect cannot be distinguished from that due to confounding in this case and calls into question the change-in-effect criterion for confounding when using odds ratios. See this paper


text:
Q: How to trigger a stagger function in animejs in react I connected animejs lib to react and call it onScroll with react-visibility-sensor. I faced with the problem that I can't call delay: anime.stagger(1100) inside the object. Not sure that I explained correctly, I am newbie. Here is some code which will provide a more prominent view.
const IntroDiv = styled.div`
    margin-bottom: 3.5em;
    max-width: 440px;
    opacity: 0;
`;

class Intro extends React.Component{

    constructor(props){
        super(props);

        this.state = {
            isVisible: "false"
        }
    }

    anime = (isVisible) => {
        console.log(isVisible)
        if(isVisible){
            anime({
                targets: this.Intro,
                translateY: -30,
                duration: 800,
                easing: 'cubicBezier(.5, .05, .1, .3)',
                opacity: 1,
                delay: anime.stagger(1100)
            });
        } else console.log("kk")
    };

    render(){
        return(
            <VisibilitySensor onChange={this.anime}>
                <IntroDiv ref={Intro => (this.Intro = Intro)}>

{this.props.title}

{this.props.text}

                    {this.props.children}
                </IntroDiv>
            </VisibilitySensor>
        );

    }
}

Intro.propTypes = {
    title: PropTypes.string,
    text: PropTypes.string
}

export default Intro;


text:
Q: Receiving error : ORA-01747 While trying to calculate COUNT(*) of a specific table Hope you're doing well.
I have two tables and as I far as I know for this scenario there is no need for their structures.
When I run this query :
SELECT COUNT(T.*) AS X
FROM table1 T INNER JOIN table2 M
     ON T.col1= M.col2

I receive this error:
ORA-01747:invalid user.table.column, table.column,or column specification

Is there something I'm missing here?? Dose this query have something which is against database rule?
thanks in advance

A: That is not valid syntax.
SQL> select count(t.*) as x from dual t;
select count(t.*) as x from dual t
               *
ERROR at line 1:
ORA-01747: invalid user.table.column, table.column, or column specification

SQL> select count(*) as x from dual t;

         X
----------
         1

SQL>


text:
Q: Master branch disappeared from my local code I have a repo that I cloned a long ago and I use the master that I push to create my branches to then merge with master.
I opened visual studio and now I don't see any branch, not even master and I did not made any changes or delete any branches.
I dont make any changes using bash, just the .net git
Is there a way to get the master branch?

A: In my particular case, for some reason I do not know yet, the .git hidden folder became corrupt. As stated in this question, the first answer fatal: Failed to resolve HEAD as a valid ref
Solve the issue. Pretty much clone the repository again somewhere, copy that .git (cloned), remove the original .git (in the original repository) and put the cloned one instead.

A: First, fall back to command-line in order to ascertain the situation:
cd /path/to/local/repository
git status
git branch -avv

Then, check which toggle is selected in the "History view" of your Visual Studio (local branches, remote tracking branches, or tags).
Getting back to the command line allowed the OP Nickso to see the local .git was no longer coherent, and needed to be restored, as details in Nickso's answer.


text:
Q: string interpolation in Get URI with httparty issue So I was using the splunk rest api to generate the search id thorugh post and then get the search results through a get request.
I am using httpparty, & this is my post and get request as follows:
  def sid
    self.class.post(
      "/services/search/jobs",
      headers: {'Content-Type' => 'application/json'},
      basic_auth: @auth
    ).parsed_response
  end

The generated sid looks like this:

1503402217.608

I make the necessary get request as follows:
 def results(sid)
   self.class.get(
    "/services/search/jobs/#{sid}/results/",
    headers: {'Content-Type' => 'application/json', 'Accept' => 'text/html'},
    basic_auth: @auth
  )

 end

The above request gives a 204 no content.
However if I manually paste the sid in my code and run it, i get results back.

for eg: "/services/search/jobs/1503402217.608/results/"

So my question is how can interpolate the above to get results back.
EDIT: my dyamic get request looks this in the console:
<- "GET /services/search/jobs/1503402217.608/results/ HTTP/1.1\r\nContent-Type: application/json\r\nAccept: text/html\r\nAuthorization: Basic something==\r\nConnection: close\r\nHost: server:8089\r\n\r\n"
-> "HTTP/1.1 204 No Content\r\n"
-> "Date: Tue, 22 Aug 2017 11:43:37 GMT\r\n"
-> "Expires: Thu, 26 Oct 1978 00:00:00 GMT\r\n"
-> "Cache-Control: no-store, no-cache, must-revalidate, max-age=0\r\n"
-> "Content-Length: 0\r\n"
-> "Vary: Cookie, Authorization\r\n"
-> "Connection: Close\r\n"
-> "X-Frame-Options: SAMEORIGIN\r\n"
-> "Server: Splunkd\r\n"
-> "\r\n"

EDIT: Just so you know, this how i am parsing the sid in the first place before sending it as an argument to the GET request:

sid.parsed_response["sid"]


text:
Q: Can't get endAt on videos when calling I'm using GET https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails%2Csnippet&maxResults=50&playlistId=PLFs4vir_WsTwwb2zqmtE2WTEFdc7AQHnc&key={YOUR_API_KEY}
This returns all data, but only videoId in each video contentDetails. Maybe I'm missing something here?

A: YouTube has removed the features that set start and end times to playlist items: here's a product forum post that details this (and indicates an official response from Google account reps):
https://productforums.google.com/forum/#!topic/youtube/Gipu_cCDScI
Since playlists can no longer set start/end times on its items, the API no longer delivers them.

A: Not an answer, but a workaround. You can retrieve a playlist and use videos list with up to 50 videoIds in the URL to retrieve each video duration.


text:
Q: How to follow symlinks in NFS? I have different disks with pictures
/media/drive1/pictures/
/media/drive2/pictures/
/media/drive3/pictures/
/media/drive4/pictures/
# ...

I have a folder called share which has symlinks for every subfolder of each pictures directory of each drive. I merge every subfolder with a script like this:
# I do this for every drive
for item in "/media/drive1/pictures/"*
do
    target=/media/share/pictures/`basename "$item"`
    if [ ! -d "$target" ]; then
        ln -s "$item" "$target"
        chown -h lsc:lsc "$target"
    fi
done

I've been sharing this successfully with Samba for a whlle now.
[global]
# ...
follow symlinks = yes

Since this is a pure private network and the share is READONLY, security isn't a big deal.
### /etc/exports
/media/share *(ro,async)

When I mount my share mount 1.2.3.4:/ foo the symlinks try to follow on the local host.
My question: How can I share a folder that follows symlinks on the host that's sharing the mount?
NOTE: The bind bind solution in /etc/fstab won't work here, since every subfolder of /media/share/ points to different locations/disks.

A: Why can't you make all the symlinks relative?  That would do the trick.
Assuming that on the NFS server (1.2.3.4), you have the following mounted (different physical drives possible)
/media/drive1/pictures/
/media/drive2/pictures/
/media/drive3/pictures/
/media/drive4/pictures/
# ...

In the script change your ln line from
 ln -s "$item" "$target"

to read
 ln -s "../${item#/media/}" "$target"

This would create your symlinks in the format of
../drive1/pictures/...

Since you mention it's a private network and security isn't a concern, you can set the exports to
### /etc/exports
/media *(ro,async)

Then on the client boxes that mount the NFS
mkdir -p foo; mount 1.2.3.4:/media foo

In foo you will now see share, drive1, drive2, drive3, drive4, ...
So in effect you've mounted the whole media directory on your client, and the symlinks are relative so they would work fine.  The amount of change needed is pretty minimal, the ${item#/media/} syntax may or may not be supported by your version of bash, any equivalent would do (you can use sed commands, awk, or anything you're familiar with to chop off the /media/).
The only problem left is unique names, if you have the following folder or file
/media/drive1/pictures/same_name1
/media/drive2/pictures/same_name1

The current code
if [ ! -d "$target" ]; then
    ln -s "$item" "$target"
    chown -h lsc:lsc "$target"
fi

Would skip creating a symlink after the first target is encountered.  So you may have files that are missing symlinks purely because the name is already used in another drive.
You would need to modify your symlink name to append some kind of unique identifier for these cases.
if [ -d "$target" ]; then
    #extract out the "drive1" part from $item and prepend it to target
    target="$(echo item | sed -e 's!/media/\([^/]*\)/pictures.*!\1!g')_${target}"
fi

if [ ! -d "$target" ]; then
    ln -s "$item" "$target"
    chown -h lsc:lsc "$target"
fi

A: This approach will not work with NFS mounted shares. Symbolic links only contain a path to another file or directory on the originating system where they're being shared from. Unless you take care to make the links relative or to duplicate the same directory structures on remote systems as the originator of the share, they simply will not work.
I cannot think of any method that will allow the directory structure as you've described through NFS, and give you the functionality that you're looking for.
You might want to take a look at the advanced features of automounting, specifically this page titled: Setting advanced automount map options.
References

*

*ArchLinux AutoFS Wiki

*AutoFS Project Page

A: You can do a bind type mount, that is better than links in many situations, in fstab file you can put:
/source    /dest    none defaults,bind   0   0

A: Yes, but...
As correctly answered by slm, you could not dereference symlinks by nfs server, but as correctly pointed out by alejandro izquierdo, you could use bind mount to make the job:

*

*Ensure to mount your VFAT or NTFS with option uid=XXX to match correct user (lsc).
mount -o uid=XXX,gid=YYY /dev/sdX1 /media/drive1

*Now you could replace your for item in... loop by something like:
for item in /media/"drive1/pictures"/*
do
    target="/media/share/pictures/$(basename "$item")"
    if [ ! -d "$target" ]; then
        mkdir "$target"
        mount --bind "$item" "$target"
    fi
done

Of course, this have to be done with root privileges! By using sudo or maybe from udev scripts...

*Care to umount the bind (umount "$target") before umounting the real source (/media/driveX) and don't forget to remove the mountpoint (rmdir "$target").
Nota: you could rmdir /media/share/pictures/*, then will see some:
rmdir: failed to remove '/media/share/pictures/drive1/': Device or resource busy

which are not harmfull, then unused empty dirs will be removed.

A: It works with NFS export options 'nohide,crossmnt'

*

*/dev/sdc1 mounted on /shared

*/dev/sdd1 mounted on /shared/disk2

*/etc/exports has the mount option nohide and crossmnt

*Now reload exports with exportfs -ra
Ref: https://linux.die.net/man/5/exports


text:
Q: Why do I SignatureDoesNotMatch error whilst saving thumbnail urls with firebase storage cloud storage triggers? I am using firebase resize extension which, when original picture is uploaded, it resizes it and creates another picture in that folder with renamed version -
user1profile => user1profile_320x320
I wrote a trigger function, that once the resized thumbnail is created, I generate url and update my documents in firestore:
        const isThumbnail = object.name.endsWith("_320x320");

        const signedURLconfig = {
          action: "read" as const,
          expires: "03-09-2491",
        };

        const signedURLArray = await file.getSignedUrl(signedURLconfig);
        const url = signedURLArray[0];

        if (folder == "profilePhotos" && isThumbnail) {
          const userPublicRef = db.collection("usersPublic").doc(userId);
          const usersPrivateRef = db.collection("users").doc(userId);

          batch.set(userPublicRef, { profilePhoto: url }, { merge: true });
          batch.set(usersPrivateRef, { profilePhoto: url }, { merge: true });

          await batch.commit();

Strangely, everything works for few days, but after some time I can't access these thumbnails for my app anymore, even though it shouldn't expire.

*

*What is causing this issue and how can I fix it?

*Why do I have to provide expiration date, I want my pictures to be accessible.

*Why are signed urls are so long compared to the ones that I create from the client with  getDownloadURL()?

A:
What is causing this issue and how can I fix it?

The Signed URLs are expiring. After the expiration date, the object is not accessible via the Signed URL.

Why do I have to provide expiration date, I want my pictures to be
accessible.

Signed URLs expire. The maximum time is 604,800 seconds (7 days).

Why are signed urls are so long compared to the ones that I create
from the client with getDownloadURL()?

Signed URLs have authorization parameters. Those parameters are large data objects.
If you do not want URLs to expired, then you cannot use Signed URLs. In that case, set the access for the Cloud Storage object to public read-only.
Google Cloud Storage Signed URLs
Google Cloud Storage: Overview of Access Control