Types of arguments in method overriding

Question: Can I change type of arguments while method overriding? If I do so, whether it'll be method overriding or overloading?
Comment: It will be overloading if you change parameter types.
Comment: No, you can't. But you can narrow the return type.
Comment: I haven't verified this but it should be allowable to change the type parameters of generics because of type erasure.
Answer: In general, no, except for one special case. A method can be overridden by using its erased signature, as in the following example:
class Example {
    void m1(List<Double> arg0) {}
    <T> void m2(T arg0) {}
}
class ErasedExample extends Example {
    // erasure of m1
    @Override
    void m1(List arg0) {}
    // erasure of m2
    @Override
    void m2(Object arg0) {}
}

This is noted in §8.4.2:

The signature of a method m1 is a subsignature of the signature of a method m2 if either:

m2 has the same signature as m1, or

the signature of m1 is the same as the erasure (§4.6) of the signature of m2.

Two method signatures m1 and m2 are override-equivalent iff either m1 is a subsignature of m2 or m2 is a subsignature of m1.

(§22.214.171.124 is also relevant.)
So in other words, a method can override another method if either 1) the methods have the same signature or 2) the subtype method has the erased signature of the supertype method.

Types of arguments in method overriding


Understanding lemma 13.2 in Topology by Munkres : Why do I need to show that it generates the same topology?

Question: Munkres states the following lemma in his Topology:
Lemma 13.2: Let $X$ be a topological space and suppose $K$ is a collection of open sets of $X$ such that for each open set $U$ of $X$ and each $x$ in $U$, there is an element $C$ of $K$ such that $x\in C\subset U$. Then $K$ is a basis for the topology of X.
I have shown that 1) Given $x \in X$ there is some open set in $K$ containing $x$.(2)Given $x\in C_1,C_2 \in K$, there is an open set $C \in K$ such that $x\in K \subset C_1 \cap C_2$.
Question: Shouldn't this be enough to prove that $K$ is a basis for the topological space $X$? After all, Munkres defines a basis as a collection of subsets of $X$ satisfying properties (1) and (2). Why do I need to show that that the topology generated by $K$ is the same as the given one?
Comment: In the book, the first paragraph of the proof shows that $\mathcal{C}$ is a basis. But a basis for $what$ space? A basis for some $Y$, $Z$ ? We must verify that it is a basis for *$X$*, and this is the content of the second paragraph f the proof.
Comment: Ok, I am a little confused now. In the definition (and I just noticed it), he says that if X is a set, a basis for a topology on X is a collection $\beta$ satisfying (1)  Given $x \in X$ there is a $B \in \beta$ containing $x$.(2)Given $x\in C_1,C_2 \in \beta$, there exists a $C \in \beta$ such that $x\in C \subset C_1 \cap C_2$. So, I don't see how the basis needs a topological space. (It should but I don't see how the definition demands it)
Comment: I've written up an answer. @user96343
Answer: Read carefully the paragraph following the definition of basis on page$78$:

If $\mathcal{B}$ satisfies these two conditions, then we define the topology $\mathcal{T}$ generated by $\mathcal{B}$ as follows: A subset $U$ of $X$ is said to be ope in $X$ (that is, to be an element of $\mathcal{T}$) if for each $x\in U$, there is a basis element $B\in\mathcal{B}$ such that $x\in B$ and $B\subset U$. Note that each basis element is itself an element of $\mathcal{T}$.

In plain English, the whole definition and the paragraph says: Ok now, given the set $X$, let's define a topology on $X$ by a new trick: we specify which sets are open in $X$ indirectly in terms of basis. Once we have a basis on $X$ first, then we can define a topology $\mathcal{T}$ as follows: A subset $U$ of $X$ is said to be open in $X$ if……blah blah…...
So the definition has not predefined any topology on $X$.
(The language of the definition is indeed prone to cause confusions. I remember I had struggle with it for a while when I was reading that as well) It just presents you a new trick to define topologies on $X$.
Now, in practice, often we already know some topology on $X$, and we would like to know:

Is there any basis that generates the topology we have?

So we want to go into the other direction. We would like to know that our old familiar topology  indeed comes from this "new trick". Once we have verified that $\mathcal{C}$ is a basis, it automatically generates a topology $\mathcal{T}'$. But is it the product we want? Is it the same as our old $\mathcal{T}$? This is a nontrivial fact to be checked.
Comment: Thank you very much! I think I understand it now. So, each time I see a question of the form "Is B a basis for top. space X?", I should read it as "Does it satisfy properties (1) and (2) and generate the same topology?". Right?
Comment: Yes, exactly. This question is of practical importance because we might be able to find some $\mathcal{B}$ that has some nice properties, for example, being countable. Once we can prove that this nice $\mathcal{B}$ does indeed generate the already-defined topology, then we know that the space $X$ at hand is *second countable* (see page $190$), and this can greatly simplifies the proofs of the many desired properties we want for the space $X$.


@Procedure gives runtime error java.lang.IllegalArgumentException: Type cannot be null

Question: I am trying to run my SQL Stored Procedure from Spring boot application. However, it throws java.lang.IllegalArgumentException: Type cannot be null
Version.java - Model
<code>@Entity
@NoArgsConstructor
@Data
@NamedStoredProcedureQuery(name = "moveVersion"
        , procedureName = "getVersionByName"
        ,  resultClasses = {Version.class}
        , parameters = {
        @StoredProcedureParameter(mode = ParameterMode.IN,name = "name", type = String.class)})
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@Table(name = "version")
public class Version {
    @Id
    private Long id;

    private String name;

    @Column(name = "gl_type")
    private String glType;

    @Column(name = "version_type")
    private String versionType;

    @Column(name = "effective_date")
    private Date effectiveDate;

}
</code>
VersionController.java - Controller
<code>@RestController
public class VersionController {

    @Autowired
    VersionRepository versionRepository;

    @GetMapping("/version")
    public Version version(@RequestParam(name = "version") String name) {
        return versionRepository.moveVersion(name);
    }
}
</code>
VersionRepository.java - JPA respository
<code>@Repository
public interface VersionRepository extends JpaRepository<Version, Long> {

    @Procedure("moveVersion")
    Version moveVersion(@Param("name") String name);
}
</code>
The code compiles file but when I try to run it. it throws following error :
<code>ERROR 8960 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Type cannot be null; nested exception is java.lang.IllegalArgumentException: Type cannot be null] with root cause

java.lang.IllegalArgumentException: Type cannot be null
    at org.hibernate.query.procedure.internal.ProcedureParameterImpl.setHibernateType(ProcedureParameterImpl.java:130) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.query.procedure.internal.ProcedureParameterImpl.<init>(ProcedureParameterImpl.java:70) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.procedure.internal.ProcedureCallImpl.registerParameter(ProcedureCallImpl.java:321) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.procedure.internal.ProcedureCallImpl.registerStoredProcedureParameter(ProcedureCallImpl.java:596) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.hibernate.procedure.internal.ProcedureCallImpl.registerStoredProcedureParameter(ProcedureCallImpl.java:69) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
    at org.springframework.data.jpa.repository.query.StoredProcedureJpaQuery.newAdhocStoredProcedureQuery(StoredProcedureJpaQuery.java:174) ~[spring-data-jpa-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.jpa.repository.query.StoredProcedureJpaQuery.createStoredProcedure(StoredProcedureJpaQuery.java:131) ~[spring-data-jpa-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.jpa.repository.query.StoredProcedureJpaQuery.doCreateQuery(StoredProcedureJpaQuery.java:92) ~[spring-data-jpa-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.jpa.repository.query.StoredProcedureJpaQuery.createQuery(StoredProcedureJpaQuery.java:83) ~[spring-data-jpa-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$ProcedureExecution.doExecute(JpaQueryExecution.java:331) ~[spring-data-jpa-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:91) ~[spring-data-jpa-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:136) ~[spring-data-jpa-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:125) ~[spring-data-jpa-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:605) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295) ~[spring-tx-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:138) ~[spring-data-jpa-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61) ~[spring-data-commons-2.1.8.RELEASE.jar:2.1.8.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at com.sun.proxy.$Proxy92.moveVersion(Unknown Source) ~[na:na]
    at com.sqlservertest.sqlservertest.controller.VersionController.version(VersionController.java:34) ~[main/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_202]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_202]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_202]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_202]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) ~[spring-webmvc-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) ~[spring-webmvc-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) ~[spring-webmvc-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:836) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1747) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_202]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_202]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_202]
</code>
Questions :

Is there anything I am missing?
Am I following the right methodology to use @Procedure annotation?

Any help would be appreciated.
Comment: This is an old question, but I faced with same issue and get fixed finally after a couple of hours of "read docs-try-error". Maybe this could be useful to someone: https://stackoverflow.com/a/65291913/9741090
Answer: try changing @Procedure("moveVersion") in @Procedure(name="moveVersion")


MySQL: Strange behavior of query

Question: I have following three queries:
This query returns 427
select count(distinct patient_id) from patient_visits where lower(gender) = 'male';

This query returns 272
select count(distinct patient_id) from patient_visits where lower(gender) = 'female';

Both the following query returns 687
select count(distinct patient_id) from patient_visits where lower(gender) in ('male', 'female');
select count(distinct patient_id) from patient_visits where lower(gender) = 'male' or lower(gender) = 'female';

Why the result from last queries is not 427 + 272 = 699?
What am I missing here?
Answer: Some patients have both "male" and "female" assigned as a gender.  You can find them:
select patient_id
from patient_visits
where lower(gender) in ('male', 'female')
group by patient_id
having count(distinct lower(gender)) = 2;

Note that in a medical setting you may be dealing with more than two genders -- in fact, significantly more.
Comment: Thanks a lot @Gordon, indeed there were both genders for some patients.

MySQL: Strange behavior of query


How to send a HTTP response in Zuul PRE_TYPE Filter

Question: I want to prevent not logged user form accessing the proxy. I can throw an exception but the response is 404 instead of `401 or '403'. It it possible?
Filter code:
@Component
public class CustomZuulFilter extends ZuulFilter {

    //FIXME - if 401,403 get the new token??, fallbackMethod = "fall",
    @HystrixCommand(
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000"),
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")
            }
    )
    @Override
    public Object run() {
        logger.debug("Adding zulu header");
        String userName = getLoggedUser();
        RequestContext ctx = RequestContext.getCurrentContext();
        if (userName == null) {
           // throw new RuntimeException("User not authenticated");
            logger.info("User not authenticated");
            ctx.setResponseStatusCode(401);
            ctx.sendZuulResponse();
            return null;
        }

        return null;
    }

    private String getLoggedUser() {
       [...]
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }

}

Answer: It might be a bit late, but i think you can remove ctx.sendZuulResponse();
and add ctx.setSendZuulResponse(false);


How to get a select's options by first and last characters

Question: I am trying to select an option to be viewed from a select dropdown. The code works by selecting the first characters of the element (e.g "Wood_20Sept" "Fire_20Sept" "Water_20Sept"). Snippet of the working code:
filterList(document.getElementById("worldElementsList"), /^Wood/i);

So this would select any options with the word "wood".
Like:

"Wood_20Sept"
"Wood_20Mar"
"Wood_20May"

Problem is now there is a version 2 of these groups  ("Wood_20Sept_V1" "Wood_20Sept_V2" "Fire_20SeptV1" "Fire_20SeptV2")
So I want to select the options by first and last: "Wood" and "V2".
So basically I need the code to say this:
filterList(document.getElementById("bankInfoList"), /^Wood/i && /v2$/i);

But that will only select the "V2"
Comment: `/^Wood(.*)v2$/i` - must begin with Wood, end with v2 ... and have arbitrary characters in between.
Comment: do these options in dropdowns not have ID attributes that you can select by? That would be more reliable.
Comment: Thank you, your an absolute life saver :)
Comment: I'll put the whole code up when I have time, basically the options are pulled in via java and then are shown and hidden via radio buttons. It's all abit of a mashed up work around the bug with IE11 where options can't have display:none, so you have to save the list.
Answer: Follow below steps:
A.Take whole string as a array
B. Find array[length-1] and array[length-2]
To match last elements with your string


How do we show that the sum is equal to $0$?

Question: We have the arithmetic function $$f(n)=\sum_{d\mid n}\mu (d)\cdot d$$ I want to show that if $n$ is divisible by $p^2$ for some prime $p$ then  $\displaystyle{\sum_{d\mid n}f(d)\mu \left (\frac{n}{d}\right )=0}$.
From the first subquestion we have that $f\left (p_1^{e_1}\cdots p_k^{e_k}\right )=(-1)^k\cdot (p_1-1)\cdots (p_k-1)$.
$$$$
I have done the following:
We have that $n=p^2\cdot k$, where $k=q_1^{a_1}\cdots q_y^{a_y}$.
\begin{align*}\sum_{d\mid n}f(d)\mu \left (\frac{n}{d}\right )&=\sum_\limits{0\leq\beta\leq 2 \\ 0\leq e_i\leq a_i}f\left (p^{\beta}\cdot q_1^{e_1}\cdots q_y^{e_y}\right )\mu \left (\frac{p^{2}\cdot q_1^{a_1}\cdots q_y^{a_y}}{p^{\beta}\cdot q_1^{e_1}\cdots q_y^{e_y}}\right ) \\& =\sum_\limits{0\leq\beta\leq 2 \\ 0\leq e_i\leq a_i}f\left (p^{\beta}\cdot q_1^{e_1}\cdots q_y^{e_y}\right )\cdot \mu \left (p^{2-\beta}\right )\cdot \mu\left (q_1^{a_1-e_1}\right )\cdots \mu \left (q_y^{a_y-e_y}\right ) \\ & = \sum_\limits{1\leq\beta\leq 2 \\ a_i-2\leq e_i\leq a_i}f\left (p^{\beta}\cdot q_1^{e_1}\cdots q_y^{e_y}\right )\cdot (-1)^{2-\beta}\cdot (-1)^{a_1-e_1}\cdots (-1)^{a_y-e_y}\end{align*}
Is everything correct so far? How could we continue? Do we maybe apply the first subquestion? But we can use this result only if $(p,q_i)=1$, $\forall 1\leq i\leq y$, right?
Comment: We don't know what it is the first subquestion... Do you know what value takes $\mu(n)$ at the $n$'s divisible by squares of primes? What it tells you about the sum do you want to show it is zero?
Comment: This can be shown with the [Mobius Inversion Formula](https://en.m.wikipedia.org/wiki/Möbius_inversion_formula#Series_relations). In this case, $b_d = \mu(d) d$ and $a_n = f(n)$.
Comment: @MaryStar https://math.stackexchange.com/questions/2041473/mobius-inversion-formula-proof
Comment: So, in the sum you want to consider all sumands with $d$ coprime with $p$ are  zero; and the same if $n/d$ is divisible by $p^2$. Now, for every $d$ divisor  such that $n/d$ is coprime with $p$, the sumand correspoding to the divisor $pd$ cancels with it.
Comment: At the first subquestion I had to show that $f\left (p_1^{e_1}\cdots p_k^{e_k}\right )=(-1)^k\cdot (p_1-1)\cdots (p_k-1)$. We have that $\mu (p^2\cdot k)=0$, $\forall k$, right? @xarles
Comment: I have understood that if $p^2$ divides $n/d$ then $\mu (n/d)=0$. But I haven't undersood how we proceed to show the desired result. Could you explain it further to me? @xarles
Comment: I haven't really understood how we use that statement. Could you explain further to me? @RobertZ
Answer: By Möbius Inversion Formula, given $f(n):=\sum_{d|n}g(d)$, then   $$g(n)=\sum_{d|n}\mu(d)f(n/d)=\sum_{d|n}\mu(n/d)f(n).$$
See also Mobius Inversion Formula [Proof] .
In your case let $g(n):=\mu (n)\cdot n$, then
$$\sum_{d|n}\mu(d)f(n/d)=\sum_{d|n}\mu(n/d)f(n)=g(n)=\mu (n)\cdot n.$$
Therefore, if $n$ is divisible by $p^2$ for some prime $p$ then by Möbius Inversion Formula,
$$\sum_{d|n}\mu(n/d)f(n)=\mu (n)\cdot n=0\cdot n=0$$
because $\mu (n)=0$.
Comment: I understand!! Thank you so much!! :-)
Answer: Define $D_n:=$ divisors $d$ of $n$ such that $p$ does not divide $n/d$.
Then
$$\sum_{d\mid n} f(d)\mu(n/d)=\sum_{d\in D_n}(f(d)\mu(n/d)+ f(d/p)\mu(pn/d),$$
since $\mu(p^kn/d)$ is zero for all $k>1$.
But for all $d\in D_n$ we have
$$f(d)=\prod_{q\mid d} (1-q)=
f(d/p)$$
(where the $q$ are the primes that divide $d$),
since $p^2\mid d$, and $\mu(pn/d)=-\mu(n/d)$, since $p$ does not divide $n/d$.


Update ready for sale, not showing up in App Store under "Update" (6 days)

Question: So I applied for an expedited review on the 8th of december and it was approved, processed and ready for sale on the 9th of December.
I have version 2.0.1 on my phone, and the version 2.0.2 is not showing up as an "Update" in app store. When going to app store it will show me the date I upgraded to 2.0.1 and shows that is the newest one.
If i then click on the cell to show more info, it takes me to my page listing 2.0.2 and all the correct details.
If I search my app on the store, it shows correct info 2.0.1, it is just everyone who already has my app, is not being promoted to update.
It has been 6 days, and Ive contacted ItunesConnect support, they tell me everything is fine on their end and if I have users who are having problems, to instruct them to call Store Support. So I told them its all 50,000 users who are having the issue, and they instructed me to inform 50,000 people to contact Store support.
So at this point Im all out of ideas.
Comment: Not sure why the downvote, clearly someone needs a hug.
Comment: Lol someone down voted? Thats super lame. I think I am running into this same problem because it has been almost 24 hours since the update has changed to "Ready for Sale"
Comment: @thekenner33 it cant take a day to show up sometimes, if it doesnt show up by in another 24 hours, just increment the version number and resubmit, and it should work. Sometimes it looks like it just hangs up in the server somewhere.
Comment: I actually called the support line and they said there is probably something wrong, so they transferred me to some manager dude who resubmitted the update and it showed up after like 15 minutes
Answer: iTunes connect called me back after a few hours, they had spoken to Store support and there is an active bug they are trying to fix. They said this is a not a wide spread issue, but it is affecting many Devs.
They told me to sit and wait.
Edit
They never were able to fix it, after 7 days of error, I uploaded a new build, submitted for review, once approved, it kick started the process again, and was pushed correctly to the iTunes Servers.


How to plot hour:min time in ISO 8601 time format?

Question: I am trying to plot temperature data points according to their time recording.
t = ['2021-12-11T0:6:15', '2021-12-11T7:15', '2021-12-11T8:15', '2021-12-11T9:15', '2021-12-11T10:15']

temp = [33.6, 33.6, 33.6, 33.6, 33.6]

Note: as you have mentioned t is represented without hour, the reason is that temp been collected in hour:second.
t is a string representing the date and time in ISO 8601 format (ref: datetime.datetime.isoformat()) and temp is a floating number. The plot should be in a way that t in x-axis (represented as hour:min) and temp in y-axis (represented in celcius). I want to keep the variables as lists and plot a graph without using Pandas but PyQtGraph library.
I tried the following:
from PySide6.QtWidgets import (
    QApplication,
    QMainWindow
    )
import pyqtgraph as pg # import PyQtGraph after Qt

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.graphWidget = pg.PlotWidget()
        self.setCentralWidget(self.graphWidget)

        t    = # declared above
        temp = # declared above

        # plot data: time, temp values
        self.graphWidget.plot(time, temp)

# Always start by initializing Qt (only once per application)
app = QApplication([])
window = MainWindow()
## Display the widget as a new window
window.show()
## Start the Qt event loop
app.exec_()

After running the above code, I got a traceback:
numpy.core._exceptions._UFuncNoLoopError: ufunc 'fmin' did not contain a loop with signature matching types (dtype('<U18'), dtype('<U18')) -> None
I know that there is a problem with t since its values are str which they should be same type as of temp (note: temp values should always stay float). I am not sure how to fix it.
I am using PySide6 and PyQtGraph, where Python is the language used. For this, I also tried to just plot the two variables using matplotlib library. I did the following:
import numpy as np
import matplotlib.pyplot as plt

x, y = t, temp

plt.plot(x, y, label='temperature fluctuation')
plt.xlabel('time (hour:min)')
plt.ylabel('temperature (C)')
plt.legend(loc='lower right')

Comment: Your "*Note*" is very unclear and what you describe after that even more confusing, especially considering that the first item of `t` has 3 time fields, while the following only two. That said, assuming that the `t` *values* always have the correct iso syntax, you could convert them to unix time, and use a `AxisItem` subclass that overrides [`tickStrings()`](https://pyqtgraph.readthedocs.io/en/latest/graphicsItems/axisitem.html#pyqtgraph.AxisItem.tickStrings).
Answer: A few assumptions:

You mean hour:minutes and not hour:seconds as written. If differently, please clarify your point
The time string is wrong: according to ISO 8601 hours and minutes should be two-character string chunks. You have to first clean the string list. I've done it manually since a Python script for that is out-of-scope
I've used a slight different temp array just for displaying some variability in the graph. Completely negligible

That said, the proposed way is:

Convert the iso strings into timestamp (float) values. This will be handled by pyqtgraph to plot numbers.
Convert the full ISO strings into strings with format HH:MM as you require and that you'll use as axis ticks. You have two choices that are in-code explained (please, read comments)
Get the x-axis from the PlotWidget and use the setTick property to set your custom ticks. To do so, you have to create a list of tuple with two values, the underlying numeric data and the custom string data

Here is the code:
from datetime import datetime

from PySide6.QtWidgets import (
    QApplication,
    QMainWindow
    )
import pyqtgraph as pg # import PyQtGraph after Qt

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.graphWidget = pg.PlotWidget()
        self.setCentralWidget(self.graphWidget)

        t_string_list = ['2021-12-11T06:15', '2021-12-11T07:15', '2021-12-11T08:15', '2021-12-11T09:15', '2021-12-11T10:15']

        # Get the timestamp value. A numeric value is needed for the underlying x-axis data
        t_time_value = [datetime.fromisoformat(t_string).timestamp() for t_string in t_string_list]

        # Get the x-axis ticks string values as HH:MM. Two ways
        # ---- straight and unsafe way - It only works if the ISO Format will end with minutes! [...THH:MM]
        t_ticks_values = [val[-5:] for val in t_string_list]

        # --- Safe and general way: create a datetime object from isoformat and then convert to string
        t_ticks_values = [datetime.fromisoformat(val).strftime('%H:%M') for val in t_string_list]

        temp = [33.6, 31.6, 35.6, 32.6, 37.6]

        # plot data: time, temp values
        self.graphWidget.plot(t_time_value, temp)

        # Get the x-axis
        x_axis = self.graphWidget.getAxis('bottom')
        # Check https://stackoverflow.com/questions/31775468/show-string-values-on-x-axis-in-pyqtgraph
        ticks = [list(zip(t_time_value, t_ticks_values))]
        x_axis.setTicks(ticks)

# Always start by initializing Qt (only once per application)
app = QApplication([])
window = MainWindow()
## Display the widget as a new window
window.show()
## Start the Qt event loop
app.exec_()

And here is the result:

For more advanced strategies, such as sub-classing AxisItem for custom tickStrings generator, please refer to this answer
Edit 1: Ticks downsamples
Note that you can downsample the ticks tuple in order to show less major/minor (in the example major only are present) ticks.
As for instance, if you want to show one tick every 2 timestamps:
ticks = [list(zip(t_time_value, t_ticks_values))[::2]]

The result:
Comment: thanks for your help. The solution tends to be so slow when we have a large number of `t_time_value` and `temp`. Is there a way to optimize this? Both lists are of length 16384, at least.
Comment: I'm afraid that 16k samples might be too many to be directly handled by a plotter widget (either pyqthraph or matplotlib). The situation gets worse if each sample should be accompanied by its label. You could try `AxisItem` subclassing and see if some customisation can help (see the link at the bottom of my answer). In any case, keep in mind that no human eye can discern 16k data points in a monitor graph: maybe some downsample technique can help?
Comment: thanks! I tried to plot `x-axis` as index and it was fast, the graph also is visible. The plot is publicly available in Google Photos: https://photos.app.goo.gl/DEvkr36y92m55rJX9
Comment: Is there any way that can overcome this memory issue and labels' visibility?
Comment: What do you mean *plot `x-axis` as index*?
Comment: Ok, but plotting 'HH:MM' format on `x-axis` was the point of this question. Plotting indices is pointless. Anyway, see my edit, could it help?
Comment: I just used: `time = range(0, 16384)` In my example I have 16384 data points (it can be more).
Comment: How to show only the first and last ticks in the plot, and whenever you zoom-in, you can see others in-between?


How to create a vpn connection on a port and only use it selectively

Question: This feels like a basic question, I'm sure other people needed something like this at some point however I couldn't find anything clear on this topic and I'm not very familiar to networking so I hope following makes sense (and sorry if I am butchering the terminology)
I often need to connect to a VPN server at work. At the moment I am using Cisco AnyConnect, which upon connection asks me the host server, my username, my password and routes all my traffic through the VPN afterwards.
The problem is, depending on what I'm doing I often need to jump back and forth to VPN (some applications need local network and others dont)
What would be perfect is to create one VPN connection and just keep it on a port without routing anything to it. Then I can use it as a proxy to selectively route my traffic through VPN (eg. I override http_proxy locally on one terminal instance and run applications that require VPN through there without having to jump back and forth). Furthermore if I create this connection from the terminal I can automate most of the process, with something like:
<code>function callExecutableThroughVPN() {
  if ! is_connected_to_vpn then
    echo "coulnt find the vpn connection, will attempt to connect. enter password:"
    # get password input here
    setup_vpn_on_port_9876 # pass password input here

    echo "setting proxy to 127.0.0.1:9876"
    http_proxy=127.0.0.1:9876/
    https_proxy=127.0.0.1:9876/
  fi

  ./executable_that_need_vpn
}
</code>
Then I can simply stay on my network and use a wrapper like above for few processes that require their traffic re-routed.
So in summary, my question is: Is it possible to create a single VPN process through terminal to listen a local port, so I dont have to route all my traffic at once, and I can simply kill this process when I'm done
Answer: I recommend using SSH tunnel/Socks Proxy (see ssh -D) and tsocks wrapper. For http(s) proxies I recommend the proxychains tool.


In-center of a triangle

Question: In geometry the in-center is the point of intersection/concurrence of angle bisectors;
If I have a triangle with three vertices
$$A=(x_a,y_a), B=(x_b,y_b), C=(x_c,y_c),$$
known to be related by
$$\left( \frac{ax_a + bx_b + cx_c}{a+b+c};\frac{ay_a + by_b + cy_c}{a+b+c} \right) \tag 1$$
how can I find/derive the above formula $(1)$ using the determinant of a matrix or by any other means?
Comment: You should be more specific. The *incenter* is the point of intersection of the *angle* bisectors; the *circumcenter* is the point of intersection of the *perpendicular bisectors of the sides*.
Comment: Well, honestly, what you've written confuses me. You refer to circumscribed polygons, but your discussion of areas seems to be referring to the inscribed circle and hence the incenter.
Comment: Do you just want a formula for coordinates of incenter, given three vertices using determinants?
Comment: I think most places you've written "circumscribed", you should actually say "inscribed". "Circumscribed polygons" is unclear - does it mean that the polygon is drawn around a circle (in which case of course it has an incircle)?
Comment: If you mean a segment length use $AB$ or $|AB|$.
Comment: @TedShifrin Hiiiiiii :-) I am scarce in English language. Please can you edit my question with your suggestion?
Comment: @aschepler I tried to eliminate what is superfluous or incorrect as a definition and not to create misunderstandings. I had copied from a textbook basically. If you could improve my question I am grateful further. Thank youuuuuuuuuuu.
Comment: @TedShifrin Kind Ted I edited my issue basically following your advice.
Comment: @MyMolecules Yes something that is as immediate and useful as a determinant if it exists.
Comment: What is a (the) "straight lines bisector"? Why don't you like the formula (1) ?
Answer: This may be similar enough to what you're looking for.
Represent the points as vectors $A=(x_a,y_a)$, $B=(x_b,y_b)$, $C=(x_c,y_c)$. Let a point $(p:q:r)$ stand for
$$\frac{pA+qB+rC}{p+q+r},$$
so that $A=(1:0:0)$, $B=(0:1:0)$, $C=(0:0:1)$; we want to show that the incenter is $(a:b:c)$. (These are called barycentric coordinates, and the ``extra dimension,'' using three coordinates instead of just two, comes from the fact that if you scale $p$, $q$, and $r$ each by the same amount, the point it represents doesn't change.)
It shouldn't be too hard to convince yourself that lines can, in this system, be represented by a triple $(\alpha,\beta,\gamma)$, and consist of the points $(p:q:r)$ with $\alpha p+\beta q+\gamma r=0$. You can see this by considering the places in which a line intersects each of the sides of the triangle.
Now, let's find the equation of the bisector of $\angle BAC$. We know this line contains $A$, and it also contains the point $D$ on $BC$ with $\frac{BD}{DC}=\frac cb$. This point can be represented as $(0:b:c)$. So, the bisector of $\angle BAC$ is the line $0p+cq-br=0$, or equivalently $\frac qb=\frac rc$.
By symmetry, the three angle bisectors intersect at the point $(p:q:r)$ with $\frac pa=\frac qb=\frac rc$, i.e. the point $(a:b:c)$.
A side-note: You mention looking for a way to show this using determinants. While this isn't as direct, one can show that area in barycentric coordinates is closely related to determinants, in that if you have three points $(p_1:q_1:r_1)$, $(p_2:q_2:r_2)$, and $(p_3:q_3:r_3)$, normalized such that
$$p+1+q_1+r_1=p_2+q_2+r_2=p_3+q_3+r_3=1,$$
then the area of the triangle represented by these three points is
$$\begin{vmatrix}p_1&q_1&r_1\\p_2&q_2&r_2\\p_3&q_3&r_3\end{vmatrix}$$
times the area of $ABC$. One way to define the incenter is as the unique point $I$ inside $ABC$ for which
$$\frac{\operatorname{Area}(IBC)}a=\frac{\operatorname{Area}(ICA)}b=\frac{\operatorname{Area}(IAB)}c.$$
Applying this barycentric area formula gives you the same result as before, i.e. that $I=(a:b:c)$. I believe this proof can, with enough work, be translated out of barycentric coordinates and into Cartesian, using the determinant version of the shoelace formula.
Comment: Thank you very very very very much.

In-center of a triangle


Last hyperlink in webpage table using Python

Question: I am using Beautifulsoup4 to parse a webpage.  Similar to how Bing works, if you enter a search term, it will return the first ten hits with the subsequent hits on following pages listed page 2, page 3 etc... The first page returned after the query does contain hyperlinks from page 2 until the very last page. What I am trying to establish is exactly what that very last page is (ie . Page 87) for example.
Below is a sample of the HTML source code from the page:

����� ������� ��������: 3543.
��������: 1 2 3 4 5 6 7 8 9 10

In the above example, how would I work out that the last link is page 10? There is further HTML after the above and so I can't simply slice X amount of positions from the end of the HTML code.
Thanks
Comment: Do you need to use BeautifulSoup? You shouldn't need it if you're using Selenium.
Comment: I'm using Beautifulsoup for most of my parsing and just using selenium to emulate specific terms being physically entered by a user
Answer: With raw Selenium you should be able to do something like this:
driver.find_elements_by_css_selector(".uilt a")[-1].text

This will find the last  tag that is a descendant of the element with class uilt and return its text. No need for BeautifulSoup.
Answer: If you are asking about how to find the last link in the provided HTML with BeautifulSoup - you can use a CSS Selector:
soup.select('td.uilt > a')[-1]

Or, using find() and find_all():
soup.find('td', class_='uilt').find_all('a')[-1]

Though, I'd agree with other participants in the topic that there is no need for BeautifulSoup. Selenium itself is a powerful tool and have a lot of techniques to locate elements on a page.
Answer: First manually search the html for the count of links. You may be able to grab that number to link directly to the last page. If you can't find the last page number that way, then you can crawl from the last page on every search result page. Just iterate through all the link pages {1...10, 11...20,...} until you reach the last page and then do your operation to find the last link on that page.


Receiving "expected expression before" Error When Using A Struct

Question: I'm in the process of creating a simple 2D game engine in C with a group of friends at school. I'd like to write this engine in an Object-Oriented way, using structs as classes, function pointers as methods, etc. To emulate standard OOP syntax, I created a create() function which allocates space in memory for the object. I'm in the process of testing it out, and I'm receiving an error. Here is my code for two files that I'm using to test:
test.c:
#include <stdio.h>

int main()
{
        typedef struct
        {
                int i;
        } Class;

        Class *test = (Class*) create(Class);
        test->i = 1;

        printf("The value of \"test\" is: %i\n", test->i);

        return 0;
}

utils.c:
#include <stdio.h>
#include <stdlib.h>
#include "utils.h"

void* create(const void* class)
{
        void *obj = (void*) malloc(sizeof(class));
        if (obj == 0)
        {
                printf("Error allocating memory.\n");
                return (int*) -1;
        }
        else {
                return obj;
        }
}

void destroy(void* object)
{
        free(object);
}

The utils.h file simply holds prototypes for the create() and destroy() functions.
When I execute gcc test.c utils.c -o test, I'm receiving this error message:
test.c: In function 'main':
test.c:10:32: error: expected expression before 'Class'

I know it has something to do with my typedef at the beginning, and how I'm probably not using proper syntax. But I have no idea what that proper syntax is. Can anyone help?
Comment: If you want to really make it object-oriented, why not use C++ instead?
Comment: You're casting a `void *` to `void *`. It really makes no sense.
Answer: Your code make no sense in this area
Class *test = (Class*) create(Class);

Class is a type name. Why are you trying to pass it as an argument to create? You cannot use type names as a function arguments in C.
Your create function seems to expect some sort of pointer as an argument. The purpose of that pointer is entirely unclear to me, but the bottom line here is that type name Class cannot be used as an argument here.
Inside your create you use sizeof(class) as the amount of memory to allocate. This sizeof(class) will simply evaluate to a pointer size, which is absolutely not what you need.
Basically, you need to rethink what you are trying to do and do it from scratch. I'd suggest reading so book on C first. What you have now is just... random.
Answer: This line:
Class *test = (Class*) create(Class);

Shouldn't it be
Class *test = (Class*) create(sizeof(Class));

instead?
Notice that class is a reversed C++ keyword:
void* create(const void* class)

EDIT
You could should be:
void* create(unsigned sz)
{
        void *obj = (void*) malloc(sz);
        if (obj == 0)
        {
                printf("Error allocating memory.\n");
        }
        return obj;
}

void destroy(void* obj)
{
        free(obj);
}

Usage:
  Class *test = (Class*) create(sizeof(Class));

Comment: He wants to allocate memory for the structure, and he is doing it wrong. He either must return the allocated block of memory OR pass the structure as an argument.
Comment: No. It should be `Class *test = create(sizeof(Class));`
Comment: Your version of the create function is C++, this question is tagged as C. But what is problematic, is that dangerous cast of the return type of malloc.


ConfigObj change key=value to key = value which I don't want to

Question: I have conf file with content:
key1=value1
key2=value2
font="\"Font\""

and it's used like values in bash script.
When I change some value with cgi+python3 and ConfigObj 4.7.0:
def set_conf_values(filename, param, value):
    config = ConfigObj(filename)
    config['%s' % param] = value
    config.write()

the conf file is rewriten and the format is new:
key1 = value1
key2 = value2
font = `\"Font\"`

Event for values which is untouched.
That's break my Bash script it takes keys as commands...
I hope there is option to avoid that but can't find such thing in docs.
Comment: Why not do `font="Font"` in your conf file
Comment: I need \" escape.
The problem is that ConfObj add spaces before and after delimiter =
Answer: There does not seem to be any meaningful way to control the output of ConfigObj. ConfigParser, though, has a space_around_delimiters=False keyword argument that you can pass to write.
config.conf:
[section1]
key1=value1
key2=value2
font="\"Font\""

code:
import configparser
from validate import Validator

def set_conf_values(filename, section, param, value):
    config = configparser.ConfigParser()
    config.read(filename)

    print({section: dict(config[section]) for section in config.sections()})
    config[section]['%s' % param] = value
    with open('config2.conf', 'w') as fid:
        config.write(fid, space_around_delimiters=False)

filename = 'config.conf'
set_conf_values(filename, 'section1', 'key2','value2_modified')

config2.conf (output):
[section1]
key1=value1
key2=value2_modified
font="\"Font\""

The dreadful thing about ConfigParser is that it REALLY wants section names. There are elaborate workarounds for this, but this code will get you started.


Python/Selenium: How to grab value from the HTML?

Question: I am trying to grab some values from the following code example but am unable to get a successful answer.
Using the US Patent and Trademark Office's website with a random trademark entered in this link. I want to grab the Registration Date which has a value of May 12, 2015

US Serial Number:

85931937

Application Filing Date:

May 14, 2013

US Registration Number:

4735834

Registration Date:

May 12, 2015

Notice this would be the fourth time the class name value is being called in the code example and is nested within other div classes.
This is what I have tried so far:
values = browser.find_elements(By.CLASS_NAME, 'value')
print(values[3])

but values returns an empty list []
Please advise on what I am doing wrong, thank you in advance.
Answer: To print the text May 12, 2015 you can use either of the following Locator Strategies:

Using xpath and text attribute:
print(driver.find_element(By.XPATH, "//div[@class='key' and text()='Registration Date:']//following-sibling::div[1]").text)

Ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

Using XPATH and get_attribute("innerHTML"):
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='key' and text()='Registration Date:']//following-sibling::div[1]"))).get_attribute("innerHTML"))

Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python

References
Link to useful documentation:

get_attribute() method Gets the given attribute or property of the element.
text attribute returns The text of the element.
Difference between text and innerHTML using Selenium
Comment: XPATH and getattribute("innerHTML") did the trick, thank you! Solved.


Using Promise.all to resolve fetch requests

Question: I have an array of 4 request objects that I want to use the Fetch API on and get back promises. I then want to resolve each of these promises and get the values back.
Here is how I am building the request objects.
let requestsArray = urlArray.map((url) => {
        let request = new Request(url, {
            headers: new Headers({
                'Content-Type': 'text/json'
            }),
            method: 'GET'
        });

        return request;
    });

And here is how I am trying to use Promise.all()
Promise.all(requestsArray.map((request) => {
        return fetch(request).then((response) => {
            return response.json();
        }).then((data) => {
            return data;
        });
    })).then((values) => {
        console.log(values);
    });

The last console.log(values) doesn't print anything to the console. Am I using Promise.all() wrong?
I know the first request goes through, and when I run each request individually, it works fine. The only issue is when I try to run them concurrently.
Comment: Theres no functionsArray
Comment: Sorry, I renamed the variables . Updated the code now.
Comment: you dont have any `catch` defined at all.. are you sure there are no errors?
Comment: Does this answer your question? [How can I fetch an array of URLs with Promise.all?](https://stackoverflow.com/questions/31710768/how-can-i-fetch-an-array-of-urls-with-promise-all)
Answer: I can't see any problems, for me it returns just fine: https://jsfiddle.net/np5bx03j/
However, this is a test with jsfiddles /echo/json URLs and not your original ones. I therefore would assume some error occured in your case.
I suggest adding a catch to log errors:
Promise.all(requestsArray.map((request) => {
    return fetch(request).then((response) => {
        return response.json();
    }).then((data) => {
        return data;
    });
})).then((values) => {
    console.log('values', values);
}).catch(console.error.bind(console));

EDIT: Just for the sake of completeness: I can't see any problems according to the API (MDN) or anything else either.
Comment: @ZaidHumayun But then the behavior is correct. According to MDN, Promise.all resolves "when all the promises in the given iterable have resolved, or if any of the promises reject". In your case, since there are pending requests, they did not resolve/reject. You should check why they're  taking that long (must be a network problem, nothing with Promises).
Comment: Yeah, I tried the `catch` error handling. No error pops up. And when I look at my network tab, it just says that the requests are pending, except the first one.
Comment: Yeah, you were right. It was a problem with the way the promise was being returned on the server.
Should I accept your answer as the accepted answer in that case? I'm confused about how to resolve this question right now.
Comment: @ZaidHumayun Since it seemed to resolve your problem, I would be glad if you accept my answer. However, you're of course free to accept any other answer if it was more helpful/detailed etc.
Answer: why map it twice? Let the request array return the actual promise from fetch.
let requestsArray = urlArray.map((url) => {
        let request = new Request(url, {
            headers: new Headers({
                'Content-Type': 'text/json'
            }),
            method: 'GET'
        });

        return fetch(request).then(res => res.json());
    });

Now you have array of promises. Which Promise.all takes in.
Promise.all(requestsArray).then(allResults => {
  console.log(allResults)
})

Here's a jsfiddle that mocks this: https://jsfiddle.net/uu58t1jj/
Comment: I did try it this way but all my requests, bar one, seem to be pending in the network tab. The only one that gets resolved is the very first request.
Comment: Well looks like your code/method is correct then, but just that the fetch request isn't resolving. Have you tried manually opening these urls in the browser? Do they return something? What happens if you individually catch each request to see what's stopping?
Comment: Yeah! I agree with @Bergur seems like the issue might be coming from your api.


When calling an AJAX post request to rails db, the return data is a list of generic objects

Question: In my rails app in my view, I am trying to call an ajax query with parameters of date_from and date_to that then route to an action in my controller which will query through the dates in my database. It should return this range of dates in the "success" feedback in the ajax code, but instead it returns, for example, "[object Object],[object Object],[object Object],[object Object]" if I were to pick a range of 1/1/2009 to 1/4/2009 (there are 4 objects for those 4 days). I would like the return data to be the objects and their column data in the database that I will eventually be able to use with a Highcharts timeplot. This is my code in question:
my JavaScript in the view:
function search() {
  var full_date_from = $( "#from" ).datepicker("getDate");
  var full_date_to = $( "#to" ).datepicker("getDate");

  var date_from = full_date_from.getMonth()+1 + "-" + full_date_from.getDate() + "-" + full_date_from.getFullYear();
  var date_to = full_date_to.getMonth()+1 + "-" + full_date_to.getDate() + "-" + full_date_to.getFullYear();

  $.ajax({
      url:"<%= url_for :controller => 'objects', :action => 'search' %>",
      data:'date_from=' + encodeURIComponent(date_from) + '&date_to=' + encodeURIComponent(date_to) + '&object_id=' + <%= @id %>,
      dataType: "json",
      cache:false,
      success:function (data) {
        $('#output').text(data); //outputs to

 on page
      }
  })
}

my search action in the controller:
def search
  @date_from = Date.strptime(params[:date_from], "%m-%d-%Y")
  @date_to = Date.strptime(params[:date_to], "%m-%d-%Y")
  @range = @object_data.where(:date => @date_from..@date_to)

  respond_to do |format|
   format.json { render :json => @range }
  end
end

current output of @range array to logger.debug() if date_from is 2009-01-01 and date_to is 2009-01-04
#<River::ActiveRecord_Relation:0xa6d4070>

each object of @range array in logger.debug() (I would like them to be string dates and I have tried .to_s and .to_formatted_s(param)
#<River:0xa595cf4>
#<River:0xa595b8c>
#<River:0xa595a38>
#<River:0xa595844>

Comment: Could you provide an example of the controller output you would be satisfied with?
Comment: Well actually, I would just like to use this output in the javascript of my view for use in a chart. The objects in the database table have a 'data' column, which would be turned into an array and used as the y of the chart, and then the other column, 'date', would be used as the x.
Comment: What about ``render :json => @range.map{|object| {data: object.data, date: object.date}}.to_json`` then? You should be able to iterate each object at client-side and ask for ``data`` or ``date`` of them.
Comment: I entered that into my action, but I still get [object Object]. Is there a certain way that I should be printing the object data on my web page? (I am printing it for now just for testing, and later I will put the object data into their respective arrays.)
Comment: Why don't you just take the ``data`` returned from controller (it is a parameter of your ``success`` callback) and iterate each of the ``[object]`` there? These object should have ``data`` and ``date`` attributes, so you should be able to access them like that:
``alert(data[0].date)`` or ``$('#output').text(data[0].date);``
Comment: Ahh ok I knew I was missing something. Thanks so much, if you post your comment as an answer I can select it as the "best answer".
Answer: I guess you're looking for something like this to return only desired attributes:
render :json => @range.select('data, date').to_json

or using map function:
render :json => @range.map{|object| {data: object.data, date: object.date}}.to_json

After getting the result in your success callback at client side, just iterate each of the objects inside of your data with something like that (coffeescript):
success: (data) ->
  for object in data
    $('#output').append(object.date);

You can also make sure that objects are received correctly with either console.log or alert:
console.log(data[0].date)
alert(data[0].date)


Meaningfully significant BPMs

Question: A bit of a trivial question perhaps, but are there any historically/intrinsically meaningful BPMs?
As in, there's obviously 60 bpm. I ask because while trying to correct my rushing, I've noticed that on my keyboard the default metronome is at 106 bpm. For another metronome I have it's at 96. Is there a meaningful reason? Are they of no meaning to me and so should I continue to treat 60 bpm as a sort of base, regardless of instrument?
Multiples of 6 I can imagine being associated with seconds (I assume they're the most familiar to our internal clocks?), but 106? Or maybe they're just some arbitrary defaults? Or heartbeat-related?
Are there examples of historically/inherently significant specific BPMs?
Comment: Recommended CPR BPMs I've read about tend to be in the 100-120 BPM range.
Comment: This is as you say heartbeat related. Also relaxing music and music recommended for super learning has this heartbeat pulse. I assume also the 60 sec/min are defined by the rhythm of our heart.
Comment: @Dekkadeci - 'Staying Alive' (ironic) is 103bpm, quite a bit faster than the average heartbeat. Never understood why CPR is substantially faster, but there we go! More ironic - Heartbeat (Buddy Holly) is 149bpm. That's what love does!
Comment: If you start with a _resting heart rate_ - I think normally around 60-70 depending on the individual - that would be a kind of _resting_ and _inactive_ base. Musically, that should be something pretty mellow. 100 bpm roughly should then have a moderate active level, and 120+ would be active
Comment: Andante – at a walking pace (76–108 bpm) that actually matches up with _Stayin Alive_ pretty well, given the scene in the move where John Travolta is walking.
Comment: Are you sure 106 is the factory defaut ? What synth is it ?
Comment: @AliceOualouest It's a Roland "GO:PIANO88" !
Answer: Short answer: yes, there are common metronome markings. This has to do with the tempo numbers that are usually printed on an actual physical metronome. As you progress upward in bpm, the number markings on the metronome jump, first by 2, then by 3, 4, 6, etc.
My guess is that this is because proportionally, the higher on the metronome you go, the greater a tempo shift must be to be felt. The proportional difference between 40 and 44 is much greater than between 120 and 124.
Thus, a metronome will give you "milestones" along the way, but these will become increasingly further apart the higher in bpm you get. Because these numbers have been pretty much standardized through the years, it's not uncommon for composers to choose one of these "standard" markings since they're so easy to find.
Here is a list of the common markings you'll find on a physical pendulum type metronome.
Comment: My oldest metronome has 104 and 108.In fact, every one of them has! So, as the question, why 106..?
Comment: The 106 baffles me. I'd say that was something the keyboard manufacturer chose at random!
Answer: Heart beat, breathing rate. Walking, running, and skipping speeds.
You could probably extend that with other rates that are more physics based. The time to jump up and land, waves hitting the shore, the spring of a tree branch. Common things that oscillate in nature.
IMO and experience 60-160 bpm is sort of a range of normal extremes, and I can notice a change in tempo at around 4 bpm changes. I notice a change in mood/character at somewhere around 15 bmp changes.
Separate, but related, length of breath and phrase length.
Answer: A bit of a short answer, but at the very extremes, Adam Neely has two videos on his exploration of the fastest and slowest tempi possible in music. In his endeavor, he discusses the limits of human perception: As the time between notes in a pattern becomes longer and longer, Neely finds/researches that humans stop feeling it as a pattern at around 33BPM. The question of the fastest tempo is a little more up in the air, but it's still a question of human limitations on perception and pattern recognition. To me, those two tempi at the absolute limit of human experience are intrinsically meaningful, even though they're not super-common.
Into the more practical realm, 120BPM is a pretty common average/default setting in most notation programs I know of, and I imagine it's pretty common around musical circles (120BPM is like the "C major" of tempi, or the "4/4" of tempi). It's also equal to exactly one quarter note per 0.5 seconds, or a half note per second. I imagine tempi that align well with notes-per-second are pretty common, especially in fields where music intersects with other sunject areas (physics, architecture, mathematics, etc).
Answer: Tempos are especially important for processional music and dancing.
Marches and processions

The modern march tempo is typically around 120 beats per minute. Many funeral marches conform to the Roman standard of 60 beats per minute. The tempo matches the pace of soldiers walking in step. Both tempos achieve the standard rate of 120 steps per minute.

SOURCE: Wikipedia, "March (music): Characteristics"

John Philip Sousa conducted his marches using around 120 beats per minute. Most European march composers, however, conducted their marches in a slower style, using around 100 beats per minute.

SOURCE: Wikipedia "American march music: Tempo"
The US Army's training circular "Army Ceremonial Music Performance" is explicit in giving bpm for specific occasions.

2-17. ... Army musicians march at a cadence of 112-118 beats per minute.

5-89. If the deceased was entitled to honors, they are played at a tempo of 80-100 beats per minute to preserve the solemn dignity of the ceremony.

5-93. ... The march from the chapel to the grave is played at a tempo of 100 beats per minute. If the distance from the chapel to the grave is extremely great, the drum section gradually increases the tempo to 112-118 beats per minute.

And Wikipedia again, in "Military step: Marching types and commands" specifies that:

Quick march

Standard pace: 120 bpm
British light infantry and rifle regiments: 140 bpm
Highland regiments: 112 bpm
Australian Army: 116 bpm
Canadian Armed Forces: 120 bpm
United States Army: 120

Slow march

Standard pace: 60 bpm
French Foreign Legion: 88 bpm
Australian Army: 70 bpm

A short article on marching speeds (marching speeds, as opposed to music speeds) offers some different numbers than above.
Dances
Below are the international standard tempos for various dances. All of these come from ballroomdancers.com.

Slow Waltz: 84-90
Tango: 128-132
Viennese Waltz: 174-180
Foxtrot: 112-120
Quickstep: 200-208
Cha Cha: 128
Samba: 100
Rumba: 104
Paso Doble: 120-124
Jive: 176
American Waltz: 84-96
American Tango: 120-128
American Foxtrot: 120-136
American Viennese Waltz: 162
American Cha Cha: 112-120
American Rumba: 128-144
East Coast Swing: 136-144
Bolero: 96-104
Mambo: 188-204
Lindy Hop: 130-200
Salsa: 160-220

Meaningfully significant BPMs


Javascript var to php after click

Question: I have a table where it displays the ID and on click I get the ID.
I then used Json and sent it to page editReport.php where i want to get to the variable to view the report I wish to edit. Can I get it to a php variable on the editReport page. I have used JSON to populate a javascript variable with PHP but cant find a way to get javascript to PHP.
   //Reports.PHP
   function myFunction() {
   $(".reportId").click(function () {

            var selectedReportId = $(this).text();

            //alert to test if gets ID from click
            alert(selectedReportId);

            selectedReportId = JSON.stringify(selectedReportId);
            localStorage.setItem('selectedReportId', selectedReportId);

             window.location = "editReport.php";
        });
  }

this here is the page the var is sent to. Any possible way to get that variable into a PHP var
   //editReports

<?php
$offset  = ob_get_clean();
$cl      =  strip_tags($offset);
$pattern = "/document\.write\('([^)]*)'\)/";
preg_match($pattern, $cl, $match);
print_r($match[1]);
?>

This should pull it into PHP via the screen output.
Hope this helps!

Javascript var to php after click


Drupal 7 Views Exposed Filter - How to Select all Taxonomy terms Upon adding new terms?

Question: Whenever I add new taxonomy terms I have to manually go into my exposed view filter to have them show up in the dropdown box when filtering. Is there a way to just select all terms with what im filtering by?
Comment: I also stuck with the same thing, did anyone know ?
Comment: read below in my comment.
Answer: You have the answer in the attached image itself.
Just Un-select the Limit list to selected items then save the configuration. Now the all the terms for that selected vocabulary will be listed automatically.
When you selected Limit list to selected items options, only the selected terms alone will be exposed to the user.
Comment: lol can't believe i didnt see that. also for those getting stuck on the same issue, make sure you DESELECT everything in the box. I was stuck because there is no way to deselect all and there is always ONE option selected. You will have to hold CTRL and click to deselect the last option as left clicking just selects it.


Find the values that let me split x in equally numbered groups

Question: I have some data:
x <- c(0.0636931012704989, 0.0421033586843369, 0.0214721845269228,
0.038624779052474, 0.033235347720021, 0.0307709640052774, 0.0606316442337883,
0.0289958997354256, 0.0573689255248752, 0.044448618126441, 0.0164384406368751,
0.0357802024114138, 0.0133831663454831, 0.0329126088838874, 0.051468481535772,
0.0302927520748979, 0.169023097551101, 0.0311182034472608, 0.117954563949638,
0.0593735124639249, 0.0110273691186214, 0.0286868155187407, 0.0522496344459376,
0.0298854332250777, 0.0626024185545931, 0.106914814257457, 0.0396392209572767,
0.0111988702332617, 0.0276848766950444, 0.0142151606082234)

I would like to find the values, in R preferably, in order to split x equally numbered groups.
Answer: Use the quantiles:
ngroups <- 3
q <- quantile(x, 0:ngroups/ngroups)
sprintf("The boundaries of the %d groups are: %s", groups, paste(signif(q, 3), collapse=", "))
# Or simply:
q

You can then cut:
cut.x <- cut(x, breaks=q, include.lowest=TRUE)
table(cut.x)
# Or split if you want to keep the exact numeric values:
split(x, cut.x)

Comment: The cut points are in `q`. I added some information to show them. Also if you want to keep the numeric data you can use `split`. There are thousands of ways to use this.
Comment: Thank you. Perfect. Just how do I access the values? I tried table(cut.x)[1][1], etc, but cannot find a value directly.


Can't block spammy IP

Question: I'm being attacked by 18.104.22.168. It's sending me a great amount of data, which is destroying my dataplan.
I've added the iptables
Chain            num   pkts bytes target     prot opt in     out     source               destination
DENYIN           400      0     0 DROP       all  --  !lo    *       184.108.40.206           0.0.0.0/0
DENYOUT          216      0     0 DROP       all  --  *      !lo     0.0.0.0/0            220.127.116.11
PREROUTING       439      0     0 REDIRECT   tcp  --  !lo    *       18.104.22.168           0.0.0.0/0           multiport dports 80,2082,2095 redir ports 8888
PREROUTING       440      0     0 REDIRECT   tcp  --  !lo    *       22.214.171.124           0.0.0.0/0           multiport dports 21 redir ports 8889

Event after a restart, the connection still persists.
 PID USER     PROGRAM                                  SENT      RECEIVED
  ?  root     184.108.40.206:31108-220.127.116.11:39583     0.000     31.219 KB/sec

What can I do to counter this attack?
Comment: Can you elaborate on DENYIN / DENYOUT chains content ?
Comment: @XavierLucas It's not necessary anymore - my provider found a solution.
Answer: I don't know your iptables command but normally something like this:
iptables -A INPUT -s 22.214.171.124 -j DROP

Comment: That did not solve the issue.
Answer: if its destroying your dataplan you have to work with your provider. There is nothing a firewall can do as your provider sees the traffic coming to you anyway. If it hasn't sent anything back that tells me your firewall is probably working as its dropping the packets and not sending back a reject or such.
So ya work with your provider. Give them logs and tell them what is happening.
Comment: I will contact my provider and see what they can do.
Comment: My provider found a bug in their system, causing all this traffic. They've issued a non surcharge order for my account in October and will be fixing the bug soon.
Comment: glad you got to the bottom of it

Can't block spammy IP


Getting angles for rotating $3$D vector to point in direction of another $3$D vector

Question: I've been trying to solve this in Mathematica for $2$ hours, but got the wrong result.
I have a vector, in my case $\{0, 0, -1\}$. I want a function that, given a different vector, gives me angles DX and DY, so if I rotate the original vector by an angle of DX around the X axis, and then rotate it by an angle of DY around the Y axis, I'll get a vector with the same direction as the given vector.
(I want this so I could input angles to SolidWorks to rotate a part so it will satisfy a constraint I defined in Mathematica.)
Comment: You're starting with a vector along the z axis. To get where you want to go, it's super easy to rotate first about the x-axis, and then about the z-axis. Is there some reason you're making it hard on yourself by rotating first about x, and then about y?
Comment: An x-z answer is acceptable too.
Answer: So you need a 3×3 rotation matrix $E$ such that
$$ E\,\begin{pmatrix} x \\ y \\ z \end{pmatrix} = \begin{pmatrix} 0 \\ 0 \\ -1 \end{pmatrix} = -\hat{k} $$
This rotation matrix consists of two elementary rotations
$$ \begin{aligned}
  E & = {\rm Rot}(\hat{i},\varphi_x){\rm Rot}(\hat{j},\varphi_y) \\
    & = \begin{pmatrix}
1 & 0 & 0 \\
0 & \cos\varphi_x & -\sin\varphi_x \\
0 & \sin\varphi_x & \cos\varphi_x
\end{pmatrix} \begin{pmatrix}
\cos\varphi_y &0 & \sin\varphi_y \\
0 & 1 & 0 \\
- \sin\varphi_y & 0 &  \cos\varphi_y
\end{pmatrix}
\end{aligned} $$
This is solved with
$$  \varphi_x = - \tan^{-1} \left( \frac{y}{\sqrt{x^2+z^2}} \right) \\
     \varphi_y = \pi - \tan^{-1} \left( \frac{x}{z}  \right) $$
if $\sqrt{x^2+y^2+z^2}=1$ is true.
Verification
use $(x,y,z) = (\frac{1}{2}, \frac{3}{4}, \frac{\sqrt{3}}{4}) = (0.5, 0.75, 0.4330) $ to get
$$  \varphi_x = - \tan^{-1} \left( \frac{\frac{3}{4}}{\sqrt{\left(\frac{1}{2}\right)^2+\left(\frac{\sqrt{3}}{4}\right)^2}} \right) = -0.8481 \\
\varphi_y = \pi - \tan^{-1} \left( \frac{\frac{1}{2}}{\frac{\sqrt{3}}{4}}  \right) =  2.2845$$
With a rotation matrix
$$ E = \begin{pmatrix} -0.6547 & 0 & 0.7559 \\ -0.5669 & 0.6614 & -0.4910 \\ -0.5 & -0.75 & -0.4330 \end{pmatrix} $$
and $$ \begin{pmatrix} -0.6547 & 0 & 0.7559 \\ -0.5669 & 0.6614 & -0.4910 \\ -0.5 & -0.75 & -0.4330 \end{pmatrix} \begin{pmatrix} 0.5 \\ 0.75 \\ 0.4330 \end{pmatrix} = \begin{pmatrix} 0 \\ 0 \\ -1\end{pmatrix} $$

NOTICE: Some combinations of $(x,y,z)$ will not yield the correct result because it won't be possible with the specific rotation sequence used.
Comment: Thanks for the detailed answer! Two things: 1. I think you misunderstood me (my language was vague): I want to rotate the {0,0,-1} vector into the given vector, not the other way around. 2. I want to know how you did the "This is solved with" step. Where did arctan come from? I want to know how to make this step for future calculations.
Comment: You know the $E^\top$ above will rotate the $\hat{k}$ vector into $(x,y,z)$.
Comment: What you are looking for are called Euler angles, and so search for "finding Euler angles" to get things like this [paper](http://www.soi.city.ac.uk/~sbbh653/publications/euler.pdf) which explains how to extract them for various rotation scenarios.
Comment: Also, to solve in your case you just create the system of equations from the rotation $\vec{v}=-E\hat{k}$ or in expanded form $$\begin{aligned} &x = -\sin\varphi_y \\ y &= \sin\varphi_x \cos\varphi_y \\ z &= -\cos\varphi_x \cos\varphi_y \end{aligned}$$. Divide the last two to get $\varphi_x$ and then combine them to get $$\sin\varphi_y = -x \\ \cos\varphi_y = \sqrt{y^2+z^2} $$ which is used to get the $\arctan$ values. I prefer those becasue the [`Atan2()`](http://en.wikipedia.org/wiki/Atan2) function works miracles.
Answer: Okay, if you don't mind rotating about the y and z axes, we can do it like this. Let's take a typical vector like (6,3,2) so the overall length is 7. You want to rotate a vector from the z axis into this orientation. First you look at the angle whose cosine is 2/7...that's how far down you have to come from the z axis. So you rotate about the y axis by that amount. Now you just have to swing around the z axis by the angle whose tangent is 3/6.
I think that's all you need to line up your vectors.


Is $_SERVER['SERVER_ADDR'] safe to rely on?

Question: My site relies heavily on $_SERVER['SERVER_ADDR']. Can I trust the data retrieved? There is a possibility of finding an empty string?
Comment: `SERVER_ADDR` should always be available if you're loading the page via a web server. What made you think it wouldn't be? `REMOTE_ADDR` and other settings for the client are unreliable, but your local `SERVER_ADDR` should always be valid.
Comment: A server might have several ip addresses. If consistency here is important to your application, you'd better examine how your web server behaves.
Comment: @spudley: How is remote_addr unreliable? It's extracted from the socket level setup and isn't subject to user manipulation, other than proxy/nat firewall stuff
Comment: @Mark B: if the user comes via a proxy, you may not get to see their real IP address.
Comment: @Spudley On my local web server, $_SERVER['SERVER_ADDR'] is empty.  Apparently the web server decides whether or not to include it.  Running Ubuntu.
Comment: If you are using docker, are behind a nginx proxy, or even cloudflare this can get messed up
Answer: From the php reference I quoted some
It seems that it depends on the server hosting PHP (especially apache , IIS ...)
http://php.net/manual/en/reserved.variables.server.php

On Windows IIS 7 you must use
  $_SERVER['LOCAL_ADDR'] rather than
  $_SERVER['SERVER_ADDR'] to get the
  server's IP address.

And another.

Windows running IIS v6 does not
  include $_SERVER['SERVER_ADDR']
If you need to get the IP addresse,
  use this instead:

<?php $ipAddress =
 gethostbyname($_SERVER['SERVER_NAME']);
?>

Comment: Warning: `gethostbyname` relies on a DNS lookup - this could present a significant performance penalty depending on your usage.
Answer: From Marc, this might work in a cross-platform situation:
array_key_exists('SERVER_ADDR',$_SERVER) ? $_SERVER['SERVER_ADDR'] : $_SERVER['LOCAL_ADDR'];

Comment: This yielded in `Undefined index: LOCAL_ADDR` on Debian Jessie while running PHPUnit
Answer: I use the following function in a varying server environment (Windows and Linux):
function getServerAddress() {
if(array_key_exists('SERVER_ADDR', $_SERVER))
    return $_SERVER['SERVER_ADDR'];
elseif(array_key_exists('LOCAL_ADDR', $_SERVER))
    return $_SERVER['LOCAL_ADDR'];
elseif(array_key_exists('SERVER_NAME', $_SERVER))
    return gethostbyname($_SERVER['SERVER_NAME']);
else {
    // Running CLI
    if(stristr(PHP_OS, 'WIN')) {
        return gethostbyname(php_uname("n"));
    } else {
        $ifconfig = shell_exec('/sbin/ifconfig eth0');
        preg_match('/addr:([\d\.]+)/', $ifconfig, $match);
        return $match[1];
    }
  }
}

Comment: From an operations standpoint, relying on the interface name or hostname is a really really bad idea. Depending on the network driver or network configuration, the interface name can change at any time and so can the hostname. It is not something you as a developer can control, and therefore shouldn't be relied on. If you do, your application is going to break for a seemingly unrelated reason and you will be left with some painful debugging to do.

Short version: if the webserver doesn't tell you the IP address the request arrived on, you can't guess it. Period.


Nullable generic object collection

Question: public class CubicMatrix<Object?>
    {
        private int width;
        private int height;
        private int depth;
        private Object[, ,] matrix;

        public CubicMatrix(int inWidth, int inHeight, int inDepth)
        {
            width = inWidth;
            height = inHeight;
            depth = inDepth;
            matrix = new Object[inWidth, inHeight, inDepth];
        }

        public void Add(Object toAdd, int x, int y, int z)
        {
            matrix[x, y, z] = toAdd;
        }

        public void Remove(int x, int y, int z)
        {
            matrix[x, y, z] = null;
        }

        public void Remove(Object toRemove)
        {
            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    for (int z = 0; z < depth; z++)
                    {
                        Object value = matrix[x, y, z];
                        bool match = value.Equals(toRemove);
                        if (match == false)
                        {
                            continue;
                        }

                        matrix[x, y, z] = null;
                    }
                }
            }
        }

        public IEnumerable<Object> Values
        {
            get
            {
                LinkedList<Object> allValues = new LinkedList<Object>();
                foreach (Object entry in matrix)
                {
                    allValues.AddLast(entry);
                }
                return allValues.AsEnumerable<Object>();
            }
        }

        public Object this[int x, int y, int z]
        {
            get
            {
                return matrix[x, y, z];
            }
        }

        public IEnumerable<Object> RangeInclusive(int x1, int x2, int y1, int y2, int z1, int z2)
        {
            LinkedList<Object> list = new LinkedList<object>();
            for (int a = x1; a <= x2; a++)
            {
                for (int b = y1; b <= y2; b++)
                {
                    for (int c = z1; c <= z2; c++)
                    {
                        Object toAdd = matrix[a, b, c];
                        list.AddLast(toAdd);
                    }
                }
            }

            return list.AsEnumerable<Object>();
        }

        public bool Available(int x, int y, int z)
        {
            Object toCheck = matrix[x, y, z];
            if (toCheck != null)
            {
                return false;
            }

            return true;
        }
    }

I've created a Cubic Matrix class in C# to store items in 3 dimensions. I need to be able to add and remove items which is why I'm using Object? (I've been led to understand that you can't use nullable generics ie. T?). However this approach gnerates an error

Type parameter declaration must be an identifier not a type

If i don't use Object? though and just use Object or T i get this error instead

Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' instead.

What's the correct syntax and approach to use in this case?
Comment: There are some possible solutions here:
http://stackoverflow.com/questions/19831157/c-sharp-generic-type-constraint-for-everything-nullable
Answer: If you want to restrict your generic type to objects only - i.e. no structs or simple types - you can add the where clause
public class CubicMatrix<T> where T : class

These means that T can only be a class.
Comment: Using an object constraint generates the error _Constraint cannot be special class 'object'_

But using where T : class constraint works. Thanks for the help
Comment: That's not true, structs satisfy the [`new()`](https://msdn.microsoft.com/en-us/library/sd2w2ew5.aspx) constraint. [Compiling example](http://ideone.com/hf56HY). You're probably looking for the `class` constraint.
Comment: @31eee384 you're right - thanks, I've updated the answer.
Comment: @Darkreaper thanks - updated. My C# must be a little rusty.
Answer: I think you want to use the generic parameter T. You're making a simple container class, so allowing any generic parameter makes sense, whether it's nullable or not. To fix the error, just do what it says and use default(T) instead of null.
The error is because T could be a class or a struct, and structs can't be null. Therefore assigning a variable with type T to null is invalid. default(T) is null when T is a class and default values when T is a struct.
Answer: When returning default(T) instead (as the error you are getting suggests), reference types will return null, numeric types will return 0, your custom classes will return null and nullables will return System.Nullable<T>. More about this in default Keyword in Generic Code (C# Programming Guide)
 on MSDN.

Nullable generic object collection


How to solve no suitable method found for put(String,long)

Question: Can someone help me to solve this ? I'm trying to send data from android to MySQL using code below but I get error long cannot converted to String. I can find plenty of solution related to  no suitable method found .put(String) but not in my case, so I decided to seek help from here.  Any help would be appreciated.
 public void addWorkForce(final String subcontractors, final String noPeople, final String noHours,final long twf)
    {
        class AddWorkForce extends AsyncTask<String, Void, String> {
            ProgressDialog loading;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(WorkDetailsTable.this, "Please Wait",null, true, true);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
            }

            @Override
            protected String doInBackground(String... params) {

                HashMap<String, String> data = new HashMap<String,String>();
                data.put(Config.KEY_SUBCONTRACTORS,subcontractors);
                data.put(Config.KEY_NUMBERPERSONS,noPeople);
                data.put(Config.KEY_NUMBERHOURS,noHours);
                data.put(Config.KEY_TWF,twf);
                RequestHandler rh=new RequestHandler();
                String result = rh.sendPostRequest(Config.ADD_WORKFORCE,data);
                return  result;
            }
        }

        AddWorkForce ru = new AddWorkForce();
        ru.execute(subcontractors,noPeople,noHours,twf);
    }

Error
Error:(281, 21) error: no suitable method found for put(String,long)
method AbstractMap.put(String,String) is not applicable
(argument mismatch; long cannot be converted to String)
method HashMap.put(String,String) is not applicable
(argument mismatch; long cannot be converted to String)

Comment: you are using String where Long is expected. http://stackoverflow.com/questions/22079429/error-no-suitable-method-found-for-putstring-int
Comment: dear@Seng u are putting long value in string use data.put(Config.KEY_TWF,Strig.valueof(twf)); like this, it will work for u
Answer: Use
data.put(Config.KEY_TWF,String.valueOf(twf));

Answer: By passing the correct type of parameters. Your class only has that method with two Strings as a parameter, while you try to call it with a String and a long.
Either change the method in the original type to take a long instead (which is a bad idea, since you might break other code doing so.
Or, add a new method that takes a String and a long as parameters.
Or: call it like this:
Instead of
long l = 2L;
callMethod("String", l);

do this
callMethod("String", String.valueOf(l));

Answer: Your HashMap is <String, String> means it awaits for String key and String value. You can change the HashMap to <String, Long> or convert your long value to String with method:
String.valueOf(long);