text:
Q: What are the pros and cons on Encryption at rest and client side encryption in DynamoDb tables I have the following two design choices for a dynamodb table

*

*Using Encryption at Rest

*Using Client Side Encryption with a AWS KMS managed key

So far from the research I did Encryption at Rest is easier to manage and debug since it will have the data in plain text in console where as if you use client side encryption, you have to do an extra step of decrypting these information before viewing for debugging purposes. What are the other advantages of Encryption at Rest over Client Side Encryption?
What will provide the most efficient performance among the two?
If you were given a choice to select one, which you would choose and why?

A: *

*DynamoDb tables are always encrypted at rest. You can't disable it.

Server-side encryption at rest is enabled on all DynamoDB table data and cannot be disabled.

*Second one is up to you. For some regulatory reasons you may require encryption of your items which are stored in DynamoDb. If its not required, your life will be much easier without this. Otherwise every single application that writes/reads your items will need to keep encrypting and decrypting the items before they can do anything. It will only cost you in KMS charges, makes development and maintenance of your applications more difficult.

A: DynamoDB encryption client[1] owner here. :)
As with so many things, which option is best for you depends on your use-case and security (or compliance) requirements.
If server-side encryption satisfies those requirements, then yes, that is the simplest answer and will require the least complexity on your end. You cannot turn off DynamoDB server-side encryption, but you do need to decide how much control you want over the KMS CMK that DynamoDB uses to protect your table[2].
There are some capabilities that client-side encryption offers that server-side does not. Some scenarios where client-side encryption can help you include:

*

*You have a security or compliance requirement that all data is encrypted locally before it is sent to any service.

*You have items in your table that need to be encrypted under different master keys. For example, if you have a multi-tenant table and you encrypt each customer's data under a customer-specific CMK.

*You have different security requirements for different item attributes. For example, if you have some attributes that are not secret and some that are, and it would be useful to be able to have some portions of your service or application able to read the non-secret attributes but not the secret attributes. In this scenario, you could configure the DynamoDB encryption client to only sign those attributes rather than encrypting and signing them, letting you retain the item integrity check while leaving those non-secret attributes readable to components that cannot decrypt the secret attributes.

There are also some costs to client-side encryption.

*

*Increased code complexity. If you are working in Java or Python, the DynamoDB encryption client can address a lot of the complexity for you, but using it is still more complex than not doing client-side encryption.

*Increased KMS costs (assuming you're using KMS). This can be reduced using the "most recent provider"[3]; the DynamoDB encryption client's answer to data key reuse.

*Decreased console visibility. As far as DynamoDB is concerned, if you are doing client-side encryption then your items are just data that happen to have an unusually high percentage of Binary attributes, so the console cannot show you the plaintext of your client-side-encrypted attributes.

[1] https://docs.aws.amazon.com/dynamodb-encryption-client/latest/devguide/what-is-ddb-encrypt.html
[2] https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/EncryptionAtRest.html
[3] https://docs.aws.amazon.com/dynamodb-encryption-client/latest/devguide/most-recent-provider.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: LitElement appending custom elements using button I have a custom LitElement and inside it, I need to have a button that will dynamically append new custom elements (preferably using TemplateResult objects generated by html function) inside a container:
import { LitElement, html, render } from "lit";
import { customElement } from "lit/decorators.js";

    @customElement('example-custom-component')
    class CustomComponent extends LitElement {

       render() {
          return html`

             <button @click=${this.appendNewCustomEl}>click me!</button>
          `;
       }

       appendNewCustomEl() {
          const templateToAppend = html`
            <another-custom-component>
               some other things added here
            </another-custom-component>
          `;
          render(templateToAppend, this.shadowRoot?.querySelector('#custom-el-container'));
       }
    }

As you can see above I tried to achieve it by using the render function, but instead of appending it at the end of the container, I'm simply overwriting the content of the div. What am I doing wrong? What's the best approach to achieve those results? Please help.
EDIT:
New example for my question from comments about click events:
appendNewCustomEl() {
  this.shadowRoot!.querySelector('#custom-el-container').insertAdjacentHTML("beforeend", `
            <another-custom-component>
               <button @click=${this.functionFromCustomComponent}>click me!</button>
            </another-custom-component>
          `)
}

A: If you really want to do it with lit-html and your container's content is purely what you are dynamically rendering on each button click, (i.e. not server side rendered content) or you are using lit-html v2 then you could have a list and track what you have rendered. something like:
items=[];

appendNewCustomEl() {
  this.items.push(null);
  const templatesToAppend = this.items.map(() => html`
            <another-custom-component>
               some other things added here
            </another-custom-component>
          `);
   render(templatesToAppend, this.shadowRoot?.querySelector('#custom-el-container'));
}

in general what lit-html is good at and tries to achieve is an optimal re-render of markup when only parts are changed. not necessary a template engine alternative to handlebars, mustache and co.
In your example, you don't need it and could do it simply without lit-html:
appendNewCustomEl() {
  this.shadowRoot!.querySelector('#custom-el-container').insertAdjacentHTML("beforeend", `
            <another-custom-component>
               some other things added here
            </another-custom-component>
          `)
}

A: I've slightly modified your example code to be more idiomatic Lit. Instead of using a querySelector and insertAdjacentHTML, it is preferred to render the array of templates declaratively. This has the added benefit that your functionFromCustomComponent event bindings "just work".
I've written the full example in a Lit playground.
The list of templates are stored in a reactive property, this.templates that schedules an efficient update whenever the list is updated.
Then the this.appendNewCustomEl method can push new templates to the list, and an automatic efficient render happens automatically.
this.templates is rendered into the #custom-el-container div using an expression:

  ${this.templates}

See Lit expressions documentation for other examples.
In my linked example, the list of templates turn blue when clicked to demonstrate the event working.
Not necessary but related, Lit.dev has a tutorial all about Working with lists that goes much more in depth if you're curious.


text:
Q: GraphX : How to fetch all edges with a given label I have a Graph with millions of edges where edges are represented by org.apache.spark.rdd.RDD[org.apache.spark.graphx.Edge[String]] = MappedRDD[4] . I have two questions :
1)How can I fetch all the nodes with a given edge label
2) Is it possible to create indexes on the RDDs or a specific column of the RDD to make the look up faster?
Please excuse me for the triviality of the question, I am new to the language and its taking me sometime to get used to it.
Thanks

A: 1) Cant you just .filter(_._2=="label") on the rdd?
2) I think what youre looking for is IndexedRDD, but I think you need to rebuild spark from the latest source


text:
Q: How to make Top and bottom view using ext js chart I am trying to make Amount and Month graph using ext js chart plugin where the month should come in the top and the amount should come in the bottom, I am successfully able to bring that view but the issue is, amount is changing to decimal value
here is the left(Amount) and bottom(Month) view
http://jsfiddle.net/djaydxnd/52/
here is what I am tring to bring, bottom(Amount) and top(Month) view
http://jsfiddle.net/djaydxnd/51/
Here is the code
Ext.require([
    'Ext.chart.Chart'
]);

Ext.define('CricketScore', {
    extend: 'Ext.data.Model',
    fields: ['month', 'data1' ]
});

var store = Ext.create('Ext.data.Store', {
    model: 'CricketScore',
            data: [
                { month: 'Jan', data1: 20 },
                { month: 'Feb', data1: 20 },
                { month: 'Mar', data1: 19 },
                { month: 'Apr', data1: 18 },
                { month: 'May', data1: 18 },
                { month: 'Jun', data1: 17 },
                { month: 'Jul', data1: 16 },
                { month: 'Aug', data1: 16 },
                { month: 'Sep', data1: 16 },
                { month: 'Oct', data1: 16 },
                { month: 'Nov', data1: 15 },
                { month: 'Dec', data1: 15 }
            ]
});

Ext.create('Ext.chart.Chart', {
   renderTo: Ext.getBody(),
   width: 400,
   height: 300,
   theme: 'Green',
   store: store,
    animate: true,
   axes: [
       {
                type: 'Numeric',
                position: 'bottom',
                fields: ['data1'],
                minimum: 0
            }, {
                type: 'Category',
                position: 'top',
                fields: ['month'],
            }
    ],

      series: [
       {
                type: 'column',
                axis: 'left',
                xField: 'month',
                yField: 'data1',
                style: {
                    opacity: 0.80
                },
                highlight: {
                    fill: '#000',
                    'stroke-width': 20,
                    stroke: '#fff'
                },
                tips: {
                    trackMouse: true,
                    style: 'background: #FFF',
                    height: 20,
                    renderer: function(storeItem, item) {
                        this.setTitle(storeItem.get('month') + ': ' + storeItem.get('data1') + '%');
                    }
                }
            }
    ]
});

If you check for "position" it will be in "axes: [ ]" array list
Update in Question
the bottom graph values will be custom values, a have shared my expected image.

A: Column Chart can not be use with top axis and bottom axis  for that you have to use Bar Chart.
    series: [
           {
                    type: 'bar',
                    ...
           }

Please refer this link.
In general all charts has to have one vertical line(left/right) and one horizontal line(top/bottom) by that way only you can identify connection points which is essential to create any charts.


text:
Q: how to set a javascript calculate function to wait until it sees a value in another field I have a function that calculates (adds) values from 2 other fields and diplays the results in a third field. This works perfectly. However, I now need this calculate function to "wait" until it sees a value populated in a separate date field. Once this date field has a value then the calculate function can display the results. See current calculate function below.
Thanks for any help you can provide.
function Calculate() {
  var item1 = Xrm.Page.getAttribute("new_step1amount").getValue();
  if (item1 == null) {
    item1 = 0;
  }

  var item2 = Xrm.Page.getAttribute("new_step2amount").getValue();
  if (item2 == null) {
    item2 = 0;
  }

  Xrm.Page.getAttribute("new_totalamountcollected").setValue(item1 + item2);
}

A: Here is pseudo code:
if(dateFieldHasValue)
{
    Xrm.Page.getAttribute("new_totalamountcollected").setValue(item1 + item2);
}

Just call your function onchange of the date field...


text:
Q: VSTS - Add a field to a task definition, with a value based on another field I'd like to add the following functionality to my VSTS extension (plugin).
I have a build task definition which includes a string input. I need to create a new version of my plugin, which adds a new string input to this task.
The new input should be created with a value, which is based on the value of the old field.
For example, if the old field has a value of a/b/c.txt, then the value of the new field should be { path="a/b/c.txt" }.
Is there a way to use node.js or Powershell to achieve this? Another way perhaps?

A: From my test, it's not able to get the value of a filed from another one. You may try to get the field when the task runs and set value to another field.


text:
Q: Servidor tomcat 9.0 solo devuelve el primer servicio Hola buenas tardes, formulo esta pregunta porque he buscado bastante por internet pero no he encontrado una solución a este problema. El tema es que arranco el servidor y todo va como la seda, tengo varios servicios implementados, servicios PUT y GET, y al llamarlos a través de postman todos me devuelven una respuesta 200, siempre y cuando sea la primera solicitud después de arrancar el servidor. Es decir el segundo servicio y posteriores se pierden en el limbo, ya que la conexión es aceptada por el servidor. Por supuesto he puesto puntos de ruptura en los servicios y he arrancado el servidor en "debug-mode" para ver si podía sacar algo de info pero todo ha sido en vano. Adjunto imágenes de la consola del servidor, de la configuración del persistence.xml, ya que utilizo JPA con Hibernate como gestor de persistencia y del pom.xml. En principio creo que las anotaciones de JPA están bien, ya que el ide no me canta ningún error y en el primer servicio añado, borro y consulto registros de la base de datos. Añadir que utilizo Jersey como serializador. Muchas gracias de antemano, espero que me puedan ayudar. :) EDITO:
He conseguido aislar los los fallos, y estos son en los servicios GET, los servicios PUT funcionan bien. Parece ser que hay algún problema con la conexión a la base de datos, ya que cuando se queda "colgado" si intento acceder a los registros de la base de datos a través de la consola mysql, la consulta no es devuelta hasta que cierro el servidor a lo bruto (pulsando el botón "terminate") añado el stacktrace del error más abajo. Muchas gracias again.
Información de la consola del servidor, del persistance.xml y del pom.xml:

INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@5eb3a986] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
  may 16, 2018 10:06:00 AM org.apache.catalina.core.StandardServer await
  INFORMACIÓN: Se ha recibido un comando de apagado a través del puerto de apagado. Parando la instancia del Servidor.
  may 16, 2018 10:06:00 AM org.apache.coyote.AbstractProtocol pause
  INFORMACIÓN: Pausing ProtocolHandler ["http-nio-8080"]
  may 16, 2018 10:06:00 AM org.apache.coyote.AbstractProtocol pause
  INFORMACIÓN: Pausing ProtocolHandler ["ajp-nio-8009"]
  may 16, 2018 10:06:00 AM org.apache.catalina.core.StandardService stopInternal
  INFORMACIÓN: Parando servicio [Catalina]
  may 16, 2018 10:06:00 AM org.apache.catalina.core.StandardWrapper unload
  INFORMACIÓN: Esperando por 1 instancia(s) para recuperar su espacio reservado
  may 16, 2018 10:06:01 AM org.apache.catalina.core.StandardWrapper unload
  INFORMACIÓN: Esperando por 1 instancia(s) para recuperar su espacio reservado
  may 16, 2018 10:06:02 AM org.apache.catalina.core.StandardWrapper unload
  INFORMACIÓN: Esperando por 1 instancia(s) para recuperar su espacio reservado
  may 16, 2018 10:06:02 AM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesJdbc
  ADVERTENCIA: La aplicación web [ILoan] registró el conductor JDBC [com.mysql.jdbc.Driver] pero falló al anular el registro mientras la aplicación web estaba parada. Para prevenir un fallo de memoria, se ha anulado el registro del conductor JDBC por la fuerza.
  may 16, 2018 10:06:02 AM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
  ADVERTENCIA: The web application [ILoan] is still processing a request that has yet to finish. This is very likely to create a memory leak. You can control the time allowed for requests to finish by using the unloadDelay attribute of the standard Context implementation. Stack trace of request processing thread:[
   java.net.SocketInputStream.socketRead0(Native Method)
   java.net.SocketInputStream.socketRead(Unknown Source)
   java.net.SocketInputStream.read(Unknown Source)
   java.net.SocketInputStream.read(Unknown Source)
   com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:101)
   com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:144)
   com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:174)
   com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:3005)
   com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3466)
   com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3456)
   com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3897)
   com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2524)
   com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2677)
   com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)
   com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2503)
   com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:839)
   com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:739)
   org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
   org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:525)
   org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:470)
   org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applyForeignKeys(AbstractSchemaMigrator.java:429)
   org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:245)
   org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:110)
   org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:183)
   org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
   org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:309)
   org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:445)
   org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:889)
   org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
   javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
   javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
   daos.Dao.(Dao.java:14)
   daos.FriendDao.(FriendDao.java:12)
   deal.FriendDeal.(FriendDeal.java:13)
   recursos.ResourceFriend.(ResourceFriend.java:23)
   sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
   sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
   sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
   java.lang.reflect.Constructor.newInstance(Unknown Source)
   org.glassfish.hk2.utilities.reflection.ReflectionHelper.makeMe(ReflectionHelper.java:1375)
   org.jvnet.hk2.internal.ClazzCreator.createMe(ClazzCreator.java:272)
   org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:366)
   org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:487)
   org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:162)
   org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)
   org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:774)
   org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:737)
   org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:707)
   org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:169)
   org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:185)
   org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74)
   org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:109)
   org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
   org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
   org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
   org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
   org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:92)
   org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:61)
   org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
   org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:300)
   org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
   org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
   org.glassfish.jersey.internal.Errors.process(Errors.java:315)
   org.glassfish.jersey.internal.Errors.process(Errors.java:297)
   org.glassfish.jersey.internal.Errors.process(Errors.java:267)
   org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
   org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:291)
   org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1140)
   org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:403)
   org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
   org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
   org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
   org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
   org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
   org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
   org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
   org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
   org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
   org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
   org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
   org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:409)
   org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
   org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754)
   org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1376)
   org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
   java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
   java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
   org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
   java.lang.Thread.run(Unknown Source)]
  may 16, 2018 10:06:02 AM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
  ADVERTENCIA: The web application [ILoan] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
   java.lang.Object.wait(Native Method)
   java.lang.ref.ReferenceQueue.remove(Unknown Source)
   com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:43)
  may 16, 2018 10:06:02 AM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
  ADVERTENCIA: The web application [ILoan] appears to have started a thread named [pool-2-thread-1] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
   sun.misc.Unsafe.park(Native Method)
   java.util.concurrent.locks.LockSupport.parkNanos(Unknown Source)
   java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(Unknown Source)
   java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(Unknown Source)
   java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(Unknown Source)
   java.util.concurrent.ThreadPoolExecutor.getTask(Unknown Source)
   java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
   java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
   java.lang.Thread.run(Unknown Source)
  may 16, 2018 10:06:02 AM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
  ADVERTENCIA: The web application [ILoan] appears to have started a thread named [pool-3-thread-1] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
   sun.misc.Unsafe.park(Native Method)
   java.util.concurrent.locks.LockSupport.parkNanos(Unknown Source)
   java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(Unknown Source)
   java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(Unknown Source)
   java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(Unknown Source)
   java.util.concurrent.ThreadPoolExecutor.getTask(Unknown Source)
   java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
   java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
   java.lang.Thread.run(Unknown Source)
  may 16, 2018 10:06:02 AM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
  ADVERTENCIA: The web application [ILoan] appears to have started a thread named [pool-4-thread-1] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
   sun.misc.Unsafe.park(Native Method)
   java.util.concurrent.locks.LockSupport.parkNanos(Unknown Source)
   java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(Unknown Source)
   java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(Unknown Source)
   java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(Unknown Source)
   java.util.concurrent.ThreadPoolExecutor.getTask(Unknown Source)
   java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
   java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
   java.lang.Thread.run(Unknown Source)
  may 16, 2018 10:06:02 AM org.apache.catalina.loader.WebappClassLoaderBase checkThreadLocalMapForLeaks
  GRAVE: La aplicación web [ILoan] creó un ThreadLocal con clave del tipo [java.lang.ThreadLocal] (valor [java.lang.ThreadLocal@39c0db85]) y un valor del tipo [org.glassfish.jersey.internal.Errors] (valor [org.glassfish.jersey.internal.Errors@42630ea9]) pero no pudo quitarlo cuando la aplicación web se paró. Los hilos se van a renovar con el tiempo para intentar evitar in posible fallo de memoria.
  may 16, 2018 10:06:02 AM org.apache.catalina.loader.WebappClassLoaderBase checkThreadLocalMapForLeaks
  GRAVE: La aplicación web [ILoan] creó un ThreadLocal con clave del tipo [java.lang.ThreadLocal] (valor [java.lang.ThreadLocal@23fdc732]) y un valor del tipo [org.glassfish.jersey.process.internal.RequestScope.Instance] (valor [Instance{id=37621d2c-f027-4731-b0e6-c0ec9732fb4a, referenceCounter=2, store size=3}]) pero no pudo quitarlo cuando la aplicación web se paró. Los hilos se van a renovar con el tiempo para intentar evitar in posible fallo de memoria.
  may 16, 2018 10:06:02 AM org.apache.coyote.AbstractProtocol stop
  INFORMACIÓN: Stopping ProtocolHandler ["http-nio-8080"]
  may 16, 2018 10:06:07 AM org.apache.tomcat.util.net.AbstractEndpoint shutdownExecutor
  ADVERTENCIA: The executor associated with thread pool [http-nio-8080] has not fully shutdown. Some application threads may still be running.
  may 16, 2018 10:06:07 AM org.apache.coyote.AbstractProtocol stop
  INFORMACIÓN: Stopping ProtocolHandler ["ajp-nio-8009"]
  may 16, 2018 10:06:07 AM org.apache.coyote.AbstractProtocol destroy
  INFORMACIÓN: Destroying ProtocolHandler ["http-nio-8080"]
  may 16, 2018 10:06:07 AM org.apache.coyote.AbstractProtocol destroy
  INFORMACIÓN: Destroying ProtocolHandler ["ajp-nio-8009"]

A: El problema son los bucles infinitos que se crean en las consultas a la base de datos. Cuando un Usuario tiene muchos Amigos y un Amigo puede pertenecer a muchos Usuarios(One to many y Many to one, relacion bidireccional), si no se mapea bien, se pueden generar bucles infinitos que saturen la base de datos.
Añado este tutorial en el que se explican muy bien las relaciones bidireccionales. Este es el mejor artículo que he podido encontrar.
Artículo sobre relaciones bidireccionales
EDITO:
Añado un nuevo tutorial.
Tutorial sobre relaciones JPA


text:
Q: Javascript file isn't appending to a filtered list As the title reads, my javascript file won't append to a filtered list via a random generator function, for context it's being built in replit so perhaps its just a buggy bit of software on replits end, though I'm certain I've done something wrong and can't for the life of me figure out what. The main idea for this project is to have it randomly select an item from a list, append it to an empty list, then pass that string to an HTML textarea tag to be displayed as text.
Code in question:

var LowercaseList = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];

var NumList = ["1","2","3","4","5","6","7","8","9","0"];

var SpecialCharList = ["`","~","!","#","$","%","^","&","*","_","-","+","=","<",">","?","/"];

// Letter list ID's since I couldn't figure out how to run this using a database
var LetterIDList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26];

// Number list ID's since I couldn't figure out how to run this using a database
var NumIDList = [1,2,3,4,5,6,7,8,9,10];

// Special character list ID's since I couldn't figure out how to run this using a database
var SpecialID = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];

// Filtered Lists
var UpperFiltered = [];
var LowerFiltered = [];
var NumFiltered = [];
var SpecialFiltered = [];

// Global declarations of random number variables to grab values from intial lists
var UpperGenVariable;
var LowerGenVariable;
var NumGenVariable;
var SpecialGenVariable;

// Creates a basic password with 2 of each kind of character
function Basic () {
  for (var i = 1; i < 2; i++) {
    UppercaseGenerate();
  }
  for (var i = 1; i < 2; i++) {
    LowercaseGenerate();
  }
  for (var i = 1; i < 2; i++) {
    NumGenerate();
  }
  for (var i = 1; i < 2; i++) {
    SpecialGenerate();
  }
};
let passwordGen = document.getElementById("PasswordDisplay")

function UppercaseGenerate () {
  var UpperFiltered = [];
  UpperGenVariable = Math.random(0, LetterIDList.length);
  for (var i = 0; i < LetterIDList.length - 1; i++) {
    if (LetterIDList[i] == UpperGenVariable) {
      appendItem(UpperFiltered, UppercaseList[i]);
    }
  };
  console.log(UpperFiltered);
  passwordGen.value = UpperFiltered
};

HTML textarea code:
<label style = "color:white;" for="PasswordDisplay">Your generated password ----></label>
     <textarea  readonly id="PasswordDisplay" name="PasswordDisplay" rows="10" cols="50">
       Please select a password complexity setting
     </textarea>

A: I changed how you generate the random number.
Also added the UppercaseList, added i <= 2 rather then i < 2 in the cycles so the yould really run 2 times, added += to passwordGen.value += UpperFiltered so the value would add up.
I guess that is it.
var UppercaseList = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

var LowercaseList = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];

var NumList = ["1","2","3","4","5","6","7","8","9","0"];

var SpecialCharList = ["`","~","!","#","$","%","^","&","*","_","-","+","=","<",">","?","/"];

// Letter list ID's since I couldn't figure out how to run this using a database
var LetterIDList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26];

// Number list ID's since I couldn't figure out how to run this using a database
var NumIDList = [1,2,3,4,5,6,7,8,9,10];

// Special character list ID's since I couldn't figure out how to run this using a database
var SpecialID = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];

// Filtered Lists
var UpperFiltered = [];
var LowerFiltered = [];
var NumFiltered = [];
var SpecialFiltered = [];

// Global declarations of random number variables to grab values from intial lists
var UpperGenVariable;
var LowerGenVariable;
var NumGenVariable;
var SpecialGenVariable;

// Creates a basic password with 2 of each kind of character
function Basic () {
  for (var i = 1; i <= 2; i++) {
    UppercaseGenerate();
  }
  for (var i = 1; i <= 2; i++) {
    LowercaseGenerate();
  }
  for (var i = 1; i <= 2; i++) {
    NumGenerate();
  }
  for (var i = 1; i <= 2; i++) {
    SpecialGenerate();
  }
};

let passwordGen = document.getElementById("PasswordDisplay")

function UppercaseGenerate() {
  var UpperFiltered = [];
  UpperGenVariable = Math.floor(Math.random() * LetterIDList.length);
  for (var i = 0; i < LetterIDList.length; i++) {
    if (LetterIDList[i] == UpperGenVariable) {
      UpperFiltered.push(UppercaseList[i]);
    }
  };
  passwordGen.value += UpperFiltered
};


text:
Q: Python pandas explode (one to many relationship) Suppose I have a the following dataframe with columns name, preference, fruits:
name   preference   fruits
adam    likes       apples
mike   dislikes     orange

If the dataframe above had a one to many relationship like column name would have have multiple relationship with column preference, fruits. For example the output dataframe I am looking for is:
name   preference   fruits
adam    likes       apples
adam    likes       orange
adam    dislikes    apple
adam    dislikes    orange
mike    likes       apples
mike    likes       orange
mike    dislikes    apple
mike    dislikes    orange

Wondering if it is possible. From my knowledge about pandas so far I believe I will have to use groupby?
Any help is appreciated!
Thanks!

A: Is it just cross product:
(pd.MultiIndex.from_product([df[col] for col in df],
                           names=df.columns)
   .to_frame().reset_index(drop=True)
)

Output:
   name preference  fruits
0  adam      likes  apples
1  adam      likes  orange
2  adam   dislikes  apples
3  adam   dislikes  orange
4  mike      likes  apples
5  mike      likes  orange
6  mike   dislikes  apples
7  mike   dislikes  orange

A: I'd use itertools.product
import pandas as pd
from itertools import product

df = pd.DataFrame({
    'name': ['adam', 'mike'],
    'preference': ['likes', 'dislikes'],
    'fruits': ['apples', 'oranges']
})

ndf = pd.DataFrame(
    product(*[df[c] for c in df.columns]),
    columns=df.columns
)

print(ndf)
#    name preference   fruits
# 0  adam      likes   apples
# 1  adam      likes  oranges
# 2  adam   dislikes   apples
# 3  adam   dislikes  oranges
# 4  mike      likes   apples
# 5  mike      likes  oranges
# 6  mike   dislikes   apples
# 7  mike   dislikes  oranges

As for speed, this seems to be a bit faster as well.
%%timeit
ndf = pd.DataFrame(
    product(*[df[c] for c in df.columns]),
    columns=df.columns
)
# 624 µs ± 32.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit
(pd.MultiIndex.from_product([df[col] for col in df],
                           names=df.columns)
   .to_frame().reset_index(drop=True)
)
# 3.51 ms ± 176 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


text:
Q: Present perfect and its interpretation I have a question.
Does this mean the consequence or the continuous state?

A half century past the beginning of the movement, it's been invested with an aura of mystique.

I think it can be both...
What is your take?
Thank you.

A: To my eye this is a resultative present perfect; but it is very easy to see why you might think it is a continuative present perfect:

*

*The verb here is ambiguous. Has been invested may be parsed as either the present perfect passive of the eventive verb INVEST or as the present perfect of the stative verb BE + the present participle of INVEST employed as an adjective.

*At first glance, the temporal expression which introduces the sentence looks like it's defining just such a duration as a continuative perfect requires:

A half century past the beginning of the movement

But in fact what this defines is not a duration but a location, a single point: now.

The movement has now been invested with an aura of mystique.

The inferences you may draw are that:

The movement, at its beginning, did not have an aura of mystique.
  At some later point it was invested with an aura of mystique.
  As a result it now possesses an aura of mystique.

That's a classic resultative perfect:

(2)a. Resultative: There is one event of the type denoted by the base sentence
  in the interval terminating at the evaluation point, and its direct result
  holds at this point.
    b. Policeman (on road): Can I see your license please. Driver: I've left it at
  home.
    Anita Mittwoch, "The English Resultative perfect and its relationship
  to the Experiential perfect and the simple past tense", *Linguistics & Philosophy (2008) 31:324
  .


text:
Q: How To Write XML file foreach datarows in dataset? How can I write xml foreach datarow in dataset? I have dataset with 5 record in table, I want to write to xml file with 5 xml files. In one xml file have one record.

A: Why don't you just make a loop ?
foreach (Datarow row in dataset.table["Table"].Rows)
{
    WriteXML();
}

Maybe you're wondering how to write the XML?

A: Try this :
Dim dtXML As New DataTable

Dim dtData As New DataTable

Dim dtRow As DataRow

Dim dtXMLRow As DataRow

Dim XMLFilename As String

'==============Fill dtData from database============

'Add matching columns to your XML datatable

dtXML.Columns.Add("Column Name")

dtXML.Columns.Add("Column Name2")

For Each dtRow In SQLTable.Rows

'Clear last row

dtXML.Rows.Clear()

'Make new row

dtXMLRow = dtXML.NewRow

'Copy data from one Datarow to another

dtXMLRow("Column Name") = dtRow("Column Name").ToString

dtXMLRow("Column Name2") = dtRow("Column Name2").ToString

'Add the new built row to the dtX

dtXML.Rows.Add(dtXMLRow)

'Write XML file

dtXML.WriteXml(XMLFilename)

Next

Can do a quick google and find lot of stuff on this.


text:
Q: is GCM a robust method to keep database in sync? I'm developing a client for a webservice API, some of the data is persistent stored in a SQLite database.
is GCM a robust method to keep the data in sync ?
what I mean is, is GCM push notifications enough for keeping the data in sync or messages might get "lost" or the service might be unavailable ?

A: GCM is primarily designed to serve as a "tickle" mechanism, to help you proactively realize that there is information for you to retrieve by some other means. While it is possible to pack more data than that in 4K payloads, GCM does not have any sort of reliability guarantees, timeliness guarantees, etc.
So, using GCM as an adjunct to polling to keep databases in sync seems perfectly reasonable. Using GCM as the sole delivery mechanism of database changes seems dangerous.


text:
Q: Carriage returns appear for no apparent reason in Sharepoint's task description field I use Sharepoint's task description field as a log for my team's project status updates. I'll enter in a line by sometimes typing it and sometimes copy pasting something from an email.  Later, when I go back to edit or add something else, a bunch of carriage returns have appeared in the description field adding a ton of annoying blank space to the description field.  What causes this?

A: Description field on the Task list is of type multi line of text and by default it is set to allow Enhanced rich text (Rich text with pictures, tables, and hyperlinks) which is why you are getting Carriage returns in your text.
Option 1:
you can change it to plain text if you don't need Rich text
Option 2:
When you enter text that has these characters, you can manually remove them, by clicking on Format Text (from the Ribbon) and click on Edit Source and remove the extra characters you don't like!


text:
Q: String to Float in DataFrame's Column The 5th column of my DataFrame is a list of floats. I want to replace the list with the maximum value from the list. How could I do so?
I'm trying this but I get an error:
import pandas as pd
import numpy as np

colNames = ['unixTime', 'sampleAmount','Time','samplingRate', 'Data']

data = pd.read_csv("project_fan.csv",  sep = ';', error_bad_lines = False, names = colNames)
print(data.head())
data['Data'] = [float(x) for x in data.Data.values]
data['Data'] = [np.array(x).mean()for x in data.Data.values]

Traceback (most recent call last):
  File "new.py", line 9, in <module>
    data['Data'] = [float(x) for x in data.Data.values]
ValueError: could not convert string to float: [1618.6294555664062, 1619.0826416015625, 1620.0897216796875, 1620.0393676757812, 1620.0393676757812, 1620.240783691406, 1620.391845703125, 1620.0897216796875, 1619.435119628906, 1620.4925537109373, 16

Also tried to use astype(float).mean but doesn't work.
Sample DataFrame:
       unixTime  sampleAmount  Time  samplingRate   Data
0  1.556891e+09         16384   340  48188.235294  [1618.6294555664062,1619.0826416015625,1620.489622]
1  1.556891e+09         16384   341  48046.920821  [1619.78759765625,1619.0826416015625,1620.49754]

A: From your error message, it's clear that the data in your "Data" column is stored as a string containing what looks like a Python representation of a list of floats. Which is natural, considering that is coming from a CSV file, which can't otherwise represent a list of numbers in a single column.
You can check that with type(data.Data[0]), which I expect will tell you str.
Since it looks like a Python representation of a list of floats, one good way is to use Python's module to evaluate a Python literal, which you can do with the ast.literal_eval() function. That function is able to interpret Python basic types (integers, floats, strings, lists, tuples, dicts) and it's a safe way to parse contents coming from an external source such as a CSV file.
So you can convert it to an actual list of floats with:
import ast
data['Data'] = data.Data.transform(ast.literal_eval)

Another approach is to claim that this column contains JSON-encoded data and parse it as JSON instead. It turns out in this case, for a list of floats, both the Python and the JSON representation are equivalent, so either method should work. (It's possible the JSON decoding will be faster, JSON is generally simpler than the general Python literal syntax.)
To decode it as JSON (alternative to the above):
import json
data['Data'] = data.Data.transform(json.loads)

At this point (after either Python or JSON conversion), you can use functions such as np.mean on the result, since it's just a list of floats and no longer a string:
data['Data'] = data.Data.apply(np.mean)


text:
Q: Planning a school workshop on the Goldbach Conjecture So I'm doing a mathematics education extension for my current undergraduate maths course, and for one bit of the final assessment we're asked to create a detailed lesson plan on the (strong) Goldbach Conjecture.
Part of the task is to make it a flexible enough plan that it's fairly independent of age and time allotted. We're also assuming the students know at least what primes are.
I've got a few ideas (listed below), but I was just wondering if there's any interesting/novel ways of explaining or exploring the Goldbach Conjecture at primary or secondary student level? There seems to be some interesting symmetry/geometric number line intuition one can draw, but I'm not sure how to make that concrete.
Here's what I got so far,

*

*Explain the conjecture, provide some simple examples to begin

*Visual worksheet to get a 'feel' for it, (eg. Filling in blanks in on a diagram similar to the one on Wikipedia)

*(For secondary students, having not mentioned whether its proved or not), practice forming an induction argument. Why does it fail? (eg. this post.)

*Talk a bit about the twin prime conjecture and how it's related

*(For any age) discuss the difference between showing the conjecture is true for many numbers, and a rigorous proof. (Eg. We know the pythagorean theorem is always true)

Are there any other interesting, mathematical concepts one can easily draw from the Goldbach conjecture?
Thanks!


text:
Q: TypeError : return_entry takes 0 positional arguments but 1 was given ; The converse seems true. Fails with no argument Using Windows 10 , python 3.5 , tkinter 8.6
def return_entry() :
    content = ew.get()
    print(content)

ew = Entry(root, font = myfont, width = 30)
ew.place(x = 170, y = 100)
ew.bind('<Return>', return_entry)

run as above get TypeError. If any string is given as argument , eg  return_entry(anything) the code runs fine. Error message seems to contradict itself.


text:
Q: How to solve Apollo subscriptions "Error during WebSocket handshake: Unexpected response code: 400" I have a legacy application working with React and subscribing to a GraphQL backend. Today, I upgraded all my packages especially thoses (I suppopse that they are the origin of my problem but I'm not sure):

*

*react-apollo from ^2.4.0 to ^3.1.3

*apollo-link-ws from ^1.0.14 to ^1.0.19
The working code was this:
import {ApolloClient} from 'apollo-client';
import {HttpLink} from 'apollo-link-http';
import {WebSocketLink} from 'apollo-link-ws';
// Other imports....

const wsLink = new WebSocketLink({
  uri: `ws://localhost:3000/graphql`,
  options: {
    reconnect: true,
  },
});

const splittedLink = split(
  ({query}) => {
    const {kind, operation} = getMainDefinition(query);
    return (
      kind === 'OperationDefinition' && operation === 'subscription'
    );
  },
  wsLink,
  httpLink,
);

const link = ApolloLink.from([
  onError(({graphQLErrors, networkError}) => {
    // Handle graphQLErrors and networkError
  }),
  withClientState({
    //...
    cache
  }),
  splittedLink
]);

export default new ApolloClient({
  link,
  cache
});

So it's the basic code as described on Apollo website but after the upgrade I'm getting this error (when looking on my graphQL response in the network):

Error during WebSocket handshake: Unexpected response code: 400

and in my dev terminal, I see an infinite logs saying:

Remark
In my setupProxy.js I have ws set to true:
const proxy = require('http-proxy-middleware');

module.exports = app => {
  app.use(proxy('/graphql', {
    target: 'ws://my-backend-url:my-backend-port',
    changeOrigin: true,
    ws: true,
  }));
};

Any feedback or experience about this?


text:
Q: Graviton properties defined In this video Dr.Lincoln says that the weak interaction is weak in low energies because the particles cannot emit the Z and W bosons easily. He mentions the decay of a neutron to a proton an electron and an electron antineutrino.He says the beta decay through the weak interaction happens slowly because for it to happen a W boson with mass 0.002 billion eV/c^2 must be emmited and the W boson has an average mass of 90 billion eV/c^2 -> it is very rare to find a W boson with such low mass which will cause the decay.
He made another video about quantum gravity which highlights some of the properties graviton must have:
averagely massless ( averagely moving at c , does not decay(infinite range) )
electrically neutral
quantum spin = 2 ( gravity is only attractive )
I was wondering according to his first video if gravitons were massless then it would be easy to be emmited from a particle ( fermion) and gravity should be really strong.But on the other hand gravitons must be massless because gravitational waves propagate at c ( special relativity).
So what's the point here?

A: Superficial answer:
Two factors determine the 'strength' of a force.

*

*The coupling constant and

*the mass of the gauge boson

Deeper answer:
The weak and electromagnetic force are unified, i.e. use the same gauge framework and the same coupling. The differentiation of electromagnetic and weak force only happens because of the W/Z masses. For massless W/Z bosons, these beta decays would happen instantly.
Gravity is a different kind of gauge theory that cannot easily be unified with the electroweak theory. It is an open question why the coupling constant is so small. We probably need a completely new unified field theory to explain this.

A: The confusion comes because the video is talking of virtual particles as if they are real particles.
All particle interactions and decays are calculated using Feynman diagrams. The diagrams are an  iconic representation of  the interactions , the diagram can be rigorously translated to  the integral of the interaction, which integral will give the crossection or the decay distributions of the real particles exiting an  interaction
It is called a virtual photon because its invariant mass is off mass shell.

An internal line in an interaction also allows us to see how the quantum  numbers are conserved in the interaction.
The strength of an interaction depends on the coupling constants, whether gravitationsl, electromagnetic,weak, strong, and a propagator representing the virtual particle .
Do not forget that in quantum mechanics everything is distribution of probability.  The probability of exchanging an 80 gev particle is zero, because if the real mass was reached in the integral, there would be a real(on mass shell) W decay and  energy conservation  would be violated. So the video is  hand waving on this part. It just means that the overall probability is depressed because the 80GeV W mass is in the denominator of the propagator, diminishing the integral further than the coupling constants diminish it.

I was wondering according to his first video if gravitons were massless then it would be easy to be emmited from a particle ( fermion) and gravity should be really strong.But on the other hand gravitons must be massless because gravitational waves propagate at c ( special relativity).

Spontaneous emission does not happen either with photons, an interaction has to happen for a photon to be emitted from a charged particle, see this as an example, otherwise energy would be violated.
The same is true for graviton radiation, and as the coupling of gravity is so very small, it is not detectable in the lab, the way bremsstrahlung  is .


text:
Q: SSRS 2005: How do I create a collapsible Text Field in Table? I have a batch detail report in SSRS 2005, the left most column is an NTEXT SQL field. I need to show the field in the report either as:
1). A collapsible text box so users can view detail in the field by clicking the expansion control OR
2). As a tool tip, so when users hover over the column, they can view the full detail
I can find code to collapse or expand all columns (i.e. the entire row) but not for a single text box in a table.
Any assistance greatly received, thanks!

A: I don't know how to make a collapsible text box in SSRS, but there is a ToolTip property for text boxes - just select the Text Box, then select the required value for the ToolTip property from the dropdown list of expressions in the Properties window.
The tool tip is only displayed in browsers, not in preview mode in the SQLServer BIDS report designer (as far as I can tell).


text:
Q: How to show the Systray Icon and also the corresponding executable in the taskmanager by default when we run the installer using NSIS? My requirement is: When i installed a software using NSIS, once the installation is successfully completed it should show a notification icon (systray icon).
I am able to create the installer with the required dlls, executables and other files. But it is not showing the systray icon automatically.

A: Use ExecShell, Exec or ExecWait to start a new process:
Section
SetOutPath $INSTDIR
File "something\Display.exe"
ExecShell "" "$INSTDIR\Display.exe"
SectionEnd

If you are using the Modern UI then you can put a run checkbox on the finish page instead if you want to give the user the option of not running the app:
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!define MUI_FINISHPAGE_RUN "$INSTDIR\Display.exe"
!insertmacro MUI_PAGE_FINISH
!insertmacro MUI_LANGUAGE "English"

Section
SetOutPath $INSTDIR
File "something\Display.exe"
SectionEnd


text:
Q: Change the y-axis limits in a ggplot of multiple plots I have the following ggplot:

that is generated using the following script:
df_long <- melt(df)

ggplot(df_long, aes(x = variable, y = value)) +
  geom_boxplot() +
  facet_wrap(~variable, scales = 'free', ncol = 6)

I would like to change the y-axis limits to start with 0 and end with the maximum value for each variable, and also to have the same breaks for all the variables. Currently, the AC and ND are fine since they have same breaks (their labels are even aligned) but the other variables are different. For the NV and IC, they don't end with the maximum value and they don't have the same breaks as with AC and ND. For the PIC and DBI, they don't have the same breaks as with AC and ND. In other woeds, I want all y axes to be aligned and look elegant.
Do you have any idea how to fix that?

A: You need to specify your requirements for the y axis and set it up with the scale_y_continuous statement.
The breaks argument can be a function returning breaks from the given data, so you can set up a function to give a sequence of set length between its min and max values.
Note that these axis values may not make much sense (eg. 2.09, 2.83, ...) but they will be at the same y positions on the graph.
The selected break values are pretty unreadable so we can also specify a function for the labels argument that takes the breaks as input and returns the rounded labels.
library(ggplot2)
# generate dummy data
set.seed(2)
df <- data.frame(var = sample(LETTERS[1:4], 1000, replace = T),
                 val = abs(rnorm(1000)))
df$val[df$var%in%c("B", "D")] <- df$val[df$var%in%c("B", "D")] / 2
head(df)

# actual plotting
my_breaks <- function(x){seq(min(x), max(x), length.out = 5)}
my_labels <- function(x){round(x, digits = 2)}

ggplot(df, aes(x=var,y=val)) + geom_boxplot() + facet_wrap(~var, scales = 'free', ncol = 4) +
  scale_y_continuous(breaks = my_breaks, labels = my_labels)

This outputs the following graph

EDIT : adding some constraints to the axes
If you want to restrain your axes to specific ranges, you have to play around with the my_breaks() function definition. I'll give you a few examples below as per your comments.

*

*Start the axes on 0 :
my_breaks <- function(x){seq(0, max(x), length.out = 5)}

*End the on 1 or max value if smaller :
my_breaks <- function(x){seq(min(x), min(1, max(x)), length.out = 5)}
I'm sure you can figure out the specific requirements to your needs ;)


text:
Q: Jmeter. Как собрать в массив и потом использовать данные из json К примеру ответ вернул
{
    "success": true,
    "data": [
        {
            "IntDocNumber": "20600008976239"
        },
        {
            "IntDocNumber": "20600008982575"
        },
        {
            "IntDocNumber": "20600008982554"
        },
..............................
как мне собрать значения для ключей "IntDocNumber" и далее использовать?

A: *

*Добавьте JSON Extractor к тому элементу, который возвращает этот ответ

*Настройте его примерно вот так:

*На выходе вы получите следующие переменные (можно посмотреть при помощи Debug Sampler и View Results Tree Listener):
IntDocNumber_1=20600008976239
IntDocNumber_2=20600008982575
IntDocNumber_3=20600008982554
IntDocNumber_matchNr=3

*View Results Tree также позволяет тестить JSON Path выражения при помощи JSON Path Tester, в этом случае не нужно перезапускать тест и добавлять Debug Sampler

*Обычно переменные такого вида используют, например, в ForEach Controller


text:
Q: Clicking the action part of @angular/service-worker push notifications I've been trying to redirect users to the "action" part of Web push coming from the backend (PHP).
    return (new WebPushMessage)
        ->title('Title')
        ->icon('icon.png')
        ->body('Body Msg')
        ->action('Open Notification', 'open_notification')
        ->data(['id' => $notification->id,'url'=>'http://somewhere']);

Default service workers use:
self.addEventListener('notificationclick', function(event) {
    console.log('On notification click: ', event.notification.tag);
    event.notification.close();

    // This looks to see if the current is already open and
    // focuses if it is
    event.waitUntil(clients.matchAll({
       type: "window"
    }).then(function(clientList) {
       for (var i = 0; i < clientList.length; i++) {
          var client = clientList[i];
              if (client.url == '/' && 'focus' in client)
                 return client.focus();
       }
       if (clients.openWindow)
          return clients.openWindow('/');
    }));
});

From https://developer.mozilla.org/en-US/docs/Web/Events/notificationclick
Angular 5 uses
import {SwPush, SwUpdate} from '@angular/service-worker';

My question then is how to interpret this in the front end (Angular 5) using @angular/service-worker

A: Got a response from u-ryo on Github
There is a workaround.
Add the codes below to ngsw-worker.js around the line
this.scope.addEventListener('push', (event) => this.onPush(event));(Line 1775).
  this.scope.addEventListener('notificationclick', (event) => {
    console.log('[Service Worker] Notification click Received. event', event);
    event.notification.close();
    if (clients.openWindow && event.notification.data.url) {
      event.waitUntil(clients.openWindow(event.notification.data.url));
    }
  });

Then you can specify the URL in the "notification.data.url".
https://github.com/angular/angular/issues/20956#issuecomment-374133852

A: If you want to have actions, and each action with a different url, here is my fix.
    this.scope.addEventListener('notificationclick', (event) => {
        event.notification.close();
        var payload = event.notification.data;
        var url = payload.url;
        if (event.action && payload.actions && payload.actions.length) {
            var actions = payload.actions.filter(x => x.action == event.action);
            if (actions.length && actions[0].url) {
                url = actions[0].url;
            }
        }
        if (clients.openWindow && url) {
            event.waitUtil(clients.openWindow(url));
        }
    });


text:
Q: Long URL in Spring MVC application I'm creating a Spring MVC application using a lot of form inputs and model attributes with multiple List fields.On my jsp page I have something like catalog in which user can specify which product of different size he want's to order.
index.jsp:

Фундаментные блоки

Размер L H B

Кол

                            <c:forEach items="${FBContainer.products}" varStatus="i" var="product">

${product.toString()}

                                    <form:input cssClass="amount_input"
                                                path="fbContainer.products[${i.index}].amount"/>

                            </c:forEach>

Плиты перекрытия

Размер L H B

Кол

                            <c:forEach items="${CPContainer.products}" varStatus="i" var="product">

${product.toString()}

                                    <form:input cssClass="amount_input"
                                                path="cpContainer.products[${i.index}].amount"/>

                            </c:forEach>

So, in forEach loop I create an input for amount for every kind of product. And every product type(there is 6 of them) has its own container.
Something like CPContainer:
public class CPContainer implements Container {

    private List<CPProduct> products;
    private int id;
    private int amount;

    @Override
    public List<CPProduct> getProducts() {
        return products;
    }

    @Override
    public CPProduct getProductById(int id) {
        return products.get(id);
    }

    public void setProducts(List<CPProduct> products) {
        this.products = products;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }

    @Override
    public String toString() {
        return "CPContainer{" +
                "products=" + products +
                ", id=" + id +
                ", amount=" + amount +
                '}';
    }
}

Not sure if that's a problem but when I fill the form, on order's page I see a very long URL,with many parameters :
http://localhost:8080/calculate?fbContainer.products%5B0%5D.amount=3&fbContainer.products%5B1%5D.amount=2&fbContainer.products%5B2%5D.amount=0&cpContainer.products%5B0%5D.amount=0&cpContainer.products%5B1%5D.amount=0&cpContainer.products%5B2%5D.amount=0&jumperContainer.products%5B0%5D.amount=0&jumperContainer.products%5B1%5D.amount=0&jumperContainer.products%5B2%5D.amount=0&vbContainer.products%5B0%5D.amount=0&vbContainer.products%5B1%5D.amount=0&vbContainer.products%5B2%5D.amount=0&bbContainer.products%5B0%5D.amount=0&bbContainer.products%5B1%5D.amount=0&bbContainer.products%5B2%5D.amount=0&pbContainer.products%5B0%5D.amount=0&pbContainer.products%5B1%5D.amount=0&pbContainer.products%5B2%5D.amount=0.
Is this bad, or should I leave it like that?

A: Use POST method in place of GET. GET request generate request parameter which are visible in URL.
Like this:


text:
Q: unique_ptr swap doesn't work My code is:
#include <memory>
#include <vector>

struct Core{
    Core(int n){} };

int main() {
    int base;
    std::vector<std::unique_ptr<Core>> cores;

    cores.push_back( std::move(std::unique_ptr<Core>(new Core(base))) );
    cores[0].swap(std::unique_ptr<Core>(new Core(base)));

    return 0;
}

And I get this error:

||=== Build: Release in Test (compiler: GNU GCC Compiler) ===|
In function 'int main()' error: no matching function for call to 'std::unique_ptr<Core>::swap(std::unique_ptr<Core>)'
note: candidate is:
note: void std::unique_ptr<_Tp,_Dp>::swap(std::unique_ptr<_Tp,_Dp>&) [with_Tp = Core; _Dp = std::default_delete<Core>]
note: no known conversion for argument 1 from 'std::unique_ptr<Core>' to 'std::unique_ptr<Core>&'

A: You can not swap with a temporary object (an rvalue) like this:
cores[0].swap(std::unique_ptr<Core>(new Core(base))); // error

But a temporary can swap with a named object (lvalue) like this
std::unique_ptr<Core>(new Core(base)).swap(cores[0]); // but this works

Alternatively you can just set the value directly:
cores[0] = std::unique_ptr<Core>(new Core(base));

Or (better) using std::make_unique
cores[0] = std::make_unique<Core>(base);

You pass the parameters for the object's constructor directly to the std::make_unique function.
And if you must use new there is always the std::unique_ptr::reset function:
cores[0].reset(new Core(base));

A: You are using std::move too much. In your cases, the move happens automatically. So, you can just write
cores.push_back( std::unique_ptr<Core>(new Core(base)) );
cores[0] = std::unique_ptr<Core>(new Core(base));

Or, using std::make_unique and std::unique_ptr::reset,
cores.push_back( std::make_unique<Core>(base) );
cores[0].reset(new Core(base));

If, however, you had your unique_ptr, say, as a local variable, you'd have to use std::move:
std::unique_ptr<Core> p(new Core(base));
cores.push_back(std::move(p));

This is as efficient as the above, but creates a potentially needless local variable.

A: You need an lvalue std::unique_ptr<Core> to swap with, an unnamed temporary isn't allowed.
What you can do is
cores.push_back(std::unique_ptr<Core>(new Core(base))); // don't need move here
{
    std::unique_ptr<Core> other(new Core(base));
    cores[0].swap(other);
}


text:
Q: Passing selected parameters from a page to another page I've 2 pages:
Moods page

         Angelic

         Angry

         Anxious

         Assertive

         Bored

         Confident

         Cranky

         Depressed

         Dissapointed

         Distrustful

         Embarrassed

         Emotional

         Evil

         Excited

         Exhusted

         flirtatious

         forgetful

Javascript:
function saveSmileys() {
        /* var a = document.getElementById("angelic");
        var b = document.getElementById("angry");
        var c = document.getElementById("anxious");
        var d = document.getElementById("assertive");
        var e = document.getElementById("bored");
        var f = document.getElementById("confident");
        var g = document.getElementById("cranky");
        var h = document.getElementById("depressed");
        var i = document.getElementById("disappointed");
        var j = document.getElementById("distrustful");
        var k = document.getElementById("emotional");
        var l = document.getElementById("evil");
        var m = document.getElementById("excited");
        var n = document.getElementById("exhausted");
        var o = document.getElementById("flirt");
        var p = document.getElementById("forget");
         */
        /* if (a & b & c & d & e & f & g & h & i & j & k & l & m & n & o
                & p == true) { */

        /*          var ang = parseInt(a);
         var an = parseInt(b);
         var anx = parseInt(c);
         var asse = parseInt(d);
         var bo = parseInt(e);
         var co = parseInt(f);
         var cr = parseInt(g);
         var de = parseInt(h);
         var dis = parseInt(i);
         var distr = parseInt(j);
         var em = parseInt(k);
         var ev = parseInt(l);
         var ex = parseInt(m);
         var exh = parseInt(n);
         var fl = parseInt(o);
         var fo = parseInt(p); */

        $(function() {
            $("#savesmiley").bind(
                    "click",
                    function() {
                        var url = "notes.html?Angelic="
                                + encodeURIComponent($("#angelic").val())
                                + "&Angry="
                                + encodeURIComponent($("#angry").val())
                                + "&Anxious="
                                + encodeURIComponent($("#anxious").val())
                                + "&Assertive="
                                + encodeURIComponent($("#assertive").val())
                                + "&Bored="
                                + encodeURIComponent($("#bored").val())
                                + "&Confident="
                                + encodeURIComponent($("#confident").val())
                                + "&Cranky="
                                + encodeURIComponent($("#cranky").val())
                                + "&Depressed="
                                + encodeURIComponent($("#depressed").val())
                                + "&Disappointed="
                                + encodeURIComponent($("#disappointed").val())
                                + "&Distrustful="
                                + encodeURIComponent($("#distrustful").val())
                                + "&Embarassed="
                                + encodeURIComponent($("#embarassed").val())
                                + "&Emotional="
                                + encodeURIComponent($("#emotional").val())
                                + "&Evil="
                                + encodeURIComponent($("#evil").val())
                                + "&Excited="
                                + encodeURIComponent($("#excited").val())
                                + "&Exhausted="
                                + encodeURIComponent($("#exhausted").val())
                                + "&Flirtatious="
                                + encodeURIComponent($("#flirt").val())
                                + "&Forgetful="
                                + encodeURIComponent($("#forget").val());
                        window.location.href = url;
                        console.log(url);
                    });
            var QueryString = function() {

                var query_string = url;
                var query = window.location.search.substring(1);
                var vars = query.split("&");
                for (var i = 0; i = vars.length; i++) {

                    var pair = vars[i].split("=");
                    if (typeof query_string[pair[0]] === "undefined") {

                        query_string[pair[0]] = pair[1];

                    } else if (typeof query_string[pair[0]] === "string") {

                        var arr = [ query_string[pair[0]], pair[1] ];
                        query_string[pair[0]] = arr;

                    } else {

                        query_string[pair[0]].push(pair[1]);

                    }

                }

                console.log(query_string[pair[i]]);

            }
            alert("Moods have been saved");
        });

    }

console.log(url); produces this output in console:
 notes.html?Angelic=&Angry=&Anxious=&Assertive=undefined&Bored=&Confident=&Cranky=&Depressed=&Disappointed=&Distrustful=&Embarassed=&Emotional=&Evil=&Excited=&Exhausted=&Flirtatious=&Forgetful=

But values of smileys like Assertive, Evil etc aren't getting appended to the url. How can I fix it? I think that if values are appended to url successfully, then I can pass the paramenters to another page.


text:
Q: Copy and paste across logout/reboot? Is there an application or feature that allows a copy and paste across log outs or reboots?
Linux rome 4.8.0-32-generic #34-Ubuntu SMP Tue Dec 13 14:30:16 UTC 2016 i686 i686 i686 GNU/Linux

A: A quick Google for "linux persistent clipboard" gave a few sites listing several clipboard managers for Linux with various options for history management - I'm sure at least one of them will do what you want!
http://www.tecmint.com/best-clipboard-managers-for-linux/


text:
Q: How to solve "TypeError: invoker is not a function" in Jest test case? I ran the test using ramda with jest and I am getting the following error.
Error code
I don't know why, but the pointer appears on line 7, floor method probably has nothing to do with it.
> jest_sample@1.0.0 test /app
> jest

 FAIL  Tests/Utils/StringUtils.test.js
  ● Test suite failed to run

    TypeError: invoker is not a function

       5 |   if (!Number.isFinite(num)) return '';
       6 |
    >  7 |   const intValue = num > 0 ? Math.floor(num) : Math.ceil(num);
         |                                     ^
       8 |
       9 |   const decimalStr = String(num).indexOf('.') > -1 ? `.${String(num).split('.')[1]}` : '';
      10 |

      at Object.<anonymous> (node_modules/ramda/src/join.js:27:1)
      at Object.<anonymous> (app/StringUtil.js:7:37)
      at Object.<anonymous> (Tests/Utils/StringUtils.test.js:1:2)

Here is the relevant code where the error occurred.
src
import R from 'ramda';

export const commize = num => {
  if (!Number.isFinite(num)) return '';

  const intValue = num > 0 ? Math.floor(num) : Math.ceil(num);

  const decimalStr = String(num).indexOf('.') > -1 ? `.${String(num).split('.')[1]}` : '';

  const intStr = R.pipe(Math.abs, R.toString, R.split(''), R.reverse, R.splitEvery(3), R.intersperse(','), R.flatten, R.reverse, R.join(''));
  return num < 0 ? `-${intStr(intValue)}${decimalStr}` : `${intStr(intValue)}${decimalStr}`;
};

test code
 import {
  commize,
} from '../../app/StringUtil';

test('commize', () => {
  expect(commize(123456)).toEqual('123,456');
  expect('123').toEqual(commize(123));
  expect('23,456').toEqual(commize(23456));
});

babel.config.js
module.exports = {
  presets: [
    'module:metro-react-native-babel-preset',
    '@babel/preset-flow',
  ],
  plugins: [
  ],
  env: {
    test: {
      presets: [
        '@babel/preset-react',
        ['@babel/preset-env', {
          modules: false,
        }],
      ],
      plugins: [
        '@babel/plugin-proposal-class-properties',
        'ramda',
      ],
    },
  },
};

I've tried the following, but it didn't work.

*

*I have changed the babel settings, referring to the official documentation
If you know how to fix the problem, please let me know. Thank you for reading my question.


text:
Q: Limit the maximum value of the composition of an integer I was doing a coding test (already finished, so no cheating for me) and came across this problem, which I'll describe in few steps:

*

*We have a keypad, like on cellphones, with keys from 1 to 9, where 1 is the space key (" ")

*We are given a message to convert to numbers based on the "distance" of each letter (P = 7, S = 7777, K = 55, ...), for example DRSA becomes 377777772

*Now we need to calculate the the number of the possible messages we could write with that same number (DPPPPPPPA, DPPPPPQA, ...)

The method I came up with is the following:

*

*I split the number by its different digits obtaining for example 3, 7777777, 2

*I ignored single digits as they do not add "value" to the permutations (as far as I understood it)

*I take each section of digits and based on its length (in this case 7 digits) I calculate every possible permutation and count them

Now this method works, but it's slow so I wanted to find a way to calculate the number of these permutations without counting them manually.
I found out about integer compositions, which in my case should have a maximum value. In this case the key 7 has a maximum value of 4 so its composition would be something like this:

*

*4+3

*3+4

*4+1+2

*4+2+1

*1+2+4

*1+4+2

*...

How can I limit the maximum value of the composition (4) of a number (7)? How can I know the number of elements in it?

A: For numbers limited to $3$ you have the Tribonacci numbers, OEIS A000073, which begin $$ 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504,$$ and for numbers limited to $4$ you have the Tetranacci numbers, OEIS A00078 which begin $$ 1, 2, 4, 8, 15, 29, 56, 108, 208, 401, 773, 1490,$$
Each number in the Tribonacci series is the sum of the previous three, because to get a composition of $n$ you can take a composition of $n-1$ and add a $1$, a composition of $n-2$ and add a $2$, or a composition of $n-3$ and add a $3$.

A:
How can I know the number of elements in it?

Two-variable recurrence. If $a_m(n, k)$ is the number of compositions of $k$ numbers from $1$ to $m$ which total $n$ then $$a_m(n, k) = \begin{cases}
0 & \textrm{if } n < 0 \\
1 & \textrm{if } n=0, k=0 \\
0 & \textrm{if } n=0, k \neq 0 \\
\sum_{i=1}^m a_m(n-i, k-1) & \textrm{otherwise}
\end{cases}$$
For practical computation, you would want to use dynamic programming.


text:
Q: Strip all characters after a delimiter in filenames I have filenames in a directory in the format of "APP_ENTITY_part___20120910.txt"
I would like to strip off everything after the 3 underscores and keep the first portion of the filename.
Is there a good website that could direct me in how to accomplish this?
Or, maybe one of you dos batch experts can lead me in how to do this?

A: There is a very simple solution that uses variable expansion search and replace to inject a REM command.
@echo off
setlocal
for %%F in (*) do call set "var=%%F" & call :procName
exit /b

:procName
::truncate at the 1st occurance of ___
set "var=%var:___="&rem %
::print the result
set var
exit /b

The critical line is set "var=%var:___="&rem %
Suppose var=Part1___Part2
After substitution, the line becomes: set "var=Part1"&rem Part2
The above solution truncates at the first occurance of ___.
A name like Part1___Part2___Part3 will result in Part1.
If you want to truncate at the last occurance of ___ and get a result like Part1__Part2, then the solution is more complicated.
I use search and replace to change ___ to a folder delimiter, then a 2nd FOR with the ~p modifier to strip off the last part, and then search and replace to restore the leading ___ delimiter(s).
@echo off
setlocal disableDelayedExpansion
for %%F in (*) do (
  set "var=%%F"
  setlocal enableDelayedExpansion
  set "var2=!var:___=\!"
  if "!var2!" neq "!var!" for %%A in ("\!var2!") do (
    endlocal
    set "var=%%~pA"
    setlocal enableDelayedExpansion
    set "var=!var:~1,-1!"
    set "var=!var:\=___!"
  )
  echo var=!var!
  endlocal
)

A: You can install Cygwin or some alternative (with the proper libraries included, like the "rename" program) and use one of the top two answers from this SO question (pasted below). You may want to test the regular expressions and globs before implementing either of these:
rename 's/___(.*)\.txt/\.txt/' *_part___*.txt
or
for f in *_part___*.txt; do mv $f $(echo $f | sed 's/___(.*)\.txt/\.txt/g'); done

A: A simple one-line solution for you:
set DirNam=%DirNam:~,-12%

This will work for you if you are always just stripping 4 underscores plus a date ____YYYYMMDD from the end of the name.
Maybe sort out other Directory names by doing this:
setlocal enabledelayedexpansion
for /d %%x in (*____????????) do (
  set DirNam=%%x
  set DirNam=!DirNam:~,-12!
  echo %%x is now !DirNam!
)


text:
Q: Mac OS X: Trying to install prolog using fink I am trying to install prolog on Mac OS X 10.4.11.
I just downloaded fink because I think that that should help me and I am trying to get either:
Package swi-prolog-5.8.1-2
or
Package gprolog-1.3.1-1
But I am not having any luck.
Here is what I was doing:
% fink install swi-prolog-5.8.1-2
Information about 1723 packages read in 0 seconds.
Failed: no package found for specification 'swi-prolog-5.8.1-2'!
%

Question 1: Are these what I want to download?
Question 2: Why isn't fink working?

Update
% apt-cache search prolog --full
Package: yap
Source: yap
Version: 4.4.4-1002
Priority: optional
Section: languages
Maintainer: Matthias Neeracher <neeracher@mac.com>
Depends: readline-shlibs (>= 4.3-1028), gmp-shlibs (>= 4.1.4-1), libmpfr1-shlibs, darwin (>= 8-1)
Architecture: darwin-i386
Filename: dists/fink-0.8.1/main/binary-darwin-i386//languages/yap_4.4.4-1002_darwin-i386.deb
Size: 2112546
Installed-Size: 6400
MD5sum: f78c8cd4534426ac799dae84ff3fea14
Description: Yet another prolog
 A high speed implementation of the Prolog programming language.
 .
 Web site: http://yap.sourceforge.net
 .
 Maintainer: Matthias Neeracher <neeracher@mac.com>
builddependsonly: Undefined

Question: Does this mean that Prolog is installed?  How do I find out where?

A: I believe it should be:
fink install swi-prolog

The package name is swi-prolog.  Fink will take care of getting the right version.  You may also find apt-cache helpful:
apt-cache search prolog

EDIT: I think the issue is that swi-prolog and gprolog are in the unstable section.  The Fink FAQ explains how to turn unstable on.  After following those instructions, you should be able to install them.
yap comes up in apt-cache because it is in the stable section.  However, it's not installed.  If you choose to use that, you still have to do:
fink install yap


text:
Q: How to change column name based on given month in sql server 2008R2 i want to show my pivot table column name as Monday 1,Tuesday 2 based on the month from  the given date...i.e if it is July the month then Monday 1 Tuesday 2 so on for all days of the month..
this is my coding how to achieve this
set @query='SELECT
        P.tenant_id,CI.companyname,BM.brandname,bl.buildingname,T.Unitname,tm.tradecategoryname,l.locationname,T.adsrid,T.carpetarea,T.chargeablearea,
        P.[1],P.[2],P.[3],P.[4],P.[5],P.[6],P.[7],P.[8],P.[9],P.[10],P.[11],P.[12],P.[13],P.[14],P.[15],P.[16],P.[17],
        P.[18],P.[19],P.[20],P.[21],P.[22],P.[23],P.[24],P.[25],P.[26],P.[27],P.[28],P.[29],P.[30],P.[31]
        FROM
        (
        select tenant_id,Day1=day(RECEIPT_DATE),Net_Amt from Daywiseconsolidate WITH(NOLOCK)
         where tenant_id in (' + @filter + ') and month(receipt_date)='+ convert(nvarchar(2),month(@fromdate)) +' and year(receipt_date)='+convert(nvarchar(4),year(@fromdate))+'
    ) A
    PIVOT
    (
    SUM(NET_AMT)
    FOR DAY1 IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],
    [18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
    ) AS P
    inner join tenant T on P.tenant_id=T.adsrid
    left outer join locationmaster l on t.locationId=l.locationId
    left outer join companyinfo CI on T.companyid=CI.companyid
    left outer join brandmaster BM on T.brandid=BM.brandid
    left outer join buildingmaster bl on t.buildingid=bl.buildingid
    left outer join tradecategorymaster tm on T.tradecategory=tm.tradecategoryid
    where bl.active=''Y'' and tm.active=''Y'''

i tried like this for day 1 column as Monday 1 but it didnt woked!!
SELECT
P.tenant_id,CI.companyname,BM.brandname,bl.buildingname,T.Unitname,tm.tradecategoryname,
l.locationname,T.adsrid,T.carpetarea,T.chargeablearea,
**P.[1] as datename(dw,dateadd(dd,-(day(@FromDate)-1),@FromDate))+' '+datename   (day,dateadd(dd,-(day(@FromDate)-1),@FromDate))**,
P.[2],P.[3],P.[4],P.[5],
P.[6],P.[7],P.[8],P.[9],P.[10],P.[11],P.[12],P.[13],P.[14],P.[15],P.[16],P.[17],
P.[18],P.[19],P.[20],P.[21],P.[22],P.[23],P.[24],P.[25],P.[26],P.[27],P.[28],P.[29],
P.[30],P.[31]

FROM
(
select tenant_id,Day1=day(RECEIPT_DATE),Net_Amt from Daywiseconsolidate WITH(NOLOCK)
where tenant_id in (select adsrid from tenant where active='Y' ) and
month(receipt_date)=9 and year(receipt_date)=2011
) A

PIVOT
(
SUM(NET_AMT)
FOR DAY1 IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],
[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) AS P

inner join tenant T on P.tenant_id=T.adsrid
left outer join locationmaster l on t.locationId=l.locationId
left outer join companyinfo CI on T.companyid=CI.companyid
left outer join brandmaster BM on T.brandid=BM.brandid
left outer join buildingmaster bl on t.buildingid=bl.buildingid
left outer join tradecategorymaster tm on T.tradecategory=tm.tradecategoryid
where bl.active='Y' and tm.active='Y'

could you please help me to get those desired columns


text:
Q: Comparing two dates results 0 so i'm currently making a small php application and I need to compare two dates to get the number of days between them.
I sadly can't use datediff() since the php version is 5.2.
I've search how to do and I found a lot of answers but I always have the same problem. When I make the difference between my dates, I always got 0 as a result.
function date_diff($dateFrom, $dateTo) {
    echo $dateFrom->format('d-m-Y') . " : " . $dateTo->format('d-m-Y') . '
';
    $diff = abs($dateTo-$dateFrom);

    return sprintf
    (
        "%d Days, %d Hours, %d Mins, %d Seconds",
        intval( $diff / 86400 ),
        intval( ( $diff % 86400 ) / 3600),
        intval( ( $diff / 60 ) % 60 ),
        intval( $diff % 60 )
    );
}

I currently use this function and the parameters are here :
    while ($donnees = mysqli_fetch_array($res))
        $date = new DateTime($donnees['Date']);

    $date = date_create($date->format("Y-m-d"));
    $today = new DateTime();

    echo $utilDate->date_diff($date, $today);

My $date and $today variables are not empty, so I don't understand why this code doesn't work.
Does anyone have an idea?

A: I think $dateTo and $dateFrom are objects and you are doing a substraction on them in $diff = abs($dateTo-$dateFrom);
Try $diff = abs($dateTo->getTimestamp()-$dateFrom->getTimestamp());

A: You want to use the diff operator:
function date_diff($dateFrom, $dateTo) {
    echo $dateFrom->format('d-m-Y') . " : " . $dateTo->format('d-m-Y') . '
';
    $diff = $dateNow->diff($dateTo);

    $day = $diff->format('%d');
    $hour = $diff->format('%h');
    $min = $diff->format('%i');
    $seconds = $diff->format('%s');

    return /*string involving above formats*/;
}


text:
Q: How to retrieve values from from a table with Foreign Keys in Java? I'm a bit new to Java and Spring and I have encountered a problem while trying to complete an assignment for a course I'm following.
What I had to do was to create a online shop in Spring MVC while connecting the web app to a MySQL database - the first JSP with Clients where I would have the options to display, add, delete and modify clients - the second JSP with Products having the same options available(display, add, delete and modify) - and the last JSP with Sales or Transactions.
The Models/Beans
public class Client {
private int clientID;
private String firstname;
private String lastname;
private String address;
private String city;
private String country;

public Client(){
}

public Client(int clientId){
    this.clientID=clientId;
}

public int getClientID() {
    return clientID;
}

public void setClientID(int clientID) {
    this.clientID = clientID;
}

public String getFirstname() {
    return firstname;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}

public String getLastname() {
    return lastname;
}

public void setLastname(String lastname) {
    this.lastname = lastname;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

}
public class Sale {
private int saleId;
private Client client_id;
private Product productId;

public Sale() {
}

public int getSaleId() {
    return saleId;
}

public void setSaleId(int saleId) {
    this.saleId = saleId;
}

public Client getClientId() {
    return client_id;
}

public void setClientId(Client client_id) {
    this.client_id = client_id;
}

public Product getProductId() {
    return productId;
}

public void setProductId(Product productId) {
    this.productId = productId;
}

}
public class Product {
private int productId;
private String productName;
private double unitPrice;
private String description;
private long unitsInStock;

public Product(){}

public Product(int productId){
    this.productId=productId;
}

public int getProductID() {
    return productId;
}

public void setProductID(int productId) {
    this.productId = productId;
}

public String getProductName() {
    return productName;
}

public void setProductName(String productName) {
    this.productName = productName;
}

public double getUnitPrice() {
    return unitPrice;
}

public void setUnitPrice(double unitPrice) {
    this.unitPrice = unitPrice;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public long getUnitsInStock() {
    return unitsInStock;
}

public void setUnitsInStock(long unitsInStock) {
    this.unitsInStock = unitsInStock;
}

}
The problem is in SaleDAO.java class where the getSales() method does not allow me to retrieve the values from the db.
The clients table has clientId(PK), firstname, lastname, address, city, country as rows.
products - productId(PK), productName, unitPrice, description and unitsInStock
sales - saleId(PK), client_id(FK) related to clients (clientId), product_id(FK) related to products (productId).
public class SaleDAO {
private final Connection conn;

public SaleDAO() {

    conn = DBConnection.getConnection();
}

public void addSale(Sale sale) {
    try {

        String sql = "INSERT INTO sales(saleId, client_id, product_id) VALUES (?,?,?)";

        PreparedStatement ps = conn.prepareStatement(sql);

        ps.setInt(1, sale.getSaleId());
        ps.setInt(2, sale.getClientId().getClientID());
        ps.setInt(3, sale.getProductId().getProductID());

        ps.executeUpdate();

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

public void removeSale(int saleId) {
    try {

        String sql = "DELETE FROM sales WHERE saleId=?";

        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1, saleId);
        ps.executeUpdate();

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

public void editSale(Sale sale) {
    try {

        String sql = "UPDATE sales set client_id=? ,product_id=? where saleId=?;";

        PreparedStatement ps = conn.prepareStatement(sql);

        ps.setInt(1, sale.getClientId().getClientID());
        ps.setInt(2, sale.getProductId().getProductID());
        ps.setInt(3, sale.getSaleId());

        ps.executeUpdate();

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

public List getSales() {

    List saleList = new ArrayList();
    try {

        String sql = "SELECT * FROM sales";

        PreparedStatement ps = conn.prepareStatement(sql);

        ResultSet rs = ps.executeQuery();

        while (rs.next()) {

            Sale sale = new Sale();

            sale.setSaleId(rs.getInt("saleId"));
            sale.setClientId(rs.getInt("client_id"));
            sale.setProductId(rs.getInt("product_id");

            saleList.add(sale);
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }
    return saleList;
}

public Sale getSaleById(int saleId) {

    Sale sale = new Sale();
    try {
        String sql = "SELECT * FROM sales WHERE saleId=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1, saleId);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {

            sale.setSaleId(rs.getInt("saleId"));
            sale.setClientID(rs.getInt("client_id"));
            sale.setProductID(rs.getInt("product_id"));

        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return sale;
}

}

A: ResultSet.getInt() returns an int.
sale.setClientID() expects an argument of type Client.
And yet you're calling
sale.setClientId(rs.getInt("client_id"));

That can't possibly compile: an int is not a Client.
Your Sale class should not contain instances of Client and Product. Just like in the database row that a Sale is supposed to represent, the clientId should be an int, not a Client.
Or, if a Sale is supposed to represent a Sale, its client, and its product, your SQL query should return all of that information, and not just the ID of the client and the product. That's where joins are useful. A less efficient alternative would be to execute 3 queries: one that retrieves the sale, a second one that retrieves the client, and a third one that retrieves the product. And once all the information is available, you can finally create your Sale object and return it.
If you go that way, then please rename Sale.clientId to Sale.client: the attribute represents a complete client, not just the ID of a client.


text:
Q: Terminal adds extra spaces after $ when running history commands with up and down arrows I tried to update my terminal for a better look. I followed this guide here.
I got the result I wanted but when I try to see previous commands with up and down arrows, it freezes the terminal to start at a random midpoint of the terminal. Also, I noticed that this happens when there is a longer command in my history like connecting a remote desktop with ssh.
These are my edits on ".bashrc"
force_color_prompt=yes
color_prompt=yes
parse_git_branch() {
 git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
if [ "$color_prompt" = yes ]; then
 PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\>
else
 PS1='${debian_chroot:+($debian_chroot)}\u@\h:\W$(parse_git_branch)\$ '
fi
unset color_prompt force_color_prompt

export PS1='\[\e[01;32m\][\W]=>\e[0m\] :\e[01;33m\]$(parse_git_branch)$\e[37;1m\]\]'
PS1=$PS1'\[\e]2;\u@\w\a\]' #set teminal title


text:
Q: IIS Rewriting url with parameter I'm trying to setup rewrite for url from /place/search-the-places/item-detail/id=123 to /place/explore-our-places/item-detail/id=123
but it doesn't work, what I'm doing wrong?
<rewrite>
        <rules>
            <rule name="Collections" stopProcessing="true">
                <match url="^place/search-the-places/item-detail/id=([0-9]+)" ignoreCase="true" />
                <action type="Redirect" url="/place/explore-our-places/item-detail/?id={R:1}" />
                <conditions>
                </conditions>
            </rule>
        </rules>
    </rewrite>

Thanks!

A: If you just want to match numeric id as a parameter, then instead of
id=([0-9]+)/([_0-9a-z-]+)

use
id=([0-9]+)

because the slash between regexes means your route is like this
/place/search-the-places/item-detail/id=123/end-of-route

and this is not true, I suppose.
Also try using type="Rewrite" instead of "Redirect".


text:
Q: Changing hosts file using c++ or directly I want to block
     websites on browser
    by changing hosts file . but`this code gives me " permission denied . and  can even change hosts file directly changing the permissions or by opening it as administrator.
#include<fstream>
#include<iostream>
#include<conio.h>

using namespace std;
int main()
 {
    // clrscr();
     char site[20],ch;
     ifstream in;
     ofstream out;
     int i;

     cout<<"1.block site \n2.unblock all site\n\nEnter the value:";
     cin>>i;

     if(i==1)
     {

     cout<<"\nEnter the Name of the Site to Block :";
     cin>>site;

     out.open("C:\Windows\System32\drivers\etc\hosts",ios::app);
     if(!out)
     cout<<"File Not Found or Permission Denied";
     else
     {
     out<<"\n127.0.0.1"<<"\t"<<site;
     out<<"\n127.0.0.1"<<"\twww."<<site;
     out<<"\n127.0.0.1"<<"\thttp://"<<site;
     out<<"\n127.0.0.1"<<"\thttp://www."<<site;
     out<<"\n127.0.0.1"<<"\thttps://"<<site;
     out<<"\n127.0.0.1"<<"\thttps://www."<<site;
    cout<<"\n"<<site;
    cout<<" is blocked";
    }
     out.close();
    }
    else if(i==2)
    {

     out.open("C:\Windows\system32\drivers\etc\hosts");
     if(!out)
     {
     cout<<"File Not Found(not for linux)";
     }
     else
     {
     out<<"\n127.0.0.1"<<"\t"<<"localhost";
     cout<<"\nAll site are unblocked";

     }
     out.close();}
     else
     {
     cout<<"\nEnter proper value";
     }
     getch();
 }