text:
Q: ldap filter in CAS configuration I need to run a CAS server (v3.5.2) connected with an Openldap directory.
The problem is that i need to filter every search on 2 fields:

*

*uid=%u (the classical search)

*accountEnabled=TRUE (a filter to see if the account is able to login to the CAS server)

According to that, i specified the following configuration in the deployerConfigContext.xml
<bean class="org.jasig.cas.adaptors.ldap.BindLdapAuthenticationHandler" >
  <property name="filter" value="(&(uid=%u,ou=people,dc=mydomain,dc=org)(accountEnabled=TRUE))" />
  <property name="contextSource" ref="contextSource" />
</bean>

Using that configuration cause the failure of starting CAS server and i can see that error in the tomcat logs:
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 132 in XML document from ServletContext resource [/WEB-INF/deployerConfigContext.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 132; columnNumber: 39; The entity name must immediately follow the '&' in the entity reference.

Do you know any way to make this configuration working?
Thanks by advance for any answer.

After modifying the conf following the xml syntax, i'm getting the following java error when i'm trying to log in on the CAS server:
2014-01-06 11:27:07,640 ERROR [org.jasig.cas.authentication.AuthenticationManagerImpl] - <org.jasig.cas.adaptors.ldap.BindLdapAuthenticationHandler threw error authenticating [username: myuser]>

java.lang.NullPointerException
    at javax.naming.InitialContext.getURLScheme(InitialContext.java:288)
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:337)
    at javax.naming.directory.InitialDirContext.getURLOrDefaultInitDirCtx(InitialDirContext.java:106)
    at javax.naming.directory.InitialDirContext.search(InitialDirContext.java:267)
    at org.jasig.cas.adaptors.ldap.BindLdapAuthenticationHandler$1.executeSearch(BindLdapAuthenticationHandler.java:94)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:292)
    at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:360)
    at org.jasig.cas.adaptors.ldap.BindLdapAuthenticationHandler.authenticateUsernamePasswordInternal(BindLdapAuthenticationHandler.java:90)
    at org.jasig.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler.doAuthentication(AbstractUsernamePasswordAuthenticationHandler.java:71)
    at org.jasig.cas.authentication.handler.support.AbstractPreAndPostProcessingAuthenticationHandler.authenticate_aroundBody2(AbstractPreAndPostProcessingAuthenticationHandler.java:85)
    at org.jasig.cas.authentication.handler.support.AbstractPreAndPostProcessingAuthenticationHandler.authenticate_aroundBody3$advice(AbstractPreAndPostProcessingAuthenticationHandler.java:57)
    at org.jasig.cas.authentication.handler.support.AbstractPreAndPostProcessingAuthenticationHandler.authenticate(AbstractPreAndPostProcessingAuthenticationHandler.java:1)
    at org.jasig.cas.authentication.AuthenticationManagerImpl.authenticateAndObtainPrincipal(AuthenticationManagerImpl.java:93)
    at org.jasig.cas.authentication.AbstractAuthenticationManager.authenticate_aroundBody0(AbstractAuthenticationManager.java:57)
    at org.jasig.cas.authentication.AbstractAuthenticationManager.authenticate_aroundBody1$advice(AbstractAuthenticationManager.java:57)
    at org.jasig.cas.authentication.AbstractAuthenticationManager.authenticate(AbstractAuthenticationManager.java:1)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:80)
    at org.perf4j.aop.AbstractTimingAspect$1.proceed(AbstractTimingAspect.java:47)
    at org.perf4j.aop.AgnosticTimingAspect.runProfiledMethod(AgnosticTimingAspect.java:53)
at org.perf4j.aop.AbstractTimingAspect.doPerfLogging(AbstractTimingAspect.java:45)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:621)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:610)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:65)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:161)
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:80)
    at com.github.inspektr.audit.AuditTrailManagementAspect.handleAuditTrail(AuditTrailManagementAspect.java:126)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:621)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:610)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:65)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:161)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at com.sun.proxy.$Proxy24.authenticate(Unknown Source)
    at org.jasig.cas.CentralAuthenticationServiceImpl.createTicketGrantingTicket_aroundBody10(CentralAuthenticationServiceImpl.java:477)
    at org.jasig.cas.CentralAuthenticationServiceImpl.createTicketGrantingTicket_aroundBody11$advice(CentralAuthenticationServiceImpl.java:57)
    at org.jasig.cas.CentralAuthenticationServiceImpl.createTicketGrantingTicket(CentralAuthenticationServiceImpl.java:1)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:80)
    at org.perf4j.aop.AbstractTimingAspect$1.proceed(AbstractTimingAspect.java:47)
    at org.perf4j.aop.AgnosticTimingAspect.runProfiledMethod(AgnosticTimingAspect.java:53)
    at org.perf4j.aop.AbstractTimingAspect.doPerfLogging(AbstractTimingAspect.java:45)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:621)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:610)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:65)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:161)
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:80)
    at com.github.inspektr.audit.AuditTrailManagementAspect.handleAuditTrail(AuditTrailManagementAspect.java:126)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:621)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:610)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:65)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:161)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at com.sun.proxy.$Proxy25.createTicketGrantingTicket(Unknown Source)
    at org.jasig.cas.web.flow.AuthenticationViaFormAction.submit_aroundBody2(AuthenticationViaFormAction.java:109)
    at org.jasig.cas.web.flow.AuthenticationViaFormAction.submit_aroundBody3$advice(AuthenticationViaFormAction.java:57)
    at org.jasig.cas.web.flow.AuthenticationViaFormAction.submit(AuthenticationViaFormAction.java:1)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:851)
    at ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1253)
    at ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68)
    at ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1329)
    at ognl.ASTMethod.getValueBody(ASTMethod.java:90)
    at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
    at ognl.SimpleNode.getValue(SimpleNode.java:258)
    at ognl.ASTChain.getValueBody(ASTChain.java:141)
    at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
    at ognl.SimpleNode.getValue(SimpleNode.java:258)
    at ognl.Ognl.getValue(Ognl.java:494)
    at org.springframework.binding.expression.ognl.OgnlExpression.getValue(OgnlExpression.java:85)
    at org.springframework.webflow.action.EvaluateAction.doExecute(EvaluateAction.java:75)
    at org.springframework.webflow.action.AbstractAction.execute(AbstractAction.java:188)
    at org.springframework.webflow.execution.AnnotatedAction.execute(AnnotatedAction.java:145)
    at org.springframework.webflow.execution.ActionExecutor.execute(ActionExecutor.java:51)
    at org.springframework.webflow.engine.ActionState.doEnter(ActionState.java:101)
    at org.springframework.webflow.engine.State.enter(State.java:194)
    at org.springframework.webflow.engine.Transition.execute(Transition.java:227)
    at org.springframework.webflow.engine.impl.FlowExecutionImpl.execute(FlowExecutionImpl.java:393)
    at org.springframework.webflow.engine.impl.RequestControlContextImpl.execute(RequestControlContextImpl.java:214)
    at org.springframework.webflow.engine.TransitionableState.handleEvent(TransitionableState.java:119)
    at org.springframework.webflow.engine.Flow.handleEvent(Flow.java:555)
    at org.springframework.webflow.engine.impl.FlowExecutionImpl.handleEvent(FlowExecutionImpl.java:388)
    at org.springframework.webflow.engine.impl.RequestControlContextImpl.handleEvent(RequestControlContextImpl.java:210)
    at org.springframework.webflow.engine.ViewState.handleEvent(ViewState.java:232)
    at org.springframework.webflow.engine.ViewState.resume(ViewState.java:196)
    at org.springframework.webflow.engine.Flow.resume(Flow.java:545)
    at org.springframework.webflow.engine.impl.FlowExecutionImpl.resume(FlowExecutionImpl.java:261)
    at org.springframework.webflow.executor.FlowExecutorImpl.resumeExecution(FlowExecutorImpl.java:169)
    at org.springframework.webflow.mvc.servlet.FlowHandlerAdapter.handle(FlowHandlerAdapter.java:183)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.jasig.cas.web.init.SafeDispatcherServlet.service_aroundBody2(SafeDispatcherServlet.java:128)
    at org.jasig.cas.web.init.SafeDispatcherServlet.service_aroundBody3$advice(SafeDispatcherServlet.java:57)
    at org.jasig.cas.web.init.SafeDispatcherServlet.service(SafeDispatcherServlet.java:1)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.github.inspektr.common.web.ClientInfoThreadLocalFilter.doFilter(ClientInfoThreadLocalFilter.java:63)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.jk.server.JkCoyoteHandler.invoke(JkCoyoteHandler.java:190)
    at org.apache.jk.common.HandlerRequest.invoke(HandlerRequest.java:291)
    at org.apache.jk.common.ChannelSocket.invoke(ChannelSocket.java:776)
at org.apache.jk.common.ChannelSocket.processConnection(ChannelSocket.java:705)
    at org.apache.jk.common.ChannelSocket$SocketConnection.runIt(ChannelSocket.java:898)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:690)
    at java.lang.Thread.run(Thread.java:744)

I tested my ldap filter with a ldap_search command, it's working.
Any idea?
Thanks

A: Try replacing your & with &. See http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML.


text:
Q: Load an image in R, with no external package Is it possible to load an image with R (.bmp or .jpg or .png or anything else), but without using an external package like this one :
> library(png)

Note: I don't want to require an external package, because it's for a course I'm teaching on university's computers where I think I cannot install package myself (and no time to ask sys-admin before the course...).
Thus, I'd like to load an image, but without having this error:
Error in library(png) : there is no package called 'png'

because the package is not installed... This message was produced on my computer, showing that png seems to not be installed by default on Windows binaries.

A: If you write an image to .RData file without using any dependencies, then yes. Otherwise no, you will have to meet all the dependencies.

A: For future reference, here is a trick that allows to install packages on university computers that might have limited access:
setInternet2(T)

then:
install.packages('png')
library(png)
x = readPNG('d:\\photo.png')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Taking time to read from properties file I am new to angular JS. I am facing one issue. Please see the below issue description.
applicationLabel.properties:
{
 "globalLabel":
 {
   "name" : "testName",
   "address" : "testAddress"
 }
}

Controller File :
var app = angular.module('app', []);

app.controller('test', function ($scope, $http) {
  $http.get('applicationLabel.properties').then(function (response) {
    var applicationLabels = response.globalLabel;
  });
});

Issue Description :
I am able to fetch values from property file properly. But problem is that angular js taking too much time to load the property file into controller and reflect those values to respective html file. It is taking more than 3 seconds to render completely. When I am facing this issue when using this functionality for website development.
Is there any way to speed up the processing of same functionality or there is another approach to fetch data other than property file.
Thanks in advance.

A: https://plnkr.co/edit/9XLaHG9rIXHLY1HGd7Ly?p=preview
app.controller('test', function ($scope, $http) {
  $scope.pp="Pankaj";
  $http.get('app.properties').then(function (response) {
    var applicationLabels = response.globalLabel;
  });
});

it took only 391ms to load this(app.properties) file.You can have a look..
Check in the network using inspect element option


text:
Q: implementing search using java technology(java web) I want to implement a search functionality in my web application that I am building using java technology. I would have to search through the database, depending on the user query and will display the results. Which way can I go about doing this(please take note I am using java technology)??.Thanks.

A: You can use a product like http://lucene.apache.org/core/ or http://lucene.apache.org/solr/ for this instead of writing this on your own.
Lucene is a high-performance search engine for documents.
SOLR is built on top of Lucene and provides additional features (like hit highlighting, faceted search, database integration or rich document (Word, PDF, ..) search)
Lucene will analyze your text data and build up an index. When performing a search you run a lucene query against this index.

A: Assuming you mean free text searching of the data in the database...
For free text searching Lucene and/or SOLR are very good solutions. These work by creating a separate index of the data in your database. It is up to you to either pull the data from the database and index it using Lucene/SOLR or arrange your code that writes to the database to also update the Lucene/SOLR index. Given what you have said it sounds like this is being retrofitted to an existing database so pulling the data and indexing it may be the best solution. In this case SOLR is probbaly a better fit as it is a packaged solution.
Another option would be Hibernate Search. Again this would be a solution to use if you are starting out. It would be more difficult to add after the fact.
Also bear in mind some databases support free text searching in addition to normal relational queries and could be worth a look. SQL Server certainly has text search capabilities and I would imagine other databases have some sort of support. I am not too sure how you access these but I would expect to be able to do it using SQL via JDBC. It is likely to be database specific though.
If you just mean normal SQL searching then there are a whole load of Java EE technologies, plain JDBC, Spring templates, ORM technologies (JPA, JDO, Hibernate etc). The list goes on and it would be difficult to suggest any particular approach without a lot more info.


text:
Q: Why do I need cast in this case? Example:
class AbstractConverter <T> {
   public abstract T convert(AbstractEntity e);
}

class CityEntity extends AbstractEntity {...}

class CityConverter extends AbstractConverter {
  @Override
  public CityDTO convert(CityEntity entity) {...} // why can't I do that??
}

As my CityEntity is of type AbstractEntity, why can't I do that in my cityConverter?
  The method convert(CityEntity) of type CityConverter must override or implement a supertype method

I guess the solution is to cast, but it's not ellegant:
 @Override
public CityDTO convert(AbstractEntity entity) {
  CityEntity cityEntity = (CityEntity) entity;
}

A: You can't reduce the allowed parameter type, because you would break Liskov substitution principle. If one calls convert on an unknown AbstractConverter implementation (due to polymorphy), (s)he would guess that he can always pass any AbstractEntity implementation. This wouldn't be the case if CityConverter only allows a very specific subtype.
Now about your code:
class AbstractConverter <T> {
   public abstract T convert(AbstractEntity e);
}

The first thing that wonders me here is: why is AbstractEntity a fixed type here? I would name the converter class AbstractEntityConverter or something like this if I always want to convert AbstractEntity instances into something different.
So I guess you really want something like this:
class AbstractConverter<F, T> {
   public abstract T convert(F source);
}

Where F is the "from" type which acts as the source and T is the target type, which will be returned. So you can let the AbstractConverter subtypes decide what they likes to convert.
Then you have this:
class CityConverter extends AbstractConverter {
}

Why do you use AbstractConverter as a raw type here? Shouldn't it be?
class CityConverter extends AbstractConverter<CityDTO> {
}

But anyway, if you like to use my suggestion, then also add the source type:
class CityConverter extends AbstractConverter<CityEntity, CityDTO> {
    @Override
    public CityDTO convert(CityEntity entity) {...}
}

This would work.

A: Your CityConverter extends AbstractConverter and AbstractConverter<T> requires implementation for
public abstract T convert(AbstractEntity e);

It is not a problem that extends AbstractConverter uses raw-types because overridden method can be more specific in case of returned object (since it is still of type described by parent class).
But problem appears when in derived class you want to require more specific type as argument.
Remember that derived class can still be used from reference which is of one of parents type like it is possible to have code like:
AbstractConverter ac = new CityConverter();

So when we will invoke ac.convert(...) compiler will allow us to use any type of AbstractEntity as argument, not only CityEntity which could brake code of CityConverter#convert.
Which is why we can't declare more specific type of method argument when overriding it.
Now about question from your title:

Why do I need cast in this case?
  ...
CityEntity cityEntity = (CityEntity) entity;

you need casting because entity is declared to be AbstractEntity which means there is a chance that passed instance may not be of type CityEntity so compiler can't compile code like:
CityEntity cityEntity = entity;//error without cast

By casting you are basically saying "I am sure that passed instance will be of type (CityEntity) and if not, I am willing to face consequences and am ready to see my application stopped by ClassCastException".


text:
Q: I need to create animation effect I have tried a lot to do animation exactly the same. I am sharing the link to how I want the animation.
http://stepntoys.com/login-register.php
Same effect when clicking on the Sign Up button and Sign In button.
Try to open in mobile browser or Resize your browser screen as per mobile dimentions
Please help me out.

A: you can have a look at https://www.freecodecamp.org/learn and in the section of Learn Applied Visual Design, there are many lessons about animation effect.

A: I know the answer of your question you can use this code to create animation mode.
button:hover {
    animation-name: background-color;
    animation-duration: 500ms;

  }
  @keyframes background-color {
    100% {
      background-color: #4791d0;
    }
  }


text:
Q: rabbit-c Consume message from default exchange Am trying to consume message from a queue which has binding to default exchange.
rabbit-c client requires exchange name and tried with the following options
option 1 : setting the exchange name as empty string ( "" ) as suggested in RMQ Docs
option 2 : passing amqp_empty_bytes in the place of exchange name.
For both options
amqp_queue_bind method is failing with reply code 3.
Is it possible to consume from a default exchange using rabbit-c client?
Note: Queue is already created

A: amqp_bind_queue was not needed since the queue was already binded to an exchange. Calling amqp_basic_consume works directly.


text:
Q: Convert Page to PersonalWebPartPage I've a strange question for you. I have to fix bugs in the another's code (webpart for sharepoint 2010). So in the code there is a line with the code below:
  var s = (String)((PersonalWebPartPage)Page).Profile["AccountName"][0];

and then I tried to view next error appears:
Unable to cast object of type 'ASP._layouts_wpprevw_aspx' to type 'Microsoft.SharePoint.Portal.WebControls.PersonalWebPartPage'.

But this code somehow working on the corporate portal. What it can be? =) Or maybe I've missing some references?

A: Many kinds of pages can have Web Parts in them. Make sure that the actual page where the Web Part is deployed inherits from Microsoft.SharePoint.Portal.WebControls.PersonalWebPartPage.
Look for something like this:
<%@ Page Inherits="Microsoft.SharePoint.SharePoint.Portal.WebControls.PersonalWebPartPage,Microsoft.SharePoint,Version=14.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" %>


text:
Q: How to set a column to fit the longest text programmatically in Excel? In Excel, you can double-click a column header (actually the line between 2 column headers) and the column to the left will expand in width to fit the length of the longest text. Is there a way to do this programmatically? I am using Excel 2010 with C# and .Net framework.

A: I believe you can use:
    Rng.Columns.AutoFit()


text:
Q: Jersey: @PathParam with commas to List I would like to call my Webservice with this pattern :
/resource/1,2,3

And in my Class I want to bind my parameters to a List of Object
@Path("/resource")
public class AppWS {

    @GET
    @Path("/{params}")
    public Response get(@PathParam("params") List<MyObject> params) {
        return Response.status(200).entity("output").build();
    }
}

With a simple Object:
public class MyObject {
    Integer value;
    public MyObject(Integer value) {
        this.value = value;
    }
}

nb: If it possible I don't want to create an MyObjectList which extends List (and have a constructor which split my string)
How may I proceed ?

A: I'm not sure the way of 1,2,3.
If you insist,
private Response get(List<MyObject> params) {
}

@GET
@Path("/{params}")
public Response get(@PathParam("params") String params) {

    return get(Stream.of(params.split(","))
        .map(MyObject::new)
        .collect(Collectors.toList()));
}

If you really insist,
annotation,
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface MyObjectsParam {

}

converter,
public class MyObjectsParamDateConverter
    implements ParamConverter<List<MyObject>> {

    @Override
    public List<MyObject> fromString(final String value) {
        return Stream.of(params.split(","))
          .map(MyObject::new)
          .collect(Collectors.toList())
    }

    @Override
    public String toString(final List<MyObject> value) {
        return value.stream()
            .map(o -> o.getValue())
            .map(Object::toString)
            .collect(Collectors.joining(","));
    }
}

provider,
@Provider
public class MyObjectsParamConverterProvider
    implements ParamConverterProvider {

    @Override
    @SuppressWarnings("unchecked")
    default ParamConverter getConverter(final Class<S> rawType,
                                        final Type genericType,
                                        final Annotation[] annotations) {
        for (final Annotation annotation : annotations) {
            if (MyObjectsParam.class.isInstance(annotation)) {
                return new MyObjectsParamDateConverter();
            }
        }

        return null;
    }
}

Now you can use it like this.
@GET
@Path("/{params}") // still '1,2,3'
public Response get(
    @PathParam("params")
    @MyObjectsParam // IN ACTION!!!
    List<MyObject> params) {

}


text:
Q: Wordpress Vs Fcgid - 500 internal server error I am using wordpress application with multisite concept. Also my web hosting working with mod_fcgid as a server API. At some instances the my site getting 500 internal server error. When I looked into the error log, it shows the repeated warning errors like "[warning] mod_fcgid: stderr: PHP Warning: Creating default object from empty value in /var/www/vhosts/mywjb.com/httpdocs/wp-includes/ms-load.php on line 113". How do I resolve this problem. Can any one help?
Thanks in advance,

A: My Web server was working with FCGI mode. So the FCGI processing with multiple PHP requests (wordpress), and the apache logging the FCGI related errors, when the requests gets failed with FCGI.
Below is my wordpress code,
    111 global $wpdb, $current_site, $domain, $path, $sites, $cookie_domain;
    112  if ( defined( 'DOMAIN_CURRENT_SITE' ) && defined( 'PATH_CURRENT_SITE' ) ) {
    113 $current_site->id = defined( 'SITE_ID_CURRENT_SITE' ) ? SITE_ID_CURRENT_SITE : 1;
    .........

I have fixed this issue by shifting the server mode from FCGI to CGI.
But compared to CGI, working with FCGI only most efficient and performance boosting technology.
Thanks


text:
Q: How do I right-click in iOS Safari to access website specific functionality? More and more desktop websites these days use javascript to offer specific website functionality which is available when you right-click on something. Often the developers create something that looks like a menu, but could be anything.
If I'm browsing desktop websites on iOS Safari (mainly iPad, but sometimes iPhone), how do I perform a right-click to display this functionality?
For a simple example, visit https://swisnl.github.io/jQuery-contextMenu/demo.html and try to display the menu under the box which states "right click me". On a desktop it's pretty obvious, but I cannot work out how to trigger it on an iPhone or iPad.
I've tried tapping and holding but this either brings up the browser menu or the text selection tool. I've also tried double-tapping but that tends to zoom the page in and out.

Side note: If you do a Google search for this, you'll find many posts from people assuming that you want to right-click to access functionality that desktop browsers typically offer (such as back, forwards, reload, save as, view page source and inspect element). This is not the functionality I'm interested in accessing.

A: Since the original iPhone, mobile safari and iOS in general has multitouch and there is no concept of a cursor. The iOS idiom is direct manipulation of objects and not to have a floating object that exists to move content up when you drag something else down in the case of a scroll bar and thumb. The multitasking idiot is also shattered on iOS / iPadOS which also weakens the need for a cursor and window managers.
Recent iOS and iPad OS do have all the cursor control you expect. Use a Magic Keyboard, Bluetooth trackpad, Bluetooth mouse or USB device and you get your cursor that meets your right click needs.
For most people, the initial concept of multitouch on the original iPhone explicitly chose to eliminate entirely the concept of a cursor: for which many people still will not forgive Apple. Macintosh was all about cursors, mice and contextual menus despite sticking to one button mice (for which many will never "forgive Apple" either.)
Without a pointing device, the OS still uses multitouch to forego "right click" emulation and instead recognize other gestures that use the up to 11 different point interactions that track surface area change in time as well as two-dimensional motion.
The core problem is that web sites not designed for touch fail to deliver a good experience. Whether we blame Apple for this or the web developers for this or the groups that design software tools for this is open to debate amongst even good intentioned professionals.

*

*There is no hover if you don't have one pointer - so all the hover to show details falls flat

*There is no control / right shift / option / mofifier click to map to a pointer that doesn't exist - so your use case simply fails to exist.

Some things do translate well:

*

*Mouse down event can be processed when multitouch shows a tap (finger down and no large movement)

*Mouse up event can be processed when multitouch shows a finger up (no more contact in the region of the initial touch or tracked moving touch)

*Multiple finger touch can sometimes map as option click.

Sorry to say there simply isn't a mouse or pointer on iOS, but that's kind of the summary. I'm not saying anyone here is wrong, just explaining what happened and that there may be two or more sides with differing goals that can yield to really bad implementations of a web design.


text:
Q: How do I invert the Y Axis for iPhone / backbone for Call Of Duty Mobile I have a backbone game controller for the iPhone (it's nice) and I want to play Call Of Duty Mobile, but the game has no setting for inverting the Y Axis. What other options are there? Are there options for any controller in general?

A: I found a solution that works for the backbone and maybe any controller. On iOS 14.6 you can use the iOS settings app to invert the Y Axis for any game.
This works for the Backbone and general controllers.

*

*Attach the Backbone. Or Connect your controller.

*On your iOS device's open the Settings app.

*Touch the "General" option.

*Scroll down a little and touch the "Game Controller" option.

*There are several options but we are only interested in one of them.

*Touch the "Customizations" option.

*At the Top of the screen turn on "Enable Customizations".

*You can customize the settings for all games here. OR Customize for a specific game.

*For a specific game scroll all the way to the bottom and touch "Add App" and Select your App.

*Scroll down and touch "Right Thumbstick".

*Turn on "Invert Vertically".

Happy Gaming!

A: Well great! There is now a setting in CoD:M. In game push the very tiny gear icon. Then on the top across all the tabs there is one called "Controller". (you might have to drag the tabs to the left to see it.) The invert options are in there.


text:
Q: .cvs export of sharepoint list removes leading zero's My site includes functionality that exports a list as a .csv file. I can't change the fact that the list is being exported as a .csv.
The problem is that when the list is exported, the leading zeros get automatically removed from one of the numeric columns.
Does anyone know a way to STOP this from happening BEFORE the list is exported? AKA Changing excel settings does not satisfy the customer and I need code that I can add to the existing export functionality.

A: There is nothing you can do to interfere with the Export to Excel function.
Is this a Number column you have in your list? Per my test, no leading zero will be allowed in a numeric value, which is the rule for both SharePoint list and Excel. You can only have leading zero if you are using a Text column.
You can change the column type to Text and then try exporting again. The exported csv file will keep the number column as the type of General, and the text column as the type of Text in Excel.


text:
Q: Editable PIC Serial Number in HEX File Currently I have a serial number hard-coded in my firmware for a design I'm working with.  The firmware can read and report back the serial number.  That works fine for what I need.  The trouble is that each new serial number requires me to change my code and recompile.  This is cumbersome when there are a lot of units to be built, has the possibly to introduce errors, and is all-around bad practice.  The serial numbers are given to me and the hardware design is set in stone, so I can't add any features in hardware to serialize the units (EEPROM/Silicon ID Chip/Pull-Ups).  What I would like to do is locate the serial number at a fixed address, compile the code once, then edit that address in the compiled HEX file for each new serial number.  The number is referenced in several places, so ideally, I want to define & locate it once, then reference that "variable" everywhere else in my code.  Does anyone know how to locate constant data at a specific addressable memory location of my choosing, using the C18 Compiler?  Is there a better way anyone can suggest?

A: I've done the serial number (s/n for short) in a way similar to what Joel is describing.  I was using PIC18F4620 and CCS compiler.  The location of s/n in Flash memory was forces to the last 4 bytes.  Since I was using only 80% of Flash, my compiler and linker wouldn't write executable code in the last 4 bytes.
Then I had 2 alternative ways for actually writing s/n into individual units:

*

*CCS in-circuit debugger (ICD) had a feature which allowed to manipulate any location inside Flash.  It was a useful hack.  In later revisions they have removed it, unfortunately.

*PIC had a serial link to a PC. s/n was uploaded through it.  Firmware had a routine which would receive the s/n and store it in Flash.

Reply to Joel's comment
Don't know about C18, but CCS compiler comes with library functions write_program_eeprom(...) andread_program_eeprom(...) .  Here's what they look like in assembly.

....................    write_program_eeprom(i_ADDR, iWord);
EF84:  BSF    FD0.6
EF86:  CLRF   FF8
EF88:  MOVLW  7F
EF8A:  MOVWF  FF7
EF8C:  MOVLW  F0
EF8E:  MOVWF  FF6
EF90:  MOVLB  0
EF92:  BRA    EF24
EF94:  MOVLW  F0
EF96:  MOVWF  FF6
EF98:  MOVFF  490,FF5
EF9C:  TBLWT*+
EF9E:  MOVFF  491,FF5
EFA2:  TBLWT*
EFA4:  BCF    FA6.6
EFA6:  BSF    FA6.4
EFA8:  RCALL  EF3C
EFAA:  RCALL  EF3C
EFAC:  CLRF   FF8
EFAE:  CLRF   FF8

....................    iWord = read_program_eeprom(i_ADDR);
EF60:  CLRF   FF8
EF62:  MOVLW  7F
EF64:  MOVWF  FF7
EF66:  MOVLW  F0
EF68:  MOVWF  FF6
EF6A:  TBLRD*+
EF6C:  MOVF   FF5,W
EF6E:  TBLRD*
EF70:  MOVFF  FF5,03
EF74:  CLRF   FF8
EF76:  MOVLB  4
EF78:  MOVWF  x90
EF7A:  MOVFF  03,491

A: Specifically to resolve the question of binding variables to specific addresses in flash memory on the PIC18 with the C18 compiler, please reference the section "Pragmas" in the hlpC18ug.chm in the doc directory where the compiler is installed.
To do this you need to define a new "section" in memory and bind it to a start address so
#pragma romdata serial_no_section=0x1700
This creates a new section called "serial_no_section" that starts at address 0x1700 in flash (program) memory (because we defined "romdata" in the #pragma).
Directly after the #pragma line, define your variable(s) so:
#pragma romdata serial_no_section=0x1700
const rom int mySerialNumber = 0x1234;
#pragma romdata

Now you have 0x12 at address 0x1700 and 0x34 at address 0x1701 in memory (because PIC18 uses the little-endian model). The "const rom" ensure that the compiler knows that this is a const variable type, and that the variable lies in "rom" memory and thus need to be accessed via table read instructions.
The final #pragma romdata statement ensures that any following variable declarations are linked to default memory sections as the linker sees fits rather than following on in the "serial_no_section" section.
Now all code can simply reference the variable "mySerialNumber", and you know exactly what address the serial number can be found at in memory.
Editing the HEX code can be a bit challenging as you need to calculate the checksum for each line you edit. I am working on a C++ class to decode and encode Intel HEX files which should make this easier, but it is not finished yet. Decoding files works, encoding again is not yet implemented. The project (if you are interested) is here https://github.com/codinghead/Intel-HEX-Class
Hope this helps

A: I have done this a few times.  Usually I define a firmware info area in a fixed location in program memory, then write a program that makes a serialized HEX file from the template HEX file.  These are all easy things to do.
In production, you run the serialize program once after all the tests have passed.  It makes the temporary HEX file with the unique serial number, that gets programmed into the PIC, then the temporary HEX file deleted.
I would not let the location be relocatable, then have to find it.  That can change every build as the linker moves things around.  I have done that for very small PICs like the 10F series where these constants are part of MOVLW instructions.  In those cases I have it read the MAP file on the fly to determine where those locations are.  I have MPLINK MAP file parsing code in a library just for that purpose.
To put something in a fixed location define a segment at a fixed address.  The linker will place such absolute segments first, then the relocatable ones around it.  Don't forget to use CODE_PACK instead of just CODE on a PIC 18, else you'll be dealing with whole instuction words instead of individual bytes.  For example (just typed in, not run past the assemlber):

.fwinfo  code_pack h'1000'     ;firmware info area at fixed known address
         db        h'FFFFFFFF' ;serial number, filled in by production program
         db        fwtype      ;type ID of this firmware
         db        fwver       ;version number
         db        fwseq       ;build sequence number

A: I would suggest storing the serial number in a fixed address.  Depending upon your compiler/linker and the part in question, there are a few approaches you could take:

*
*Define a relocatable section which will contain the serial number, use a #pragma directive in your code to force the serial number into that section, and force the address of that section within the link spec.

*For parts that can read code memory directly, exclude an area of memory from the area the linker is allowed to use (i.e. tell it the part is e.g. four bytes smaller than it really is), and then read the serial number in code using something like `((unsigned long const *)0x3FFC)`.

*For parts that can't read code memory directly, you may be able to put "RETLW" instructions at some fixed address, and then convince the linker that there are callable functions which return 'byte' at those addresses.  Then one would say e.g. "out_hex(ser_byte0()); out_hex(ser_byte1()); out_hex(ser_byte2()); to output the bytes of the serial number.

A: I would do the opposite: compile and link the code, then find out where the value is stored from the linker file. You might need to locate the variable explicitly in a segment that is mapped to flash.
Do did not ask for this, but the PC software I provide for my Wisp648 programmer has the ability to read a .hex file, modify a specific location, and write the .hex file back (to the same or another file). No need to have my programmer present. Source is available (in Python), license allows all use: www.voti.nl/xwisp Might be handy once you solved your primary problem.


text:
Q: Recyrcleview Android No meu caso vou precisar colocar vários botões em um recyrcleview tem como reconhecer em que botão foi  clicado ou somente a posição de um item na lista?

<TableRow
    android:id="@+id/tableRow1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/nome"
        android:layout_weight="1"
        android:background="@drawable/cell_shape"
        android:gravity="center"
        android:padding="10dip" />

    <Button
        android:id="@+id/divisao"
        android:layout_weight="1"
        android:background="@drawable/cell_shape"
        android:gravity="center" />

    <Button
        android:layout_weight="1"
        android:background="@drawable/cell_shape"
        android:gravity="center"
        android:padding="10dip"
        android:text="LANÇAR" />
</TableRow>

A: Você pode fazer uma interface que terá um método que será implementado na sua Activity, passar este listener para seu adapter setar o onClickListerner para o seu botão dentro do adapter e chamar o método da interface que você implementou.
Exemplo
Parte 1
public interface OnClickButton{
    void onClick(View view);
}

Parte 2
public class SuaActivity extends AppCompatActivity implements OnClickButton{

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.seu_arquivo_xml);

   seuAdapter.OnClickButton(this);
}

@Override
public void onClick(View view) {
   //Aqui você consegue capturar o id da View clicada
   switch(view.getId()){
       case R.id.nome:
           //ação
           break;
       default:
           break;
   }
}

Parte 3
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter .MyViewHolder> {

    private OnClickButton onClickButton;

     public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public Button btNome;

        public MyViewHolder(View view) {
            super(view);
            btNome= (Button) view.findViewById(R.id.nome);

            btNome.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            onClickButton.onClick(view);
        }
    }
.
.
.

Tente esta solução, abraços!


text: Q: Bias correction models in forecasting A forecast model (esp. Time Series model) may not be able to self-correct forecast biases primarily because the model does not take any feedback from forecast misses. Are there methods available that can be made to do so?


text:
Q: Add Opacity to CGPath CGPathRef defines an opaque type that represents an immutable graphics path. CGMutablePathRef defines an opaque type that represents a mutable graphics path.
But how do we change the opacity in the CGPath in CoreGraphics?
Can it be addd in percentage?

A: It's called "alpha" in UIKit and Core Graphics. For example:
UIColor *color = [[UIColor alloc] initWithWhite:0.5f alpha:0.5f];
CGContextSetStrokeColor(context, color.CGColor); // Assuming you have a context.
CGContextStrokePath(context);


text:
Q: Sum the next value of hash in an array of hashes I have an array of hashes like this:
[{Mon, 09 May 2016 14:49:17 UTC +00:00=>12},
{Sun, 17 Apr 2016 14:08:40 UTC +00:00=>30},
{Sun, 16 Apr 2016 14:08:40 UTC +00:00=>18},
{Sun, 15 Apr 2016 14:03:33 UTC +00:00=>21}]

How can I sum the previous value from the oldest date to the current date, my expected output will be:
[{Mon, 09 May 2016 14:49:17 UTC +00:00=>81},
{Sun, 17 Apr 2016 14:08:40 UTC +00:00=>69},
{Sun, 16 Apr 2016 14:08:40 UTC +00:00=>39},
{Sun, 15 Apr 2016 14:03:33 UTC +00:00=>21}]

Thanks!

A: Assuming that the key of every hash in your array is a DateTime object, you can get what your want with this:
balance = [
  {DateTime.parse('Mon, 09 May 2016 14:49:17 UTC +00:00')=>12},
  {DateTime.parse('Sun, 17 Apr 2016 14:08:40 UTC +00:00')=>30},
  {DateTime.parse('Sun, 16 Apr 2016 14:08:40 UTC +00:00')=>18},
  {DateTime.parse('Sun, 15 Apr 2016 14:03:33 UTC +00:00')=>21}
] # => your original array

# Get expected array.
balance.map{ |h|
  {
    h.keys.first => balance.select{ |e|
                      e.keys.first <= h.keys.first }.map{ |s|
                        s[s.keys.first] }.reduce(:+)
  }
}

I split the code in lines in order to improve readability.

A: Another approach would be to sort the array first and then use the map function to keep a running total to collect the required data.
# sort the balances by date
balance = balance.sort {|a, b| a.keys.first <=> b.keys.first }

# get running total and collect for each date
total = 0
balance.map do |entry|
  date, value = entry.first
  total += value
  {date => total}
end

A: I assume your array is in lastest-to-earliest date order and looks something like arr below:
a = [{ "Mon, 09 May 2016 14:49:17 UTC +00:00"=>12 },
     { "Sun, 17 Apr 2016 14:08:40 UTC +00:00"=>30 },
     { "Sun, 16 Apr 2016 14:08:40 UTC +00:00"=>18 },
     { "Sun, 15 Apr 2016 14:03:33 UTC +00:00"=>21 }]

require 'date'
arr = a.map do |h|
  (d, v) = h.to_a.first
  { DateTime.parse(d) => v }
end
  #=> [{#<DateTime: 2016-05-09T14:49:17+00:00 ((2457518j,53357s,0n),+0s,2299161j)>=>12},
  #    {#<DateTime: 2016-04-17T14:08:40+00:00 ((2457496j,50920s,0n),+0s,2299161j)>=>30},
  #    {#<DateTime: 2016-04-16T14:08:40+00:00 ((2457495j,50920s,0n),+0s,2299161j)>=>18},
  #    {#<DateTime: 2016-04-15T14:03:33+00:00 ((2457494j,50613s,0n),+0s,2299161j)>=>21}]

We can then compute the required array as follows.
cumv = 0
arr.reverse.
    map { |h| h.to_a.first }.
    each_with_object([]) do |(d,v),a|
      cumv += v
      a << { d => cumv }
    end.
    reverse
  #=> [{#<DateTime: 2016-05-09T14:49:17+00:00 ((2457518j,53357s,0n),+0s,2299161j)>=>81},
  #    {#<DateTime: 2016-04-17T14:08:40+00:00 ((2457496j,50920s,0n),+0s,2299161j)>=>69},
  #    {#<DateTime: 2016-04-16T14:08:40+00:00 ((2457495j,50920s,0n),+0s,2299161j)>=>39},
  #    {#<DateTime: 2016-04-15T14:03:33+00:00 ((2457494j,50613s,0n),+0s,2299161j)>=>21}]


text:
Q: Is there a Regex-like that is capable of parsing matching symbols? This regular expression
/\(.*\)/

won't match the matching parenthesis but the last parenthesis in the string. Is there a regular expression extension, or something similar, with a proper syntax that allows for this? For example:
there are (many (things (on) the)) box (except (carrots (and apples)))

/OPEN(.*CLOSE)/ should match (many (things (on) the))
There could be infinite levels of parentheses.

A: If you only have one level of parentheses, then there are two possibilities.
Option 1: use ungreedy repetition:
/\(.*?\)/

This will stop when it encounters the first ).
Option 2: use a negative character class
/\([^)]*\)/

This can only repeat characters that are not ), so it can necessarily never go past the first closing parenthesis. This option is usually preferred due to performance reasons. In addition, this option is more easily extended to allow for escaping parenthesis (so that you could match this complete string: (some\)thing) instead of throwing away thing)). But this is probably rather rarely necessary.
However if you want nested structures, this is generally too complicated for regex (although some flavors like PCRE support recursive patterns). In this case, you should just go through the string yourself and count parentheses, to keep track of your current nesting level.
Just as a side note about those recursive patterns: In PCRE (?R) simply represents the whole pattern, so inserting this somewhere makes the whole thing recursive. But then every content of parentheses must be of the same structure as the whole match. Also, it is not really possible to do meaningful one-step replacements with this, as well as using capturing groups on multiple nested levels. All in all - you are best off, not to use regular expressions for nested structures.
Update: Since you seem eager to find a regex solution, here is how you would match your example using PCRE (example implementation in PHP):
$str = 'there are (many (things (on) the)) box (except (carrots (and apples)))';
preg_match_all('/\([^()]*(?:(?R)[^()]*)*\)/', $str, $matches);
print_r($matches);

results in
Array
(
    [0] => Array
        (
            [0] => (many (things (on) the))
            [1] => (except (carrots (and apples)))
        )
)

What the pattern does:
\(      # opening bracket
[^()]*  # arbitrarily many non-bracket characters
(?:     # start a non-capturing group for later repetition
(?R)    # recursion! (match any nested brackets)
[^()]*  # arbitrarily many non-bracket characters
)*      # close the group and repeat it arbitrarily many times
\)      # closing bracket

This allows for infinite nested levels and also for infinite parallel levels.
Note that it is not possible to get all nested levels as separate captured groups. You will always just get the inner-most or outer-most group. Also, doing a recursive replacement is not possible like this.

A: Regular expressions are not powerful enough to find matching parentheses, because parentheses are nested structures. There exists a simple algorithm to find matching parentheses, though, which is described in this answer.
If you are just trying to find the first right parenthesis in an expression, you should use a non-greedy matcher in your regex. In this case, the non-greedy version of your regex is the following:
/\(.*?\)/

A: Given a string containing nested matching parentheses, you can either match the innermost sets with this (non-recursive JavaScript) regex:
var re = /\([^()]*\)/g;

Or you can match the outermost sets with this (recursive PHP) regex:
$re = '/\((?:[^()]++|(?R))*\)/';

But you cannot easily match sets of matching parentheses that are in-between the innermost and outermost.
Note also that the (naive and frequently encountered) expression: /\(.*?\)/ will always match incorrectly (neither the innermost nor outermost matched sets).


text:
Q: WARNING: Module mcrypt ini file doesn't exist under /etc/php/7.2/mods-available I've been trying to install phpmyadmin in Ubuntu 16.04.3 LTS having a lamp installed, php 7.2, mysql  Ver 15.1 Distrib 10.2.12-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2 and apache2.
and I am following this article from digitalOcean, but when I came to the part that I need to run sudo phpenmod mcrypt I got a message saying..
WARNING: Module mcrypt ini file doesn't exist under /etc/php/7.2/mods-available
WARNING: Module mcrypt ini file doesn't exist under /etc/php/7.2/mods-available
I am doing this on ubuntu installed in godaddy
Can you give best solution for this?

A: First install php7.1. Then copy mcrpyt.ini.
sudo apt-add-repository ppa:ondrej/php
sudo apt-get install php7.1-mbstring
sudo apt-get install php7.1-mcrypt
sudo ln -s /etc/php/7.1/mods-available/mcrypt.ini /etc/php/7.2/mods-available/
sudo phpenmod mcrypt
sudo service php7.2-fpm restart

A: Just try and run this code and your error should be gone.
sudo ln -s /etc/php/7.1/mods-available/mcrypt.ini /etc/php/7.2/mods-available/

You should have the mcrypt.ini file inside mods-available and if you don't have this file there you will get this error.
NOTE: If you do it this way you will not get this error anymore, but you will get other error:
PHP Warning:  PHP Startup: Unable to load dynamic library 'mcrypt.so' (tried: /usr/lib/php/20170718/mcrypt.so (/usr/lib/php/20170718/mcrypt.so: cannot open shared object file: No such file or directory), /usr/lib/php/20170718/mcrypt.so.so (/usr/lib/php/20170718/mcrypt.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0

So, based on my research mcrypt is not supported in php7.2, so you don't have to execute sudo phpenmod mcrypt at all. Maybe I am wrong, but if someone have more information, let me know.


text:
Q: Fantasy trilogy from the 90s where guy starts out as the only person dragons are afraid of, and by the third book he turns into a dragon I'm pretty sure it was under one of those banners like D&D or similar. And I remember an early scene in the first book where the guy has to ride a horse and gets incredibly saddlesore to the amusement of his fellow travelers.
Oh, I remembered another thing. The author's last name had an interesting Icelandic ending like Olafsdottir.

A: Based off of your comment that they had an Icelandic-sounding name, I looked at the list of D&D book authors, and picked Thorarinn Gunnarsson, and started searching on the titles. I'm pretty sure you're looking for the Dragonlord Chronicles.
Dragonlord of Mystara

As dragons roam the lands that will become Glantri, leaving havoc, destruction, and death in their wake, an unpromising young man, a female sword-fighter, her dwarven sidekick, and a ne'er-do-well storyteller and prophet set out to defend their world.

Dragonking of Mystara

Establishing a shaky peace with the dragons, Dragonlord Thelvyn Fox Eyes is distraught when they attempt to use him as a pawn and weapon against their enemies in a new plot for power, which he fears will spark another war.

Dragonmage of Mystara

In the third episode, Thelvyn is a full-fledged dragon who has learned everything necessary to perform his main task. First he must find the stolen Dragon Necklace. In doing so, he finds an enemy that threatens his entire world. When he regains the Dragon Kings power badge, he becomes the Dragon King and begins to organize the defense of the country. It is high time, since the enemy has already launched an attack.

Incidentally, by his own confession, Thorarinn's claim of being Norwegian was entirely false, a backstory he created in early days of the Internet when people could be whoever they wanted to be, and which he furthered because it sold well.


text:
Q: Umbraco cache issue - front end not refreshing immediately I have Umbraco CMS Version (Umbraco v6.1.6 (Assembly version: 1.0.5021.24867)).
I have a strange issue, whenever I make any change in back-end using editContent.aspx page, it some times reflect on front end immediately, but most of time it doesn't reflect on front end.
Then I use "Republish entire site", this works on Production but not on my local environment. I have checked umbraco.config file in App_Data folder. And it contains the changes immediately, when i save in back-end.
But I studied some where that touching web.config reflects the changes immediately, and this works in my case.
But this is very annoying solution, for both Production & local environment.
Even if I need to use "Republish entire site" all the time I save any back-end content on Production is very frustrating.
Note: I searched a lot about this, but no solution worked for me.
Thanks


text:
Q: Inserting PHP variable into mySQL table I have a booking system, in which once a user books a flight, their details are sent to a mySQL table called OABS_customers.
It's structure is the following:

Name         Type(Length)    Null     Default

name         varchar(60)     No       noname
address1     varchar(60)     No       noaddress
address2     varchar(60)     No       noaddress2
county       varchar(60)     No       nocounty
postcode     varchar(32)     No       nopostcode
customer     tinyint(4)      No
seats        varchar(11)     No       0
number       tinyint(4)      No       0
class        varchar(11)     No       noclass
username     varchar(60)     No       nousername

Now, my script adds all of the details with no problem - except for one column - the username column. I'm using this code: $query = "INSERT INTO OABS_customers (username) VALUES ('$user')"; (provided kindly by eggyal) to take the logged in users name (which is stored in the cookie ID_my_site and $user = $_COOKIE['ID_my_site'] - and I have tested that and it does contain the username of the logged in user) and add it into the username table, however this doesn't seem to work, and it instead displays the default value of nousername.
If anyone could help amend this issue I would greatly appreciate it.

A: You need to modify you login mechanism to track the user ID for the session.
Store the ID in memory or in a cookie.
Once you can store the user id now you can save it to the DB.


text:
Q: Read a line and store as variable Background:
Just need some assistance with a batch file that is meant to read (by line) a text file (it's an error log).  Each line has a file path of files that have not been backed up.  I need to read these paths into their own variable of sorts so I can copy them manually using this batch (running robocopy or xcopy or something).
Assistance:
I would like some help with trying to find the string starting with "\\" and saving everything that follows into an array which is then passed to some "functions" that do the checking and copying.
Current progress:
I can at the moment do the following:

*

*Read the file

*Make checks on the variable to ensure it's not already part of a manual copy process

*Copy the data

Code:
This is where I am stuck. Reading the file into %%a and trying to now read %%a into a variable to check the string for "\\" and then copying that+the_rest_of_the_line into the variable I would ultimately do the checking and copying from.
set LOGPATH=C:\logs\
echo finding path
cd %LOGPATH%
for /f "tokens=* delims=" %%a in (err.log) do (
)
pause

I have tried to use findstr but I can't see how it works becuase it keeps delimiting at a singular "\"
Also here's a sample of the log:

18:34:55  Cannot open \\server\path\file

A: Updated content base on the file format:
Try this command:
for /f "tokens=2* delims=\" %%a in (test.txt) do (
    @echo \\%%a\%%b
)

to see if it output the path correctly. This is assume the path is the last item in the line.


text:
Q: Create many-to-many field data in serializer I am trying to send a post request to create an object - course, but every time I get an error, how can I write a serializer for a class - course. What do I need to do so that it creates an object and at the same time displays a list of contacts instead of a list of keys?
Models:
class Category(models.Model):
    title = models.CharField(max_length=30)
    imgpath = models.CharField(max_length=100)

    def __str__(self):
        return self.title

class Branch(models.Model):
    latitude = models.CharField(max_length=250)
    longitude = models.CharField(max_length=250)
    address = models.CharField(max_length=250)

    def __str__(self):
        return self.address

class Contact(models.Model):

    class Type(models.IntegerChoices):
        PHONE = 1,
        FACEBOOK = 2,
        EMAIL = 3

    type = models.IntegerField(choices=Type.choices)
    value = models.CharField(max_length=250)

    def __str__(self):
        return self.value

class Course(models.Model):
    name = models.CharField(max_length=30)
    description = models.TextField()
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category')
    logo = models.CharField(max_length=20, blank=True)
    contacts = models.ManyToManyField(Contact)
    branches = models.ManyToManyField(Branch, blank=True)

    def __str__(self):
        return self.name

Serializer:
from rest_framework import serializers

from application.category.models import Category, Branch, Contact, Course

class CategorySerializers(serializers.ModelSerializer):

    class Meta:
        model = Category
        fields = '__all__'

class BranchSerializer(serializers.ModelSerializer):

    class Meta:
        model = Branch
        fields = '__all__'

class ContactSerializer(serializers.ModelSerializer):

    class Meta:
        model = Contact
        fields = '__all__'

class CourseSerializer(serializers.ModelSerializer):

    class Meta:
        model = Course
        fields = '__all__'

    def create(self, validate_data):
        contacts_data = validate_data.pop('contacts')
        branchs_data = validate_data.pop('branches')
        contacts = []
        branchs = []
        course = Course.objects.create(**validate_data)
        # for contact_data in contacts_data:
        #     contact = Contact.objects.get(id=contact_data['id'])
        #     contacts.append(contact)
        # validate_data['contacts'] = contacts
        # return course
        for contact_data in contacts_data:
            print(contact_data)
            contact_id = contacts_data.pop('id')
            print(contact_id)
            contact = Contact.objects.get_or_create(id=contact_id, defaults=contact_data)

            contacts.append(contact)

        course.contacts.add(**contact)
        return course

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        return rep

Views:
class CategoryView(APIView):
    def get(self, request):
        category = Category.objects.all()
        serializer = CategorySerializers(category, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

class BranchView(ListAPIView):
    queryset = Branch.objects.all()
    serializer_class = BranchSerializer

class ContactViewSet(viewsets.ModelViewSet):
    queryset = Contact.objects.all()
    serializer_class = ContactSerializer

class CourseListView(APIView):

    def get(self, request,  *args, **kwargs):
        course = Course.objects.all()
        serializer = CourseSerializer(course, many=True)
        return Response(serializer.data, status.HTTP_200_OK)

    def post(self, request):
        serializer = CourseSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors)

class CourseDetailView(APIView):

    def get_object(self, pk):
        try:
            return Course.objects.get(pk=pk)
        except Course.DoesNotExist:
            raise KeyError('ТААА-ШАААААA')

    def get(self, request, pk):
        course = self.get_object(pk)
        serializer = CourseSerializer(course)
        return Response(serializer.data)

    def delete(self, request, pk):
        course = self.get.get_object(pk)
        course.delete()
        return Response(f'{course} was deleted!', status=HTTP_204_NO_CONTENT)

I get this error:
enter image description here
enter image description here

A: To answer your first question:

What do I need to do so that it creates an object and at the same time displays a list of contacts instead of a list of keys?

Sounds like you want to create a course and return a list of contacts? If that's the case then you need to alter your code in the POST request to the course. Perhaps to something like:
def post(self, request):
        serializer = CourseSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()

            # Get courses to return them as response
            courses = Course.objects.all()
            courses_serializer = CourseSerializer(courses)
            return Response(courses_serializer.data)

        return Response(serializer.errors)

It's a bit of an odd thing to make an API request to create a certain object and return objects of another type! But the above is how you would roughly do it if that's what your app needs.
For the error you are experiencing I would need more information such as a stack trace.


text:
Q: Plotting multiple lines grouped by one column dataframe, with date time as x axis My data looks like the following:
Date,values,ids
2018-10-02,0.9907,1
2018-10-11,3.3784,1
2018-10-11,2.9163,1
2018-10-18,3.7815,1
2018-10-18,0.0874,1
2018-10-08,12.9632,2
2018-10-08,10.4358,2
2018-10-14,9.0246,2
2018-10-14,50.8519,2
2018-10-21,6.9922,2
2018-10-21,5.8701,2

Here I want to plot the values as a line with respect to time, each line correspond to the values of one id. Below is my attempt and the image it generated.
data = pd.read_csv('data.txt')
data['Date'] = pd.to_datetime(data['Date'], format='%Y-%m-%d')

fig, ax = plt.subplots()
data.groupby('ids').plot(kind='kde', x='Date', y='values', ax=ax)

I think the reason the x axis doesn't look right is that the Date values for the two groups don't match. Is there a way to put these two groups into the same scale as xticks? For example: 2018-10-02 to 2018-10-21 with 1-day increment.


text:
Q: VBA move selected range up / down (with offset?) I am building a tool where user-selected cell contents is moved around with arrow shapes.
The code below works great to move 1 or more group of adjacent cells down.
However, reversing the code seems tricky (+1 in offset does not work :-?)
Any idea?
Thank you,
Augustin
Sub Move_Up()
    Selection.Cut
    Selection.Offset(-1, 0).Select
    Selection.Insert Shift:=xlDown
End Sub

A: supposing cells are to be moved around and overwritten ones are just shifted where moved ones once were, the code could be the following:
Sub MoveUp()
    Selection.Rows(Selection.Rows.count + 1).Insert Shift:=xlDown
    Selection.Rows(1).Offset(-1).Cut Selection.Rows(Selection.Rows.count + 1)
    Selection.Rows(1).Offset(-1).Delete Shift:=xlUp
    Selection.Offset(-1).Select
End Sub

Sub MoveDown()
    Selection.Rows(1).Insert Shift:=xlDown
    Selection.Rows(Selection.Rows.count).Offset(2).Cut Selection.Rows(1)
    Selection.Rows(Selection.Rows.count).Offset(2).Delete Shift:=xlUp
    Selection.Offset(1).Select
End Sub

A: If you want to move a Selected block of cells up by one row then:
Sub ShiftBlockUp()
    Dim r As Range
    Set r = Selection
    Intersect(r(1).EntireRow, r).Offset(-1, 0).Delete Shift:=xlUp
End Sub

If you want to move a Selected block of cells down by one row then:
Sub ShiftBlockDown()
    Dim r As Range
    Set r = Selection
    Intersect(r(1).EntireRow, r).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub


text:
Q: How can i find a specific element/field in the class I have 2 page app. First page MainPage, and second page is class and name "Links". I have buttons in mainpage. and i have string variables in "Links" with the same name as the buttons.
For example
class Links
{
    public static string a1 = "data1";
    public static string a2 = "data2";
    public static string a3 = "data3";
}

//Main page
public partial class MainPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();
    }

    private void allclickevents(object sender, RoutedEventArgs e)
    {
       Button x = (Button)sender;
       string findthisname=x.Content.ToString();
       //I need to find the string data of the same name in "Links" class. And show messagebox, for ex if button a2 messagebox shows "data2".
    }
}

Design Page(Xaml page):
<Button x:Name="a1" Content="a1" HorizontalAlignment="Left" Margin="260,48,0,0" VerticalAlignment="Top" Click="allclickevents"/>
<Button x:Name="a2" Content="a2" HorizontalAlignment="Left" Margin="360,48,0,0" VerticalAlignment="Top" Click="allclickevents"/>
<Button x:Name="a3" Content="a3" HorizontalAlignment="Left" Margin="460,48,0,0" VerticalAlignment="Top" Click="allclickevents"/>

All buttons click events set to allclickevents method, and i am use (Button). sender and find specific button name. Need only find same named string data in Links class.
I need to find the string data of the same name in "Links" class. And show messagebox, for ex if button a2 messagebox shows data2. Please help.

A: The only way to do this is via reflection, which is a pretty good indicator that its not the right approach to solving the overall problem.
That being said, the following code will do it:
string data = (string) typeof(Links).GetField(findthisname).GetValue(null);

See MSDN for GetField and SO for how to use it to access static members.
To get the message box, just use MessageBox.Show(data).

A:         FieldInfo f_key = typeof(Links).GetField(p);
        var o = f_key.GetValue(null);

these code should work, but if you use Dictionary,it will be much easier,like this:
        Dictionary<String,String> links = new Dictionary<string, string>();
        links.Add("a1","data1");
        links.Add("a2", "data2");
        links.Add("a3", "data3");

when you use it :
links["ai"] will return "datai"


text:
Q: How to count the number of elements present in a JSON object? I have a PHP/JSON as show below.
JSON:
{"posts_id_en":"101, 102, 103","posts_id_fr":"", "reports_id_en":"101, 102", "reports_id_fr":"101"}

PHP code:
echo count(explode(",", $data->posts_id_en));    //  Line A  (3)

echo count(explode(",", $data->posts_id_fr));    // Line B   (1)

echo count(explode(",", $data->reports_id_en));    // Line C  (2)

echo count(explode(",", $data->reports_id_fr));    // Line D  (1)

Line A php code, Line C php code and Line D php code print 3, 2, and 1.
Problem Statement:
I am wondering what changes I need to make in the php code above at Line B so that it prints 0 as there are no elements inside posts_id_fr

A: You just need to make sure there is no empty values inside that array. Because when empty string is exploded it will create one element with value as blank.
Remove those values using array_filter
echo count(array_filter(explode(",", $data->posts_id_fr)));

// Will print 0

Just in case if you want to loop through as suggested by GrumpyCrouton
foreach($data as $key => $value)
{
  echo $key . ' : ' . count(array_filter(explode(",", $value))) . PHP_EOL;
}

Output:
posts_id_en : 3
posts_id_fr : 0
reports_id_en: 2
reports_id_fr: 1

A: You must check if the value is set before trying to use the value
$str = '{"posts_id_en":"101, 102, 103","posts_id_fr":"", "reports_id_en":"101, 102", "reports_id_fr":"101"}';

$obj = json_decode($str);

foreach ( $obj as $o=>$v) {
    echo $o . ' ';
    echo strlen($v) > 0 ? count(explode(",", $v)) : 0 ;
    echo PHP_EOL;
}

Results
posts_id_en 3
posts_id_fr 0
reports_id_en 2
reports_id_fr 1

A: Slight variation here, you can use preg_split and use a flag to ignore empty splits.  Here we are splitting on non-digits.
<?php

$str = '{"posts_id_en":"101, 102, 103","posts_id_fr":"", "reports_id_en":"101, 102", "reports_id_fr":"101"}';
$arr = json_decode($str, true);

$arr = array_map(function($item) {
    $nums = preg_split('/[^0-9]/', $item, -1, PREG_SPLIT_NO_EMPTY);

    return $nums;
}, $arr);

var_export($arr);

$arr = array_map('count', $arr);

var_export($arr);

Output:
array (
  'posts_id_en' =>
  array (
    0 => '101',
    1 => '102',
    2 => '103',
  ),
  'posts_id_fr' =>
  array (
  ),
  'reports_id_en' =>
  array (
    0 => '101',
    1 => '102',
  ),
  'reports_id_fr' =>
  array (
    0 => '101',
  ),
)array (
  'posts_id_en' => 3,
  'posts_id_fr' => 0,
  'reports_id_en' => 2,
  'reports_id_fr' => 1,
)

The intermediate step is included so you can see the result of the preg_split.

A: echo count(preg_split("/,/", $data->posts_id_fr,-1, PREG_SPLIT_NO_EMPTY));


text:
Q: How do I automate file upload in cucumber with Ruby if the upload file is a button tag How do I automate file upload in cucumber with ruby if the upload file is a button tag. I tried to convert the type to file with the script:
@browser.execute_script("document.getElementById('elementid').setAttribute('type', 'file');")
@browser.div(:class => "classname").file_field.set(file.path)

Then I get the error:
unable to locate element, using `{:tag_name=>"input", :type=>"file"}`

The error occurs as the tag name in my application is <button>.
How do I handle this, any suggestions?
HTML:
<button type="button" id="pickfiles" class="btn btn-default" data-ng-class="{'disabled': noRuntime}" style="position: relative; z-index: 1;"> Select file </button>


text:
Q: Program type already present: tv.danmaku.ijk.media.player.AbstractMediaPlayer I have defined below gradles in my app.gradle
 implementation 'tv.danmaku.ijk.media:ijkplayer-java:0.8.8'
 implementation 'tv.danmaku.ijk.media:ijkplayer-armv7a:0.8.8'

and also defined same in one of the module integrated.
When I try to run the code it throws error as below

AGPBI: {"kind":"error","text":"Program type already present:
  tv.danmaku.ijk.media.player.AbstractMediaPlayer","sources":[{}],"tool":"D8"}


text:
Q: Pulling Date From Cell in Google Sheet Using Script App As a disclaimer, I am rather new to programming concepts. If you really wanted to be my best friend, the more specific the explanation the better. But any help is appreciated.
My very small tiny business uses QuickBooks for our payroll timekeeping, however for logistical purposes, we have our employees use a google spreadsheet to enter in their times.
I want to write a script that checks the first column for the date twice a day (as per the trigger I have set up). If the date is equal to or greater than today's date, I need the script to also check a cell a few columns down in the same row to see if the cell has been filled out. If it is 0 or null, I want to send a notification.
Please see the picture below for reference.
Test
So far, this is what I have:
function values2()
{
    var ss = SpreadsheetApp.getActiveSpreadsheet(),
      sheet = ss.getSheetByName("TimeSheet"),
      range = sheet.getDataRange(),
      values = range.getValues(),
      indx, logToday, today, body,
      recipients = "xxxxx@xxx.zzz",
      subject = "Timesheet Notification" + ss.getName();

//Finds current date and creates string. I would prefer to have a numeric value associated to the current date, as well as a numeric value associated with the date for each row.
  var CurrentDate = new Date();
  Logger.log(CurrentDate);
      logToday = Logger.getLog();
      indx = logToday.indexOf("INFO");
      today = logToday.substring(indx + 6, indx + 16);

//I'm having things sent to my email for test purposes
  MailApp.sendEmail(recipients, subject, today);
//Clears Log
  Logger.clear();
  for (var r=1; r<values.length; r++)
  {
  var row = values[r],
      date = row[0],
      price = row[1],
      units = row[2],
      total = row[3],
      name = row[4];

   Logger.log(date);
   Logger.log(price);
   Logger.log(units),
   Logger.log(total),
   Logger.log(name);
  }

  body = Logger.getLog();
  MailApp.sendEmail(recipients, subject, body);
}

At this point, I want to be able to catch each date from the first column, compare it to today's date, check another cell in the same row, then move on to the next date in the first column. I've played around with IF/Else statments, but to no avail.

A: If you want to compare date elements of first column included empty cells to today, how about following script?
function values2()
{
    var ss = SpreadsheetApp.getActiveSpreadsheet(),
      sheet = ss.getSheetByName("TimeSheet"),
      range = sheet.getDataRange(),
      values = range.getValues(),
      indx, logToday, today, body,
      recipients = "xxxxx@xxx.zzz",
      subject = "Timesheet Notification" + ss.getName();

    var lR = sheet.getLastRow();
    var dateinfo = sheet.getRange('a1').offset(0, 0, lR, 1).getValues();
    var today = new Date();
    var y0 = today.getFullYear();
    var m0 = today.getMonth() + 1;
    var d0 = today.getDate();

    for (var i=0; i<dateinfo.length; i++){
        x = Date.parse(dateinfo[i]);
        var date = new Date(x);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        if (y0 === y && m0 === m && d0 === d) {
            Logger.log("ok:" + i) // same date
        } else {
            Logger.log("error:" + i)  // difference date
        };
    };
}


text:
Q: jQuery ajax returning 'Object Object' I am trying to send data to a PHP script using jQuery Ajax. For some reason the Ajax request is throwing up an error and returning the following data from the PHP script - [object Object]
I've copied my code in below. I've also copied code using the exact same method elsewhere on the page which seems to work fine!
Can anyone explain why this is happening?
Firstly, the code that is working fine
jQuery
 $("#reqtable a").click(function(){
  var cells = [];
  var name;
  var account;
  var module;
  var email;
  $(this).parent().parent().find("td").each(function(){
  cells.push($(this).html());
  });
  $(this).parent().parent().find("input").each(function(){
  email = $(this).val();
  });
  $(this).parent().parent().prop('id', 'die');
  name = cells[0];
  account = cells[1];
  module = cells [2];

  $.ajax({
            url: "release.php",
            type: "POST",
            data: {name: name, account: account, module: module, email: email},
            success: function(){
            $("#die").remove();
           }
         });
 });

PHP
<?php
include('../../dbconnect.php');

$name = $_POST['name'];
$account = $_POST['account'];
$email = $_POST['email'];
$module = $_POST['module'];

$releasequery = "INSERT INTO release_assignment(name, account, email, module) VALUES ('$name', '$account', '$email', '$module')";
$release = $conn->query($releasequery);

$erasequery = "DELETE FROM request_assignment WHERE email='$email' AND module = $module";
$erase = $conn->query($erasequery);

?>

And now the code that IS NOT working.
jQuery
 $("#downloadtable a").click(function(){
  var dlcells = [];
  var dlname;
  var dlaccount;
  var dlmodule;
  var dlemail;
  var dlsub;
  var dlpath;

  $(this).parent().parent().find("td").each(function(){
  dlcells.push($(this).html());
  });
  $(this).parent().parent().find("input.dlemail").each(function(){
  dlemail = $(this).val();
  });
  $(this).parent().parent().find("input.dlsub").each(function(){
  dlsub = $(this).val();
  });
  $(this).parent().parent().find("input.dlpath").each(function(){
  dlpath = $(this).val();
  });

  $(this).parent().parent().prop('id', 'die2');
  dlname = dlcells[0];
  dlaccount = dlcells[1];
  dlmodule = dlcells [2];

  $.ajax({
            url: "download.php",
            type: "POST",
            data: {dlname: dlname, dlaccount: dlaccount, dlmodule: dlmodule, dlemail: dlemail, dlsub: dlsub, dlpath: dlpath},
            success: function(data){
            $("#die2").remove();
            },
            error: function(data){
             $('#downloaddiv').html('<p>' + data + '</p>');
            }
         });
 });

PHP
<?php
include('../../dbconnect.php');

$name = $_POST['dlname'];
$email = $_POST['dlemail'];
$account = $_POST['dlaccount'];
$module = $_POST['dlmodule'];
$path = $_POST['dlpath'];
$submission = $_POST['dlsub'];

$feedbackquery = "INSERT INTO feedback_assignments(name, email, level, unit, assignmentpath, submission) VALUES ('$name', $email, '$account', '$module', '$path', '$submission')";
$feedback = $conn->query($feedbackquery);

$erasequery = "DELETE FROM uploaded_assignments WHERE email='$email' AND unit = $module";
$erase = $conn->query($erasequery);

?>

When I comment out all the PHP code and simply put echo ($_POST['dlname']); it returns the data [object Object]
Can anyone explain what is going on and why it seems to work with one block of code but not the other?
Thanks!
Chris
Update: It might be worth mentioning that the initial link ('#downloadtable a') actually instigates a file download as well as the ajax call, whereas in the code that is working it simply makes the ajax call and nothing else. I don't know if this is throwing a spanner in the works but thought it worth mentioning.
Update 2: Using the jQuery Ajax error callback as described below I'm getting the following response:
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
AJAX error: error :

The code I've used in the error callback is as follows:
error: function(jqXHR, textStatus, errorThrown) {
   console.log(JSON.stringify(jqXHR));
   console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
   }

Unfortunately I don't understand what this means. Can anyone shed any light on this?
Update 3 OK, I've found the reason for Ajax blowing up on me, and it relates to update number 1 (above). Basically because the link is to a file download (a .docx file) it seems to be causing the problem with ajax. When I change the link to href='#' instead of href="document.docx", the ajax and PHP script works.
This throws up a new question, of course - how can I get the link to download the file whilst simultaneously updating the database?

A: Specify a dataType and use console to debug your data response.
Also, notice that the error callback contains the following arguments and not any "data";

error Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )

Update
The target file download.php might be throwing an exception. Possibly because of some missing quotes around $email on the line;
$feedbackquery = "INSERT INTO feedback_assignments(name, email, level, unit, assignmentpath, submission) VALUES ('$name', $email, '$account', '$module', '$path', '$submission')";
Debug download.php and make sure it generates the expected output/response.
I advice you to escape the values you are using to build your SQL query with to prevent SQL injection.


text:
Q: Drupal .htaccess rewrite/substitution without redirect I have a URL as follows: www.site.com/catalog/?type=6  which I need to rewrite to www.site.com/white-wines/white-cases.
What is important is that it is not a redirect, for example the URL should remain as www.site.com/white-wines/white-cases when visited, but show content from www.site.com/catalog/?type=6.
The current solution that I have performs a redirect and I'm struggling to work this out.
RewriteRule ^white-wines/white-cases$ http://www.site.co.uk/catalog/?type=6 [L]

A: Setting full address in the target implies a redirect if the target is different then the current hostname, not rewrite. Try root-relative path.
RewriteRule ^white-wines/white-cases$ /catalog/?type=6 [L]

You can't do a re-write to a different hostname.

Absolute URL
If an absolute URL is specified, mod_rewrite checks to
see whether the hostname matches the current host. If it does, the
scheme and hostname are stripped out and the resulting path is treated
as a URL-path. Otherwise, an external redirect is performed for the
given URL. To force an external redirect back to the current host, see
the [R] flag below.
Source: Apache Module mod_rewrite


text:
Q: How do I set up Firefox to keep only cookies from select sites, when I use Firefox-Sync? I use Firefox on a desktop iMac, a MacBook and my Android Samsung Galaxy S III mobile phone. All installations of Firefox are set to sync over Firfox's inbuilt Firefox-Snyc feature.
On my desktop computer I have set Firefox to delete all cookies when I close Firefox and defined exceptions, telling Firefox to keep cookies from those sites. I followed this instruction.
This worked fine at first: I visited some sites, closed Firefox, opened Firefox, looked at the cookies, and all cookies had been deleted except those from the excepted sites.
But after I began using Firefox on my other computers, I noticed that:
(a) all cookies were being deleted sometimes; sometimes all remained
(b) the exceptions disappeared sometimes; sometimes they remained
So the question is:
How do I set up Firefox to keep only cookies from select sites, when I use Firefox-Sync?

A: Firefox Sync doesn't support site permissions, unfortunately.
It's been requested with bug 470699: add yourself to the CC list to be notified of future development.


text:
Q: symfony2 form twig input value I am doing a form with symfony2 and twig, form who get infos from BDD.
I want to customize render in function of some informations.
If my data chanson is empty, I want to show input to set it.
If my data is not empty I want to show a paragraphe who shows data, and a link for modify the value and show the input.
I try something like that :
{% if form_widget(session.chanson).attrvalue!='' %}

{{form_widget(session.chanson).attrvalue}} modify

{% else %}

{{ form_label(session.chanson,"Chanson : ") }}
 {{ form_errors(session.chanson) }}
 {{ form_widget(session.chanson) }}

{% endif %}

It's not working. I try with value instead of attrvalue, it's not working neither.
Here is what symfony say : Item "attrvalue" for "<input type="text" id="form_chanson" name="form[chanson]" required="required" value="La Rage" />" does not exist in CDUserBundle:Prof:edit_session.html.twig at line 19
Did someone know the issue ?
Thank you,

A: You could check if the app.session.chanson variable is empty instead using:
{% if app.session.chanson %}

{{ app.session.chanson }} modify

{% else %}

{{ form_label(app.session.chanson,"Chanson : ") }}
   {{ form_errors(app.session.chanson) }}
   {{ form_widget(app.session.chanson) }}

{% endif %}

You then need to plug the action you want on the modify link.
Also note that if your object chanson is stored in a session, the right way to access it in your twig template is by using the app.session object.


text:
Q: rotating div pie with transition First I would like to explain what I want to achieve. I can't post picutes yet so I hope words will help. I have a pie with four sections.
And I want to link every of the sections with different links, and when hovering over a section, the pie should rotate. The degree of it's rotation depends on the section.
In my first attempt I tried it with imagemapping. Until I found out that they can't rotate.
After a long time of thinking I came up with this idea: Seperating my four parts, and bringing them together to a pie with four divs.
This worked and I was kinda proud, haha. Since I want the whole pie to rotate I tried this:
https://jsfiddle.net/canaika/dL569v6d/
When you hover over one of the sections a new image (the whole) pie appears, and it rotates. I wanted a smooth rotation, so I added a transition, but this ist where my problem started: yes the transition works, but it affects the come in of the image that appears, because the sections and the whole pie image have different sizes, and I can't change the sections side, otherwise the other sections are not accessible.
I hope this wasn't too confusing, maybe my idea or at least the way I tried to achieve it is dumb or impossible, but I wanted to give it a try.

#rotation1 {
  background-image: url('http://www.imgbox.de/users/canaika/blue_navi.png');
  height: 112px;
  width: 112px;
  position: fixed;
  top: 100px;
  left: 300px;
}
#rotation1:hover {
  background-image: url('http://www.imgbox.de/users/canaika/navigation.png');
  height: 224px;
  width: 224px;
  z-index: 1;
  -webkit-transform: rotate(45deg), ;
  -moz-transform: rotate(45deg);
  -o-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
  -o-transition: all 0.5s linear;
  -moz-transition: all 0.5s linear;
  -khtml-transition: all 0.5s linear;
  -webkit-transition: all 0.5s linear;
  -ms-transition: all 0.5s linear;
  transition: all 0.5s linear;
}
#rotation2 {
  background-image: url('http://www.imgbox.de/users/canaika/pink_navi.png');
  height: 112px;
  width: 112px;
  position: fixed;
  top: 100px;
  left: 412px;
}
#rotation2:hover {
  background-image: url('http://www.imgbox.de/users/canaika/navigation.png');
  height: 224px;
  width: 224px;
  position: fixed;
  top: 100px;
  left: 300px;
  -webkit-transform: rotate(315deg);
  -moz-transform: rotate(315deg);
  -o-transform: rotate(315deg);
  -ms-transform: rotate(315deg);
  transform: rotate(315deg);
  z-index: 1;
  -o-transition: all 0.5s linear;
  -moz-transition: all 0.5s linear;
  -khtml-transition: all 0.5s linear;
  -webkit-transition: all 0.5s linear;
  -ms-transition: all 0.5s linear;
  transition: all 0.5s linear;
}
#rotation3 {
  background-image: url('http://www.imgbox.de/users/canaika/yellow_navi.png');
  height: 112px;
  width: 112px;
  position: fixed;
  top: 212px;
  left: 300px;
}
#rotation3:hover {
  background-image: url('http://www.imgbox.de/users/canaika/navigation.png');
  height: 224px;
  width: 224px;
  position: fixed;
  top: 100px;
  left: 300px;
  -webkit-transform: rotate(135deg);
  -moz-transform: rotate(135deg);
  -o-transform: rotate(135deg);
  -ms-transform: rotate(135deg);
  transform: rotate(135deg);
  z-index: 1;
  -o-transition: all 0.5s linear;
  -moz-transition: all 0.5s linear;
  -khtml-transition: all 0.5s linear;
  -webkit-transition: all 0.5s linear;
  -ms-transition: all 0.5s linear;
  transition: all 0.5s linear;
}
#rotation4 {
  background-image: url('http://www.imgbox.de/users/canaika/green_navi.png');
  height: 112px;
  width: 112px;
  position: fixed;
  top: 212px;
  left: 412px;
}
#rotation4:hover {
  background-image: url('http://www.imgbox.de/users/canaika/navigation.png');
  height: 224px;
  width: 224px;
  position: fixed;
  top: 100px;
  left: 300px;
  -webkit-transform: rotate(225deg);
  -moz-transform: rotate(225deg);
  -o-transform: rotate(225deg);
  -ms-transform: rotate(225deg);
  transform: rotate(225deg);
  z-index: 1;
  -o-transition: all 0.5s linear;
  -moz-transition: all 0.5s linear;
  -khtml-transition: all 0.5s linear;
  -webkit-transition: all 0.5s linear;
  -ms-transition: all 0.5s linear;
  transition: all 0.5s linear;
}
#zeiger {
  background-image: url('http://www.imgbox.de/users/canaika/zeiger.png');
  height: 35px;
  width: 9px;
  position: fixed;
  top: 100px;
  left: 407px;
  z-index: 2;
}

link 1

link 2

link 3

link 4

A: You need to change your transition to work only on transform not all like this :
transition: transform 0.5s linear;

not
transition: all 0.5s linear;

https://jsfiddle.net/IA7medd/dL569v6d/2/


text:
Q: unzip zip files that are contained in a zip file on windows I have a zip file results.zip. It contains two folders that contain a bunch of zip files -- PASS/test1.zip, FAIL/test2.zip, FAIL/test3.zip.
On linux it is trivial to unzip these in a couple of steps:
$ unzip results.zip
$ echo FAIL/*.zip PASS/*.zip | xargs -n1 unzip

Some windows users complain that it is cumbersome to unzip all the files on windows. (There are dozens of zips inside the main zip.) Is there a mechanism that would allow them to expand the contents of all of the files at once?
Some customer boxes are newer, but there are many that are still using WinXP.

A: Give them unzip.exe and a batch script like
unzip results.zip
for %%i in (FAIL\*.zip PASS\*.zip) do unzip %%i

A: Try ExtractNow. I haven't tested this feature myself, but it does claim to support it.

A: Here is a solution for windows assuming 7zip is installed in the default location.
@echo off
Setlocal EnableDelayedExpansion
Set source=%1
Set SELF=%~dpnx0
For %%Z in (!source!) do (
    set FILENAME=%%~nxZ
)
set FILENAME=%FILENAME:"=%
"%PROGRAMFILES%\7-zip\7z.exe" x -o* -y "%FILENAME%"
rem DEL "%FILENAME%"
For %%Z in (!source!) do (
    set FILENAME=%%~nZ
)
for %%a in (zip rar jar z bz2 gz gzip tgz tar lha iso wim cab rpm deb) do (

    forfiles /P ^"%FILENAME%^" /S /M *.%%a /C "cmd /c if @isdir==FALSE \"%SELF%\" @path"
)

This has been adapted from here https://social.technet.microsoft.com/Forums/ie/en-US/ccd7172b-85e3-4b4a-ad93-5902e0abd903/batch-file-extracting-all-files-from-nested-archives?forum=ITCG
Notes:

*

*The only way to do variable modification using the ~ modifiers is to use a dummy for..in loop. If there is a better way please edit.

*~nx modifies the variable to make it a full path+file name.

*~dpnx also does the same thing to %0 i.e. gets the full path and filename of the script.

*-o* in the 7zip command line allows 7zip to create folder names without the .zip extension like it does when extracting with a right click in the gui.

*~n modifies the variable to make it a filename without an extension. i.e. drops the .zip

*Note that the escape character (for quotes) in FORFILES /P is ^ (caret) while for the CMD /C it is \. This ensures that it handles path and filenames with spaces also recursively without any problem.

*You can remove the REM from the DEL statement if you want the zip file to be deleted after unzipping.

A: See this
http://www.softpedia.com/get/Compression-tools/Multi-Unpacker.shtml
"Nested archive handling (recursively extract archives that were packed in other archives)."
OS: Windows 2K / XP / 2003 / Vista


text:
Q: MongoDB query - find one of each from tag array I'm trying to do a "where $in" query in MongoDB/Mongoose where I only want one result back for each tag in an array. Sort of like:
db.images.find( { hashtag : { $in : ['tag1', 'tag2', 'tag3'] } } );

And I would get three unique results back; each from the set of tags I specified.
[{name:'image1', hashtag:'tag1'},
{name:'image55', hashtag:'tag2'},
{name:'image99', hashtag:'tag3'}]

In SQL you'd use something like GROUP BY, but I can't find the equivalent in MongoDB without doing a Map/Reduce.
Anyway of doing that? Thanks.
--edit
The equivalent SQL for what I want would be:
SELECT * FROM images WHERE hashtag in ('tag1', 'tag2', 'tag3') GROUP BY hashtag;

Or ideally, though MongoDB has no random
SELECT * FROM images WHERE hashtag in ('tag1', 'tag2', 'tag3') GROUP BY hashtag ORDER BY rand();

A: Sounds like you are waiting for the 2.2 release of MongoDB which will include an aggregation pipeline that will allow you to unwind arrays into multiple results.
http://www.mongodb.org/display/DOCS/Aggregation

A: I can't find a way to do this in 2.0 but in 2.2 (currently available as development version 2.1.1 - only available for testing but not production) the aggregation framework will allow you to do it like this (just as an example, I'm sure other ways are possible):
  db.images.aggregate(
       {$match   : {hashtag: {$in:["tag1","tag2"]}}},
       {$group   : {_id:"$hashtag", name: {$first:"$name"}}},
       {$project : {hashtag:"$_id", name: "$name", _id:0}}
  )

Which returns:
{
         "result" : [
        {
            "hashtag" : "tag2",
            "name" : "1"
        },
        {
            "hashtag" : "tag1",
            "name" : "1"
        }
    ],
    "ok" : 1
  }

This is assuming your documents are of the form {name:"xxx",hashtag:"tagX") and many names correspond to each hashtag.  What the aggregation pipeline is doing is it's using $match to limit the working set to ones that have hashtag as "tag1" or "tag2", then we group by hashtag and specify we only want to keep $first result of each grouping ($last is another option) - this assumes you don't care which of the names you get back as long as it's just one.  $project is used to map _id which group requires back to field name "hashtag".