text:
Q: Absence of anti-csrf tokens in authenticationendpoint cookies/headers of wso2 IS 5.9 I have tried all WSO2 guidelines for enabling the CSRF properties on network cookies and submit forms of GET methods of authenticationendpoint webapp but still not able to achieve the result.
I was getting "Absence of Anti-CSRF tokens" ZAP vulnerability for the authenticationendpoint in the response of the GET methods because it doesnt contain the hidden parameter - csrf token in form submit tag of the response body.
WSO2 Links referred:
https://is.docs.wso2.com/en/5.9.0/administer/mitigating-cross-site-request-forgery-attacks/#securing-web-applications
https://wso2.com/technical-reports/wso2-secure-engineering-guidelines#C03
https://medium.com/@PrakhashS/overview-cross-site-request-forgery-csrf-recommended-approach-for-wso2-products-bb0e2437307
Information provided in ZAP vulnerability:
No known Anti-CSRF token [anticsrf, CSRFToken, __RequestVerificationToken, csrfmiddlewaretoken, authenticity_token, OWASP_CSRFTOKEN, anoncsrf, csrf_token, _csrf, _csrfSecret] was found in the following HTML form: [Form 1: "tocommonauth" "username" "password" "chkRemember" "sessionDataKey" ].

web.xml of authenticationendpoint webapp
<?xml version="1.0" encoding="UTF-8"?><!--
  ~ Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ WSO2 Inc. licenses this file to you under the Apache License,
  ~ Version 2.0 (the "License"); you may not use this file except
  ~ in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0" metadata-complete="true">
    <absolute-ordering />

    <!-- OWASP CSRFGuard context listener used to read CSRF configuration -->
    <listener>
        <listener-class>org.owasp.csrfguard.CsrfGuardServletContextListener</listener-class>
    </listener>
    <!-- OWASP CSRFGuard session listener used to generate per-session CSRF
        token -->
    <listener>
        <listener-class>org.owasp.csrfguard.CsrfGuardHttpSessionListener</listener-class>
    </listener>
    <!-- OWASP CSRFGuard per-application configuration property file location -->
    <context-param>
        <param-name>Owasp.CsrfGuard.Config</param-name>
        <param-value>/repository/conf/security/Owasp.CsrfGuard.properties</param-value>
    </context-param>
    <!-- OWASP CSRFGuard filter used to validate CSRF token -->
    <filter>
        <filter-name>CSRFGuard</filter-name>
        <filter-class>org.owasp.csrfguard.CsrfGuardFilter</filter-class>
    </filter>
    <!-- OWASP CSRFGuard filter mapping used to validate CSRF token -->
    <filter-mapping>
        <filter-name>CSRFGuard</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- OWASP CSRFGuard servlet that serves dynamic token injection JavaScript
        (application can customize the URL pattern as required) -->
    <servlet>
        <servlet-name>JavaScriptServlet</servlet-name>
        <servlet-class>org.owasp.csrfguard.servlet.JavaScriptServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>JavaScriptServlet</servlet-name>
        <url-pattern>/csrfguard.js</url-pattern>
    </servlet-mapping>

    <!-- *************** Account Recovery Endpoint Context URL Configuration
        ********************** -->
    <!--context-param> <param-name>IdentityManagementEndpointContextURL</param-name>
        <param-value>https://localhost:9443/accountrecoveryendpoint</param-value>
        </context-param -->
    <context-param>
        <param-name>AccountRecoveryRESTEndpointURL</param-name>
        <param-value>/t/tenant-domain/api/identity/user/v1.0/</param-value>
    </context-param>

    <!-- *************** End of Authentication REST API URL Configuration ********************** -->

    <!--Display scopes in the consent page. -->
    <context-param>
        <param-name>displayScopes</param-name>
        <param-value>true</param-value>
    </context-param>

    <filter>
        <filter-name>HttpHeaderSecurityFilter</filter-name>
        <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
        <init-param>
            <param-name>hstsEnabled</param-name>
            <param-value>false</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>HttpHeaderSecurityFilter</filter-name>
        <url-pattern>*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>AuthenticationEndpointFilter</filter-name>
        <filter-class>
            org.wso2.carbon.identity.application.authentication.endpoint.util.filter.AuthenticationEndpointFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>AuthenticationEndpointFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>URLBasedCachePreventionFilter</filter-name>
        <filter-class>org.wso2.carbon.ui.filters.cache.URLBasedCachePreventionFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>URLBasedCachePreventionFilter</filter-name>
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>ContentTypeBasedCachePreventionFilter</filter-name>
        <filter-class>
            org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter</filter-class>
        <init-param>
            <param-name>patterns</param-name>
            <param-value>"text/html" ,"application/json" ,"plain/text"</param-value>
        </init-param>
        <init-param>
            <param-name>filterAction</param-name>
            <param-value>enforce</param-value>
        </init-param>
        <init-param>
            <param-name>httpHeaders</param-name>
            <param-value>
                Cache-Control: no-store, no-cache, must-revalidate, private
            </param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>ContentTypeBasedCachePreventionFilter</filter-name>
        <url-pattern>*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

    <listener>
        <listener-class>
            org.wso2.carbon.identity.application.authentication.endpoint.util.listener.AuthenticationEndpointContextListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>retry.do</servlet-name>
        <jsp-file>/retry.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>wait.do</servlet-name>
        <jsp-file>/long-wait.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>idf-confirm.do</servlet-name>
        <jsp-file>/identifier-logout-confirm.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>dynamic_prompt.do</servlet-name>
        <jsp-file>/dynamic_prompt.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>handle-multiple-sessions.do</servlet-name>
        <jsp-file>/handle-multiple-sessions.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>claims.do</servlet-name>
        <jsp-file>/requested-claims.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>oauth2_login.do</servlet-name>
        <jsp-file>/login.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>oauth2_authz.do</servlet-name>
        <jsp-file>/oauth2_authz.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>oauth2_consent.do</servlet-name>
        <jsp-file>/oauth2_consent.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>oauth2_logout_consent.do</servlet-name>
        <jsp-file>/oauth2_logout_consent.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>oauth2_logout.do</servlet-name>
        <jsp-file>/logout.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>oauth2_error.do</servlet-name>
        <jsp-file>/oauth2_error.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>samlsso_login.do</servlet-name>
        <jsp-file>/login.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>samlsso_logout.do</servlet-name>
        <jsp-file>/logout.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>samlsso_redirect.do</servlet-name>
        <jsp-file>/login.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>samlsso_notification.do</servlet-name>
        <jsp-file>/samlsso_notification.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>openid_login.do</servlet-name>
        <jsp-file>/login.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>openid_profile.do</servlet-name>
        <jsp-file>/openid_profile.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>passivests_login.do</servlet-name>
        <jsp-file>/login.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>tenantlistrefresher.do</servlet-name>
        <jsp-file>/tenant_refresh_endpoint.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>registration.do</servlet-name>
        <jsp-file>/registration.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>consent.do</servlet-name>
        <jsp-file>/consent.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>cookie_policy.do</servlet-name>
        <jsp-file>/cookie_policy.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>privacy_policy.do</servlet-name>
        <jsp-file>/privacy_policy.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>authenticate.do</servlet-name>
        <jsp-file>/authenticate.jsp</jsp-file>
    </servlet>

    <servlet>
        <servlet-name>error.do</servlet-name>
        <jsp-file>/generic-exception-response.jsp</jsp-file>
    </servlet>

    <servlet-mapping>
        <servlet-name>retry.do</servlet-name>
        <url-pattern>/retry.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>wait.do</servlet-name>
        <url-pattern>/wait.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>idf-confirm.do</servlet-name>
        <url-pattern>/idf-confirm.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>dynamic_prompt.do</servlet-name>
        <url-pattern>/dynamic_prompt.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>handle-multiple-sessions.do</servlet-name>
        <url-pattern>/handle-multiple-sessions.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>oauth2_login.do</servlet-name>
        <url-pattern>/oauth2_login.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>oauth2_authz.do</servlet-name>
        <url-pattern>/oauth2_authz.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>oauth2_consent.do</servlet-name>
        <url-pattern>/oauth2_consent.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>oauth2_logout_consent.do</servlet-name>
        <url-pattern>/oauth2_logout_consent.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>oauth2_logout.do</servlet-name>
        <url-pattern>/oauth2_logout.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>oauth2_error.do</servlet-name>
        <url-pattern>/oauth2_error.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>samlsso_login.do</servlet-name>
        <url-pattern>/samlsso_login.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>samlsso_logout.do</servlet-name>
        <url-pattern>/samlsso_logout.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>samlsso_redirect.do</servlet-name>
        <url-pattern>/samlsso_redirect.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>samlsso_notification.do</servlet-name>
        <url-pattern>/samlsso_notification.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>openid_login.do</servlet-name>
        <url-pattern>/openid_login.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>openid_profile.do</servlet-name>
        <url-pattern>/openid_profile.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>passivests_login.do</servlet-name>
        <url-pattern>/passivests_login.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>tenantlistrefresher.do</servlet-name>
        <url-pattern>/tenantlistrefresher.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>registration.do</servlet-name>
        <url-pattern>/registration.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>claims.do</servlet-name>
        <url-pattern>/claims.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>consent.do</servlet-name>
        <url-pattern>/consent.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>cookie_policy.do</servlet-name>
        <url-pattern>/cookie_policy.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>privacy_policy.do</servlet-name>
        <url-pattern>/privacy_policy.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>authenticate.do</servlet-name>
        <url-pattern>/authenticate.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>error.do</servlet-name>
        <url-pattern>/error.do</url-pattern>
    </servlet-mapping>

    <error-page>
        <exception-type>java.lang.Throwable</exception-type>
        <location>/generic-exception-response.jsp</location>
    </error-page>

    <!-- custom error pages -->
    <error-page>
        <error-code>400</error-code>
        <location>/errors/error_400.html</location>
    </error-page>
    <error-page>
        <error-code>401</error-code>
        <location>/errors/error_401.html</location>
    </error-page>
    <error-page>
        <error-code>403</error-code>
        <location>/errors/error_403.html</location>
    </error-page>
    <error-page>
        <error-code>404</error-code>
        <location>/errors/error_404.html</location>
    </error-page>
    <error-page>
        <error-code>405</error-code>
        <location>/errors/error_405.html</location>
    </error-page>
    <error-page>
        <error-code>408</error-code>
        <location>/errors/error_408.html</location>
    </error-page>
    <error-page>
        <error-code>410</error-code>
        <location>/errors/error_410.html</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/errors/error_500.html</location>
    </error-page>
    <error-page>
        <error-code>502</error-code>
        <location>/errors/error_502.html</location>
    </error-page>
    <error-page>
        <error-code>503</error-code>
        <location>/errors/error_503.html</location>
    </error-page>
    <error-page>
        <error-code>504</error-code>
        <location>/errors/error_504.html</location>
    </error-page>
    <error-page>
        <location>/errors/error.html</location>
    </error-page>

    <session-config>
        <cookie-config>
            <secure>true</secure>
        </cookie-config>
    </session-config>

</web-app>

A: By default all the web applications shipped with the product are protected from the CSRF attacks[1]

For WSO2 Identity Server, the configurations for mitigating CSRF
  attacks are enabled by default for all the applications that are built
  into the product. Therefore, you need to apply these configurations
  manually, only if you have any custom applications deployed in your
  product.

So you don't any extra configuration.

According to the information provided in ZAP vulnerability scan, it detects the commonauth request inside the authenticationendpoint web app as vulnerability. That is wrong let me explain why.
What is authenticationendpoint webapp and commonauth request?
In the WSO2 Identity server, authenticationendpoint serves the login, consents pages during the authentication. And the user actions (like credential, OTP code, federated login flows, consent approval) are submitted to the server using the commonauth request.
So these interactions happen from the browser before the user is not authenticated.
What is CSRF?[2]

Cross-site request forgery (also known as CSRF) is a web security
  vulnerability that allows an attacker to induce users to perform
  actions that they do not intend to perform.

So as the user is not authenticated yet, there is no additional advantage the attacker can get by submitting those authentication pages.
So these are configured to be skipped from the CSRF protection. You can check those endpoints in IS_HOME/repository/conf/security/Owasp.CsrfGuard.Carbon.properties file
# please remove the below entry to enable protection for services.
org.owasp.csrfguard.unprotected.Services=%servletContext%/services/*
org.owasp.csrfguard.unprotected.commonauth=%servletContext%/commonauth/*
org.owasp.csrfguard.unprotected.samlsso=%servletContext%/samlsso/*
org.owasp.csrfguard.unprotected.authenticationendpoint=%servletContext%/authenticationendpoint/*
org.owasp.csrfguard.unprotected.wso2=%servletContext%/wso2/*
org.owasp.csrfguard.unprotected.oauth2=%servletContext%/oauth2/*
org.owasp.csrfguard.unprotected.oidc=%servletContext%/oidc/*
org.owasp.csrfguard.unprotected.openid=%servletContext%/openid/*
org.owasp.csrfguard.unprotected.openidserver=%servletContext%/openidserver/*
org.owasp.csrfguard.unprotected.passivests=%servletContext%/passivests/*
org.owasp.csrfguard.unprotected.acs=%servletContext%/acs/*
org.owasp.csrfguard.unprotected.iwa=%servletContext%/iwa/*
org.owasp.csrfguard.unprotected.oauthiwa=%servletContext%/commonauth/iwa/*
org.owasp.csrfguard.unprotected.thrift=%servletContext%/thriftAuthenticator/*
org.owasp.csrfguard.unprotected.mex=%servletContext%/mexut/*
org.owasp.csrfguard.unprotected.identity=%servletContext%/identity/*

As you can see these are the endpoints used in the authentication flows.
[1] - https://is.docs.wso2.com/en/5.9.0/administer/mitigating-cross-site-request-forgery-attacks/#configuring-applications-in-wso2-product-to-mitigate-csrf-attacks
[2] - https://portswigger.net/web-security/csrf


text:
Q: Symfony EntityType - How to use custom layout? In my Symfony 3.x project, I have 3 entities:

*

*Project

*Property

*Category

Assumptions:

*

*Each Project has multiple Properties.

*Each Property has one Category.

*Each Property might have parent Property.

I would like to render Symfony form for Project entity. I'm using EntityType field for properties. However, instead of displaying them in one, long list, I would like to divide them in columns, with Categories as headers.
Regular way of displaying EntityType field:

What I would like to get:

How do I do that? - Without using dirty hacks in entities or views.

A: So the only way I found it working was:
In Repository class (pulling list of all properties with child properties and categories):
$this->getEntityManager()
    ->createQueryBuilder()
    ->select('t, category, children')
    ->join('t.category', 'category')
    ->leftJoin('t.children', 'children')
    ->where('t.parent IS NULL')
    ->orderBy('category.sortOrder', 'ASC')
    ->addOrderBy('t.sortOrder', 'ASC')
    ->addOrderBy('t.name', 'ASC');

$entities = $query->getResult();

$options = [];
/** @var Property $entity */
foreach ($entities as $entity) {
    $options[$entity->getCategory()->getName()][] = $entity;
}

In Entity class (pulling the list of IDs of selected properties, to preselect checkboxes in the view file):
public function getPropertyIds() {
    $properties = $this->getProperties();

    $propertyIds = [];
    foreach ($properties as $property) {
        $propertyIds[] = $property->getId();
    }

    return $propertyIds;
}

Edition form class, so the data can be validated:
$builder
    ->add(
        'properties',
        EntityType::class,
        [
            'label' => 'Properties',
            'class' => Property::class,
            'choice_label' => 'name',
            'placeholder' => '',
            'expanded' => true,
            'multiple' => true,
            'required' => false,
        ]
    );

And finally, the view file:
{% for categoryName, items in properties %}

{{ categoryName }}

        {% for property in items %}

                <input type="checkbox"
                       name="{{ form.properties.vars.full_name }}[]"
                       value="{{ property.id }}"
                       id="{{ form.properties.vars.id }}_{{ property.id }}">

                    {{ property.name }}

        {% endfor %}

{% endfor %}

{% do form.properties.setRendered %}

(I omitted the "checked" and "children" part in the view)
However this solution is not ideal in my point of view. I would rather to get rid of manually generating <input...> in the view - I would rather want to use some helper functions.
Anyway, this is some kind of low-level solution to my problem. Hope that helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create Plot with 2 Axes in R I need to plot MeanDailySteps (range 0 to 30000) and MeanDailySleepHours (0-600)on two different Y axis of the same chart with the  column data ID  (a unique string of discrete Characters which is common to both the Y axis variables) on the X axis. The data is in a dataframe "Steps_Sleep_Data".
I tried using the ggplot and scale_y_continuous as below, unfortunately this doesn't work. I tried other means using  par(new = TRUE)  which didn't work. I seem to be wrong somewhere.
Please help.
 ggplot(data=Steps_Sleep_Data, aes(x=Id, y=MeanDailySteps, fill=Id,colour="red", label=MeanDailySteps))+
  geom_bar(stat='identity')+
ggplot(data=Steps_Sleep_Data, aes(x=Id, y=MeanDailySleepMinutes, fill=Id, colour="blue", label=MeanDailySleepMinutes)) +
  geom_bar(stat='identity')+

scale_y_continuous(sec.axis = ~.*500)+
  theme(axis.text.y.left = element_text(color = "red"),
        axis.text.y.right = element_text(color = "blue"))


text:
Q: How to sum a list of integers with java streams? I want to sum a list of Integers. It works as follows, but the syntax does not feel right. Could the code be optimized?
Map<String, Integer> integers;
integers.values().stream().mapToInt(i -> i).sum();

A: From the docs

Reduction operations
  A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers, or accumulating elements into a list. The streams classes have multiple forms of general reduction operations, called reduce() and collect(), as well as multiple specialized reduction forms such as sum(), max(), or count().
Of course, such operations can be readily implemented as simple sequential loops, as in:
int sum = 0;
for (int x : numbers) {
   sum += x;
}

However, there are good reasons to prefer a reduce operation over a mutative accumulation such as the above. Not only is a reduction "more abstract" -- it operates on the stream as a whole rather than individual elements -- but a properly constructed reduce operation is inherently parallelizable, so long as the function(s) used to process the elements are associative and stateless. For example, given a stream of numbers for which we want to find the sum, we can write:
int sum = numbers.stream().reduce(0, (x,y) -> x+y);

or:
int sum = numbers.stream().reduce(0, Integer::sum);

These reduction operations can run safely in parallel with almost no modification:
int sum = numbers.parallelStream().reduce(0, Integer::sum);

So, for a map you would use:
integers.values().stream().mapToInt(i -> i).reduce(0, (x,y) -> x+y);

Or:
integers.values().stream().reduce(0, Integer::sum);

A: I have declared a list of Integers.
ArrayList<Integer> numberList = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));

You can try using these different ways below.
Using mapToInt
int sum = numberList.stream().mapToInt(Integer::intValue).sum();

Using summarizingInt
int sum = numberList.stream().collect(Collectors.summarizingInt(Integer::intValue)).getSum();

Using reduce
int sum = numberList.stream().reduce(Integer::sum).get().intValue();

A: May this help those who have objects on the list.
If you have a list of objects and wanted to sum specific fields of this object use the below.
List<ResultSom> somList = MyUtil.getResultSom();
BigDecimal result= somList.stream().map(ResultSom::getNetto).reduce(
                                             BigDecimal.ZERO, BigDecimal::add);

A: This will work, but the i -> i is doing some automatic unboxing which is why it "feels" strange. mapToInt converts the stream to an IntStream  "of primitive int-valued elements".  Either of the following will work and better explain what the compiler is doing under the hood with your original syntax:
integers.values().stream().mapToInt(i -> i.intValue()).sum();
integers.values().stream().mapToInt(Integer::intValue).sum();

A: This would be the shortest way to sum up int type array (for long array LongStream, for double array DoubleStream and so forth). Not all the primitive integer or floating point types have the Stream implementation though.
IntStream.of(integers).sum();

A: You can use reduce method:
long sum = result.stream().map(e -> e.getCreditAmount()).reduce(0L, (x, y) -> x + y);

or
long sum = result.stream().map(e -> e.getCreditAmount()).reduce(0L, Integer::sum);

A: You can use reduce() to sum a list of integers.
int sum = integers.values().stream().reduce(0, Integer::sum);

A: Unfortunately looks like the Stream API only returns normal streams from, say, List<Integer>#stream().  Guess they're pretty much forced to because of how generics work.
These normal Streams are of generic objects so don't have specialized methods like sum() etc. so you have to use the weird re-stream "looks like a no-op"  conversion by default to get to those methods... .mapToInt(i -> i).
Another option is using "Eclipse Collections" which are like an expanded java Stream API
IntLists.immutable.ofAll(integers.values()).sum();

A: I suggest 2 more options:
integers.values().stream().mapToInt(Integer::intValue).sum();
integers.values().stream().collect(Collectors.summingInt(Integer::intValue));

The second one uses Collectors.summingInt() collector, there is also a summingLong() collector which you would use with mapToLong.

And a third option: Java 8 introduces a very effective LongAdder accumulator designed to speed-up summarizing in parallel streams and multi-thread environments. Here, here's an example use:
LongAdder a = new LongAdder();
map.values().parallelStream().forEach(a::add);
sum = a.intValue();

A: You can use collect method to add list of integers.
List<Integer> list = Arrays.asList(2, 4, 5, 6);
int sum = list.stream().collect(Collectors.summingInt(Integer::intValue));

A: There is one more option no one considered here and it reflects on usage of multi-core environment. If you want to use its advantages, then next code should be used instead of the other mentioned solutions:
int sum = integers.values().parallelStream().mapToInt(Integer::intValue)
        .reduce(0, Integer::sum, Integer::sum);

This solution is similar to other ones, but please notice the third argument in reduce. It tells compiler what to do with partial summaries calculated in different chunks of the stream, by different threads. Also instead of stream(), the parallelStream() is used. In this case it would just summarize it. The other option to put as third argument is (i, j) -> i + j, which means that it would add a value of a stream chunk (j) to the current value (i) and use it as a current value for the next stream chunk until all partial results are processed.
Even when using plain stream() it is useful to tell to reduce what to do with stream chunks' summaries, just in case someone, or you, would like to parallelize it in the future. The initial development is best time for that, since later on you need to remember what this is supposed to be and need to spend some time in understanding the purpose of that code again.
And of course instead of method reference operator you can have different dialect of lambda. I prefer it this way as more compact and still easy readable.
Also remember this can be used for more complex calculations too, but always be aware there are no guarantees about sequence and deployment of stream elements to threads.

A: IntStream.of(1, 2, 23).sum();
IntStream.of(1, 2, 23,1, 2, 23,1, 2, 23).max().getAsInt();


text:
Q: Is there a way to detect whether there is an element blocking a clickable element using Selenium? I'm trying to create a script that would click on every link on a given URL, but occasionally there are pop-ups/overlays that appear that block the link.
Would be be possible to detect these pop-ups/overlays using Selenium or Javascript?
I've tried using is_displayed, is_enabled, and EC.element_is_clickable but nothing seems to work.
EDIT: I'm hoping to find a way to detect the blocking element without having to click.

A: this using this:
try:
    element.Click()
except ElementNotClickableException as x:
    //handle not being able to click element here, you can try to select the element by taking the attributes that are returned in the exception message, or check the exception message to see if it really is an ad, something like x.Message.Contains("class=pop-up")

Hope it helps


text:
Q: Jugs of water puzzle... The problem:

Explain how to measure 8 units of water using only two jugs, one of
  which holds precisely 12 units, the other holding precisely 17 units of water.

Given the hint "Find $gcd(12,17)$", it is clear that since 17 is prime, $gcd(12,17)=1$. But I am not sure how that actually helps to solve the problem. I don't need a full answer , but just an idea of how to proceed. Anybody have ideas?

A: First, for any jug problem with jugs of capacities $X$ and $Y$ with $g=\gcd(X,Y)$, you can only end up with quantities of water that are multiples of $g$ after any number of operations (check that every operation you perform conserves the residual respect to $g$). Therefore, the hint has a point of making you realize this connection. In this case you learn that there exists a solution but there's more, which brings me to...
... Second, once you realize this connection, then you know you can write an integer equation $aX+bY=ng$ where one of ${a,b}$ is positive and the other one is non-positive, and $n$ is the desired factor to reach your goal multiple of $g$. I will not solve this equation for your example but I will tell you how to continue once you do. Let's say $a$ is the positive one (since I am not assigning values to $X$ and $Y$, there's no loss of generality), then I can think of $a$ as filling up $X$ and $b$ as emptying $Y$. How do you operate then?
Fill $X$ up, and pour it into $Y$. Every time $Y$ fills up, throw the water away, and continue pouring $X$ into $Y$. After $a$ times you have filled $X$ and poured it into $Y$, and you had thrown the water away $b$ times, then you have $ng$ gallons of water in one of the jugs. Which one will depend on whether you reach $a$ or $b$ first.
This is NOT the most efficient way, but it is what shows the connection between the jugs problems and the $\gcd$. It also lets you know whether it is possible to solve.

A: See Bézout's identity.  This series of equations closely follow a gcd algorithm for 12 and 17.
$$\begin{align}
\text{(1)}&& 17a - 12b = 8
\\ \text{(2)} && \text{Let } c = b - a
\\ \text{(3)} && 5a - 12c = 8
\\ \text{(4)} && \text{Let } d = a - 2c
\\ \text{(5)} && 5d - 2c = 8
\\ \text{(6)} && \text{Let } e = c - 2d
\\ \text{(7)} && d - 2e = 8, \text{ so } d = 8 + 2e
\\ \text{(8), from (6) and (7)} && c = 16 + 5e
\\ \text{(9), from (4), (7), (8)}&& a = (8+2e) + 2(16+5e) = 40 + 12e
\\ \text{(10), from (2), (8), (9)}&& b = (16+5e) + (40 + 12e) = 56 + 17e
\end{align}
$$
Set $e = -3$ and you get $a = 4, b = 5$.  Fill the 17-jug 4 times and empty the 12-jug 5 times and you get $4\cdot17 - 12\cdot5 = 68 - 60 = 8$ units.


text:
Q: Format used in INPUT section while importing a CSV file into SAS I'd like to get a list of formats used for each variable in the INPUT section. For example, say, we have a csv file and manually import data into SAS. In the code section, we will have smth like that:
DATA WORK.SAS_data_1;
LENGTH
    A                  8
    B                $ 9
    C                  8
    D                  8
    E                  8 ;
FORMAT
    A                BEST1.
    B                $CHAR9.
    C                MMDDYY10.
    D                BEST1.
    E                BEST3. ;
INFORMAT
    A                BEST1.
    B                $CHAR9.
    C                MMDDYY10.
    D                BEST1.
    E                BEST3. ;
INFILE 'C:\Users\AppData\Local\Temp\SEG3592\SAS_data_1-ab6243ce7f064047b5e010c113d2f6a3.txt'
    LRECL=27
    ENCODING="WLATIN1"
    TERMSTR=CRLF
    DLM='7F'x
    MISSOVER
    DSD ;
INPUT
    A                : ?? BEST1.
    B                : $CHAR9.
    C                : ?? MMDDYY9.
    D                : ?? BEST1.
    E                : ?? BEST3. ;
RUN;

I'd like to know what formats are used in the INPUT section, that is: BEST1. for A, $CHAR9. for B, MMDDYY9. for C, etc.
I've found the code that summaries the format and informat for each variable in SASHELP.CARS dataset but I cannot find the format used in the INPUT section. Does anyone know where to find it? At times (for numerical variables) these formats can be different. Here is the code:
proc sql noprint ;
create table varlist as
select memname,varnum,name,type,length,format,informat, label
from dictionary.columns
where libname='SASHELP' and memname='CARS'
;
quit;

Thank you.

A: It's not possible to recover the original input code used for a particular dataset.  If informats were used with the INFORMAT statement, then you can see those (as you did in your example).
But determining whether a dataset was read in like this:
data have;
  input x;
  datalines;
1
2
3
4
5
;;;;
run;

Or like this:
data have;
  input @1 x 1.;
datalines;
1
2
3
4
5
;;;;
run;

Or even this:
data have;
  input @1 x 12.;
datalines;
1
2
3
4
5
;;;;
run;

All would appear exactly identically in SAS and have exactly identical metadata.  The only way to know how they were input would be to have access to the input program and log it.

A: SAS does not need be told how to convert most strings into values. In your example only the variable C needs to use special informat so that SAS knows how to interpret the text as a date.
You can use the INFORMAT statement to attach an informat specification to a variable in a dataset. However that metadata does not really serve much purpose in SAS, except perhaps if you are still using PROC FSEDIT.
If you want to store instructions on how your text file (CSV files are text files) is formatted then you should store that information into another document (or database). Or just save the SAS program.


text:
Q: Why doesn't grep give the matching line? I've just noticed that
grep -rni 'a2}' *

does not give all documents that have a string a2} the matching line. Why is this the case?
I've tried to create a minimal example, but when I create a new file and paste the content, it fails. So I've uploaded the file to a Git repository. Perhaps it's a encoding problem.
The content of the file is:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{KV-Diagramme}
\label{chap:a2}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  \PsTexAbbildungOhneCaption{figures/a2-1}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "skript"
%%% End:

The result of grep -rni 'a2}' * is
moose@pc08 ~/Downloads/algorithms/grep $ grep -rni "a2}" *
%%% End:master: "skript"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

but I expected
moose@pc08 ~/Downloads/algorithms/grep $ grep -rni "a2}" *
\label{chap:a2}

Why do I get this result?

A: The file has CR line terminators so it looks a a single-line file:
#> file anhang-2.tex
anhang-2.tex: LaTeX document, ASCII text, with CR line terminators

convert it to Linux format:
#>  mac2unix anhang-2.tex
mac2unix: converting file anhang-2.tex to Unix format ...
#>  grep -rni 'a2}' anhang-2.tex
3:\label{chap:a2}

A: It's because your file is using Mac OS 9 line endings. You will need to first translate to UNIX line endings. How you do so depends on your scenario but you can do one file with this:
tr '\r' '\n' < anhang-2.tex > anhang-2.txt

Then you will be able to grep that new file.


text:
Q: Examples of groups that are not subgroup Sorry, my English is poor, but I have a question. It is usual to find the definition of subgroup as: "We define a subgroup $H$ of a group $G$ to be a nonempty subset $H$ of $G$ such that when the group operation of $G$ is restricted to $H$, $H$ is a group in its own right". But it is known that $A=\left\{\begin{pmatrix}a & a\\a& a\end{pmatrix} \mbox{ with  } a \in R \mbox{ and } a\neq 0 \right\}$ is a group with the usual product of matrices but it is not a  subgroup of $M_{2\times2}$. Do you know another examples of subsets like this?
Edit: I'll try to change a little the question: In the set of matrices $M_{2\times2}$ there are subsets which are groups in regard to the usual matrix product but have a different neutral element. An example would be the group of all nonsingular matrices over $\mathbb R$,  $GL(2,\mathbb R)$ and $H=\left\{\begin{pmatrix}a & a\\a& a\end{pmatrix} \mbox{ with  } a \in \mathbb R \mbox{ and } a\neq 0 \right\}$. Do you know of other examples of subsets (groups) with elements of the same nature, that given the same operation have a different neutral element?

A: If $M$ is a monoid and $X\subseteq M$ is a subset closed under multiplication, it possible for $X$ to not contain $\mathrm{id}_M$ and yet have its own identity element, even being a group. In particular, every ring is a monoid with respect to multiplication, like matrix algebras, so we can use them.

*

*If $R\oplus S$ is a direct sum of nontrivial unital rings, then $R^\times\times\{0_S\}$ fails to contain the identity element $1_{R\oplus S}=(1_R,1_S)$, but it is a group with respect to multiplication. In particular if these are matrix algebras $R=M_n(\mathbb{F})$ and $S=M_m(\mathbb{F})$ over a field $\mathbb{F}$ then this is the group of all block diagonal matrix with $n\times n$ block an invertible matrix and all other blocks zeroed. More generally we can use $R^\times\times\{e\}$ with any idempotent $e^2=e$ in $S$.

*The ideal $(x)=\mathbb{F}x$ minus $\{0\}$ in the ring $\mathbb{F}[x]/(x^2-x)$.

*If $G$ is a group (or monoid really), we can adjoin a new identity $e$ to it, so that the multiplication table on $\{e\}\cup G$ extends that of $G$ with $eg=g=ge$ for all $g\in \{e\}\cup G$; then $G$ does not contain the identity element $e$.

A: The set of non-zero real numbers is a group under multiplication. As a subset of real numbers, it is not a subgroup under addition.
The  subset $\{-1, +1\}$ of integers is a group wrt multiplication but not a subgroup under addition of integers.
All continuous maps $f\[a,b]\to[a,b]$ that are bijective form a group under composition of functions as binary operation. It is a subset of the group of all functions $[a,b]\to \mathbf{R}$ (this being a group under point-wise addition of functions). But not a subgroup.


text:
Q: What will I see if I travelled to a distant planet in 100 times faster than speed of light and look back? Consider this scenario. I enter a space ship at 10:00 AM, it starts to move at a speed 100 times faster than  light, I travel for 55 mins. And then slow down to very much less than speed of light and land on another planet at 11:00 AM. Now I look at Earth with a telescope. What period of Time am I going to see?

A: Lets make it 10 minutes of travel, because I'm lazy. At 100x light speed you travel 1000 light minutes from Earth, so looking at earth you see images from 10:10 minus 1000 minutes which is 10:10 minus 16.6 hours. Which I am also too lazy to work out, but you get the idea?


text:
Q: How to exclude specific subfolders from the generated tar file? I am using Python 3 with the tarfile module to compress some folders (with subfolders). What I need to do: to set a couple of subfolders to be excluded from the final tar file.
For example, say my folders looked like:
dir/
├── subdirA
│   ├── subsubdirA1
│   │   └── fileA11.txt
│   │   └── fileA12.txt
│   ├── subsubdirA2
│   │   └── fileA21.txt
│   │   └── fileA22.txt
│   └── fileA.txt
├── subdirB
│   ├── subsubdirB1
│   │   └── fileB11.txt
│   │   └── fileA12.txt
│   ├── subsubdirB2
│   │   └── fileB21.txt
│   │   └── fileB22.txt
│   └── fileB.txt
└── main.txt

Now, I say I wanted to include everything in dir/ except the contents of subsubdirA2 and of subsubdirB2. Based on this answer, I have tried:
EXCLUDE_FILES = ['/subdirA/subsubdirA2', '/subdirB/subsubdirB2']
mytarfile.add(..., filter=lambda x: None if x.name in EXCLUDE_FILES else x)

Or:
EXCLUDE_FILES = ['/subdirA/subsubdirA2/*', '/subdirB/subsubdirB2/*']
mytarfile.add(..., filter=lambda x: None if x.name in EXCLUDE_FILES else x)

Or:
EXCLUDE_FILES = ['/subdirA/subsubdirA2/*.*', '/subdirB/subsubdirB2/*.*']
mytarfile.add(..., filter=lambda x: None if x.name in EXCLUDE_FILES else x)

I also tried variants of the three options above where the subfolder paths started without / or with dir or with /dir. None worked - all the time, everything within dir was included.
How could I correctly exclude specific subfolders from a tar file I want to generate? If a different module/library is required instead of tarfile, that is fine.

A: I didn't find reference about tarfile the way you need, but you can use thread and include shell command like this:
import subprocess

exclude=['dir/subdirA/subsubdirA2','dir/subdirA/subsubdirA1','dir/subdirA/text.tx']
excludeline=''
for x in exclude:
    excludeline += ' --exclude '+x
# cmd has tar command
cmd='tar -czvf dir.tar dir  '+ excludeline
print(cmd)
process = subprocess.Popen(cmd,shell=True,stdin=None,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
result=process.stdout.readlines()
# All files were compressed
if len(result) >= 1:
    for line in result:
        print(line.decode("utf-8"))

Where cmd has value in this example :
cmd = tar -czvf dir.tar dir   --exclude dir/subdirA/subsubdirA2 --exclude dir/subdirA/subsubdirA1 --exclude dir/subdirA/text.tx

A: I think the EXCLUDE_FILES that you are using should be matched against the file names with pattern matching. Here is how I would do that:
import re, os
EXCLUDE_FILES = ['/subdirA/subsubdirA2/*', '/subdirB/subsubdirB2/*']
pattern = '(?:% s)' % '|'.join(EXCLUDE_FILES) #form a pattern string

For using a filter against the pattern we'll use re.match,
mytarfile.add(..., filter=lambda x: None if re.match(pattern, x.name) else x)

We exclude the file if file.name matches any of the patterns specified in EXCLUDE_FILES. Hope this helps.


text: Q: How to install Gnome specific version on Arch I am using Arch with GNOME 41.2 and want to use GNOME 3.38.3 how can I install it, I checked everywhere but I am unable to find any installation guide that tells how to install any specific version of GNOME. I am new to Linux and I've spent my 5 hours searching for this please help me out.


text:
Q: normalize the input of relu function encountered a runtime error when I try to pass the maximum activation value from previous layer to normalize the input of relu in next layer I encounter a runtime error as below. However, when I pass fixed value it works well without any error.
File "/usr/local/lib/python3.7/dist-packages/torch/autograd/__init__.py", line 175, in backward allow_unreachable=True, accumulate_grad=True)  # Calls into the C++ engine to run the backward pass
RuntimeError: Trying to backward through the graph a second time (or directly access saved
tensors after they have already been freed). Saved intermediate values of the graph are freed
when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to
backward through the graph a second time or if you need to access saved tensors after calling
backward.

As you see in this code below, I pass the argument prev_layer_max from the previous layer and encounter the error:
class th_norm_ReLU(nn.Module):
    def __init__(self, modify):
        super(th_norm_ReLU, self).__init__()
        self.therelu = F.relu

    def forward(self, input, prev_layer_max):
      output = input * (prev_layer_max / input.max())
      norm_output = self.therelu (output)

      return norm_output

But if I use a fixed value instead of passed prev_layer_max argument, as this code below I make it equal to 1 it works normally without any error:
    def forward(self, input, prev_layer_max = 1):
        output = input * (1 / input.max())
        norm_output = self.therelu (output)

the training loop is as below :
for epoch in range(params.epochs):
    running_loss = 0

    start_time = time.time()
    for i, (images, labels) in enumerate(train_loader):
        model.train()
        model.zero_grad()
        optimizer.zero_grad()
        labels.to(device)
        images = images.float().to(device)
        outputs = model(images, epoch)
        loss = criterion(outputs.cpu(), labels)
        running_loss += loss.item()
        loss.backward()
        optimizer.step()

here is the forward in the model where I record the max of each layer in a list ( thresh_list ):
def forward(self, input, epoch):
    x = self.conv1(input)
    x = self.relu(x,1)
    self.thresh_list[0] = max(self.thresh_list[0], x.max()) #to get the max activation
    x = self.conv_dropout(x)
    x = self.conv2(x)
    x = self.relu(x, self.thresh_list[0])
    self.thresh_list[1] = max(self.thresh_list[1], x.max())
    x = self.pool1(x)
    x = self.conv_dropout(x)
    x = self.conv3(x)
    x = self.relu(x, self.thresh_list[1] )
    self.thresh_list[2] = max(self.thresh_list[2], x.max())

The Relue function I call is :
self.relu = th_norm_ReLU(True)

and the_norm_ReLU model is shown above.


text:
Q: Can you get smaller integer in any low level language independent of architecture? An integer could be 8 bytes, which is 2^64. A lot of values.
Let say I wanted to write a small program that would store value like this in a file:
3 1 5 6 2 8 9 0 1 2 ....
at no point my value is going to be higher that 9. So I only need 10 combinations,
that I can get by data type that takes 2^4 (16 combinations) only. Not 2^64.
won't it be more efficient.. how can I accomplish that. Does C++ has native single digit type.

A: You can make such a type, but you probably don't want to.
I would suggest you use unsigned char or signed char, which are both single-byte types.  (You may consider using the type aliases std::uint8_t and std::int8_t, which better express your intent to store 8-bit numbers.)
It is possible to create a class with a single-byte numeric member that can store two separate digits, but you will lose performance since operations will have to extract the digit you care about, possibly shift it, and then the reverse operation when assigning to it.  That is to say, statements like:
numbers[1] = v;

Would wind up being implemented something like:
combined_numbers[0] = (combined_numbers[0] & 0x0f) | (v << 4);


text:
Q: Powershell System.IO.StreamReader Read method I'm trying to learn how to use streams in PowerShell. I've been able to understand all of the methods in StreamReader except the Read(char[], In32, In32).
I've only been able to get this method to work using
[char[]]$ca = 'a','b','c','d','e'
$reader = [System.IO.StreamReader]::new($inputFile)
$reader.Read($ca,0,$ca.Length)
$reader.Close()

My question is how can use the Read method without creating an array before hand?  Do I have to create and array of 1024 chars if That is the amount of data I want to read into the buffer?
Thanks

A: You will have to create the buffer array beforehand, but you don't need to initialize it:
$ca = [char[]]::new(1024)
$reader = [System.IO.StreamReader]::new($inputFile)
$reader.Read($ca,0,$ca.Length)
$reader.Close()


text:
Q: A really complicated question on newtonian (classical) mechanics
A particle is moving along the positive $y$-direction with a velocity $v_1$. A belt is placed in front of it which is moving in the positive $x$-direction with a velocity $v_2$.

If the co-efficient of friction between the belt and the particle is say $z$ and the point where the belt and the particle collide is taken as the origin, then find the point where the relative sliding between them stops, given the mass of the particle is $m$. (We have to find the $x$ and $y$ co-ordinates with respect the origin).
The way i understand the question is that the friction acts in the backward direction and provides negative acceleration. So we have to integrate it using the relation $a$ = $vdv/dx$ where $dv/dx$ refers to the slope of velocity and acceleration in the velocity displacement graph.Problem is what are the integration limits.


text:
Q: Investigate jar differences I am currently trying to rebuild an old application from a tag and unfortunately I get jar files containing "non binary equals" .class files.
I've tried to compare the decompiled version of these .class files and they seem to be equals but is there a secure and automated way to diagnose such .class equality ?
It's important for me to know if my generated jars are equal to the old ones, even if the .class files inside are not binary equals, but functionally equals (certainly due to a different javac version).
Thx
PS.

*

*Both are compiled with the same major version (Major: 52)

*If I compare the output of "old" and "new" using javap -c command I have no differences

*If I compare the output using javap -v command I find a few lines shift (eg: #480 in old becomes #478 in new for the same instruction) and some missing errors declarations (eg: 365 = Utf8 Lorg/eclipse/ui/PartInitException; only in old)

A: It depends on what you mean by "equals".
If you mean byte for byte equality, then just use the cmp utility.
You appear to mean something else.  But here's the problem: there is sufficient potential for variability in ".class" files that accurate comparison may be difficult:

*

*The content of a .class file will depend on the compiler used; e.g. the Oracle compiler, the Eclipse compiler and others such as Jikes will most likely emit different byte codes.

*The content will depends on compiler options; e.g. -source and -target, -g settings, and so on.

*The content of a .class file may depend on the precise compiler major / minor / patch version numbers.  And build platform.

*Trivial changes such as adding / removing source code blank lines or comments can alter source line numbers resulting in different .class files

*Some Java compiler store the compiler version and/or timestamp as non-standard attributes in the .class files.

*Differences in libraries can change lead to differences in code compiled against them.

I would suggest two approaches:

*

*compare javap output, ignoring things that don't affect code, signatures and constants in the constant pool

*identify the compiler, version and options used to compile the preexisting JARs, and use the exactly the same when recompiling.

A: I finally found an approach which is acceptable from my point of view

*

*Compare "generated" and "old" equivalent jar files using zipcmp

*If differences are found in ".class" files, diff a decompilation of "generated" and "old" .class and print this diff

*If no decompilation diffs are found consider the .class are equivalent

I wrote this script to help with the work
#!/bin/bash

GENERATED="<changeme>/application_5.2.0_generated"
OLD="<changeme>/application_5.2.0_old"
#DECOMPILER="javap -c"
DECOMPILER="java -jar <changeme>/procyon-decompiler-0.5.30.jar"

for plugin in $GENERATED/plugins/*; do
    echo "$plugin"
    base=$(basename "$plugin")
    old_plugin="$OLD/plugins/$base"

    zipcmp $plugin $old_plugin

    if [ $? -ne 0 ]; then
        mkdir -p "$GENERATED/unzip/$base" && cd "$GENERATED/unzip/$base" && jar xf $plugin
        mkdir -p "$OLD/unzip/$base" && cd "$OLD/unzip/$base" && jar xf $old_plugin

        for class in $(zipcmp $plugin $old_plugin | grep ".class" | awk '{print $4;}' | uniq); do
            diff <($DECOMPILER "$GENERATED/unzip/$base/$class") <($DECOMPILER "$OLD/unzip/$base/$class") > /tmp/output
            if [ $? -ne 0 ]; then
                echo "diff <($DECOMPILER $GENERATED/unzip/$base/$class) <($DECOMPILER $OLD/unzip/$base/$class)"
                cat /tmp/output
            fi
        done
    fi
done


text:
Q: Canvas getImageData and putImageData load image partially Here is my code. I am uploading a image and using like this :
> var canvas = document.createElement('canvas');
> var context = canvas.getContext('2d');
> context.drawImage(image, 0, 0);

This works fine but if I copy the imagedata like below to another canvas. It loads image partially.
var canvas = document.getElementById('myCanvas');
var context1 = canvas.getContext('2d');
context1.putImageData(context.getImageData(0, 0, image.width, image.height), 0, 0);

I tried same approach by creating two canvas and this code which worked fine but without image.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 300, 300);

var d = document.getElementById("myCanvas1");
var btx = d.getContext('2d');
var imgData = ctx.getImageData(0, 0, 300, 300);
btx.putImageData(imgData, 0, 0);

If i create two canvas it works fine but not like the above where I am using in memory canvas.
My HTML file has this :
<canvas id="myCanvas" width="960" height="960"></canvas>
<canvas id="myCanvas1" width="960" height="960"></canvas>

A: When you create canvases, you need to set their width manually. Default canvas size is 300x150. From here HTMLCanvasElement.
Something like this:
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0);

A: To copy one canvas to another use drawImage rather than getImageData, setImageData That way you will use the GPU to move the pixels rather than the CPU. You also have the option to resize, crop, and apply a variety of FXs.
// create a copy of canvasSource
// returns the newly created canvas.
function copyCanvas(canvasSource){
    var canvasCopy = document.createElement("canvas");
    canvasCopy.width = canvasSource.width;
    canvasCopy.height = canvasSource.height;
    canvasCopy.getContext("2d").drawImage(canvasSource, 0, 0);
    return canvasCopy;
}


text:
Q: Constructor takes Integer but not String This works:
struct Comic
    endpoint::String
end

function Comic(id::Int)
    url = "https://xkcd.com/$id/info.0.json"
    Comic(url)
end

Comic(1)

It returns Comic("https://xkcd.com/1/info.0.json").
This doesn't work:
struct Comic
    endpoint::String
end

function Comic(id::String)
    url = "https://xkcd.com/$id/info.0.json"
    Comic(url)
end

Comic("1")

It kills the Julia process.
Why doesn't the second example work?

A: In your code Comic("1") calls Comic(id::String).
Comic(id::String) calls Comic(url) which again means calling Comic(id::String)
So you simply end up with an endless recursive loop.

A: The other answer explains why this crashes the Julia process; now, to make this work the way you intended, you can simply use an inner constructor:
julia> struct Comic
           endpoint::String
           Comic(id::String) = new("https://xkcd.com/$id/info.0.json")
       end

julia> Comic("1")
Comic("https://xkcd.com/1/info.0.json")

This works because new doesn't recursively call this constructor (which would lead to the crash). Instead it creates the object directly with the given string as its element.
Another option to consider is the URIs.jl package.
julia> using URIs

julia> struct XComic
          endpoint::URI
       end

julia> XComic(id::String) = XComic(URI("https://xkcd.com/$id/info.0.json"))
XComic

julia> XComic("4")
XComic(URI("https://xkcd.com/4/info.0.json"))


text:
Q: For what kind of queries is In-Memory OLTP faster in Sql Server? I have been doing research on In-Memory OLTP that comes with SQL-Server 2014. I am reading many blogs, whitepapers and available presentations around the web.
So far, i have found only one scenario where In-Memory OLTP is rapid fast than disk-based tables. Insert operation in in-memory table was almost 100 times faster than on disk-based tables.
I haven't found any other queries where in-memory oltp is faster. I have tried Select, Update, Join and Where queries on both table but couldn't found scenario where In-Memory OLTP was better.
It would be great if you could suggest me some queries or scenarios.
Following are two select queries and all tables used in query have 1.4 Million Rows.
1) In-memory (Both the tables are disk-based)
SELECT SD.shoppingcartid
,SD.shoppingcartname
,sr.Createdate
,sr.TotalPrice
,Rank() OVER (
    ORDER BY TOTALPRICE DESC
    ) AS PriceRank
FROM shoppingcart SR
JOIN shoppingcartdetail SD ON (SD.shoppingcartid = SR.shoppingcartId)
WHERE (
        (
            TOTALPRICE > 50000
            AND CREATEDATE >= GETDATE()
            )
        OR (
            TOTALPRICE / 3 < 50000
            AND CREATEDATE <= GETDATE()
            )
        )
ORDER BY TotalPrice DESC

Time Taken : 8 Seconds to return 0.7 Million Rows
2) In-Memory (Both tables are In-Memory table)
SELECT SD.shoppingcartid
    ,SD.shoppingcartname
    ,sr.CreatedDate
    ,sr.TotalPrice
    ,Rank() OVER (
        ORDER BY TOTALPRICE DESC
        ) AS PriceRank
FROM shoppingcart_reg SR
JOIN shoppingcartdetail_regular SD ON (SD.shoppingcartid = SR.shoppingcartId)
WHERE (
        (
            TOTALPRICE > 50000
            AND CREATEdDATE >= GETDATE()
            )
        OR (
            TOTALPRICE / 3 < 50000
            AND CREATEdDATE <= GETDATE()
            )
        )
ORDER BY TotalPrice DESC

Time Taken : 11 seconds to return 0.7 Million Rows


text:
Q: reduce a nested vector to another one in Clojure What is an idiomatic way of handling such stuff in Clojure?
I have:
(def data1
    [1 [2 3]])

(def data2
    [1 [[2 [3 [4]]]
        [22 33]]])

I want to get:
[1 2 3]

and
[[1 2 3 4]
 [1 22 33]]

respectively. The nested levels of inner vectors may be of different lengths.
I cannot wrap my head around the nature of such inputs and looking for help. Basically a function should map an input (which is a vector) to an output (vector, also) which, in essence, is a vector of all the "routes" from its head to the innermost elements. This is a vague explanation, will be grateful for a better one.

A: (defn transform [v]
  (let [[x & [xs]] v]
    (loop [r xs
           res []]
      (cond
        (empty? r) res
        (vector? (first r)) (recur (rest r)
                                   (conj res
                                         (into
                                          (conj [] x)
                                          (flatten (first r)))))
        :else (into (conj res x) r)))))

(def data1
  [1 [2 3]])

(def data2
  [1 [[2 [3 [4]]]
      [22 33]]])

(def data3
  [1 [[20 25 [30 [40 [50]]]]
      [2 3 [4 5 [6 7 [8 9]]]]
      [[60] 70 [80 [90 100 [110 120 130 [140 150]]]]]]])

; user=> (transform data1)
; [1 2 3]
; user=> (transform data2)
; [[1 2 3 4] [1 22 33]]
; user=> (transform data3)
; [[1 20 25 30 40 50] [1 2 3 4 5 6 7 8 9] [1 60 70 80 90 100 110 120 130 140 150]]

A: (defn transform [[f & r]]
(let [rr (apply concat r)]
  (if (= (flatten rr) rr)
    (vec (cons f rr))
    (mapv #(if (vector? %)
            (vec (cons f (flatten %)))
            [f %])
         rr))))

; Test Cases
(transform [1 [2 3]]) => [1 2 3]
(transform [1 [[2 [3 [4]]] [22 33]]]) => [[1 2 3 4] [1 22 33]]
(transform [1 [[2 [3 [4]]] [22 33] 44]]) => [[1 2 3 4] [1 22 33] [1 44]
(transform [1]) => [1]
(transform [1 [2]]) => [1 2]


text:
Q: Exclude all attrs auto-generated methods from sphinx I have a simple attrs data class:
from attrs import frozen

@frozen
class Person
    raw: str

I document it with the simplest *.rst file:
.. autoclass:: api.main.person.Person
   :members:
   :exclude-members: __init__

but if I need to remove __eq__, __hash__ etc. as well, Is there a better way?


text:
Q: How does BigtableIO achieves exactly once writes? Dataflow guarantees exactly once processing and delivery as well. Is this guaranteed at sinks by not allowing mutations to the existing records and only allowing idempotent overwrite?

A: You're correct. The BigtableIO Dataflow/Beam connector will only write Put and Delete mutations, ignoring Append and Increment ones. See Note in the documentation for the class.


text:
Q: Retain query params while changing url path I am currently on the following endpoint.
http://www.mydomaintest.com/first_path?param1=1&param2=2

I am looking to change this to following where the path is now /new_path:
http://www.mydomaintest.com/new_path?param1=1&param2=2

Currently performing the following command which does change the path, but it removes the query params.
window.location.href = '/new_path';

How can I change the path but still retain the query params?

A: Instead of changing href just change the pathname, like this:
window.location.pathname = '/new_path';

It will update the URL and will retain the query params.


text:
Q: How is this code working for finding the number of divisors of a number? http://www.spoj.com/problems/NDIV/
This is the problem statement. Since i'm new to programming, this particular problem ripped me off, I found this particular code on the internet which when I tried submitting got AC. I want to know how this code worked, as I have submitted it from online source which itself is bad idea for beginners.
#include <bits/stdc++.h>
using namespace std;
int check[32000];
int prime[10000];
void shieve()
{
    for(int i=3;i<=180;i+=2)
    {
        if(!check[i])
        {
            for(int j=i*i;j<=32000;j+=i)
                check[j]=1;
        }
    }
    prime[0] = 2;
    int j=1;
    for(int i=3;i<=32000;i+=2)
    {
        if(!check[i]){
            prime[j++]=i;
        }
    }
}
int main()
{
    shieve();
    int a,b,n,temp,total=1,res=0;
    scanf("%d%d%d",&a,&b,&n);
    int count=0,i,j,k;
    for(i=a;i<=b;i++)
    {
        temp=i;
        total=1;
        k=0;
        for(j=prime[k];j*j<=temp;j=prime[++k])
        {
            count=0;
            while(temp%j==0)
            {
                count++;
                temp/=j;
            }
            total *=count+1;
        }
        if(temp!=1)
            total*=2;
        if(total==n)
            res++;
    }
    printf("%d\n",res);
    return 0;
}

It looks like the code works on the sieve of eratosthenes, but a few things i'm unable to understand.

*

*Why the limit of array "check" is 32000?

*Again why the limit for array prime is 10000?

*Inside main, whatever is happening inside the for loop of j.

Too many confusions regarding this approach, can someone explain the whole algorithm how it's working.

A: *

*The hard limit on the arrays is set probably because the problem demands so? If not then just bad code.

*Inside the inner loop, you are calculating the largest power of a prime that divides the number. Why? See point 3.

*The number of factors of a number n can be calculated as follows:
Let n  = (p1)^(n1) * (p2)^(n2) ... where p1, p2 are primes and n1, n2 ... are their exponents. Then the number of factors of n = (n1 + 1)*(n2 + 1)...
Hence the line total *= count + 1 which is basically total = total * (count + 1) (where count is the largest exponent of the prime number that divides the original number) calculates the number of prime factors of the number.
And yes, the code implements sieve of Eratosthenes for storing primes in a table.
(Edit Just saw the problem - you need at least 10^4 boolean values to store the primes (you don't actually need to store the values, just a flag indicating whether the values are prime or not). The condition given is 0 <= b - a <= 10^4 , So start your loop from a to b and check for the bool values stored in the array to know if they are prime or not.)


text:
Q: How can I get only projects from the solution? I get a list of projects using following:
var solution = (IVsSolution)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(IVsSolution));

Refer following link for more details.
But it gives me each and every item in the solution like Directories, projects, etc.
I require only projects.
How can I get only projects from the solution?

A: I tried and got the expected results.
There may be other better solution but this actually works for me.
var projects = CommonMethods.GetProjects(solution).Where(item => item.FullName != string.Empty).ToList();

A: Sry I'm just begining with programming so it could be that my solving way is really not the best but i faced the same problem short time ago.
To solve this problem I parsed all items of the solution in a list and later i just checked if the relativ path of the items has the suffix '.csproj' or any other kind of project i need and wrote them into a new list maybe this could help you to?


text:
Q: Customer profiling and Anomaly detection -Python Thank you for taking the time to check this question.
I am interested in creating a profile for customers buying pattern.
Once I created a profile for everyone, we take unseen data and check with the profile to see if the customers followed their profile if not raise a flag. In this manner we do not create a set alert for all buyers but we can detect anomaly based on individual buyers to benchmark against their profile.
Any thoughts or inputs to how to approach this problem.
If you have a course or tutorial on this matter please feel free to suggest it.
Thanks in advance.

A: You can either go by supervised learning method, basically machine learning. Also, buying pattern, I would suggest to explore more about RFM rule i.e. recency, frequency and monetary value. This will help you in creating features for model or profile customers.


text:
Q: Microsoft Graph $filter returns "Invalid filter clause" on /beta/me/chats requests Using the Graph Explorer a GET request of
https://graph.microsoft.com/beta/me/chats?$expand=members&$filter=members/any(o: o/displayname eq 'Steve Ratcliffe')

succeeds, however a GET request of
https://graph.microsoft.com/beta/me/chats?$expand=members&$filter=members/any(o: o/email eq 'steve@ratcliffe.com')

fails with an error 400 - "Invalid filter clause". The same errors occurs when trying to filter by userId.
How can one make email or userId filters work on chats?


text:
Q: Use double line feed as -element in GtkSourceView I'm working on a language definition for GtkSourceView. I've got an element which starts with a "@LI:" and ends with a double line feed. The first line should get a different style, then the rest of the element another style.
My problem right now is, that I can't find a [...] definition, which matches the double line feed at the end of the segment. Something like [\r\n] doesn't work. The element ends at the end of the file.
Here's an example of my markup I work with:
@L:Lorem ipsum dolor sit amet, consectetuer adipiscing elit.

@LI:
Nulla consequat massa quis enim.
Donec pede justo, fringilla vel.
vulputate eget, arcu.

@L:In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.

And this is the part of my .lang file.
[...]
<style id="li" name="Listing" map-to="def:identifier"/>
<style id="kt" name="Kastentitel" map-to="def:type"/>
[...]
<context id="li" style-ref="li">
  <start>@LI:</start>
  <end>[\r\n]{2,}</end>
  <include>
    <context sub-pattern="0" where="start" style-ref="kt"/>
    <context sub-pattern="0" where="end" style-ref="kt"/>
    <context ref="kt"/>
  </include>
</context>

Thanks for your help!


text:
Q: Pandas transformation really slow I been trying to transform python pandas to from one representation to another but is really slow:
My current dataframe is like:
Column0, Column 1, Column 2, Column 3, Column 10...
   p1        1           2         8          3
   p2        2           4         9          6

Column0,   sample,       Exp
   p1       Column 1      1
   p1       Column 2      2
   p1       Column 3      8
   p1       Column 10     3
   p2       Column 1      2
   .           .          .
   .           .          .

I use the iterrows inserting into a new dataframe but is really slow. The Column 1,2 is not fixed but I have a collection with all the names.

A: IIUC, you can use melt,
generally looping is discouraged in pandas unless there is no other option or you have a justifiable usecase.
d = """Column0, Column 1, Column 2, Column 3, Column 10
   p1,        1,           2,         8,          3
   p2,        2,           4,         9,          6"""

from io import StringIO

df = pd.read_csv(StringIO(d),sep=',')

df2 = pd.melt(df,id_vars=['Column0'],var_name='Sample',value_name='Exp')

print(df2)

  Column0       Sample  Exp
0      p1     Column 1    1
1      p2     Column 1    2
2      p1     Column 2    2
3      p2     Column 2    4
4      p1     Column 3    8
5      p2     Column 3    9
6      p1   Column 10     3
7      p2   Column 10     6

Chaining Operations
pd.melt(df,id_vars=['Column0'],var_name='Sample',value_name='Exp').rename(
             columns = {'Column0' : 'NewCol',...})


text:
Q: how to make my navbar display blocked lines in bootstrap 4 on mobile view? I am new to coding. I have below code for my navbar and I am using django. But it does collapse on mobile view but it does not make blocks, that I intend on doing. I have tried classes such as .d-sm-flex as well as col-sm-10 for various parts of the navbar. Where can I place a class .d-sm-flex so that my navbar automatically becomes blocks of letters for smaller screens such as mobiles.

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

    </button>

        {% if user.is_authenticated %}

          About Us (current)

        {% if user.userprofiles %}

            My Account

    Inbox

    Micro Posts

    Search

   {% else %}

            Create New Profile
   {% endif %}

    Logout

            {% else %}

          About Us (current)

          Sign Up

          Login

          {% endif %}

A: You will be needing to use class row first to use columns.. try adding class="row" in parent of col-sm-10


text:
Q: On deleting a button how to add again back to same position angularjs In the below plunkr, after i click on add button it is added to the below scope items and it is removed from the above scope items. I would like to know when user removes from below scope items how can i add again back to the above scope at same index point from where it is removed. plunkr link - https://plnkr.co/edit/EFqMKkC4wMsjYmg64n7q?p=preview
html-

<link rel="stylesheet" href="tree.css"/>
<link rel="stylesheet" href="font-awesome.min.css"/>
<link rel="stylesheet" href="bootstrap.min.css" />

<button type="button" class="btn btn-success" data-dismiss="modal" data-ng-click="save()">SaveFilter</button>
<button type="button" class="btn btn-Default" data-dismiss="modal" data-ng-click="delete()">Delete</button>

<button ng-repeat="name in listofSystems" style="border-radius: 25px; outline-color:#fff;" type="button" class="btn btn-default" id="{{name.name}}" ng-click="addSystemsButton($event,$index)">{{name.name}}   +</button>

Selected Systems

<button ng-repeat="name in listofSystemsAdded" style="border-radius: 25px; outline-color:#fff;" type="button" class="btn btn-default" ng-click="removeSelectedSystemsButton($index)">{{name.name}}    x</button>

A: You just have to add it back to listofSystems, like you do when you press a "system".
I have updated your plunker:
  $scope.removeSelectedSystemsButton = function(ind) {
    console.log(ind);
    $scope.listofSystems.push($scope.listofSystemsAdded[ind]);
    $scope.listofSystemsAdded.splice(ind, 1)
  };
}

https://plnkr.co/edit/oeBOY1Va9LXDJUCSWaxw?p=preview


text:
Q: Efficient algorithms for detecting finite topologies Given a finite collection $X$ of finite sets, what are some efficient methods for deciding whether or not $X$ is a topology?
Obviously it is possible to brute-force the problem by checking the conditions $\emptyset\in X$, and $\bigcup Y\in X$, $\bigcap Y\in X$ for every $Y\in \mathcal{P}(X)$; but this is extremely inefficient - $O\left(2^{|X|}\right)$, I think - for large $X$. Is there a faster way to check if $X$ is a topology?

A: One way: for each $x \in X$ compute $M_x= \bigcap\{O \in \mathcal{T}: x \in O\}$ a finite intersection of open sets, hence open. So check also that the computed $M_x \in \mathcal{T}$ as well. If you have some incidence data structure (so for each $x \in X, O \in \mathcal{T}$ a boolean to determine $x \in O$ or not), this is a simple loop to compute. Then for each (non-empty) open set $O$, check whether the $M_x$ inside it union up to $O$: for any $x \in O$ check whether $M_x \subseteq O$: if not, "no topology", else remove $M_x$ from $O$ till $O$ is empty, and try the next $O$. Precise implementation will depend on your data structures, and this is not a programming site. This will run in about $|\mathcal{T}| \cdot |X|$ steps, I think.


text:
Q: Using Nokogiri on FedEx.com I'm trying to create a small Rails application that will parse the FedEx site for my tracking information. I tried to use Nokogiri to parse the site but it seems that the content on the site is loaded via Ajax and I'm not able to capture it.
Here is the code that I was testing with:
require 'rubygems'
require 'nokogiri'
require 'open-uri'

doc = Nokogiri::HTML(open('https://www.fedex.com/fedextrack/?cntry_code=us&tab=1&tracknums=543433298736'))

doc.xpath('//*[(@id = "destinationDateTime")]').each do |status|
  puts status.content
end

Any help on this would be wonderful.

A: Parsing the entire page is bad form. Use a shipping/tracking gem such as active_shipping that utilizes the FedEx API instead. They even have a section about tracking FedEx packages:
fedex = FedEx.new(:login => '999999999', :password => '7777777')
tracking_info = fedex.find_tracking_info('tracking-number', :carrier_code => 'fedex_ground') # Ground package

tracking_info.shipment_events.each do |event|
  puts "#{event.name} at #{event.location.city}, #{event.location.state} on #{event.time}. #{event.message}"
end

A: require 'mechanize'
require 'json'

r = Mechanize.new
r.verify_mode = OpenSSL::SSL::VERIFY_NONE

def fedex(r,tracking_number)

    return r.get("https://www.fedex.com/trackingCal/track?data={%22TrackPackagesRequest%22%3A{%22appType%22%3A%22wtrk%22%2C%22uniqueKey%22%3A%22%22%2C%22processingParameters%22%3A{%22anonymousTransaction%22%3Atrue%2C%22clientId%22%3A%22WTRK%22%2C%22returnDetailedErrors%22%3Atrue%2C%22returnLocalizedDateTime%22%3Afalse}%2C%22trackingInfoList%22%3A[{%22trackNumberInfo%22%3A{%22trackingNumber%22%3A%22#{tracking_number}%22%2C%22trackingQualifier%22%3A%22%22%2C%22trackingCarrier%22%3A%22%22}}]}}&action=trackpackages&locale=en_US&format=json&version=99").body

end

puts "Package number 543433298736 is: " + JSON.parse(fedex(r,"543433298736"))["TrackPackagesResponse"]["packageList"][0]["keyStatus"]
# For the "estimated delivery datetime": ["TrackPackagesResponse"]["packageList"][0]["displayEstDeliveryDateTime"]

This code get's the job done :-)

A: I made something similar.. i ended up with using capybara and phantomjs via poltergeist... handles javascript quite well...
here is a part of my script:
# -*- encoding : utf-8 -*-

require 'rubygems'
require 'capybara'
require 'capybara/dsl'
require 'capybara/poltergeist'

class MyTest

    include Capybara::DSL

    Capybara.register_driver :poltergeist do |app|
      Capybara::Poltergeist::Driver.new(app, {debug: false})
    end

    Capybara.run_server = false
    Capybara.current_driver = :poltergeist
    Capybara.app_host = 'http://www.example.com'

    def run
        visit('/home/bezirk?bezirk=1212')
        ...
    end
end
MyTest.new.run


text:
Q: Alternative to Application.DelayInitialize for Delphi 7 Service? Is there an alternative to Application.DelayInitialize for Delphi 7?  I'm trying to create a Delphi 7 Service that hosts a COM Server but it doesn't work and I believe it is because I'm not using Application.DelayInitialize.
Re: Windows Service / DelayInitialize

A: I have written several COM-hosting services using BCB6, and they all work fine in all Windows versions from Win9x onwards, so I have had to deal with this same issue many times.
Simply don't call Application.Initialize() at process startup on Win2003+, wait until the TService's OnStart or OnExecute event to call it. That way, the service API is running before any COM objects are initialized.
The trick is to delay the call to Application.Initialize() ONLY on Win2003+ and ONLY when the service is actually running.  DO NOT delay the call if either:

*

*The service is running on Windows versions earlier than 2003.

*when the service is being (un)installed.

*when the COM object is being (un)registered.

Under those conditions, call Application.Initialize() normally at process startup.
So, you will need to check the OS version and the command line parameters to know when to call Application.Initialize() correctly.


text:
Q: Knowing more about electromagnetic waves we have discovered from radio waves to gamma rays but there may possibilities of existence of other electromagnetic waves beyond this range which we haven't discovered it, may be the reason that our current technology not have that "EYE"  to see those waves. Is there any possibility of such waves having more frequency than gamma rays and wavelength than radio waves.

A: Of course. Those are only definitions for certain intervals of frequencies that are particularly useful for something. There is nothing, at least classically, that prevents eletromagnetic waves from having an arbitrary frequency (exept technical limitations).
PS: I think that historically X-rays and gamma rays were distinguished based on their source.


text:
Q: Spring integration splitting and looping I am new to Spring Integration and have an application that accepts files as input and does some specific processing on those files depending on the contents of each file.
When the file comes in, I have a router that decides whether is type "A", "B" or a "ZIP" file and routes it to the appropriate channel.  In the case of a ZIP file I have a splitter which unzips the zip file and sends the results back to the router to determine which type of file from the zip is - A, B, or a nested ZIP file.
There is also an error-channel specified that handles file parsing errors.
The relevant part of the XML looks something like this:
<?xml version="1.0" encoding="UTF-8"?>

...
...

<int:channel id="checkFile" />
<int:channel id="A" />
<int:channel id="B" />
<int:channel id="ZIP" />

<!-- Route the file to the appropriate parser - A, B, or ZIP -->
<int:router input-channel="checkFile" ref="fileTypeIdentifier" method="identifyType" />

<!-- If we have a ZIP file, extract the contents and process each one individually -->
<int:splitter input-channel="ZIP" output-channel="checkFile" ref="extractor" />

<!-- Parse file type A -->
<int:chain input-channel="A" output-channel="Done">
    ...
    ...
</int:chain>

<!-- Parse file type B -->
<int:chain input-channel="B" output-channel="Done">
    ...
    ...
</int:chain>

...
...

If my input file is myfile.zip which contains file1.txt and file2.txt, the router correctly routes myfile.zip to the splitter which successfully extracts file1.txt and file2.txt (and returns those 2 files).
If I have an error parsing file1.txt I would still like to try to parse file2.txt.  So after reading Spring Integration: Splitter exception causes subsequent messages to abort I tried making my "checkFile" channel a queue channel, now what happens is I pass in myfile.zip which gets routed to the "ZIP" channel, which successfully returns "file1.txt" and "file2.txt", but then the router keeps getting called with "myfile.zip" in an endless loop.
A similar problem results from using an executor channel instead of a queue channel.
How can I get my flow to unzip files and process their contents individually, while allowing one or more of the files inside the zip to fail without failing the entire job?

A: It might take a lot of place here, but I'll try to post it anyway:
<bean id="fileTypeIdentifier" class="org.springframework.integration.splitter.So43527224Tests$FileTypeIdentifier"/>

<bean id="fileParser" class="org.springframework.integration.splitter.So43527224Tests$FileParser"/>

<int:channel id="checkFile">
    <int:queue/>
</int:channel>

<!-- Route the file to the appropriate parser - A, B, or ZIP -->
<int:router input-channel="checkFile" ref="fileTypeIdentifier" method="identifyType">
    <int:poller fixed-delay="1000"/>
</int:router>

<!-- If we have a ZIP file, extract the contents and process each one individually -->
<int:splitter input-channel="ZIP" output-channel="checkFile"/>

<!-- Parse file type A -->
<int:service-activator input-channel="A" output-channel="nullChannel"
                       ref="fileParser" method="parseFileA"/>

<!-- Parse file type B -->
<int:service-activator input-channel="B" output-channel="nullChannel"
                       ref="fileParser" method="parseFileB"/>

And test class:
@RunWith(SpringRunner.class)
@DirtiesContext
public class So43527224Tests {

    @Autowired
    private MessageChannel checkFile;

    @Test
    public void testSo43527224() throws InterruptedException {
        this.checkFile.send(new GenericMessage<>(2));
        this.checkFile.send(new GenericMessage<>(3));
        this.checkFile.send(new GenericMessage<>(Collections.singletonList(4)));
        this.checkFile.send(new GenericMessage<>(Collections.singletonList(5)));

        List<Object> zip = new ArrayList<>();

        zip.add(6);
        zip.add(7);

        List<Integer> nestedZip = new ArrayList<>();
        nestedZip.add(9);
        nestedZip.add(8);
        zip.add(nestedZip);

        this.checkFile.send(new GenericMessage<>(zip));

        Thread.sleep(10000);
    }

    private static class FileTypeIdentifier {

        public String identifyType(Object payload) {
            if (payload instanceof List) {
                System.out.println("ZIP: " + payload);
                return "ZIP";
            }
            else if (Integer.class.cast(payload) % 2 == 0) {
                return "A";
            }
            else {
                return "B";
            }
        }

    }

    private static class FileParser {

        public String parseFileA(Object payload) {
            throw new RuntimeException("intentional: A is always bad: " + payload);
        }

        public void parseFileB(Object payload) {
            System.out.println("Good file B: " + payload);
        }

    }

}

The logs looks like this (without stack traces):
Caused by: java.lang.RuntimeException: intentional: A is always bad: 2
Good file B: 3
ZIP: [4]
ZIP: [5]
ZIP: [6, 7, [9, 8]]
Caused by: java.lang.RuntimeException: intentional: A is always bad: 4
Good file B: 5
Caused by: java.lang.RuntimeException: intentional: A is always bad: 6
Good file B: 7
ZIP: [9, 8]
Good file B: 9
Caused by: java.lang.RuntimeException: intentional: A is always bad: 8

So, as I said before: there is something else not show here to determine the reason of the loop.
You always can switch on DEBUG for the org.springframework.integration category to analyze how your messages are travel in the flow.


text:
Q: Having issues with user Authorisation/Authentication with React Context. How do I access the variables in a class component? So I am using React Context and Hooks for the first time. I followed a YouTube tutorial and I have user authorisation and authentication working, however I am really struggling to figure out how to access the active user and if this user is authenticated with class components. The tutorial I followed only used React Hooks and I have a mix of hooks and class components for my project.
In the Code I have provided below, if we look at the NavBar class, it can easily check if the user authenticated as this is a hook component. I want to be able to do this for class components such as App.js and Step1.js. In App.js I have tried this using the context api documentation.
 const Auth = this.context;
    console.log(Auth);

However, this just returns a null set. Am I missing a consumer tag, or should the provider tag be somewhere else? I would greatly appreciate any help or advice!
AuthContext.js
import React, {createContext,useState,useEffect} from 'react';
import AuthService from '../Services/AuthService';

export const AuthContext = createContext();

export default ({ children })=>{
    const [user,setUser] = useState(null);
    const [isAuthenticated,setIsAuthenticated] = useState(false);
    const [isLoaded,setIsLoaded] = useState(true);

    useEffect(()=>{
        AuthService.isAuthenticated().then(data =>{
            setUser(data.user);
            setIsAuthenticated(data.isAuthenticated);
            setIsLoaded(true);
        });
    },[]);

    return (

            {!isLoaded ?
Loading
 :
            <AuthContext.Provider value={{user,setUser,isAuthenticated,setIsAuthenticated}}>
                { children }
            </AuthContext.Provider>}

    )
            }

AuthService.js
export default {
  login: user => {
    return fetch("/api/login", {
      method: "post",
      body: JSON.stringify(user),
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then(res => res.json())
      .then(data => data);
  },

  register: user => {
    return fetch("/api/register2", {
      method: "post",
      body: JSON.stringify(user),
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then(res => res.json())
      .then(data => data);
  },

  logout: () => {
    return fetch("/api/logout")
      .then(res => res.json())
      .then(data => data);
  },

  isAuthenticated: () => {
    return fetch("api/authenticated").then(res => {
      if (res.status != 401) return res.json().then(data => data);
      else return { isAuthenticated: false, user: { username: "", role: "" } };
    });
  }
};

App.js
import React, { Component, useContext } from "react";
import { getFromStorage, setInStorage } from "../../utils/storage";
import Navbar from "../NavBar";
import Header from "../Header/Header";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  withRouter,
  Redirect,
  useRouteMatch,
  useParams
} from "react-router-dom";
import Home from "../Home/Home";
import SideBar from "../SideBar";
import Step1 from "../SafetyPlan/Step1";
import AllSteps from "../SafetyPlan/AllSteps";
import PatientHome from "../Patient/PatientHome";
import HeaderOut from "../Header/HeaderOut";
import AddPatient from "../Patient/AddPatient";
import Step2 from "../SafetyPlan/Step2"
import SignUp from "../Register";
import Login from "../Login";
import PrivateRoute from "../HOCs/PrivateRoute";
import UnPrivateRoute from "../HOCs/PrivateRoute";
import AuthContext from '../..//Context/AuthContext'

//I want to be able to access isAuthenticated and user within this class
//I have not sure how to access them. I understand that It is possible but I am struggling to get it to work.
//The NavBar class makes use these hooks in the way I want to. It is a good example I want to look at.

class App extends React.Component {

  //Equivalent to useContext() for functional components
  static contextType = AuthContext;

  constructor(props) {
    super(props);
    this.state = {
      token: ""
    };
  }

  render() {
    //Access context using this.context (similar to this.props)
    const Auth = this.context;
    console.log(Auth);

    return (
      // This is your Context Provider (should wrap all other components that require context)
      <AuthContext>
        {/* The way you designed it, all children will be Context Consumers (see AuthContext.js) */}
      <Router>

          <SideBar></SideBar>
          <Switch>
            <Route exact path="/" component={SignUp} />
            <Route exact path="/Step1" component={Step1} />
            <Route exact path="/Step2" component={Step2} />
            <Route exact path="/AllSteps" component={AllSteps} />
            <Route exact path="/AddPatient" component={AddPatient} />
            <Route exact path="/Register" component={SignUp} />
            <Route exact path="/Login" component={Login} />
            <Route path="/PatientHome/:id" component={PatientHome} />
          </Switch>
          )

      </Router>
      </AuthContext>
    );
  }
}
export default App;

NavBar.js
import React, {useContext} from 'react';
import {Link} from 'react-router-dom';
import AuthService from '../Services/AuthService';
import { AuthContext } from '../Context/AuthContext';

const Navbar = props =>{
    const {isAuthenticated,user,setIsAuthenticated,setUser} = useContext(AuthContext);
    console.log(isAuthenticated);
    console.log(user);
    const onClickLogoutHandler = ()=>{
        AuthService.logout().then(data=>{
            if(data.success){
                setUser(data.user);
                setIsAuthenticated(false);
            }
        });
    }

    const unauthenticatedNavBar = ()=>{
        return (
            <>
                <Link to="/">

                        Home

                </Link>
                <Link to="/login">

                        Login

                </Link>
                <Link to="/register">

                        Register

                </Link>
            </>
        )
    }

    const authenticatedNavBar = ()=>{
        return(
            <>
                <Link to="/">

                        Home

                </Link>
                <Link to="/todos">

                        Todos

                </Link>
                {
                    user.role === "admin" ?
                    <Link to="/admin">

                            Admin

                    </Link> : null
                }
                <button type="button"
                        className="btn btn-link nav-item nav-link"
                        onClick={onClickLogoutHandler}>Logout</button>
            </>
        )
    }
    return(

            <Link to="/">

SafePlan View

            </Link>

                    { !isAuthenticated ? unauthenticatedNavBar() : authenticatedNavBar()}

    )
}

export default Navbar;

Step1.js
import React from "react";
import styled from "styled-components";
import axios from "axios";
import { getFromStorage, setInStorage } from "../../utils/storage";
import AuthContext from './/..//..//Context/AuthContext'
import {
  BrowserRouter as Router,
  Route,
  Link,
  withRouter
} from "react-router-dom";
import {
  Form,
  Button,
  FormGroup,
  FormControl,
  ControlLabel
} from "react-bootstrap";
import Home from "../Home/Home";
const GridWrapper = styled.div`
  p {
    font-size: 18px;
  }
  h3 {
    text-decoration: underline;
  }
  margin-top: 4em;
  margin-left: 28em;
  margin-right: 1em;
`;

class Step1 extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      token: "",
      session: 0,
      date: "",
      versions: [],
      warnings: [],
      emailOfEditor: "Hello",
      purpose: [],
      privateBenefit: "wewewe",
      achievablePlan: "wewewewe",
      purposeEvidence: "ewewe",
      achievablePlanEvidence: "wewe",
      privateBenefitEvidence: "wewewew",
      charityName: "",
      time: ""
    };
  }
  static contextType = AuthContext;

  updateInput = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  };

  getPatientId = (event, { value }) => {
    console.log(value);
    let bird_name = event.target.textContent;
    console.log(bird_name);
  };
  componentDidMount() {
    const obj = getFromStorage("the_main_app");
    if (obj && obj.token) {
      const { token } = obj; // Verify token
      fetch("/api/account/verify?token=" + token)
        .then(res => res.json())
        .then(json => {
          if (json.success) {
            this.setState({
              token,
              isLoading: false
            });
          } else {
            this.setState({
              isLoading: false
            });
          }
        });
    } else {
      this.setState({
        isLoading: false
      });
    }
    axios.get("/api/getStep1").then(res => {
      const warnings = res.data
      this.setState({ warnings });
      console.log(warnings);
    });
  }

  generateNewSession = e => {
    var that = this;
    let sessionNum = Math.floor(100000 + Math.random() * 900000);
    this.setState({ session: sessionNum });
    this.setState({ date: new Date().toLocaleString() });
    console.log(this.state.session);
    console.log(this.state.date);
    const { warning } = this.state;

    // Post request to backend
    fetch("/api/updateSession", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        warning: warning
      })
    })
      .then(res => res.json())
      .then(json => {
        console.log("json", json);
      });
  };

  render() {
    const { versions } = this.state;
    const { token } = this.state;

      return (
        <GridWrapper>

                      {" "}
                      Step 1: Warning Signs (thoughts, images, mood, situation,
                      behaviour) that a crisis may be developing

                      {this.state.warnings.map(warning => (

{warning.signDesc}

                      ))}

              <Link to>

Next Step

              </Link>

        </GridWrapper>
      );
    }

}
export default Step1;

A: Basically when the user logs in, you should be returned with a Security token key, most common would be JWT(JSON Web Token), you should store this token in localstorage or cachestorage and retrieve this in your components and see if the user is authenticated or not. If you don't have proper implementation of JWT, then you can for now use a boolean variable and check if the user is logged in.
You should have protected Route setup. I'm attaching you the snippet to store values in localstorage.
loginComponent
  if(postLogin(user)){
    localStorage.setItem('token',true);
}

Create PrivateRoute, And then in PrivateRoute,
check if user login exists or not and based on it redirect.
import {Redirect} from "react-router-dom";
import React from "react";

const Route = require("react-router-dom").Route;
export const PrivateRoute = ({component: Component, ...rest}) => {
    return (<Route {...rest} render={props => (
        localStorage.getItem('token') ? (
            <Component {...props}/>
        ) : (
            <Redirect push to={{
                pathname: '/login',   //whatever your component is
                from: props.location
            }}/>
        )
    )}/>)
};

In your App.js
import {PrivateRoute} from './PrivateRoute'
.
.
.
 <PrivateRoute exact path={"/home/posts"} component={Posts} />  //User cannot access this component without being logged in.

Note: Make sure to clear the localStorage or cacheStorage through user logout.


text:
Q: Handle car animation and collision I have different car animation running on the road which have imported from max. I want to make such an intelligent System that if car start to trigger from another car it become stop. So far I have tried this.

*

*Added four collider (as you can see in Fig 1) with tag name car, carBack, carLeft, CarRight

*car left/right contains this code. Added this script to car left,right collider that if this collider hit with car object then car become stop.(And on trigger exit it resume)
 void OnTriggerEnter(Collider c)
    {
        if (c.tag == "Car")
        {
            Debug.Log("collided with : carsideTriggerScript :" + c.transform + " - object Name to stop : " + gameObject.name);
            c.transform.gameObject.GetComponent<AnimationControlSpeed>().Speed = 0;
            //StartCoroutine(DecreaseSpeedGradually(transform.gameObject.GetComponent<AnimationControlSpeed>()));
        }
    }

    void OnTriggerExit(Collider c)
    {
        if (c.tag == "Car")
        {
            Debug.Log("Exi collided with :  carsideTriggerScript:" + c.transform + " - object Name to resume : " + gameObject.name);
             c.transform.gameObject.GetComponent<AnimationControlSpeed>().Speed = 1;
        }
    }

*Added script which check that if car start to collide with carBack collider then stop (And on trigger exit it resume. Same script as above).
But a scenario is creating which you can see in fig 2.

I am enable to handle it. it seems that one car collider hitting  carRightCollider and same thing happen with another car so that both car become stop and unable to move again.
     How can i control it? as same scripts are attached to every gameobject with same OntriggerEnter and logic.

A: So, after reading your question a few more times I think I understand now. You have two cars and when they collide, they both stop. You want just one car to stop, and one car to go.
If you don't care which one goes first, that's easiest.  You will need a collection to act as a queue to hold all the cars that collided.  Let's call it the 'resume driving queue'.  If a car collides with another car, stop it, then add it to the queue.  Then based on a timer or other logic, one by one you can take the next car from the queue and if the car is stopped, start it.
If you need to select a 'winner' to see who gets to go, that might get a little more complicated.  A basic example of this might be emergency vehicles like the police or fire cars get priority to go first, and other cars need to wait.  In this case you'll want to give each of your car objects some kind of traffic priority property which is like a die they can roll during a collision to see if they win.  Then you can use the random numbers each car generates to insert them in priority order into your resume driving queue.


text:
Q: How to avoid creating multiple data in elasticsearch using logstash While sending data into elasticsearch using logstash, same data stream is getting repeated many times. How to avoid this ?
Defining "repeating":
When we send one stream of data, for example - "key1":"name1", I am seeing multiple lines of this same data in elastic search.