text:
Q: You are trying to resolve a cross-wired service, but are doing so outside the context of an active (Async Scoped) scope with Simple Injector I'm building a .NET Core console app that uses Simple Injector and SimpleRabbit to pubish messages to RabbitMQ.
I've run into a run time exception when I attempt to get an registered instance from a container.
For guidance, I've been trying to follow the instructions in this link: SimpleInjector integration documentation
The code snippet below outlines what I'm trying to do between using a HostBuilder, configuring and
registering the required services.
Main:
public static async Task Main(string[] args)
{
    var configurationRoot = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .Build();

    // Initialize the SimpleInjector container
    var searchJobStatus = new SearchJobTrackerModel();
    Bootstrap.ConfigureServices(configurationRoot);
    var container = Bootstrap.container;

    var builder = new HostBuilder()
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.AddJsonFile(
                "appsettings.json", optional: true, reloadOnChange: true);
        })
        .ConfigureServices((context, services) =>
        {
            services.AddSimpleInjector(container, options => { });
            services.AddRabbitConfiguration(
                    configurationRoot.GetSection("RabbitConfiguration"))
                .AddSubscriberConfiguration(
                    configurationRoot.GetSection("Subscribers"))
                .AddPublisherServices()
                .AddSubscriberServices()
                .AddSingletonMessageHandler<DiscoverySubscriberService>()
                .AddSingleton<IQueueManagementService, QueueManagementService>()
                .AddSingleton<IHostedService, DiscoveryConsoleService>();
        });

    await builder.RunConsoleAsync();
}

Bootstrap:
public class Bootstrap
{
    public static Container container;

    public static void ConfigureServices(IConfigurationRoot configurationRoot)
    {
        container = new SimpleInjector.Container();
        container.Options.ResolveUnregisteredConcreteTypes = false;
        container.Options.EnableAutoVerification = false;

        RabbitConfiguration rabbitConfiguration = new RabbitConfiguration();
        configurationRoot.GetSection("RabbitConfiguration").Bind(rabbitConfiguration);
        container.ConfigureServices(rabbitConfiguration);
    }
}

public static class ServicesInstaller
{
    public static void ConfigureServices(
        this Container container, RabbitConfiguration rabbitConfiguration)
    {
        container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
        container.Options.ResolveUnregisteredConcreteTypes = false;

        // Rabbit Configuration
        container.RegisterInstance<RabbitConfiguration>(rabbitConfiguration);
        container.RegisterSingleton<IMessagePublisher, MessagePublisher>();
    }
}

Publisher and mananager:
public class MessagePublisher : IMessagePublisher
{
    IPublishService publisher;
    public IMessagePublisher(IPublishService publisher)
    {
        this.publisher = publisher;
    }
}

public class Manager : IManager
{
    public Manager(IMessagePublisher publisher)
    {
    }
}

I attempt to get an IManager instance:
var manager = Container.GetInstance<IManager>();

I get the following runtime exception:

SimpleInjector.ActivationException   HResult=0x80131500 Message=Error resolving the cross-wired IPublishService. You are trying to resolve a cross-wired service, but are doing so outside the context of an active (Async Scoped) scope. To be able to resolve this service the operation must run in the context of such scope. Please see https://simpleinjector.org/scoped for more information about how to manage scopes.

I think the issue is between the .AddPublisherServices() to add publisher services to my service collection and the constructor on the Manager class:
public Manager(IMessagePublisher publisher)

That is far as I've been able to narrow it down.
Is there an error in the way I'm building the container and adding/registering services?
Is AddPublisherServices using a scope that conflicts with the services defined in my container?

A: The exception states:

You are trying to resolve a ... service ... outside the context of an ... Async ... scope.

In other words, wrap the operation in a call to using (AsyncScopedLifestyle.BeginScope(container). For instance:
await using (AsyncScopedLifestyle.BeginScope(container))
{
    var manager = container.GetInstance<IManager>();

    await manager.DoSomethingWithMessages(myMessage);
}

For more information see the documentation.


text:
Q: Hibernate java.lang.NoSuchFieldError: INSTANCE I encounter this error when deploying to Weblogic9.2
����: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [me/irix/spring/datasource.xml]: Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.hibernate.cfg.Configuration]: Constructor threw exception; nested exception is java.lang.NoSuchFieldError: INSTANCE
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1512)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:610)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:410)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
    at weblogic.servlet.internal.EventsManager$FireContextListenerAction.run(EventsManager.java:376)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
    at weblogic.servlet.internal.EventsManager.notifyContextCreatedEvent(EventsManager.java:82)
    at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1620)
    at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:2789)
    at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:889)
    at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:328)
    at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:204)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:26)
    at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:60)
    at weblogic.application.internal.flow.ScopedModuleDriver.start(ScopedModuleDriver.java:200)
    at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:117)
    at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:204)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:26)
    at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:60)
    at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:26)
    at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:635)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:26)
    at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:212)
    at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:154)
    at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.activate(AbstractOperation.java:566)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.activateDeployment(ActivateOperation.java:136)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doCommit(ActivateOperation.java:104)
    at weblogic.deploy.internal.targetserver.operations.StartOperation.doCommit(StartOperation.java:139)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.commit(AbstractOperation.java:320)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentCommit(DeploymentManager.java:815)
    at weblogic.deploy.internal.targetserver.DeploymentManager.activateDeploymentList(DeploymentManager.java:1222)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleCommit(DeploymentManager.java:433)
    at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.commit(DeploymentServiceDispatcher.java:161)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doCommitCallback(DeploymentReceiverCallbackDeliverer.java:181)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$100(DeploymentReceiverCallbackDeliverer.java:12)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$2.run(DeploymentReceiverCallbackDeliverer.java:67)
    at weblogic.work.ServerWorkManagerImpl$WorkAdapterImpl.run(ServerWorkManagerImpl.java:518)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:181)
Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.hibernate.cfg.Configuration]: Constructor threw exception; nested exception is java.lang.NoSuchFieldError: INSTANCE
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:163)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:105)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newConfiguration(LocalSessionFactoryBean.java:821)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:552)
    at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509)
    ... 49 more
Caused by: java.lang.NoSuchFieldError: INSTANCE
    at org.hibernate.type.BasicTypeRegistry.<init>(BasicTypeRegistry.java:94)
    at org.hibernate.type.TypeResolver.<init>(TypeResolver.java:59)
    at org.hibernate.cfg.Configuration.<init>(Configuration.java:250)
    at org.hibernate.cfg.Configuration.<init>(Configuration.java:302)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:501)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
    ... 55 more

I have been searching for hours with no luck. I saw some post indicate it may be cause by conflict of hibernate jars, yet I only put in a hibernate3.jar from hibernate-distribution-3.6.10.Final-dist.zip and with jar inside lib\required. Not sure whether it matters, I'm using spring 3.2.8
Could anyone help pointing out the problem?
==========UPDATE==============
here is the xml envolved in the problem:
  <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource">
        <property name="alias">
        <value>spring</value>
        </property>
        <property name="driver">
        <value>com.mysql.jdbc.Driver</value>
        </property>
        <property name="driverUrl">
        <value>jdbc:mysql://localhost:3306/mytable?useUnicode=true&characterEncoding=UTF-8</value>
        </property>
        <property name="user">
        <value>myusername</value>
        </property>
        <property name="password">
        <value>mypassword</value>
        </property>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="lazy">false</prop>
            <prop key="hibernate.show_sql">false</prop>
            <prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
            <prop key="javax.persistence.validation.mode">none</prop>

            <prop key="connection.useUnicode">true</prop>
            <prop key="hibernate.connection.characterEncoding">GBK</prop>
          <prop key="hibernate.connection.charSet">GBK</prop>
            <prop key="connection.provider_class">org.hibernate.connection.ProxoolConnectionProvider</prop>

            <!--  <prop key="hibernate.current_session_context_class">thread</prop>  -->
        </props>
    </property>

  </bean>

 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
 </bean>

<tx:annotation-driven transaction-manager="transactionManager"/>

I follow @chrylis 's suggestion and see this:

it throws error when execute line 526 mbd.getFactoryBeanName()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove integer from each line with sed I have a list of strings that I want to remove the number and colon from the beginning of every string. How can I do this with sed?
When using:
printf '%s\n' '1:I am a sample line 1: line' '2:schafe' '11:11:11:12:' 'a'"'" | sed 's/^[0-9]\://g'

I would like to end up with:
I am a sample line 1: line
schafe
11:11:12:
a'

however running the command above seems to leave the 11:11:11:12: line untouched. I'd like sed to match any size number if possible.
I am using BSD sed (from macOS) but I also have access to GNU sed if that is necessary.
Thanks

A: Thanks to Beta and potong:
sed 's/^[0-9][0-9]*://'

This will match either one or more numbers before a :.
sed 's/^[0-9]*://' was originally used, however this could also match strings containing a : at the beginning (no number).


text:
Q: Calculate relative change in time by group I am struggeling to calculate the percent difference between the annual net sales for a company, with taken into account NA's.
Here's an sample of the data:
dt <- data.table(lpermno = c(10065, 10065, 10065, 10065, 59328, 61241, 59328, 61241, 59328, 61241, 59328, 61241), fyear = c(2001, 2002, 2003, 2004, 2001, 2001, 2002, 2002, 2003, 2003, 2004, 2004), sale = c(NA, NA, NA, NA, 26539, 3891.754, 26764, 2697.029, 30141, 3519.168, 34209, 5001.435))

lpermno fyear sale
10065   2001    NA
10065   2002    NA
10065   2003    NA
10065   2004    NA
59328   2001    26539.000
59328   2002    26764.000
59328   2003    30141.000
59328   2004    34209.000
61241   2001    3891.754
61241   2002    2697.029
61241   2003    3519.168
61241   2004    5001.435

I'd like to calculate a new variable, called sales_change. This variable should be the percentage change for sale.
[sale_n]/[sale_n-1] for each company.
For the first observation of a company, the sales_change needs to be just 1.
I've read the following posts for guidance, but it didn't work out.

*

*Calculate first difference by group in R

*

*calculate difference not percentage change

*Calculate difference between values by group and matched for time

*

*Get only na's as output after adjusting the code

*R: how to find percent diff between columns and naming accordingly?

*

*This code returns new columns for the different sales periods, as I am working with many years it is not preferable

*Calculate percentage change in an R data frame

*How to calculate percentage change from different rows over different spans

*Calculate relative changes in a time series with respect to a baseline by group. NA if no baseline value was measured

*

*Works with a baseline, and that's not what I am looking for

*Rolling mean (moving average) by group/id with dplyr

*

*Looks like an elegant solution for calculating the mean, however I am looking for the percentage change.

For the example data i gave above, the desired output would be:
output <- data.table(lpermno = c(10065, 10065, 10065, 10065, 59328, 59328, 59328, 59328, 61241, 61241, 61241, 61241), fyear = c(2001, 2002, 2003, 2004, 2001, 2002, 2003, 2004, 2001, 2002, 2003, 2004), sale = c(NA, NA, NA, NA, 3891.754, 2697.029, 3519.168, 5001.435, 26539, 26764, 30141, 34209), output = c(NA, NA, NA, NA, 1, 0.693011, 1.304831, 1.421198, 1, 1.008478, 1.126177, 1.134966))

lpermno fyear sale output
10065   2001    NA  NA
10065   2002    NA  NA
10065   2003    NA  NA
10065   2004    NA  NA
59328   2001    3891.754    1.000000
59328   2002    2697.029    0.693011
59328   2003    3519.168    1.304831
59328   2004    5001.435    1.421198
61241   2001    26539.000   1.000000
61241   2002    26764.000   1.008478
61241   2003    30141.000   1.126177
61241   2004    34209.000   1.134966

I'd appreciate some assistance. Thanks in advance.

A: Using data.table, you could do the following:
dt[, pctchnge := sale / c(sale[1], head(sale, -1)), by="lpermno"][order(lpermno)]

Here, create a new variable with :=, repeat the first month of sales, and drop the final month with tail for the denominator. perform calculations by lpermno. Then sort by lpermno.
this returns
    lpermno fyear      sale  pctchnge
 1:   10065  2001        NA        NA
 2:   10065  2002        NA        NA
 3:   10065  2003        NA        NA
 4:   10065  2004        NA        NA
 5:   59328  2001 26539.000 1.0000000
 6:   59328  2002 26764.000 1.0084781
 7:   59328  2003 30141.000 1.1261770
 8:   59328  2004 34209.000 1.1349657
 9:   61241  2001  3891.754 1.0000000
10:   61241  2002  2697.029 0.6930112
11:   61241  2003  3519.168 1.3048314
12:   61241  2004  5001.435 1.4211981

A: You could use by which applies a function to your data frame split by lpermno.
While splitted, relative change formula is applied onto sales column of every sub data frame which are combined by cbind with the new output column. With if we control for anyNA cases and throw NA since a meaningful mean cannot be calculated. With do.call(rbind) we put the data frame back together.
do.call(rbind, by(dt, dt$lpermno, function(x)
  if (anyNA(x$sale)) return(cbind(x, output=NA))
  else return (cbind(x, output=c(1, 1/x$sale[-length(x$sale)]*c(x$sale[-1]))))))
#     lpermno fyear      sale    output
#  1:   10065  2001        NA        NA
#  2:   10065  2002        NA        NA
#  3:   10065  2003        NA        NA
#  4:   10065  2004        NA        NA
#  5:   59328  2001 26539.000 1.0000000
#  6:   59328  2002 26764.000 1.0084781
#  7:   59328  2003 30141.000 1.1261770
#  8:   59328  2004 34209.000 1.1349657
#  9:   61241  2001  3891.754 1.0000000
# 10:   61241  2002  2697.029 0.6930112
# 11:   61241  2003  3519.168 1.3048314
# 12:   61241  2004  5001.435 1.4211981

Data
dt <- structure(list(lpermno = c(10065, 10065, 10065, 10065, 59328,
61241, 59328, 61241, 59328, 61241, 59328, 61241), fyear = c(2001,
2002, 2003, 2004, 2001, 2001, 2002, 2002, 2003, 2003, 2004, 2004
), sale = c(NA, NA, NA, NA, 26539, 3891.754, 26764, 2697.029,
30141, 3519.168, 34209, 5001.435)), row.names = c(NA, -12L), class = c("data.table",
"data.frame"))


text:
Q: stored procedure doesn't return control to C# code I am experiencing very strange issue: the stored procedure doesn't return even though the data is properly and timely inserted. The most staggering thing about this is that the record time stamp field is always populated within milliseconds so the data seems getting into the tables very fast. But return never happens.
Important part of all this is that it only happens under the load -- individual requests are just fine. Only when DB is stressed enough, this thing starts happening.
Any ideas are welcome because I have very little understanding what can be wrong.
Here is simplified C# part of it:
try
{
    using (var conn = new SqlConnection(connString))
    {
        conn.Open();

        using (var cmd = new SqlCommand(conn, ....)
        {
            cmd.CommandType = StoredProcedure;

            cmd.ExecuteNonQuery();

            // THIS NEVER EXECUTES:
            ReportSuccess();
        }
    }
}
catch (TimeoutException)
{
    // EXCEPTION HERE
}

And the stored procedure:
CREATE PROCEDURE dbo.Blah
BEGIN
    INSERT dbo.MyTable VALUES (...)

    INSERT dbo.MyTable2...

    -- Here is where everything stops.

END

UPDATE: we did out best to correlate timeouts and SQL server activity and it appears non-app user activity was causing locks. The process is designed to allow very quick inserts and very quick reads. However some individuals would execute quite expensive queries without actually using DIRTY READ policy, which was tipping over the fragile hardware load balance. Thanks for all your tips though.

A: Based on the information provided, my best guess is that there is a contingency problem in your stored procedure.
Try using transaction in your stored procedure. If my theory is correct, no record will be inserted.
Check if there are any locks being acquired on MyTable2. If you doing a big select on that table elsewhere, ensure you are using nolock.


text:
Q: Inelastic momentum question: How to calculate velocity before the collision? EDIT: NEVERMIND! MY APOLOGIES, I DID NOT READ THE QUESTION PROPERLY. I DID NOT SEE THAT IT SAID THAT THE GUY WAS STATIONARY.
I was doing a practice physics question and stumbled upon a question where it asked a question that goes like this:

I tried to solve it like this:
m1 = girl v1 = girl
m2 = boy v2 = boy
Therefore I got an equation:
m1v1 + m2v2 = m1&2 x v1&2
I solved for V2 (on the left hand side as the question asked for the girl's velocity before the collision). But the problem was that the question did not give me the velocity of the guy which got me stuck.
I tried to look into it in an energy perspective e.g. using kinetic energy equation to solve for v but no luck. Could someone give me an advice to solve this question?
Note: Please don't give me the answer because I wanna solve it myself using your guys' advice.

A: Are you asking about what the initial velocity of the boyfriend is? If so, it is 0, as the question tells you he is initially stationary.
However, regarding using energy to solve the problem: you stated that the collision is inelastic. What does this mean? Is energy conserved? If you think about the energy in inelastic collisions, I think you'll figure it out yourself :). If you're still stuck, I'll write the answer below.
Since the collision is inelastic, energy isn't conserved (some energy is lost to heat, sound, shape changes, etc.). Therefore, you can't use conservation of energy to solve this problem (since the initial energy doesn't equal the final energy). Momentum is the way to go.
Let me know if you want me to elaborate. Good luck.


text:
Q: Google Maps Rollover Problem in a Flex Website I'm using Google Maps in my Flex site to create a map. I've got polygons overlayed on the map. When the user rolls over a polygon an infowindow opens identifying the area and the fill Alpha of the area is set to 0. On roll-out, the info window is removed and the fill Alpha is returned to the default, 0.2.
The polygons display and the InfoWindow is added and removed correctly. The problem is that the change in fill alpha only occurs on the very last polygon in the list. So for example, if I have polygons A, B, C, and D. If I rollover A, then A's alpha should change. But, instead D's alpha changes. No matter which polygon I rollover, the last polygon's alpha changes. It's weird, because the infoWindows behave correctly on rollover. So, if I rollover polygon A, the correct information for InfoWindow A appears.
Please see the code below:
private function allEncodedPolygons(event:MouseEvent) : void {
                var myPaneManager:IPaneManager = map.getPaneManager();
                var myMapPane:IPane = myPaneManager.createPane();

                if (allHoodsToggle.selected) {

                    map.clearOverlays();
                    mapType.selectedIndex = -1;

                    for each (var neighbNode:XML in detailMapResultData){
                      outlinePolygon = this.createPoly(neighbNode);
                    map.addOverlay(outlinePolygon)};

                    allHoodsToggle.removeEventListener(MouseEvent.CLICK, allEncodedPolygons);

                }
               else {myPaneManager.clearOverlays(); allHoodsToggle.removeEventListener(MouseEvent.CLICK, allEncodedPolygons);

                    }

    }

The function below creates the polygons and has the rollover function:
private var neighbShapes:Polygon;

    private function createPoly(neighbNode:XML):Polygon {
        var optionsDefault:PolygonOptions = new PolygonOptions( { strokeStyle: {thickness: 5, color: 0xFFFF00, alpha: 0.4, pixelHinting: true}, fillStyle: { alpha: 0.2 }} );

        var neighbCenterLat:Number = neighbNode.latitudeCenter.toString();
        var neighbCenterLong:Number = neighbNode.longitudeCenter.toString();
        var neighbCenter:LatLng = new LatLng(neighbCenterLat,neighbCenterLong);
        var optionsHover:PolygonOptions = new PolygonOptions( { fillStyle: { alpha: 0.0 }} );
        var encodedData:EncodedPolylineData = new EncodedPolylineData(neighbNode.encoding.toString(), neighbNode.zoomFactor.toString(), neighbNode.level.toString(), neighbNode.numlevels.toString());
        var encodedList:Array = [encodedData];
        neighbShapes = Polygon.fromEncoded(encodedList, optionsDefault);

        neighbShapes.addEventListener(MapMouseEvent.CLICK, function(event:MapMouseEvent): void {
           map.openInfoWindow(event.latLng, new InfoWindowOptions({content: neighbNode.name.toString(), hasCloseButton:false, hasShadow:true}));
        });

        neighbShapes.addEventListener(MapMouseEvent.ROLL_OVER, function(event:MapMouseEvent): void {
            neighbShapes.setOptions(optionsHover);

            map.openInfoWindow(neighbCenter, new InfoWindowOptions({content: neighbNode.name.toString(), hasCloseButton:false, hasShadow:false}));
        });

        neighbShapes.addEventListener(MapMouseEvent.ROLL_OUT, function(event:MapMouseEvent): void {
            neighbShapes.setOptions(optionsDefault);
        });

         return neighbShapes;
    }

Any suggestions as to why the function that changes the alpha is firing on the last polygon only, even though the InfoWindow appears correctly? If anyone has any ideas, I'd love to hear them.
Thanks.
-Laxmidi

A: Okay, I figured it out. Instead of targetting neighbShapes to set the hover options, I should have used: event.currentTarget.setOptions(optionsHover);
-Laxmidi


text:
Q: Drools 6.0 dynamically load rules at runtime I want to load a drl file at runtime.  The posts I've found including this one work for version 5.0 but I can't figure out how to do it for drools version 6.0.

A: In Drools 6, your rules packages are deployed to Maven. A KieScanner is provided, which you can attach to your KieContainer. This polls your repository at a defined interval to see whether a package has been updated and downloads the latest if that's the case.
A full explanation of how to define a KieScanner (including code samples) is provided in the Drools documentation here:
https://docs.jboss.org/drools/release/latest/drools-docs/html/ch04.html

A: I used info taken from those two docs:

*

*https://docs.jboss.org/drools/release/6.0.1.Final/drools-docs/html_single/#d0e109

*https://github.com/droolsjbpm/drools/blob/master/drools-compiler/src/test/java/org/drools/compiler/CommonTestMethodBase.java
I've came out with this snippet that loads rules defined in the /drl/file/path file into the stateful session you obtain at the last line.
    File path = new File("/drl/file/path");
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newFileResource(path), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
        throw new RuntimeException("Errors: " + kbuilder.getErrors());
    }
    kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

Some methods are deprecated, so, don't expect this solution to be valid in the following releases.
Please, double check the imports, they are all from org.kie, not from drools packages. I admit those imports are too much, but I'm pasting the code from an example I'm trying to develop, so I have more things on my code, sorry for that.
import java.io.File;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieScanner;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.conf.EqualityBehaviorOption;
import org.kie.api.conf.EventProcessingOption;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.conf.ClockTypeOption;
import org.kie.internal.KnowledgeBase;
import org.kie.internal.KnowledgeBaseFactory;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;
import org.kie.internal.runtime.StatefulKnowledgeSession;

Hope it helps.


text:
Q: Can't figure out a good sql query Okay, so i have three tables,
images(ID, name,..),
 tags(ID, name, ..) and
 one with the connections image_tags(imageID, tagID).
Here's my problem, I'm trying to write a query that gets all the images that has 2+ specific tag IDs.
Sounds simple enough or so i thought. I know I can do it with getting all the images that has one tag and then check all of them if they have the other ones but the cost to performance is a bit too high that way.
Would appreciate any input on the matter..

A: try this
SELECT images.ID, COUNT(DISTINCT tags.ID) as counter FROM images
LEFT JOIN image_tags ON (images.ID=image_tags.imageID)
LEFT JOIN tags ON (image_tags.tagID=tags.ID)
GROUP BY images.ID HAVING COUNT (tags.ID) >=2

A: I think the query you want is this:
SELECT images.ID, COUNT(DISTINCT tags.ID) as counter
FROM image_tags it
group by it.imageID
having max(case when it.tagID = 1020 then 1 else 0 end) = 1 and
       max(case when it.tagID = 1016 then 1 else 0 end) = 1

The group by brings together all the tags for a given image.  The having clause makes sure that it has the two tags that you want.  If you want only those two tags, then you can add the clause:
max(case when it.tagID not in (1020, 1016) then 1 else 0 end) = 0

A: Would that work for you?
SELECT * from image_tags i1, image_tags i2
WHERE i1.imageID = i2.imageID
AND i1.tagID != i2.tagID


text:
Q: How to 'git blame' on the remote-side repository? on my server I host my personal git remote-side projects (with gitosis), and I have built a web interface to browse the repositories (something like Github).
On the remote-side, you are not allowed to do a lot of stuff, because a working tree is missing, and this is correct: btw, for a repository explorer, with few commands I can do almost everything.
Except for git blame.
I'm not able to find out how to blame a file without a working tree, within the remote-side repository. Got you some ideas?

A: The following should work even in bare repositories:
git blame <rev> -- <path>

E.g.
git blame master -- README.txt

A:
I'm not able to find where the git docs talk about -- option, by the way this works greatly

Actually, this is necessary because "git blame" is prepared to take an
ancient odd argument order "blame <path> <rev>" in addition to the
usual "blame [<rev>] <path>".
That means, as Git 2.17 (Q2 2018) will explain "git blame HEAD COPYING" in a bare repository failed to run, while "git blame HEAD -- COPYING" run just fine.
But from 2.17 on, you won't need '--' anymore.
See commit 0c668f5 (05 Feb 2018) by Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 0c668f5, 07 Feb 2018)

blame: tighten command line parser
An ancient odd argument order "blame <path> <rev>" in addition to the
  usual "blame [<rev>] <path>" has at least two negative
  ramifications:

*

*In order to tell these two apart, it checks if the last command
  line argument names a path in the working tree, using
  file_exists().
  However, "blame <rev> <path>" is a request to
  explain each and every line in the contents of <path> stored in
  revision <rev> and does not need to have a working tree version
  of the file.  A check with file_exists() is simply wrong.

*To coerce that mistaken file_exists() check to work, the code
  calls setup_work_tree() before doing so, because the path it has
  is relative to the top-level of the project tree.
  However, "blame <rev> <path>" MUST be usable even in a bare repository,
  and there is no reason for letting setup_work_tree() complain
  and die with "This operation must be run in a work tree".
To correct the former, switch to check if the last token is a
  revision (and if so, parse arguments using "blame <path> <rev>"
  rule).
Correct the latter by getting rid of setup_work_tree() and
  file_exists() check--the only case the call to this function matters
  is when we are running "blame <path>" (i.e. no starting revision and
  asking to blame the working tree file at <path>, digging through the
  HEAD revision), but there is a call in setup_scoreboard() just
  before it calls fake_working_tree_commit().

So in short, starting Git 2.17, this will work in a bare repo:
git blame master -- README.txt

And with Git 2.22, the error message "This operation must be run in a work tree" should disappear!
"git blame -- path" in a non-bare repository starts blaming from the working tree, and the same command in a bare repository errors out because there is no working tree by definition.
The command has been taught to instead start blaming from the commit at HEAD,
which is more useful.
See commit a544fb0 (07 Apr 2019) by SZEDER Gábor (szeder).
(Merged by Junio C Hamano -- gitster -- in commit d8620d3, 25 Apr 2019)

blame: default to HEAD in a bare repo when no start commit is given
When 'git blame' is invoked without specifying the commit to start
  blaming from, it starts from the given file's state in the work tree.
  However, when invoked in a bare repository without a start commit,
  then there is no work tree state to start from, and it dies with the
  following error message:
$ git rev-parse --is-bare-repository
true
$ git blame file.c
fatal: this operation must be run in a work tree

This is misleading, because it implies that 'git blame' doesn't work
  in bare repositories at all, but it does, in fact, work just fine when
  it is given a commit to start from.
We could improve the error message, of course, but let's just default to HEAD in a bare repository instead, as most likely that is what the user wanted anyway (if they wanted to start from an other commit, then they would have specified that in the first place).
'git annotate' is just a thin wrapper around 'git blame', so in the
  same situation it printed the same misleading error message, and this
  patch fixes it, too.

Note: if you are using gitweb to see the "blames", as recommended by Jakub Narębski , there is a rather old bug in gitweb, where the incremental blame output in javascript actions mode never worked.
This is fixed with Git 2.24 (Q4 2019).
See commit 52bd3e4 (27 Oct 2019) by Robert Luberda (roblub).
(Merged by Junio C Hamano -- gitster -- in commit 0d6799e, 30 Oct 2019)

gitweb: correctly store previous rev in javascript-actions mode
Signed-off-by: Jonathan Nieder
Signed-off-by: Robert Luberda
Acked-by: Jakub Narębski
Without this change, the setting
$feature{'javascript-actions'}{'default'} = 2;
in gitweb.conf breaks gitweb's blame page: clicking on line numbers displayed in the second column on the page has no effect.
For comparison, with javascript-actions disabled, clicking on line numbers loads the previous version of the line.
Addresses https://bugs.debian.org/741883.


text:
Q: Docker - ValidationError: Invalid options object I am on my way to deploy a phoenix app into DigitalOcean following this tutorial. Got to step 4, but something seems wrong here:
$ sudo docker build -t docker_phx:0.1.0 .
Sending build context to Docker daemon  279.3MB
Step 1/29 : FROM elixir:1.9-alpine as build
 ---> 9b250b1bd36e
Step 2/29 : RUN apk add --update git build-base nodejs npm yarn
 ---> Using cache
 ---> 74461e1b006f
Step 3/29 : RUN mkdir /app
 ---> Using cache
 ---> 3ad300b52050
Step 4/29 : WORKDIR /app
 ---> Using cache
 ---> fdd544f23fe7
Step 5/29 : RUN mix do local.hex --force, local.rebar --force
 ---> Using cache
 ---> d94ebdd7a0b1
Step 6/29 : ENV MIX_ENV=prod
 ---> Using cache
 ---> 35f6c0b2ea69
Step 7/29 : COPY mix.exs mix.lock ./
 ---> Using cache
 ---> 9500ee2d53a1
Step 8/29 : COPY config config
 ---> Using cache
 ---> ef57967197ed
Step 9/29 : RUN mix deps.get --only $MIX_ENV
 ---> Using cache
 ---> d0467cdbc04f
Step 10/29 : RUN mix deps.compile
 ---> Using cache
 ---> 291c3e82edd8
Step 11/29 : COPY assets assets
 ---> 68f637ef212d
Step 12/29 : RUN cd assets && npm install && npm run deploy
 ---> Running in 1259b634962d

up to date, audited 894 packages in 3s

37 packages are looking for funding
  run `npm fund` for details

4 moderate severity vulnerabilities

To address all issues, run:
  npm audit fix

Run `npm audit` for details.

> deploy
> webpack --mode production

Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
 - options[0] misses the property 'patterns'. Should be:
   [non-empty string | object { from, to?, context?, globOptions?, filter?, transformAll?, toType?, force?, priority?, info?, transform?, transformPath?, noErrorOnMissing? }, ...] (should not have fewer than 1 item)
ValidationError: Invalid options object. Copy Plugin has been initialized using an options object that does not match the API schema.
    at validate (/app/assets/node_modules/copy-webpack-plugin/node_modules/schema-utils/dist/validate.js:104:11)
    at new CopyPlugin (/app/assets/node_modules/copy-webpack-plugin/dist/index.js:38:31)
    at module.exports (/app/assets/webpack.config.js:55:7)
    at handleFunction (/app/assets/node_modules/webpack-cli/bin/utils/prepareOptions.js:21:13)
    at prepareOptions (/app/assets/node_modules/webpack-cli/bin/utils/prepareOptions.js:9:5)
    at requireConfig (/app/assets/node_modules/webpack-cli/bin/utils/convert-argv.js:117:14)
    at /app/assets/node_modules/webpack-cli/bin/utils/convert-argv.js:123:17
    at Array.forEach (<anonymous>)
    at module.exports (/app/assets/node_modules/webpack-cli/bin/utils/convert-argv.js:121:15)
    at /app/assets/node_modules/webpack-cli/bin/cli.js:71:45
    at Object.parse (/app/assets/node_modules/yargs/yargs.js:576:18)
    at /app/assets/node_modules/webpack-cli/bin/cli.js:49:8
    at Object.<anonymous> (/app/assets/node_modules/webpack-cli/bin/cli.js:366:3)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:14)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Object.<anonymous> (/app/assets/node_modules/webpack/bin/webpack.js:156:2)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
    at internal/main/run_main_module.js:17:47
The command '/bin/sh -c cd assets && npm install && npm run deploy' returned a non-zero code: 1

I really don't know how to solve this, and searching the error didn't help much. Before this error I had a
Node Sass could not find a binding for your current environment: Linux/musl 64-bit with Node.j

fixed with updating node (node -v -> v.14.4.0) and running npm install in /assets.
To mention my DockerFile:
FROM elixir:1.9-alpine as build

RUN apk add --update git build-base nodejs npm yarn
RUN mkdir /app
WORKDIR /app
RUN mix do local.hex --force, local.rebar --force
ENV MIX_ENV=prod
COPY mix.exs mix.lock ./
COPY config config
RUN mix deps.get --only $MIX_ENV
RUN mix deps.compile
COPY assets assets
RUN cd assets && npm install && npm run deploy
RUN mix phx.digest
COPY priv priv
COPY lib lib
RUN mix compile
RUN mix release
FROM alpine:3.9 AS app
RUN apk add --update bash openssl postgresql-client
EXPOSE 4000
ENV MIX_ENV=prod
RUN mkdir /app
WORKDIR /app
COPY --from=build /app/_build/prod/rel/docker_phx .
COPY entrypoint.sh .
RUN chown -R nobody: /app
USER nobody
ENV HOME=/app
CMD ["bash", "/app/entrypoint.sh"]

Any thoughts would be appreciated,
Best Regards


text:
Q: gRPC Concurrency for Stubs In gRPC I would like some more information on the way the server handles requests.
Are requests executed in parallel? Or does the server spawn a new thread for each request, and execute them in parallel? Is there a way to modify this behavior? I understand that in client-streaming rpc's that message order is guaranteed.

*

*If I send Request A followed by Request B to the same RPC, is it guaranteed that A will be executed first before B begins processing? Or are they each their own thread and executed in parallel with no guarantee that A finishes before B.

Ideally I would like to send a request to the server, the server acknowledges receipt of the request, and then the request is added to a queue to be processed sequentially, and returns a response once it's been processed. An approach I was exploring is to use an external task queue (like RabbitMQ) to queue the work done by the service but I want to know if there is a better approach.
Also -- on a somewhat related note -- does gRPC have a native retry counter mechanism? I have a particularly error-prone RPC that may have to retry up to 3 times (with an arbitrary delay between retries) before it is successful. This is something that could be implemented with RabbitMQ as well.

A: grpc-java passes RPCs to the service using the Executor provided by ServerBuilder.executor(Executor), or a cached thread pool if no executor is provided.
There is no ordering between simultaneous RPCs. RPCs can arrive in any order.
You could use a server-streaming RPC to allow the server to respond twice, once for acknowledgement and once for completion. You can use a oneof in the response message to allow sending the two different responses.
grpc-java as experimental retry support. gRFC A6 describes the support. The configuration is delivered to the client via service config. Retries are disabled by default, so overall you would want something like channelBuilder.defaultServiceConfig(serviceConfig).enableRetry(). You can also reference the hedging example which is very similar to retries.


text:
Q: Springer Journal template - override bibliography style Update: question is answered in the comment. Please close the question.
I am preparing a journal article for Springer who asked me to use a template like this: https://www.overleaf.com/latex/templates/a-general-template-file-for-the-latex-package-svjour3-for-springer-journals/pbbwqhxxvtbp
I have imported it and created a project that is publicly available here: https://www.overleaf.com/read/tzjmmnpddkwx
However, this template has a flaw with the bibliography format and the edtiorial office is aware of that. They told me that they are 'working on it' but I am not satisfied with waiting for an answer. After all the problem seems to have existed for a while. So I am asking for help here.
The problem seems to happen whenever I want to use external bibliography file and use an existing style file to format them. If you use \bibitem to add each reference entry and cite them, it looks ok, such as lines 173-175:
\bibitem{RefJ}
% Format for Journal Reference
Author, Article title, Journal, Volume, page numbers (year)

But when I use the following command to import references, the code compiles but the format of the references and citation is very messy (lines 181 - 183)
\bibliographystyle{spbasic}      % basic style, author-year citations
%\bibliographystyle{lrec2016}
\bibliography{lre2021}

And this is what the resulting citation and bibliography looks like:

Especially when the author name list is long, it looks extremely ugly. The format also appears different from the official journal such as https://link.springer.com/article/10.1007/s10579-020-09488-3. As you can see from my code above, I also tried to import a different biliography style file (lrec2016), but that does not change anything at all.
Please can I get some tips on how to fix this?
Thanks


text:
Q: git fatal: multiple stage entries for merged file Git throws an error:
fatal: multiple stage entries for merged file

I've been on the side (Getting a fatal error in git for multiple stage entries) and read the workaround:
cd /patH/to/second/cloned/repo
git --work-tree=/path/to/first/repo add .

Now, the changes can be queried via status, but after that what i have to do now? When I use git add, then everything back to last version. All changes are gone. The changes were removed and my new repo has the old status again. How can i put all change to the new repository?
I use git version 2.2.0 on OS X 10.10.

A: I resolved this problem:
In your terminal, type this:
rm .git/index (press enter key)
git add -A (press enter key)
git commit -m "your commit instruction"


text:
Q: How to find a path between two points connected by lines I try to get this code developed for a potential project at work and I think Dijkstra can help but no idea how to get started.[![enter image description here][1]][1]
I have a list of Line objects called myList and each line has EndPoint1 and EndPoint2 as Point2Dcordinates (x,y) and Name as string. So the list has L1, L2, L3, L4, L5, L6, L7, and L8 as shown in the example image. Points A, B, C, D, and E are points of these lines and they are always not connected points between two lines.
I would like to write a method that gives me a list of the lines (or names of the lines) that connected two points for example:
List<string> FindPath(Point2D P1, Point2D P2): (A, E): L1, L3, L6, L7, L8
List<string> FindPath(Point2D P1, Point2D P2): (B, D): L2, L3, L5

Edit:
I would like to find all possible paths, although 99.9% of the time there is only 1 path possible.

A: I am assuming you need to find the shortest path from one point to another. Hence you need to do a BFS *).
First convert the points into a graph. The graph could be of the format
// The key is the point and the it contains the list of all
// the neighbours
Map<Point2D, List<Point2D>> graph = new HashMap<>();

Then use a Queue and a visited matrix to keep track of the visited points. When looping through the Points make sure you add them to an answer list.
For more details on BFS look here: https://www.geeksforgeeks.org/print-paths-given-source-destination-using-bfs/

*) Breadth First Search Algorithm

A: You are talking about a data structure called a graph, a collection of nodes (points), connected by edges (line segments).
Graphs comes in several flavours. They can be directed or undirected, and they can by cyclic, or acyclic.
Directed graphs have one-way edges: the edge a→b can only be used to travel from a to b, it can't be used to get from b to a. Undirected graphs, on the other hand, have 2-way edges: as long as two nodes are connected, you can get from either one to the other.
Cyclic graphs allow cycles, where traversing the graph can return you to a node you have already visited (a → b → c → a is a cycle); acyclic graphs do not allow such cycles. If your graph is cyclic, when you traverse it, you'll need to track what nodes you've visited, so you can detect and deal with cycles. If you don't you'll wind up in an endless loop.
In addition, both nodes and edges may carry additional information, such as "cost", making them a weighted graph. Google's and Apple's maps are modeled as such weighted graphs. Each intersection is a node, and each street segment between intersections is an edge. The additional information (weigths) carried by edges are information such as average speed, starting/ending addresses, etc.
If you need to find the shortest path between two nodes in your graph, you may need a weighted graph (where the edges carry a distance. Or not: perhaps "shortest path" is defined as the least number of intermediate nodes between A and B.
So, you need the correct model:

*

*a set of nodes, and

*a set of edges, defined by the 2 nodes it connects.

One can (and it is sometimes useful to dispense with the set of nodes completely, and define the graph solely in terms of its edges:
Once you have that, finding a path from any two points in the graph is actually pretty easy. The algorithm is this:

*

*You can get from node A to node B if an edge AB exists. Otherwise...

*You can get from node A to node B if

*

*an edge AX exists, and

*you have not yet visited node X, and

*you can [recursively] get from node X to node B.

That's about all there is to it.

A: You can solve this by treating it as a graph. Each x is a vertex, and your lines are the edges. Then to find the path between P1 and P2, run BFS from P1.


text:
Q: How to display the text cursor/caret when a textbox is focused in wpf? To be clear: My TextBox is already focused when my SignupWindow loads. My problem here is that the text cursor/caret doesn't show up unless I click my textbox (I think this will be a UI issue).

I already focus my TextBox at the Window level:
<Window x:Name="this"
        x:Class="Project.MVVM.Views.Windows.SignupWindow"
        <!-- some namespaces and properties here-->
        FocusManager.FocusedElement="{Binding ElementName=UsernameTextBox}">

My TextBox:
<TextBox x:Name="UsernameTextBox"
            Grid.Row="2"
            Width="303"
            Height="38"
            Text="{Binding Path=CurrentAccount.Username}"
            Style="{StaticResource TextBoxTheme}" />

This is what it looks like when the page loads:

The image above, doesn't show the text cursor/caret. I know that my TextBox is Focused because I can type in it:

The problem here is that, the text cursor/caret only shows when I click on the TextBox:

Here is how I style my textbox (if in case this is relevant to the issue):
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="{x:Type TextBox}"
           x:Key="TextBoxTheme">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Border CornerRadius="12"
                            Background="#2E3135"
                            Width="{TemplateBinding Width}"
                            Height="{TemplateBinding Height}">
                        <TextBox Text="{Binding Path=Text,
                                                RelativeSource={RelativeSource Mode=TemplatedParent},
                                                UpdateSourceTrigger=PropertyChanged,
                                                Mode=TwoWay}"
                                 BorderThickness="0"
                                 VerticalContentAlignment="Center"
                                 Padding="20,0,20,0"
                                 Background="Transparent"
                                 Foreground="#B8BDC1"
                                 CaretBrush="#B8BDC1" />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

A: You defined TextBox inside TextBox and I guess you expected the inner TextBox to be focused when the window is shown but actually, the outer TextBox is focused.
I think nesting TextBox is not impossible but the source of trouble. Why don't you define a Style which is orthodox but has the same appearance?
<Style x:Key="TextBoxTheme" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="Foreground" Value="#B8BDC1"/>
    <Setter Property="CaretBrush" Value="#B8BDC1"/>
    <Setter Property="Padding" Value="20,0,20,0"/>
    <Setter Property="VerticalContentAlignment" Value="Center"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBox}">
                <Border CornerRadius="12"
                        Background="#2E3135">
                    <ScrollViewer x:Name="PART_ContentHost"
                                  Focusable="false"
                                  HorizontalScrollBarVisibility="Hidden"
                                  VerticalScrollBarVisibility="Hidden"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

A: Try adding a c# code (tell me if you need the exact code) to these properties in the triggers / events:
image


text:
Q: Find JToken if value matches with a given pattern I am trying to find JToken in JArray where  any JToken Value matched with __ .
the JArray is something like this , its easier if Key is known i.e. if give text as key I can find all JToken , but if I try to solve by value where key is unknown  . Not able to fit that piece of code
"annotations": [
    {
      "align": "right",
      "axref": "x",
      "ayref": "y2",
      "font": {
        "size": 12,
        "family": "Arial,Helvetica,sans-serif"
      },
      "showarrow": false,
      "text": "D16-__m__0",
      "x": 1,
      "xanchor": "right",
      "xref": "paper",
      "y": 16,
      "yanchor": "top",
      "yref": "y2"
    },
    {
      "showarrow": false,
      "font": {
        "size": 12,
        "family": "Arial,Helvetica,sans-serif"
      },
      "text": "Something",
      "textangle": -90,
      "x": "__gh__",
      "xanchor": "right",
      "y": 0.5,
      "yanchor": "middle",
      "yref": "paper"
    }
  ]

I tried something like this but Value kind i am not sure how do .
destination["annotations"] .Children<JObject>().Where(x => x?["text"] != null && x["text"].Value<string>().Contains($"__{somevalue}__"))

but this gives error
destination["annotations"].Children().Where(x => x.Value<string>().Contains($"__{somevalue}__")))

A: You can use Descendants() method here, get all properties and filter them by checking __ string in value
var json = JObject.Parse(jsonString);

var result = json.Descendants().OfType<JProperty>().Where(p =>
    p.Value.Type == JTokenType.String && p.Value.Value<string>().Contains("__"));


text:
Q: "java.sql.SQLException: After end of result set" error Following is the code having error :

java.sql.SQLException: After end of result set

Please help.
import java.sql.*;
import java.util.ArrayList;

public class ExtractCallInfo1 {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost?autoReconnect=true&useSSL=false";
static final String USER = "root";
static final String PASS = "root";
public static boolean checkDBExists(String dbName){

    try{
        Class.forName(JDBC_DRIVER); //Register JDBC Driver

        //System.out.println("Creating a connection...");
        Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); //Open a connection

        ResultSet resultSet = conn.getMetaData().getCatalogs();

        while (resultSet.next()) {

          String databaseName = resultSet.getString(1);
            if(databaseName.equals(dbName)){
                return true;
            }
        }
        resultSet.close();

    }
    catch(Exception e){
        e.printStackTrace();
    }

    return false;
}

public static boolean checkTABLEExists(String DB_NAME, String TABLE_NAME){
    try{
        Class.forName(JDBC_DRIVER);
        if(!checkDBExists(DB_NAME)){
            System.out.println("Database "+DB_NAME+" doesn't exist");
            return false;
        }
        System.out.println("Creating a connection...");
        Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
        Statement stmt = conn.createStatement();
        String sql = "USE "+DB_NAME;
        stmt.executeUpdate(sql);
        DatabaseMetaData dbm = conn.getMetaData();
        ResultSet tables = dbm.getTables(null, null,TABLE_NAME, null);
        if (tables.next()) {
            return true;
        }
        else {
            return false;
        }

    }
    catch(Exception e){
        e.printStackTrace();
    }
    return false;
}
public static void main(String[] args){
    try{
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
        Statement stmt = conn.createStatement();
        String DB_NAME = "SIP";
        String PACKET_TABLE_NAME = "PACKETDATABASE";
        String USERS_TABLE_NAME = "USERS";
        String COMPLETE_TABLE_NAME = "COMPLETECALLS";
        String INCOMPLETE_TABLE_NAME = "INCOMPLETECALLS";
        String CALLERAVERAGE_TABLE_NAME = "CALLERAVERAGE";
        String CALLERFREQUENCY_TABLE_NAME = "CALLERFREQUENCY";
        String CALLERCALLEEAVERAGE_TABLE_NAME = "CALLERCALLEEAVERAGE";
        String CALLERCALLEEFREQUENCY_TABLE_NAME = "CALLERCALLEEFREQUENCY";
        String CALLERTOTALDURATION_TABLE_NAME = "CALLERTOTALDURATION";
        String CALLERBETA_TABLE_NAME = "CALLERBETA";
        String CALLERINCOMPLETEFREQUENCY_TABLE_NAME = "CALLERINCOMPLETEFREQUENCY";
        String CALLERGAMMA_TABLE_NAME = "CALLERGAMMA";
        String CALLERALPHA_TABLE_NAME = "CALLERALPHA";
        String CALLEEFREQUENCY_TABLE_NAME = "CALLEEFREQUENCY";
        String CALLERRHO_TABLE_NAME = "CALLERRHO";
        String CALLERAVERAGECLASSIFICATION_TABLE_NAME = "CALLERAVERAGECLASSIFICATION";

        if(!checkDBExists(DB_NAME)){
            System.out.println("Database "+DB_NAME+" doesn't exist");
            return ;
        }

        String sql = "USE " +DB_NAME;
        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS "+USERS_TABLE_NAME;
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE "+USERS_TABLE_NAME+" "+
                "SELECT CallerName AS User from "+PACKET_TABLE_NAME+" "+
                "UNION "+
                "SELECT CalleeName AS User from "+PACKET_TABLE_NAME;
        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS "+COMPLETE_TABLE_NAME;
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE "+COMPLETE_TABLE_NAME+" "+
                "(CallId VARCHAR(255) NOT NULL PRIMARY KEY," +
                "CallerName VARCHAR(255) NOT NULL," +
                "CallerIp VARCHAR(255) NOT NULL," +
                "CalleeName VARCHAR(255) NOT NULL," +
                "CalleeIp VARCHAR(255) NOT NULL," +
                "CallDuration DOUBLE NOT NULL)";
        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS "+INCOMPLETE_TABLE_NAME;
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE "+INCOMPLETE_TABLE_NAME+" "+
                "(CallId VARCHAR(255) NOT NULL PRIMARY KEY," +
                "CallerName VARCHAR(255) NOT NULL," +
                "CallerIp VARCHAR(255) NOT NULL," +
                "CalleeName VARCHAR(255) NOT NULL," +
                "CalleeIp VARCHAR(255) NOT NULL," +
                "CallDuration DOUBLE)";
        stmt.executeUpdate(sql);

        sql = "SELECT DISTINCT CallId from "+ PACKET_TABLE_NAME;
        ArrayList<String> uniqueCallIds = new ArrayList<String>();
        ResultSet result = stmt.executeQuery(sql);
        while(result.next()){
            uniqueCallIds.add(result.getString("CallId"));
        }
        for(int i = 0;i < uniqueCallIds.size();i++){
            String cur_id = uniqueCallIds.get(i);
            sql = "SELECT * from "+PACKET_TABLE_NAME+" "+
            "where Method = 'INVITE' and CallId = '"+cur_id+"'";
            Statement stmt1 = conn.createStatement();
            Statement stmt2 = conn.createStatement();
            ResultSet result_one = stmt1.executeQuery(sql);
            sql = "SELECT * from "+PACKET_TABLE_NAME+" "+
            "where Method = 'BYE' and CallId = '"+cur_id+"'";
            ResultSet result_two = stmt2.executeQuery(sql);
            if(!result_two.next()){
                result_one.next();
                sql = "INSERT INTO "+INCOMPLETE_TABLE_NAME+
                        " values('"+result_one.getString("CallId")+"','"+
                        result_one.getString("CallerName")+"','"+
                        result_one.getString("CallerIp")+"','"+
                        result_one.getString("CalleeName")+"','"+
                        result_one.getString("CalleeIp")+"',"+
                        "NULL"+")";
                stmt.executeUpdate(sql);
            }
            else{
                long call_start = Long.MAX_VALUE;
                while(result_one.next()){
                    String time = result_one.getString("TimeOfArrival");
                    long cur = Long.parseLong(time);
                    if(cur < call_start){
                        call_start = cur;
                    }
                }
                result_two.next();
                long call_end = Long.parseLong(result_two.getString("TimeOfArrival"));
                long dura = (call_end - call_start);
                double duration = dura/1000.0;
                sql = "INSERT INTO "+ COMPLETE_TABLE_NAME +
                        " values('"+result_two.getString("CallId")+"','"+
                        result_two.getString("CalleeName")+"','"+
                        result_two.getString("CalleeIp")+"','"+
                        result_two.getString("CallerName")+"','"+
                        result_two.getString("CallerIp")+"',"+
                        duration+")";
                stmt.executeUpdate(sql);
            }

        }

        sql = "DROP TABLE IF EXISTS "+CALLERAVERAGE_TABLE_NAME;
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE "+CALLERAVERAGE_TABLE_NAME+" "+
                "SELECT CallerName, AVG(CallDuration) AS Average "+
                "from "+COMPLETE_TABLE_NAME+" "+
                "GROUP BY CallerName";
        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS "+CALLERAVERAGECLASSIFICATION_TABLE_NAME;
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE "+CALLERAVERAGECLASSIFICATION_TABLE_NAME+"(CallerName VARCHAR(255), Average DOUBLE, GroupId VARCHAR(255))";
        stmt.executeUpdate(sql);

        sql = "SELECT * from "+CALLERAVERAGE_TABLE_NAME;
        Statement new_stmt = conn.createStatement();
        ResultSet res = new_stmt.executeQuery(sql);

        while(res.next()){
            String Callername = res.getString("CallerName");
            Double Average = res.getDouble("Average");
            String GroupId = "";
            if(Average <= 60.0){
                GroupId = "A";
            }
            else if(Average > 60.0 && Average <= 5*60.0){
                GroupId = "B";
            }
            else if(Average > 5*60.0 && Average <= 10*60.0){
                GroupId = "C";
            }
            else if(Average > 10*60.0){
                GroupId = "D";
            }
            sql = "INSERT INTO "+CALLERAVERAGECLASSIFICATION_TABLE_NAME+
                    " values('"+Callername+"','"+
                    Average+"','"+
                    GroupId+"'"+")";
            stmt.executeUpdate(sql);
        }

        sql = "DROP TABLE IF EXISTS "+CALLERFREQUENCY_TABLE_NAME;
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE "+CALLERFREQUENCY_TABLE_NAME+" "+
                "SELECT CallerName, COUNT(CallId) AS Frequency "+
                "from "+COMPLETE_TABLE_NAME+" "+
                "GROUP BY CallerName";
        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS "+CALLERCALLEEAVERAGE_TABLE_NAME;
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE "+CALLERCALLEEAVERAGE_TABLE_NAME+" "+
                "SELECT CallerName, CalleeName, AVG(CallDuration) "+
                "from "+COMPLETE_TABLE_NAME+" "+
                "GROUP BY CallerName, CalleeName";
        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS "+CALLERCALLEEFREQUENCY_TABLE_NAME;
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE "+CALLERCALLEEFREQUENCY_TABLE_NAME+" "+
                "SELECT  CallerName,CalleeName, COUNT(CallId)  AS Frequency "+
                "from "+COMPLETE_TABLE_NAME+" "+
                "GROUP BY CallerName, CalleeName";
        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS "+CALLERTOTALDURATION_TABLE_NAME;
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE "+CALLERTOTALDURATION_TABLE_NAME+" "+
                "SELECT CallerName, SUM(CallDuration) "+
                "from "+COMPLETE_TABLE_NAME+" "+
                "GROUP BY CallerName";
        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS "+CALLERBETA_TABLE_NAME;
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE "+CALLERBETA_TABLE_NAME+" "+
                "SELECT CallerName, SUM(CallDuration)/86400.0 as Beta "+
                "from "+COMPLETE_TABLE_NAME+" "+
                "GROUP BY CallerName";
        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS "+CALLERINCOMPLETEFREQUENCY_TABLE_NAME;
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE "+CALLERINCOMPLETEFREQUENCY_TABLE_NAME+" "+
                "SELECT ALL CallerName, COUNT(CallId)  AS Frequency "+
                "from "+INCOMPLETE_TABLE_NAME+" "+
                "GROUP BY CallerName";
        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS "+CALLERGAMMA_TABLE_NAME;
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE "+CALLERGAMMA_TABLE_NAME+" "+
                "SELECT CallerName, COUNT(CallerIp) as Gamma "+
                "from "+COMPLETE_TABLE_NAME+" "+
                "GROUP BY CallerName";

        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS TEMP";
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE TEMP SELECT "+CALLERFREQUENCY_TABLE_NAME+".CallerName AS P, "+CALLERFREQUENCY_TABLE_NAME+
                ".Frequency as Q, "+CALLERINCOMPLETEFREQUENCY_TABLE_NAME+
                ".CallerName as R, "+
                CALLERINCOMPLETEFREQUENCY_TABLE_NAME+
                ".Frequency AS S FROM  "+
                CALLERFREQUENCY_TABLE_NAME+" INNER JOIN "+CALLERINCOMPLETEFREQUENCY_TABLE_NAME+
                " ON "+CALLERFREQUENCY_TABLE_NAME+".CallerName = "+CALLERINCOMPLETEFREQUENCY_TABLE_NAME+".CallerName";

        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS "+CALLERALPHA_TABLE_NAME;
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE "+CALLERALPHA_TABLE_NAME+" "+
              "SELECT P as CallerName, Q/(Q+S) as Alpha FROM TEMP";
        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS TEMP";
        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS "+CALLEEFREQUENCY_TABLE_NAME;
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE "+CALLEEFREQUENCY_TABLE_NAME+" "+
                "SELECT CalleeName, COUNT(CallId) AS Frequency "+
                "from "+COMPLETE_TABLE_NAME+" "+
                "GROUP BY CalleeName";
        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS TEMP";
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE TEMP SELECT "+CALLERFREQUENCY_TABLE_NAME+".CallerName AS P, "+CALLERFREQUENCY_TABLE_NAME+
                ".Frequency as Q, "+CALLEEFREQUENCY_TABLE_NAME+
                ".CalleeName as R, "+
                CALLEEFREQUENCY_TABLE_NAME+
                ".Frequency AS S FROM  "+
                CALLERFREQUENCY_TABLE_NAME+" INNER JOIN "+CALLEEFREQUENCY_TABLE_NAME+
                " ON "+CALLERFREQUENCY_TABLE_NAME+".CallerName = "+CALLEEFREQUENCY_TABLE_NAME+".CalleeName";

        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS "+CALLERRHO_TABLE_NAME;
        stmt.executeUpdate(sql);

        sql = "CREATE TABLE "+CALLERRHO_TABLE_NAME+" "+
              "SELECT P as UserName, Q/S as Rho FROM TEMP";
        stmt.executeUpdate(sql);

        sql = "DROP TABLE IF EXISTS TEMP";
        stmt.executeUpdate(sql);

        /*
        ArrayList<String> users = new ArrayList<String>();
        sql = "SELEECT User from "+USERS_TABLE_NAME;
        Statement new_stmt = conn.createStatement();
        ResultSet user_list = new_stmt.executeQuery(sql);
        while(user_list.next()){
            users.add(user_list.getString("User"));
        }
        */

        stmt.close();
        conn.close();
        System.out.println("Finished");
    }
    catch(Exception e){
        e.printStackTrace();
    }
    return ;
}
}

A: In this piece of code you are taking for granted than result_one is returning something and maybe that is not true.
        ResultSet result_one = stmt1.executeQuery(sql);
        sql = "SELECT * from "+PACKET_TABLE_NAME+" "+
        "where Method = 'BYE' and CallId = '"+cur_id+"'";
        ResultSet result_two = stmt2.executeQuery(sql);
        if(!result_two.next()){

            //If this return false
            result_one.next();
            sql = "INSERT INTO "+INCOMPLETE_TABLE_NAME+

                    //this is going to fail
                    " values('"+result_one.getString("CallId")+"','"+
                    result_one.getString("CallerName")+"','"+
                    result_one.getString("CallerIp")+"','"+
                    result_one.getString("CalleeName")+"','"+
                    result_one.getString("CalleeIp")+"',"+
                    "NULL"+")";
            stmt.executeUpdate(sql);
        }

A: I think the problem here is that ResultSet next() method does.
Remember, it shifts the cursor to the next row of the result set from the database and returns true if there is any row, otherwise false.
Your code looks as if it is not expecting the shift of the cursor to the next row.
For example :
if(!result_two.next()){
   -- Some code
} else {
  -- Some code
  result_two.next(); -- Whoops!
}

Also, you are assuming a relationship between result_one and result_two. Just because result_two does not return anything does not necessarily mean that result_one will!


text:
Q: Sitecore rich text editor dialog, page scrolls to top It appears that the default behavior for the rich text editor dialog in Page Editor is to scroll the entire page back to the top. This creates bad UX on long pages, since after you're done editing, you have to scroll back down the page and figure out where the text is that you edited.
Anyone know how to make the page stay scrolled to where it was?

A: I am not sure if it is related, since I am not able to reproduce your problem, but it reminds me of a bug in the Sitecore client that showed up in Internet Explorer and Firefox versions, where the content tree pane would do the same (scroll up after interaction). Please take a look at  this StackOverflow question for a possible solution.
Furthermore I want to give you the advice to build up pages in Sitecore using small building blocks (multiple hierarchical placeholders with small renderings). Only then you would be able to leverage the full potential of the system, regarding page editing features and personalization. Also, only then a content editor can alter the presentation in the Experience Editor (Page Editor for older versions). Putting long pages of HTML-code in a single rich text editor field isn't recommended.

A: I fixed it changing the positioning of the jqueryModalDialogsFrame from absolut to fixed:
#jqueryModalDialogsFrame{
    position:fixed !important;
    top:0px !important;
    left:0px !important;
}


text:
Q: Stop submit operation I am trying to stop the submit operation when username field is empty, and display some warning in div with id "err_msg"

Register

      <form role="form" method="post">

          <input type="text" name="nick" placeholder="Nick" class="form-control" style="width: 250px;">
          <input type="text" name="name" placeholder="Imię" class="form-control" style="width: 250px;">
          <input type="text" name="surname" placeholder="Nazwisko" class="form-control" style="width: 250px;">
          <input type="text" name="email" placeholder="Email" class="form-control" style="width: 250px;">
          <input type="text" name="phone" placeholder="Telefon" class="form-control" style="width: 250px;">
          <input type="text" name="password" placeholder="Hasło" class="form-control" style="width: 250px;">
          <input type="text" name="repassword" placeholder="Powtórz hasło" class="form-control" style="width: 250px;">

        <button type="submit" name='Proceed' value='register' class="btn btn-success">Zarejestruj</button>
      </form>

The problem is that submitting a form refreshes a page, and reset every element to it's default value
Should I handle every field with JS and then use a jQuery to post a data? I don't like possible overkill solutions

A: Hi there html form attribute onsubmit to validation using java-script before form get submitted. Please go through following example to resolve your issue.
<!DOCTYPE html>

<form name="myForm" action="demo_form.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

This is to do any stuff you want to do before form submission. But you could use html5 require attribute too.

A:

<form role="form" name="myForm" method="post" onsubmit="return validate()">

      <input type="text" name="nick" placeholder="Nick" class="form-control" style="width: 250px;">
      <input type="text" name="name" placeholder="Imię" class="form-control" style="width: 250px;">
      <input type="text" name="surname" placeholder="Nazwisko" class="form-control" style="width: 250px;">
      <input type="text" name="email" placeholder="Email" class="form-control" style="width: 250px;">
      <input type="text" name="phone" placeholder="Telefon" class="form-control" style="width: 250px;">
      <input type="text" name="password" placeholder="Hasło" class="form-control" style="width: 250px;">
      <input type="text" name="repassword" placeholder="Powtórz hasło" class="form-control" style="width: 250px;">

    <button type="submit" name='Proceed' value='register' class="btn btn-success">Zarejestruj</button>
  </form>

A: Example with your code to check for nick:

Register

      <form id="myform" role="form" method="post">

          <input id="nick" type="text" name="nick" placeholder="Nick" class="form-control" style="width: 250px;">
      <input type="text" name="name" placeholder="Imię" class="form-control" style="width: 250px;">
      <input type="text" name="surname" placeholder="Nazwisko" class="form-control" style="width: 250px;">
      <input type="text" name="email" placeholder="Email" class="form-control" style="width: 250px;">
      <input type="text" name="phone" placeholder="Telefon" class="form-control" style="width: 250px;">
      <input type="text" name="password" placeholder="Hasło" class="form-control" style="width: 250px;">
      <input type="text" name="repassword" placeholder="Powtórz hasło" class="form-control" style="width: 250px;">

    <button type="submit" name='Proceed' value='register' class="btn btn-success">Zarejestruj</button>
  </form>

Javascript:
 $('#myform').on("submit", function() {
    if(!$("#nick").val()) {
         alert("Missing fields");
        return false;
    }

    return true;
});

However, you should still check for the actually sent values using $_POST (if you use php)


text:
Q: laravel unit testing with factories Unable to locate factory with name [default] I try to create a factory for one of my models in laravel unit test
use Illuminate\Support\Collection;
use phpDocumentor\Reflection\Types\Parent_;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\User;
use Illuminate\Auth;
use App\Role;
use App\AppName\HolidaysEmployees;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class TestApiCalls extends TestCase
{

    public function setUp()
    {
        parent::setUp();

        $this->user = factory(User::class)->create([
            'firstname' => 'RA',
            'lastname' => 'Tester',
            'password' => bcrypt('tester'),
            'email' => 'ra@tester.com'
        ]);

        $this->holidays = factory(HolidaysEmployees::class)->make();
    }

}

but when I run the test I keep getting
InvalidArgumentException: Unable to locate factory with name [default] [App\MyName\HolidaysEmployees].

What I do wrong in this case?

A: I found how to fix this online:
Change
class TestApiCalls extends TestCase

to
class TestApiCalls extends \Tests\TestCase


text:
Q: Typescript Check if "any n consecutive elements are same" in M size array I've an array of strings or numbers of size M(M>n). I want to check if any n consecutive elements are same where n can vary between 1-M.
For instance, let assume I've below array, and I want to check there are four consecutive '5's or two consecutive '3's are present or not:
{1,2,3,4,5,5,5,5,2,6,3,3,1}
How can I achieve this?
P.S. I'm also using Linq.JS to perform linq functions on array.

A: You might do as follows

var arr = [1,2,3,4,5,5,5,5,2,6,3,3,1],
 result = arr.reduce((p,c,i,a) => c !== a[i+1] ? (p[p.length-1][0] = c, p.concat([[0,1]]))
                                               : (p[p.length-1][0] = c, p[p.length-1][1]++, p),[[true,1]])
             .slice(0,-1);
console.log(result);


text:
Q: Missing Messages Using the Office 365 Rest API Between the times of 16:13 BST and 17:17 BST today (5-June 2015) messages received into a shared mailbox are not being shown via the Office 365 Rest API.
Regardless of the OData queries applied I cannot get these messages to be returned via the API, it appears as if the API is completely unaware of these messages existing.
Service has resumed now however I still cannot see these messages.
I am accessing the api using client credentials OAuth flow, with full permissions to access the mailbox in question.
What might cause this to happen? Was there some downtime in the API or something else? Any information would be useful to help debug.

A: That definitely shouldn't be happening. I would try moving these messages into a subfolder (so they are the only messages present in the folder), then doing a non-filtered GET to that subfolder's messages collection and see if they are returned. I'd also check doing a GET on ../folders/{folder id}/messages/$count to see if the message count is accurate.


text:
Q: Block XMLHTTP request vanilla javascript I am working on a scenario, where i need to cancel third party library request based on some condition and then unblock if condition evaluates to false. Let us assume that third party URL is being loaded with following URL:
https://cdn-thirdparty.com/...

Now, once it is loaded, it captures user clicks on the application and sends data as another URL:
https://cdn-info-thirdpart.com/...

Now, say i want to block all the requests to URL which contains thirdparty in it.. How do i achieve this in Vanilla Javascript...
P.S: I do not have access to remove the library from code, instead i have to do some engineering that requests are getting blocked based on some conditions(we can assume any) and then getting unblocked on falsy condition.
The code i tried to intercept all XMLHttpRequest is as below and i do get URL, method of call but i need to block it now and then unblock.
let oldXHROpen = window.XMLHttpRequest.prototype.open;
 window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
   // do something with the method, url and etc.
   this.addEventListener('load', function() {
  // do something with the response text
  console.log('load: ' + url, method);
});

 return oldXHROpen.apply(this, arguments);
}

Source of above code: https://medium.com/@gilfink/quick-tip-creating-an-xmlhttprequest-interceptor-1da23cf90b76


text:
Q: Highhcarts with huge datasets in angularjs I have JSON data of around 50 mb that i need to sent to Angularjs front end which will be used by highcharts to show line graphs. But the fetching such amount of data over http is really time consuming (timeouts too in some cases) impacting user experience.
I also suggested , to client, to show aggregated data that reduces the sizes of json but client is not ready for that as that won't be of much use for analysis for his customers. Here is the fiddle demo with aggregated data. Just replace the query param  file=1min_raw in following piece of code with file=merged_json to check the time taken to download data and render chart.
$.getJSON('http://srijan-best.s114.srijan-sites.com/merged_script.php?file=1min_raw'

So is there a way in highcharts to show the data as soon as it starts receiving. ? I have gone through the docs but not able to find anything to me requirements.
Is there any other alternative for showing such amount json data in highcharts or any other charting api without degrading the performance occurring due to http response payload size?
And yes, The json data to be fetched can go upto 200 MB.
Thanks


text:
Q: nil can't be coerced I'm trying to return the 12 monthly data, however I keep getting that nil can't be coerced into Integer, this happen when starting with mapping from 0..11 because I use months.ago to group the data which it starts to count from the current month.
def yearly_results
    return [] unless user.results.order(id: :desc).where('created_at >= ?', 30.days.ago)

    attributes = [:skin_age, :skin_age_adjusted, :skin_tightness, :purity, :hyperpigmentation_face_score]

    results = []
    #  We create a Hash with every months attributes and values

    (0..11).map do |months_ago|
      month_results = grouped_by_months[months_ago.months.ago.strftime('%Y%m')] || []

      months_with_attr = month_results.reduce({}) do |key, value|

        attributes.each do |attr_name|
          key[attr_name] ||= 0
          key[attr_name] += value.send(attr_name)
        end
        key
      end

      if months_with_attr.present?
        months_with_attr.transform_values do |value|
          value.to_f / month_results.count
        end
      end
      results << months_with_attr.presence
    end
    results.reverse
  end

This is the error that I keep getting.
*** TypeError Exception: nil can't be coerced into Integer

nil

A: Given you want to use as little SQL as possible i´d propose the following:
attributes = [:skin_age, :skin_age_adjusted, :skin_tightness, :purity, :hyperpigmentation_face_score]

user.results.order(id: :desc).where('created_at >= ?', 30.days.ago)
.group_by{|result| result.created_at.month }
.transform_values{|results_per_month| attributes.map{|attr| [attr, results_per_month.map(&attr).reduce(&:+).to_f / results_per_month.count] }.to_h }

A: So if i get this right, you want to calculate the average per month.
I´d suggest to do this with SQL:
attributes = [:skin_age, :skin_age_adjusted, :skin_tightness, :purity, :hyperpigmentation_face_score]

# Get the average with SQL (for Postgres)
averages = user.results.order(id: :desc).where('created_at >= ?', 30.days.ago)
.group("date_trunc('month', created_at)").select("date_trunc('month', created_at) AS month", attributes.map{|attr| "AVG(#{attr}) AS average_#{attr}" })

# Then group by month
averages.group_by{|res| res['month'].month }
.transform_values{|results_per_month| results_per_month.map{|result_per_month| result_per_month.without('id', 'month') }  }
# => {1 => [{"average_skin_age" => 30, ...}], 2 => [{"average_skin_age" => 32, ...}],}


text:
Q: Scala pattern matching - error while creating a new case object from another I have a very simple case class called FooPosition:
case class FooPosition(x: Int, y: Int)

and a Foo class that has a FooPosition. I am interested in creating a function that returns -1 only for coordinates that are equal to (x-1, y) with respect to a Foo object and returns 0 everywhere else. So I wrote:
class Foo(position: FooPosition) {
  def bar = (p: FooPosition) => p match {
    case FooPosition(position.x - 1, position.y) => -1
    case FooPosition(_, _) => 0
  }
}

which results in an error that says "Not found: value -". Interestingly,
val myFoo = FooPosition(1, 0)
val newFoo = FooPosition(myFoo.x - 1, myFoo.y)

works just fine. I'm obviously missing something about pattern matching here (since I am a beginner). But what would be an elegant solution to this problem? I have worked around the problem using
class Foo(position: FooPosition) {
  private val left = FooPosition(position.x - 1, position.y)
  def bar = (p: FooPosition) => p match {
    case `left` => -1
    case FooPosition(_, _) => 0
  }
}

but I think there must be a better way.
Thanks in advance.

A: You can't use such syntax in pattern matching. But here are two options -- first one is to use guards:
def bar = (p: FooPosition) => p match {
  case FooPosition(x, _) if (x == p.x - 1) => -1
  case _ => 0
}

Here _ denotes anything, I don't care about the actual value.
Second is to do match-by-value (values with capitalized name will be matched by it's value, instead of producing new alias):
def bar = (p: FooPosition) => {
    val Px = p.x - 1
    p match {
      case FooPosition(Px, _) => -1
      case _ => 0
    }
}

Finally, your code will always default to 0 -- you're feeding some point p to it and then expecting it's X coordinate to be one unit less. Perhaps, you should write
def bar(p: FooPosition) = p match {
      case FooPosition(x, _) if (x == p.x -1) => -1
      case _ => 0
}

instead


text: Q: Is there a way to retrace previous conversation between characters in transcript? In GTA series you normally can retrace the conversation between characters in the pause menu. I'd love to have this option in Watch Dogs 2 as well, since I'm showing subtitles in a language I'm currently learning, and I'd like to see words I previously missed/didn't understand. Is there a way to do so?


text:
Q: How to avoid onbeforeunload preventing Watir test from exiting I have a webpage that uses onbeforeunload to prompt the user for confirmation whenever they try and navigate away from the page. This confirmation even fires when the browser window is closed.
My problem is that this prompt is preventing Watir from closing IE at the end of a test run, at least until I manually intervene and click "OK".
How can I write my tests such that Watir automatically dismisses this prompt, even if the test fails? I'm thinking there might be some conditional logic in the test teardown method, but I need help interacting with the popup.
Note: I have a different question pertaining to interacting with the onbeforeunload prompt when it is created by a click event. This question is about handling that popup when it is created by a request to close the window.

A: If you don't really need to test that dialog, you can overwrite onbeforeunload.
Not sure how it can be done in Watir, but in Watir-WebDriver it'll look like
browser.execute_script "window.onbeforeunload = null"


text:
Q: phpexcel -How to change data type for whole column of an excel I'm trying to change the datatype for a whole column (for eg: i need to change for "M" Column to general format). Its displaying as 2.00 in quantity field,I need to change this whole column to general format ie. display as "2". But its not changing the datatype.
Here is the code:
$objPHPExcel->getActiveSheet()
    ->setCellValue(
        $aCells[$eExcelColumn] . $eExcelRow,
        $sCellData ,
        PHPExcel_Cell_DataType::TYPE_NUMERIC
    );

$objPHPExcel->getActiveSheet()->getStyle('M1:M97')
    ->getNumberFormat()
    ->setFormatCode('0');

How to do for the whole column "M" as general format

A: You can do a column like this:
$objPHPExcel->getActiveSheet()->getStyle('M:M')
    ->getNumberFormat()
    ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_GENERAL);

A complete working example. The result in column A has two 2, column B two 2.00
$sheet = $objPHPExcel->getActiveSheet();

$sheet->getStyle('A:A')
        ->getNumberFormat()
        ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_GENERAL);

$sheet->getStyle('B:B')
        ->getNumberFormat()
        ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00);

$sheet->setCellValue('A1', 2);
$sheet->setCellValue('A2', 2.0);
$sheet->setCellValue('B1', 2);
$sheet->setCellValue('B2', 2.0);

A few more examples for column and row selections that I pulled from my actual base:
$objPHPExcel->getActiveSheet()->getStyle('1:1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('A:A')->getNumberFormat()->setFormatCode('yyyy/mm');
$objPHPExcel->getActiveSheet()->getStyle('D:D')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('E:E')->getNumberFormat()->setFormatCode('$#,###');

A: PHPExcel doesn't support column or row styling: you need to set the style for a range of cells, exactly as you are doing with
$objPHPExcel->getActiveSheet()->getStyle('M1:M97')
->getNumberFormat()
->setFormatCode('0');

if you want General format rather than '0', then set it to General Instead:
$objPHPExcel->getActiveSheet()->getStyle('M1:M97')
    ->getNumberFormat()
    ->setFormatCode('General');

or
$objPHPExcel->getActiveSheet()->getStyle('M1:M97')
    ->getNumberFormat()
    ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_GENERAL);

A: $mfisinArr = $this->isObject->getAllDataMfisinQuery();
if(isset($mfisinArr) && !empty($mfisinArr))
{
    $excel_row = 2;
    foreach ($mfisinArr as $key => $value)
    {
        // PHPExcel Style getting default number format
        $object->getActiveSheet()->getStyle('A'.$excel_row)->getNumberFormat()->setFormatCode('0');
        $object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row, sprintf('%09d',$value['security']));
        $object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $value['name']);
        $object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $value['mf_isin']);
        $object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, empty($value['mat_dt'])?'':date('d-m-Y',strtotime($value['mat_dt'])));
        $excel_row++;
    }
}


text:
Q: Display accented letters in iTerm2 When I type accented letter in iTerm2, I get a strange behaviour. For instance when i type "sélectionner", iTerm2 displays "sé lectionner".
Preferences/Profiles/Terminal/Character Encoding is set to Unicode (UTF-8).
Any idea of what I should do to have iTerm2 display characters correctly?
Thanks

A: Make sure "prefs>profiles>text>treat ambiguous-width characters as double-width" is turned off.
See also this issue.


text:
Q: How to prove that $5^q<7^q$ implies $q>0$? Consider $q\in \mathbb{Q}\:$ , $5^{q\:}<\:7^q$
How to prove that $q>0$ using only Power rules?
So far, I just know that if $q=0$ we get $1>1$ and its false. But what to do get contradict for $q< 0$?

A: First, note that for $q > 0$ we have
$$a > 1 \Rightarrow a^q > 1 \text{ and } 0 < a < 1 \Rightarrow 0 < a^q < 1.$$
Hence, for $q > 0$ it follows that
$$7^q = \left( 5 \cdot \frac{7}{5} \right)^q = 5^q \cdot \underbrace{\left( \frac{7}{5} \right)^q}_{>1} > 5^q \cdot 1 = 5^q,$$
i.e. the inequality is true for $q > 0$. As you already noted, it is false for $q = 0$. Now assume $q < 0$. Then $q = - q'$ where $q' > 0$ and we have
$$ 7^q = 7^{-q'} = \frac{1}{7^{q'}} = \frac{1}{\left( 5 \cdot \frac{7}{5} \right)^{q'}} = \frac{1}{5^{q'}} \cdot \underbrace{\left( \frac{5}{7} \right)^{q'}}_{< 1} < \frac{1}{5^{q'}} = 5^{-q'} = 5^q.$$
It follows that $q < 0$ implies $7^q < 5^q$.
Now if you assume that $7^q > 5^q$, then it follows that $q > 0$, because the inequality is false for $q = 0$ and $q<0$.
Sorry if this is a bit long.

A: $5^q<7^q \implies 1<\left(\dfrac{7}{5}\right)^q\implies\left(\dfrac{7}{5}\right)^0<\left(\dfrac{7}{5}\right)^q \implies q>0$

A: $$5^q<7^q$$
Since the function $\log_5(\cdot)$ is strictly increasing,
$$q<q\log_57$$
or
$$q(\log_57-1)>0$$
and since $\log_57>\log_55=1$,
$$q>0$$


text:
Q: Why doesn't my model produce accurate training results from the MNIST database? I am relatively new to neural networks. I am currently trying to make a model to identify written characters from the MNIST database, however my training accuracy is extremely low. I was wondering, what can I do to improve my results and what was wrong with how I was originally approaching the issue. Thanks!
import keras
from keras.models import Sequential
from keras.layers import Activation
from keras.layers.core import Dense
from keras.optimizers import SGD
from keras.datasets import mnist
import numpy as np

BATCH_SIZE = 20
EPOCHS = 15

#load data. x is images, y is label
(train_x, train_y), (test_x, test_y) = mnist.load_data()

#reshape into 784 1d array rather than 28, 28 2d array
train_x = np.reshape(train_x, (60000, 784))
train_x = train_x.astype('float32')
train_x = train_x / 255.0

test_x = np.reshape(test_x, (10000, 784))
test_x = test_x.astype('float32')
test_x = test_x / 255.0

print("Done!")

model = Sequential([
    Dense(16, input_shape=(784,), activation='relu'),
    Dense(32, activation='relu'),
    Dense(10, activation='softmax')
])

model.compile(optimizer='SGD', loss='mse', metrics=['accuracy'])

model.fit(train_x, train_y, batch_size=BATCH_SIZE, epochs=EPOCHS, shuffle=True, verbose=2, validation_data=(test_x, test_y))

print("Done!")

def visualize_data():
    string = ""
    count = 0
    for x in train_x[2]:
        if ((count % 28) == 0):
            print(string)
            string = ""
        if x < 10:
            string = string + " " + str(x)+ " "
        elif x < 100:
            string = string + " " + str(x)
        elif x < 1000:
            string = string + str(x)

        count += 1


text:
Q: How do I click on a link in the same row as another string which I've made into a list? I want to click on a link in the same row as another link/text which I have copied into a list. What is the best way to go about this?
I want to click on the "Edit" Button in the same row as the Invoice. I copied all the Invoices into a list but I had to remove the "invoice #" part out of each invoice.
Thank you for your help!

Edit | View

ID

ID2

Customer

Stripe Code

Event Date

Invoice

Invoice Sales Order

Invoice Terms

Event Type

Balance

Edit | View
214433
245950
Salads & Wraps
funds
11/14/2019
Invoice #INV10
Order #0073
On Shipping
The account has insufficient funds
476.00

Edit | View
214502
3831
Bbq and Pizzeria
funds
11/14/2019
Invoice #INV20
Order #0068
ACH on Shipping
The account has insufficient funds
1,027.18

Edit | View

ID

ID2

Customer

Stripe Code

Event Date

Invoice

Sales Order

Invoice Terms

Event Type

Balance

A: I'd say if the you wanted to click based on the invoice id, you should know the invoice id right or at leas part of it e.g : INV10 . so you need to construct xpath around that like so
"//tr[ .//a[contains(text(),'INV10')]]//a[contains(@class, 'edititem')]"

the xpath //tr[ .//a[contains(text(),'INV10')]] means looks for tr that has descendant anchor that has text containing INV10
but if you wanted it to be dynamic let say it's always had INV + something, you could construct the string there and append as needed
String dummyVar = 10;
"//tr[ .//a[contains(text(),'INV"+dummyVar +"')]]//a[contains(@class, 'edititem')]"

Sorry i'm not familiar with phyton, but it should be understandable.
EDIT : i'm assuming the id is the INV10, but when i take a look you have id column. so if the id column is the invoice ID then you could do
"//tr[ .//td[contains(text(),'245950')]]//a[contains(@class, 'edititem')]"

just a warning, if you are able to put at least class in the id's td to make it more accurate for you to find it as well as more robust in case you have a coincident 2 elements found with the xpath

A: It seem like you want click Edit based on particular #INV number, try the following xpath:
//tr[contains(.,"#INV10")]//td//a[text()="Edit"]

Try change #INV10 to #INV20 and see the result.


text:
Q: Simplicial complex of a graph? Starting with a graph $G$, form a simplicial complex $X$ which has $G$ as the 1-skeleton, and then has higher dimensional simplices whenever more than two vertices of $G$ are mutually adjacent. So any $n$ mutually adjacent vertices in $G$ will correspond to a $(n-1)$-simplex in $X$.
Is this a valid/common construction? Does it have a name? Thanks-

A: Self-answer: This is the clique complex.