text:
Q: How can I test un-exported pre ES6 JS files with karma/jasmine? I have a plain JS file that is written with pre ES6 JS code that I want to test using a karma/jasmine test suite. The file is large but I just want to get a super simple example working.
// pluginV3.js
// This is the file I am trying to test. It is written in pre ES6 JS and has no exports
var myvar = null;

I have found a library called rewire that I think will allow me to test plain JS files like this but I am having trouble getting it to work with my karma/jasmine stack. So far I have tried this:
// var rewire = require("rewire"); // Can't use require. Test code is also pre ES6
beforeEach(module('rewire')); // I have been trying to instance "rewire" here using the exported module in rewire's index.js

describe('V3 Helper.js', function() {
    describe('$pluginV3.myvar', function () {
        fit('Tests a certain variable in pluginV3 is set to an expected initial value', function () {
            var pluginV3 = rewire("../../../../public/static/js2/pluginV3.js");
            expect(pluginV3.myvar).toEqual(null); // expect this scope var to be something
        });
    });
});

But I get this error:
LOG: '----------------------------------------------------'
Chrome 96.0.4664.55 (Mac OS 10.15.7): Executed 0 of 30 SUCCESS (0 secs / 0 secs)
LOG: 'What is rewire?'
Chrome 96.0.4664.55 (Mac OS 10.15.7): Executed 0 of 30 SUCCESS (0 secs / 0 secs)
LOG: function rewire(filename) { ... }
Chrome 96.0.4664.55 (Mac OS 10.15.7): Executed 0 of 30 SUCCESS (0 secs / 0 secs)
Chrome 96.0.4664.55 (Mac OS 10.15.7) CN Plugin Client V3 Helper $scope.transferData Tests a certain variable in Plugin Client V3 is set to an expected initial value FAILED
    TypeError: rewireModule is not a function
        at rewire (node_modules/rewire/lib/index.js:11:12)
        at UserContext.<anonymous> (tests/helpers/cn-plugin-client-v3-test.js:25:28)
        at <Jasmine>
Chrome 96.0.4664.55 (Mac OS 10.15.7): Executed 1 of 30 (1 FAILED) (0 secs / 0.002 secs)
Chrome 96.0.4664.55 (Mac OS 10.15.7) CN Plugin Client V3 Helper $scope.transferData Tests a certain variable in Plugin Client V3 is set to an expected initial value FAILED
    TypeError: rewireModule is not a function
        at rewire (node_modules/rewire/lib/index.js:11:12)
        at UserContext.<anonymous> (tests/helpers/cn-plugin-client-v3-test.js:25:28)
        at <Jasmine>

Which makes me think the beforeEach(module('rewire')); is working but but for some reason it is not able to run rewireModule (perhaps because it is ES6+)?
Here is rewire's index.js:
var rewireModule = require("./rewire.js");

/**
 * Adds a special setter and getter to the module located at filename. After the module has been rewired, you can
 * call myModule.__set__(name, value) and myModule.__get__(name) to manipulate private variables.
 *
 * @param {!String} filename Path to the module that shall be rewired. Use it exactly like require().
 * @return {*} the rewired module
 */
function rewire(filename) {
    return rewireModule(module.parent, filename);
}

module.exports = rewire;

delete require.cache[__filename];   // deleting self from module cache so the parent module is always up to date

Which is what I imported in my karmaconfig file along with the file I am trying to test:
// karma.conf.js
files: [
            './node_modules/rewire/lib/index.js',
            '../../public/static/js2/cn-plugin-client-v3.js',
    ]

Am I doing something wrong? Or am I just unable to use rewire with my pre ES6 restriction. Has anyone tested pre ES6 JS files that have no exports with karma/jasmine? Is there a different solution?

A: Turns out rewire was unnecessary. After you add the file to your karma config you can usually instance it in a test by calling it as a module:
beforeEach(module('pluginV3'));

The only drawback to this approach is you need to satisfy every dependancy. If there is a variable in pluginV3.js that comes from pluginV2.js or something, you will need to add that to the karma file imports before the file that depends on it.
I have not tested this much but I imagine this solution is still inadequate for files that have unrealistically long dependency chains and I have no idea how you would handle files with circular dependancies.


text:
Q: Spring LDAP returning exception: java.lang.ClassNotFoundException: org.springframework.ldap.core.LdapEncoder I'm using Spring 3.2.7 and Spring Security 3.2.0
I'm using Apache DS 2.0.0 on my local Windows computer.  All of the users have their passwords stored as plain text, no encryption.
I have the following defined in my spring config XML:
        <?xml version="1.0" encoding="UTF-8"?>
        <beans xmlns="http://www.springframework.org/schema/beans"  xmlns:security="http://www.springframework.org/schema/security"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xmlns:jdbc="http://www.springframework.org/schema/jdbc"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
    http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd">
    <security:http auto-config="true" >
    <security:intercept-url pattern="/hello" access="ROLE_SCARVAREZ_MEMBER" />
<security:form-login/>
    </security:http>
    <security:authentication-manager>
                            <security:ldap-authentication-provider
                            user-dn-pattern="uid={0},ou=people"
                            group-search-base="ou=groups"
                            group-search-filter="(member={0})"
                            >
                            </security:ldap-authentication-provider>
    </security:authentication-manager>
    <security:ldap-server url="ldap://localhost:10389/dc=example,dc=com" />
    </beans>

I get the default Spring login form.  However, when I attempt to log in, I get the following exception:
java.lang.ClassNotFoundException: org.springframework.ldap.core.LdapEncoder
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491)
    org.springframework.security.ldap.authentication.AbstractLdapAuthenticator.getUserDns(AbstractLdapAuthenticator.java:95)
    org.springframework.security.ldap.authentication.BindAuthenticator.authenticate(BindAuthenticator.java:80)
    org.springframework.security.ldap.authentication.LdapAuthenticationProvider.doAuthentication(LdapAuthenticationProvider.java:178)
    org.springframework.security.ldap.authentication.AbstractLdapAuthenticationProvider.authenticate(AbstractLdapAuthenticationProvider.java:61)
    org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
    org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:177)
    org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)

I can't figure out what JAR file I need to include to get past this exception.
I'm not using Maven, but here are the JAR files in my project:
aopalliance.jar
aspectj-1.7.2.jar
aspectjweaver-1.7.2.jar
commons-logging-1.1.1.jar
javax.servlet.jsp.jstl-1.2.1.jar
javax.servlet.jsp.jstl-api-1.2.1.jar
log4j-1.2.17.jar
sl4j-api-1.7.5.jar
spring-aop-3.2.7.jar
spring-aspects-3.2.7.jar
spring-beans-3.2.7.jar
spring-context-3.2.7.jar
spring-core-3.2.7.jar
spring-expression-3.2.7.jar
spring-jdbc-3.2.7.jar
spring-ldap-core-2.0.1.jar
spring-ldapcore-tiger.2.0.1.jar
spring-security-config-3.2.0.jar
spring-security-core.3.2.0.jar
spring-security-ldap-3.2.0.jar
spring-security-taglibs-3.2.0.jar
spring-security-web-3.2.0.jar
spring-tx-3.2.7.jar
spring-web-3.2.7.jar
spring-webmvc-3.2.7.jar

Any help would be much appreciated!

redpajama_set_name: RedPajamaStackExchange


text:
Q: jquery: I want to show a specific div when its corresponding link is clicked I am a bit of a novice with jquery. Basically I want to show only the div that corresponds to the link clicked and hide the divs unrelated to that link.
Below is an example of what I want to do and the script I am struggling with. This is for Wordpress which is why "JQuery" is spelled out rather than just "$".

jQuery(document).ready(function() {
 var clickLink = [".link1", ".link1", ".link1"];
 var toggleDiv = ["#link1", "#link1", "#link1"];
 for (i=0; i < toggleDiv.length; i++) {
  jQuery(toggleDiv[i]).hide();
 }
 jQuery('#linkBank a').click(function() {
           for (i=0; i < clickLink.length; i++) {
             if (this.id == clickLink[i]) {
              jQuery(toggleDiv[i]).toggle();
             }
           }

           return false;
       });
});

First Link
Second Link
Third Link

You clicked on First Link

You clicked on Second Link

You clicked on Third Link

A: You should make use of html data attributes and use that in order to know which element to show, that's the cleanest way and you don't depend on an array of values or ID values being identical to classes you wish to show. In this example, I named the 'data-show' html attribute and the value of it is basically the selector of the element you wish to select (eg '.sth' for elements with class 'sth', you could use #foo for an element with id 'foo' etc)

jQuery(document).ready(function() {
        var $divs = jQuery('.toggling-divs');
        $divs.hide();
 jQuery('#linkBank a').click(function() {
           $divs.hide();
           var showDiv = jQuery(this).attr('data-show');
           jQuery(showDiv).show();

           return false;
       });
});

First Link
Second Link
Third Link

You clicked on First Link

You clicked on Second Link

You clicked on Third Link


text:
Q: How many Avatars have there been? If Avatar Wan lived 10,00 years prior to Korra's lifetime, then how many Avatars have there been?

A: In the Avatar episode "Southern Air Temple" we see a chamber containing approximately 130 statues representing prior incarnations of the Avatar. These are tiered in 7 ascending rows plus a further 51 statues at floor level giving a grand total of 181 previous avatars.

In the film "Avatar : The Last Airbender" we see the same temple, but this time with 6 tiers, each containing 30 status (in 5 blocks of 6) plus a larger statue of the most recent avatar; Roku. This gives a grand total of 181
Given the similarity in numbers, it seems likely that this figure is intended to be the canon figure.

A: There are approximately 1000 avatars according to roku statement in desert which says"I have lived a1000 years and a 1000 lifetimes it is an exaggeration

A: When Roku stated I have lived 10000 lifetimes, a lifetime is not always a hundred years. But if an avatar lived at all (for instance if an avatar died at twenty) that's still a lifetime. He has lived the life of every avatar no matter how short their life was. I say there have been 10,000 avatars but since some of them have died early then maybe it adds up to what he sees as 1000 lifetimes.

A: Hard to say, in avatar TLA when in the air temple and when talking to roku about avatar state you see hundreds of avatars, however the first avatar wan lived 10,000 years ago, and avatars live quite long (like Kyoshi who lived about 200 years) so assuming all avatars live between 100 and 200 years, 10,000 / 200 = 50 and 10,000 / 100 = 100, that would only be between 50 and 100 avatars, which would contradict what's seen in the air temple, the math doesn't add up but I seem to be the only person I know who cares

A: Considering there were 181 avatar statues in the southern air temple when Aang visited it in episode three, book 1. We can say that there are 183 including Korra. That's what most of us got so that should be a close approximation of the real amount of avatars there have been in the full 10000 years from Wan to Korra.

A: Roku once said to Jong Jong after he refused to teach Avatar Aang fire bending, that the Avatar has learned the elements a thousands times in a thousand lifetimes. This means that there are way more then just 183.

A: The problem with this is that we don't know the ages of most avatars, the statue of Wan is of when he was young.  But at the end of his storyline we see him right before he dies, and he had grey hair in that scene. The temple  estimate seems most realistic because there is a statue of the first avatar which suggests they know how many there are between him and Karra/Aang. It seems like the average age is about 55-60 which could fit, seeing as the job is not exactly "safe". There is also a possibility that lots of avatars died at a early age.


text:
Q: How to increase or decrease x- and y- axis step for ListDensityPlot I would like to change the increment of the x- and y- axis from one to 1.5.
I tried PlotRange...It is not working, I can't define the step of 0.15...
For exemple I would like the following scale -3,-1.5,0,1.5,3 as x- and y- axis instead of -3,-2,-1,0,1,2,3
How to set these conditions in ListDensityPlot ?
Here an exemple of code...
   SetOptions[ListDensityPlot,
        Mesh -> None,
        PlotRange -> All,
        ColorFunctionScaling -> True,
        Frame -> True,
        BaseStyle -> {FontSize -> 18, FontFamily -> "Arial"},
        LabelStyle -> Directive[Black, FontSize -> 20],
        ImageSize -> UpTo[550]

      ];

data = Table[{#, #2, Sin[#] Cos[#2]} & @@ RandomReal[{-3, 3}, 2], {1000}];

graph = ListDensityPlot[data,
  PlotLabel -> FileBaseName[file],
  ScalingFunctions -> {"Linear", "Linear", "Linear"},
  ColorFunction -> (ColorData["TemperatureMap"][#] &),
  PlotLegends -> BarLegend[Automatic,  LegendMarkerSize -> 300, LabelingFunction -> (Style[NumberForm[#, {Infinity, 2}], Black, 20] &)]]

A: ticks = Join[{#, #, {.01, 0}, Thick} & /@ Subdivide[-3, 3, 4],
   Thread[{Complement[Subdivide[-3, 3, 12], Subdivide[-3, 3, 4] ], ""}]] ;
ListDensityPlot[data,
    ColorFunction -> "TemperatureMap" ,
    PlotRange -> All,
    LabelStyle -> Directive[Black, FontSize -> 20],
    ImageSize -> Large,
    FrameTicks -> {{N@ticks, Automatic}, {N@ticks, Automatic}}]


text:
Q: Memory argument of VMOVDQU partially out of allocated range When I process N bytes of data with SIMD instructions (reading at least 16 bytes at once), normally I simply add padding to the end of the buffer, so I can safely round up the number of 16-byte blocks to read. However, this time I need to process data prepared by an external code, so theoretically it can happen that the last 16-byte vector of data partially falls outside of the allocated memory range.
For example, let's imagine I have stored 22 bytes of data, starting from 1FFF FFE4:
1FFF FFE0: 00 00 00 00 01 02 03 04 05 06 07 08 09 0A 0B 0C
1FFF FFF0: 0D 0E 0F 10 11 12 13 14 15 16 00 00 00 00 00 00

Then I want to process the data above 16 by 16 bytes, starting from 1FFFFFE4, like this:
MOV RDX, 1FFFFFE4
MOV RCX, 2
@MAIN:
  VMOVDQU XMM0, [RDX]
  ... data processing
  ADD RDX, 16
LOOP @MAIN

The last iteration will read 16 bytes from 1FFFFFF4, while I only have only 6 valid bytes of data there, with the rest of 10 bytes being potentially out of the allocated memory range (particularly the last 4 bytes from 20000000).
Can the above code fail with access violation, in the unlikely but possible situation that the last read partially exceeds the allocated memory range, or if the first byte of the VMOVDQU argument is valid, it won't fail? Could anyone indicate in the Intel 64 SDK the exact rule for this?
If it can fail, is there any other solution than processing the end of the data in a slower but safer way (byte by byte rather than 16 by 16 bytes)? This is what I did before in such cases, but it basically means doubling the code (a SIMD and a slow code for the same task), which is extra work and potential bugs.
As the access violation is very unlikely to happen, I'm also thinking about catching the exception, loading the data in a safe way, and jumping back – this could keep the code simple, as the algorithm itself would remain, only a small code would need to be added for loading the data in a safer way, executed only in very-very rare situations. Below the code, but I don't know how to catch the exception in assembly, and I don't know whether the time penalty would be small enough to make sense:
VMOVDQU XMM0, [RDX]
@DATALOADED:
... data processing
ADD RDX, 16
... the rest of the algorithm

@EXCEPTION:  // jumps here if the VMOVDQU fails with access violation, happens rarely anyway
...load data in XMM0 in a safer way
JMP @DATALOADED

I'm waiting for any other suggestions which could keep the code simple.

A: Here is my take on dealing with this. I'm using a partially overlapped final iteration (plus an optional one for the initial vector loop alignment).
The advantage of this approach is that the last few elements can be dealt with in a single extra loop iteration.
The downsides are:

*

*Needs a fallback if the entire array is less than 16 byte

*May lead to costly load-store forwarding stalls in read-modify-write loops. Use it for a[i] = b[i] + c[i] but not a[i] += b[i]. If aliasing may be used, it is easy enough to modify the code to catch the case a == b || a == c and use the fallback

*May need some hardware-specific tuning when ported to AVX2 or AVX512. Specifically: Should the final iteration use the full 32 or 64 byte vectors or should it only be used for the final 16 byte vector?

*Not applicable if the elements are not position-invariant within a vector register, e.g. if you do shuffling, variable shifting, etc.

I'm also tossing in an optional alignment of one of the memory locations; here I chose the output. I don't think that is particularly necessary for AVX but it uses the same technique and might come in handy if you adapt to SSE2 or AVX512.
I'm writing this in C++ with Intel intrinsics but the assembler output is very readable if you want to adapt it into ASM.
#include <immintrin.h>

#include <cstddef>

void vector_add(float* out, std::ptrdiff_t n, const float* left, const float* right)
{
    __m128 left_i, right_i, out_i;
    std::ptrdiff_t i = 0;
    if(n >= 4) {
#     ifdef ALIGN_OUTPUT
        /*
         * Optional: Do one unaligned iteration, then move the counter
         * up to the first 16-byte aligned output element
         */
        left_i = _mm_loadu_ps(left);
        right_i = _mm_loadu_ps(right);
        out_i = _mm_add_ps(left_i, right_i);
        _mm_storeu_ps(out, out_i);
        i = ((reinterpret_cast<std::ptrdiff_t>(out + 4) & ~15)
            - reinterpret_cast<std::ptrdiff_t>(out)) / sizeof(float);
#     endif
        for(; n - i >= 4; i += 4) {
            left_i = _mm_loadu_ps(left + i);
            right_i = _mm_loadu_ps(right + i);
            out_i = _mm_add_ps(left_i, right_i);
#         ifdef ALIGN_OUTPUT
            _mm_store_ps(out + i, out_i);
#         else
            _mm_storeu_ps(out + i, out_i);
#         endif
        }
        if(n - i > 0) {
            /*
             * Since we know we had at least 4 elements, we can just
             * repeat the operation for the last full vector.
             * If we use ALIGN_OUTPUT, have misaligned pointers, and n == 4,
             * then we compute the same 4 elements twice.
             * Probably not worth fixing
             */
            i = n - 4;
            left_i = _mm_loadu_ps(left + i);
            right_i = _mm_loadu_ps(right + i);
            out_i = _mm_add_ps(left_i, right_i);
            _mm_storeu_ps(out + i, out_i);
        }
        return;
    }
    /* Fallback if n <= 3 */
    if(n >= 2) {
        left_i = _mm_loadl_pi(_mm_undefined_ps(), (const __m64*) left);
        right_i = _mm_loadl_pi(_mm_undefined_ps(), (const __m64*) right);
        out_i = _mm_add_ps(left_i, right_i);
        _mm_storel_pi((__m64*) out, out_i);
        i = 2;
    }
    if(n - i >= 1)
        out[i] = left[i] + right[i];
}


text:
Q: A question about floor functions, exponents, and congruence classes Let $i, j, v, c, r, t$ be integers where:

*

*$i < j$

*$v > 0$

*$c \ge 0$

*$r > 1$

*$t > 1$

*$r \nmid t$
Does there always exist an integer $w$ where:

*

*$u = \left\lfloor\dfrac{t^{wv+c}}{r}\right\rfloor$

*For each prime $p | t$:

*

*$u \not\equiv i \pmod p$

*$u \not\equiv j \pmod p$

I am thinking that since there is an infinite number of $w$, eventually there will exist a $w$ where $u$ has the desired properties.
Is this straight forward to show whether it is true or false?  Does this turn out to be a question that is very difficult to resolve?

Edit:  Added property where $r \nmid t$ and changed to $r > 1$.

A: The claim is false.
Take $$i=0,\ \ j=1,\ \ v=1,\ \ c=0,\ \ r=2,\ \ t=3$$
For $w\le 0$, we get
$$\left\lfloor\dfrac{3^{w}}{2}\right\rfloor\equiv 0\pmod 3$$
For $w\gt 0$,
$$\left\lfloor\dfrac{3^{w}}{2}\right\rfloor=m\ \ (m\in\mathbb Z)$$
is equivalent to
$$2m\le 3^w\lt 2m+2$$
from which
$$3^w=2m+1\implies \left\lfloor\dfrac{3^{w}}{2}\right\rfloor=m\equiv 1\pmod 3$$
follows.
It follows that there is no integer $w$ such that
$$\left\lfloor\dfrac{3^{w}}{2}\right\rfloor\equiv 2\pmod 3$$


text:
Q: Deploying war file in Tomcat webapps directory is not running on browser I have made a project in Eclipse. It is running on local tomcat server. But when I deploy this war file in external tomcat server webapps directory. It is deploying correctly but when run on browser, Page not found. But I checked that directory and pages exists there but tomcat says Page not found. Then I made a demo.txt file inside project directory but it is also not found by tomcat. Now, I created a directory inside tomcat Webapps. It is found but my Project directory not found which exists there. What should I do now?

A: Check the port number. If not 80, try 8080 then.

A: There may be something wrong in web.xml or in library.
You can check tomcat Manager whether the Context is false(if then you will get only 404 error).
You can check the tomcat log files to get the exact error.


text:
Q: How to add a where clause that looks for an array of values I was wondering if i could use an array for the below instead of writing multiple ORs
from d in db.tblEquipments.Include(t => t.User).Include(t => t.ChangeLog).AsEnumerable()
                                    where (d.AssetType == "Laptop" || d.AssetType == "Workstation" || d.AssetType == "Mobile" d.AssetType == "Monitor" d.AssetType == "Other Peripheral" || d.AssetType == "Home Printer" || d.AssetType == "Home Router" || d.AssetType == "Removable Device")
                                            (d.Active == 1) &&
                                            (d.Deleted != 1 || d.Deleted == null) &&

Something like the below?
string[] arrItems = new string[] { "Laptop", "Workstation", "Mobile" }; etc
where (d.assetType == arrItems) &&
         (d.Active == 1) && ....

is that possible?

A: Use Contains method:
from d in db.tblEquipments.Include(t => t.User).Include(t => t.ChangeLog).AsEnumerable()
where arrItems.Contains(d.AssetType) &&  // same as SQL operator IN
      (d.Active == 1) &&
      (d.Deleted != 1 || d.Deleted == null) &&

Also don't use AsEnumerable() it brings all filtering into memory (i.e. instead of transferring only required equipments you are transferring all equipments over the network, and filter them in computer memory).

A: Yes it is. You have two ways to do it. The trivial way:
from d in myQueryable
where (arrItems.Contains(d.assetType)) &&
      (d.Active == 1) && ....

The problem with the previous method is that it checks all pair (x in myEnumerable, y in arrItems) which leads to a complexity of O(n²)
And the best way, with a complexity of O(n):
from d in myQueryable
join arrItem in arrItems on d.AssetType equals arrItem
select d


text:
Q: (Coleman QFT notes) Physical vacuum has no one-meson content? I'm looking at Lecture 14 in Coleman's QFT notes. In defining the renormalized field $\phi'(x)$ corresponding to the meson field $\phi(x)$, Coleman notes first that \begin{equation*}
\langle k | \phi(x) | 0_P \rangle = e^{ikx} \langle k | \phi(0) | 0_P \rangle \equiv e^{ikx} Z_3^{1/2}.
\end{equation*}
Here $| 0_P \rangle$ denotes the full/physical vacuum. This is generally different from the bare vacuum $|0 \rangle$ of the free theory, defines the $0$-particle sector of the Fock space. Likewise $| k \rangle$ is a one-meson momentum eigenstate (relativistically normalized, but that's orthogonal to my question). He then defines the renormalized field \begin{equation*}
\phi'(x) \equiv Z^{-1/2}_3 [\phi(x) - \langle 0_P | \phi(x) | 0_P \rangle ]
\end{equation*}
and says that this new field satisfies \begin{equation*}
\langle k | \phi'(x) | 0_P \rangle = e^{ikx}.
\end{equation*}
It seems to me that this only holds if we assume $\langle k | 0_P \rangle = 0$. But from the Fock space construction, any state other than multiples of the bare vacuum $| 0 \rangle$ must have some $n$-particle content for $n \geq 1$, and we know in general that $| 0_P \rangle$ is not simply related to $| 0 \rangle$, so it's not clear why $\langle k | 0_P \rangle = 0$ should be true.


text:
Q: OSX Command line: echo command before running it? I am writing an OSX command line which will run EXIFTool thousands of times against individual images. Sometimes the commands fail and its very difficult to see where its failing because it doesn't list which line.
Here is how my .command file looks:
exiftool - ABC
exiftool - DEF
exiftool = GHI

Here is how the output looks when successful:
/Users/User/Desktop/script.command ; exit;
    1 image files updated
    1 image files updated
    1 image files updated
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
Deleting expired sessions...258 completed.

How can I get it to tell me which command ran before the output?
Thank you!


text:
Q: Losing session when refresing I'm having a problem with Socket.io. I have a node.js server which utilizes the code from the READ.ME
The socket works fine when I initally create it, but when I refresh the page, the socket on the client side get lost.
Here is the code on my server:
'use strict';

const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const bodyParser = require('body-parser');
const messageRoutes = require('./routes/messages');
const db = require('./models');
const session = require("express-session")({
    secret: "my-secret",
    resave: true,
    saveUninitialized: true
});
const sharedsession = require("express-socket.io-session");

app.use(session);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

io.use(sharedsession(session, {
    autoSave: true
}));
io.on('connection', socket => {
    socket.on("login", function (userdata) {
        socket.handshake.session.userdata = userdata;
        socket.handshake.session.save();

        const { username } = userdata;
        const loggedInMessage = {
            message: `${username} has logged in`
        }

        console.log(loggedInMessage.message);
        socket.broadcast.emit('chat message', loggedInMessage);
    });

    socket.on("logout", function (userdata) {
        if (socket.handshake.session.userdata) {
            console.log(`${socket.handshake.session.userdata.username} has disconnected`);
            delete socket.handshake.session.userdata;
            socket.handshake.session.save();
        }
    });
});

// Setting up Routes
app.use("/api/messages", messageRoutes);

http.listen(3001, () => {
    console.log('Listening on port 3001');
});

As you can see, I import the express-session and then express-socket.io-session. Then I attach the sharedsession middleware onto the io instance.
Right after, I define my listeners for the login and logout events. When a new user log in, I save his userdata inside my session object and saves it.
The problem is, when I refresh the page, the socket get lost and I can't access the session object on the client side.
How can I solve this?


text:
Q: Oracle Fusion Middleware Installation Unexpected Error Nullpointer Exception While installing OFM 12.2.1 on a Windows machine, I am getting a NullPointerException at Installation Location Window.
In logs :

Unable to locate type distribution in namespace http://xmlns.oracle.com/cie/gdr/dbd

How can I solve this problem?

A: In my case the error is because I have a blank space in my username in Windows, and the path of temporal files is "C:\sdfdf\gdfg gxsfd\", I replace the temp variable for "C:\temp".
This is the solution.


text:
Q: Unity PlayerPrefs only save 1 item to all using UnityEngine;

using System.Collections;
using UnityEngine.UI;
public class ItemScript : MonoBehaviour {
public Click click;
public Text MPSInfo;
public ItemManager[] items;

void Start()
{
    LoadItems();
    StartCoroutine(AutoTick());
}

void Update()
{
    MPSInfo.text = "Money/Sec: " + MoneyPerSec();
}

public int MoneyPerSec()
{
    int tick = 0;
    foreach(ItemManager item in items)
    {
        tick += item.count * item.tickValue;
        PlayerPrefs.SetInt(item.ItemName + "Count", item.count);
        PlayerPrefs.SetFloat(item.ItemName + "Cost", item.cost);
        print(item.ItemName);
        print(item.count);
        print(item.cost);
    }
    return tick;
}

public void AutoMoneyPerSec()
{
    Click.money += MoneyPerSec();
}

IEnumerator AutoTick()
{
    while(true)
    {
        AutoMoneyPerSec();
        yield return new WaitForSeconds(1);
    }
}

public void LoadItems()
{
    foreach(ItemManager item in items)
    {
        item.count = PlayerPrefs.GetInt(item.ItemName + "Count");
        item.cost = PlayerPrefs.GetFloat(item.ItemName + "Cost");
        print(item.ItemName);
        print(item.count);
        print(item.cost);
    }
}

}
I have this script, and i have 2 items set up, for testing, but Playerprefs only saves the second item for the second and for the first item. They are the same cost, and count..

A: What do you put in as items from your editor?
Are they references of the same GameObject?


text:
Q: Mouse back and forward thumb buttons not working Mouse back and forward thumb buttons are not working on Ubuntu 19.04 using vmware 15.1. I don't think it's the VM though because the buttons do work with a Windows VM. And of course on the host computer, too. I have a AULA Ghost Shark gaming mouse.

A: add this to .vmx file of your Vm(just append it to the end of the file):
mouse.vusb.enable = "TRUE"
mouse.vusb.useBasicMouse = "FALSE"
usb.generic.allowHID = "TRUE"

make sure the VM and vmware is turned off(because if you will change it while VM is on it will not affect and the file changes will override when you close the VM - that what happened to me).


text:
Q: How to fill a solid defined by x^2+y^2<=9, z<=16-x^2-y^2 and z>=0 using PGFPlots I would like to draw the body D defined by x^2+y^2<=9, z<=16-x^2-y^2 and z>=0.
We have to graph x^2+y^2=9, z=16-x^2-y^2 and z=0 with less opacity, and then fill (or use patterns) the intersections to create the body D defined by the previous expressions:

However, I am not able to complete the task. Here is a MWE:
\documentclass{article}
\usepackage[a4paper,margin=1in,footskip=0.25in]{geometry}

\usepackage{pgfplots}
\pgfplotsset{compat=1.15}

\begin{document}

\begin{center}
    \begin{tikzpicture}
        \begin{axis} [
                axis on top,
                axis lines=center,
                xlabel=$x$,
                ylabel=$y$,
                zlabel=$z$,
                xmin=-5,
                ymin=-5,
                zmin=-1,
                xmax=5,
                ymax=5,
                zmax=17,
                xtick={-4,-3,0,3,4},
                xticklabels={$-4$,$-3$,$0$,$3$,$4$},
                ytick={-4,-3,0,3,4},
                yticklabels={$-4$,$-3$,$0$,$3$,$4$},
                ztick={0,16},
                zticklabels={$0$,$16$},
                ticklabel style={font=\tiny},
                legend pos=outer north east,
                legend style={at={(1.25,.81)},anchor=north east},
                legend cell align={left},
                view={135}{25}
            ]
            \addplot3[orange,opacity=.5,samples=51,samples y=21,variable=t,variable y=r,domain=0:360,domain y=0:2*pi,restrict z to domain=0:16] ({r*cos(t)},{r*sin(t)},{16-r*r});   % z=16-x^2-y^2
            \addlegendentry{\(16-x^2-y^2\)}
            \addplot3[green,opacity=.5,samples=51,samples y=21,variable=t,variable y=r,domain=0:360,domain y=0:2*pi,restrict z to domain=0:16] ({3*cos(t)},{3*sin(t)},{0});   % x^2+y^2=9
            \addlegendentry{\(x^2+y^2=9\)}
            \fill[cyan,opacity=.5] (3,3,0) -- (3,-3,0) -- (-3,-3,0)
        -- (-3,3,0);    % z=0
            \addlegendentry{\(z=0\)}    % This label is not showing because we used 'fill', not 'addplot3'
            % Here should be the code of the intersection of the three surfaces...
        \end{axis}
    \end{tikzpicture}
\end{center}

\end{document}

EDIT. Many thanks to marmot who helped me partially complete what I want:
\documentclass{article}
\usepackage[a4paper,margin=1in,footskip=0.25in]{geometry}

\usepackage{pgfplots}
\pgfplotsset{compat=1.15}

\begin{document}

\begin{center}
    \begin{tikzpicture}
        \begin{axis} [
                axis on top,
                axis lines=center,
                xlabel=$x$,
                ylabel=$y$,
                zlabel=$z$,
                xmin=-5,
                ymin=-5,
                zmin=-1,
                xmax=5,
                ymax=5,
                zmax=17,
                xtick={-4,-3,0,3,4},
                xticklabels={$-4$,$-3$,$0$,$3$,$4$},
                ytick={-4,-3,0,3,4},
                yticklabels={$-4$,$-3$,$0$,$3$,$4$},
                ztick={0,16},
                zticklabels={$0$,$16$},
                ticklabel style={font=\tiny},
                legend pos=outer north east,
                legend style={at={(1.45,.85)},anchor=north east},
                legend cell align={left},
                view={135}{25}
            ]
            \addplot3[opacity=.5,surf,shader=interp,colormap={orange}{color=(orange!50) color=(orange!50)},variable=t,variable y=r,domain=0:360,domain y=0:2*pi,restrict z to domain=0:16] ({r*cos(t)},{r*sin(t)},{16-r*r});  % z=16-x^2-y^2
            \addlegendentry{\(z=16-x^2-y^2\)}
            \addplot3[opacity=.5,surf,shader=interp,domain=0:360,domain y=0:16,colormap={green}{color=(green!50) color=(green!50)}] ({3*cos(x)},{3*sin(x)},{y}); % x^2+y^2=9
            \addlegendentry{\(x^2+y^2=9\)}
            %\fill[cyan,opacity=.5] (4,4,0) -- (4,-4,0) -- (-4,-4,0) -- (-4,4,0);    % z=0
            \addplot3[fill=cyan,opacity=.5,domain=-4:4, domain y=-4:4] (x,y,0);
            \addlegendentry{\(z=0\)}
        \end{axis}
    \end{tikzpicture}
\end{center}

\end{document}

However, we need to:

*

*Fix the output of z=0 (I do not want to use fill because then we cannot add a legend since it is not a plot).

*Fill the solid D using patterns:  or filling it:  What requires less programming time.

Some links of interest:

*

*How to graph a hyperboloid of a leaf with intersections using tikzpicture environment

*Graphing a paraboloid produces some imperfections using tikzpicture environment

*Truncated cylinder in PGFPlots

*Fill area between two parabolas using tikzpicture environment
Thanks!!

A: How about
\documentclass{article}
\usepackage[a4paper,margin=1in,footskip=0.25in]{geometry}

\usepackage{pgfplots}
\pgfplotsset{compat=1.15}

\begin{document}

\begin{center}
    \begin{tikzpicture}
        \begin{axis} [
                axis on top,
                axis lines=center,
                xlabel=$x$,
                ylabel=$y$,
                zlabel=$z$,
                xmin=-5,
                ymin=-5,
                zmin=-1,
                xmax=5,
                ymax=5,
                zmax=17,
                xtick={-4,-3,0,3,4},
                xticklabels={$-4$,$-3$,$0$,$3$,$4$},
                ytick={-4,-3,0,3,4},
                yticklabels={$-4$,$-3$,$0$,$3$,$4$},
                ztick={0,16},
                zticklabels={$0$,$16$},
                ticklabel style={font=\tiny},
                legend pos=outer north east,
                legend style={at={(1.45,.85)},anchor=north east},
                legend cell align={left},
                view={135}{25}
            ]
            \addplot3[opacity=.5,surf,shader=interp,colormap={orange}{color=(orange!50) color=(orange!50)},variable=t,variable y=r,domain=0:360,domain y=0:2*pi,restrict z to domain=0:16] ({r*cos(t)},{r*sin(t)},{16-r*r});  % z=16-x^2-y^2
            \addlegendentry{\(z=16-x^2-y^2\)}
            \addplot3[opacity=.5,surf,shader=interp,domain=0:360,domain y=0:16,colormap={green}{color=(green!50) color=(green!50)}] ({3*cos(x)},{3*sin(x)},{y}); % x^2+y^2=9
            \addlegendentry{\(x^2+y^2=9\)}
            %\fill[cyan,opacity=.5] (4,4,0) -- (4,-4,0) -- (-4,-4,0) -- (-4,4,0);    % z=0
            \addplot3[surf,shader=interp,opacity=.5,domain=-4:4, domain y=-4:4,
            colormap={dull}{color=(cyan) color=(cyan)},opacity=0.5] {0};
            \addlegendentry{\(z=0\)}
            \addplot3[mesh,color=gray,ultra thin,domain=0:360,domain y=0:4,z
            buffer=sort,samples=31,samples y=41]
            ({min(y,3)*cos(x)},{min(y,3)*sin(x)},{16-y*y});
        \end{axis}
    \end{tikzpicture}
\end{center}

\end{document}

? It might make a nice cage for nasty ducks. ;-)
This shows the surface. I do not know what you want to do with the original plots.
\documentclass{article}
\usepackage[a4paper,margin=1in,footskip=0.25in]{geometry}

\usepackage{pgfplots}
\pgfplotsset{compat=1.15}

\begin{document}

\begin{center}
    \begin{tikzpicture}
        \begin{axis} [
                axis on top,
                axis lines=center,
                xlabel=$x$,
                ylabel=$y$,
                zlabel=$z$,
                xmin=-5,
                ymin=-5,
                zmin=-1,
                xmax=5,
                ymax=5,
                zmax=17,
                xtick={-4,-3,0,3,4},
                xticklabels={$-4$,$-3$,$0$,$3$,$4$},
                ytick={-4,-3,0,3,4},
                yticklabels={$-4$,$-3$,$0$,$3$,$4$},
                ztick={0,16},
                zticklabels={$0$,$16$},
                ticklabel style={font=\tiny},
                legend pos=outer north east,
                legend style={at={(1.25,.81)},anchor=north east},
                legend cell align={left},
                view={135}{25}
            ]
%             \addplot3[orange,opacity=.5,samples=51,samples y=21,variable=t,variable y=r,domain=0:360,domain y=0:2*pi,restrict z to domain=0:16] ({r*cos(t)},{r*sin(t)},{16-r*r});   % z=16-x^2-y^2
%             \addlegendentry{\(16-x^2-y^2\)}
%             \addplot3[green,opacity=.5,samples=51,samples y=21,variable=t,variable y=r,domain=0:360,domain y=0:2*pi,restrict z to domain=0:16] ({3*cos(t)},{3*sin(t)},{0});   % x^2+y^2=9
%             \addlegendentry{\(x^2+y^2=9\)}
%             \fill[cyan,opacity=.5] (3,3,0) -- (3,-3,0) -- (-3,-3,0)
%         -- (-3,3,0);    % z=0
%             %\addlegendentry{\(z=0\)}    % This label is not showing because we used 'fill', not 'addplot3'
            % Here should be the code of the intersection of the three surfaces...
            \addplot3[surf,shader=interp,domain=0:360,domain y=0:7,z buffer=sort]
            ({3*cos(x)},{3*sin(x)},{y});
            \addplot3[data cs=polar,surf,shader=interp,domain=0:360,domain y=0:3] {16-y*y};
        \end{axis}
    \end{tikzpicture}
\end{center}
\end{document}

This looks like a poisonous mushroom to me:
\documentclass{article}
\usepackage[a4paper,margin=1in,footskip=0.25in]{geometry}

\usepackage{pgfplots}
\pgfplotsset{compat=1.15}

\begin{document}

\begin{center}
    \begin{tikzpicture}
        \begin{axis} [
                axis on top,
                axis lines=center,
                xlabel=$x$,
                ylabel=$y$,
                zlabel=$z$,
                xmin=-5,
                ymin=-5,
                zmin=-1,
                xmax=5,
                ymax=5,
                zmax=17,
                xtick={-4,-3,0,3,4},
                xticklabels={$-4$,$-3$,$0$,$3$,$4$},
                ytick={-4,-3,0,3,4},
                yticklabels={$-4$,$-3$,$0$,$3$,$4$},
                ztick={0,16},
                zticklabels={$0$,$16$},
                ticklabel style={font=\tiny},
                legend pos=outer north east,
                legend style={at={(1.25,.81)},anchor=north east},
                legend cell align={left},
                view={135}{25}
            ]
%             \addplot3[orange,opacity=.5,samples=51,samples y=21,variable=t,variable y=r,domain=0:360,domain y=0:2*pi,restrict z to domain=0:16] ({r*cos(t)},{r*sin(t)},{16-r*r});   % z=16-x^2-y^2
%             \addlegendentry{\(16-x^2-y^2\)}
%             \addplot3[green,opacity=.5,samples=51,samples y=21,variable=t,variable y=r,domain=0:360,domain y=0:2*pi,restrict z to domain=0:16] ({3*cos(t)},{3*sin(t)},{0});   % x^2+y^2=9
%             \addlegendentry{\(x^2+y^2=9\)}
%             \fill[cyan,opacity=.5] (3,3,0) -- (3,-3,0) -- (-3,-3,0)
%         -- (-3,3,0);    % z=0
%             %\addlegendentry{\(z=0\)}    % This label is not showing because we used 'fill', not 'addplot3'
            % Here should be the code of the intersection of the three surfaces...
            \addplot3[surf,shader=interp,domain=0:360,domain y=0:7,z
            buffer=sort,colormap=
        {greenblack}{color=(green!50!black) color=(green)}]
            ({3*cos(x)},{3*sin(x)},{y});
            \addplot3[data cs=polar,surf,shader=interp,domain=0:360,domain y=0:3,color=orange] {16-y*y};
        \end{axis}
    \end{tikzpicture}
\end{center}
\end{document}

You can also draw it in one stretch.
\documentclass{article}
\usepackage[a4paper,margin=1in,footskip=0.25in]{geometry}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}

\begin{document}

\begin{center}
    \begin{tikzpicture}
        \begin{axis} [
                axis on top,
                axis lines=center,
                xlabel=$x$,
                ylabel=$y$,
                zlabel=$z$,
                xmin=-5,
                ymin=-5,
                zmin=-1,
                xmax=5,
                ymax=5,
                zmax=17,
                xtick={-4,-3,0,3,4},
                xticklabels={$-4$,$-3$,$0$,$3$,$4$},
                ytick={-4,-3,0,3,4},
                yticklabels={$-4$,$-3$,$0$,$3$,$4$},
                ztick={0,16},
                zticklabels={$0$,$16$},
                ticklabel style={font=\tiny},
                legend pos=outer north east,
                legend style={at={(1.25,.81)},anchor=north east},
                legend cell align={left},
                view={135}{25}
            ]
            % Here should be the code of the intersection of the three surfaces...
            \addplot3[surf,shader=interp,domain=0:360,domain y=0:4,z
            buffer=sort,colormap=
        {greenorange}{color=(green!80!black) color=(orange)},samples=31,samples
        y=41]
            ({min(y,3)*cos(x)},{min(y,3)*sin(x)},{16-y*y});
        \end{axis}
    \end{tikzpicture}
\end{center}
\end{document}


text:
Q: Putting Breakpoint on Register Write in Trace32 I see an option for putting a breakpoint on read or write of a register when creating a new breakpoint, but it is greyed out. How do I get to select that option and how would I write, for example, that I want to break when something writes a value of 0x60002806 or > 0x60002000 to register A2?

A: I never saw a processor on chip debug implementation that allows such functionality, to stop when a CPU reg have a value.
On ARM, when facing these troubles I use to obtain a ETM trace with code and data enabled, and after the register gets that value, stop the capture and look for current value of the register along the trace with a search on it.


text:
Q: Is there an XSLT buddy available somewhere? I think a lot of people know about tools like RegexBuddy. Is there something similar for XSLT?

A: This is the closest I know that is free: XML Copy Editor
Altova XML Spy is excellent but expensive.

A: If you just want to experiment with an XSLT expression, there's a sandbox in Orbeon Forms. Obviously, there are a bunch more features in RegexBuddy that this has no equivalent to, but it's a nice interactive way to play with some strange XSLT expression that you're trying to debug.

A: XSLT IDEs (Interactive Development Environments):

*

*XSelerator (the one I've been using for 6-7 years). Free, has a Debugger for MSXML, has intellisense for both XSLT 1.0 and XSLT 2.0. In addition has some dynamic intellisense. The debugger has breakpoints, data breakpoints,visualizes temporary trees, variables, test conditions, current output, ..., etc.

*VS2008 -- a good XML Editor + XSLT Debugger. Good static intellisence. Match patterns are statically checked. Breakpoints, data breakpoints, visualization of variables and the current output.

*oXygen

*XML-SPY (Altova)

*Stylus Studio
XPath tools:

*

*The XPath Visualizer -- A popular tool for learning XPath by playing with XPath expressions. Free and open source. Allows any XPath expression to be evaluated against a given XML document and displayes the results hi-lighted in the xml document (if they are node(s)) or in a separate box (if the results are atomic values). Allows xsl:variable-s to be defined and then used in XPath expressions. Allows xsl:key-s to be defined and then referenced by key() functions within XPath expressions.

EDIT: The XPath Visualizer now has a new, safer home, due to the kindness of Lars Huttar.

A: I have used Architag XRay in the past (I have oXygen now).
XRay is free and lightweight.

A: And your guerilla option, the bugged and seemingly unsupported free family favourite: XML cooktop


text:
Q: What's the maximum number of train phrases for each intent in dialogflow? What's the maximum number of train phases for each intent in dialogflow?
I know there have max intent number 2000 for one agent. but what's the number of the train phrases?

A: You can have 2000 training phrases per intent.

A: As Taylor has pointed out, the number of Training Phrases per intent is limited to 2000.
For more such limits and quotas of Dialogflow, you can refer https://dialogflow.com/docs/reference/agent-limits-and-quotas


text:
Q: Add active class to ul container menu Does anyone know how to add a "active" class to the parent container menu in WordPress 4.1.1 ?
If an item of the menu has the "current-menu-item" class, I want to add "active" class to the  parent container.
Example of what I need (the "active" class) :

Item 1

Item 2

Item 3

Thank you !
EDIT
It's a standard WP menu.
Menu PHP :
$args = array(
    'theme_location'    =>  'main_menu',
    'fallback_cb'       =>  'wp_page_menu',
    'items_wrap'        =>  '
%3$s
'
);
$main_menu = wp_nav_menu($args);

Current HTML structure :

Item 1

Item 2

Item 3


text:
Q: How can I write a non-breaking space? Some word processing programs have a menu for entering special characters, including non-breaking spaces.  It is also possible to copy the character created in the word processing program and paste it into other places, such as a terminal or a website text field.  However, it is inconvenient to need to use a word processing program just to generate a non-breaking space in the first place.
How can I use my keyboard directly to enter a non-breaking space?

A: Try Shift-space. If this doesn't work with your configuration, you can modify it by specifying
key <SPCE> { [ space, nobreakspace ] };

in XKB symbol settings.
My explanations on how to change XKB settings.
Note also that applications should not do line breaking under certain conditions, such as before a question mark, even after a normal space (as described in the Unicode Line Breaking Algorithm), so that the non-breaking space could be unnecessary; unfortunately, most applications do not follow this behavior. The non-breaking space U+00A0 is just an explicit non-breaking space; it doesn't mean that a normal space character is always breaking.

A: Once upon a time I told my debian fairy that I want compose instead of caps lock and typing compose space space now gives me the super solid unbreakable space:
compose space space ! compose space space ! compose space space ! compose space space ! compose space space ! compose space space ! compose space space ! compose space space !
For debianish systems have a look into /etc/default/keyboard, I have the following assigment there: XKBOPTIONS="compose:caps".
Alternatively, if you're using KDE, the "advanced" tab, of the kcmshell4 kcm_keyboard command lets you configure what key to map to compose.
This setting affects the text terminals too... at least in debian...


text:
Q: When does meteor store login token during authentication? I need to set login token cookie. It works fine, but when I login from one user to another it seems that it stores wrong token that cannot be used to retrieve user from db. Here how I tried to do it:
onLogin hook on client:
Accounts.onLogin(function() {
        $.cookie('X-Auth-Token', Accounts._storedLoginToken(), { path: '/' });
    });

Tracker:
Tracker.autorun(function () {
        $.cookie('X-Auth-Token', Accounts._storedLoginToken(), { path: '/' });
    });

Login callback:
Meteor.loginWithPassword(username, password, function(){
     $.cookie('X-Auth-Token', Accounts._storedLoginToken(), { path: '/' });
});

None of them worked. What worked though is simple manual click event which set login token. I would login to a new user and then click a button which sets login token cookie and token is correct then. So I think this delay helps (as I said all my tries to do that right after new login fails). My question is - when it is ok to use Accounts._storedLoginToken() after new login?

A: OK after some debugging and reading source code I found out that Meteor.logoutOtherClients() modifies login token and I was invoking this method in my login callback (when user logs in it is logged out from other devices). I didn't solve it and simply removed this method as I was rethinking my use case and decided that I don't need to logout other clients. After that it started working perfectly.


text:
Q: deriving cdf of uniform distribution I have that the pdf for a uniform distribution is given by $$f(x) = \frac{1}{b-a}$$ if $a \leq x \leq b $ and $0$ otherwise.
I am trying to derive the cdf.
From definition I have that the cdf is given by $F(x) = \int_{-\infty}^x f(t) \ dt$
So I will split it up to 3 intervals:
If $x < a$ we have that $f(x) = 0$ so $F(x) = 0$ here.
If $ a \leq x \leq b $ we have that $$F(x) = \int_{a}^x f(t) \ dt = \frac{x-a}{b-a}$$
If $ x > b$ the pdf says that $f(x) = 0$ here, so surely the cdf would be $$F(x) = \int_{-\infty}^\infty 0 \ dt = 0 $$ but however it is equal to $1$.
What is wrong with my approach, and how would you usually derive these answers.

A: If $x>b$:
$$
F(x)=\int_{-\infty}^af(t)\;dt+\int_a^b f(t)\;dt+\int_b^xf(t)\;dt
$$
The first integral is $0$, the second $1$ and the third $0$.

A: Everything up to $x > b$ is perfect.
But your reasoning in the final case is not quite correct, because the integral is taken over an interval that includes parts of the PDF that are nonzero.  In other words, the interval $(a,b)$ is a subset of the interval $(-\infty, x)$ if $x > b$.  Just because the density is zero when $x > b$, it doesn't mean that the integral from $(-\infty, x)$ is itself zero, because as we can see, there are points within the interval of integration for which the density is positive.
For example, if I say to you to calculate the integral of $g(x) = 1-x$ from $x = 0$ to $x = 1$, what would you write?  $$\int_{x=0}^1 1-x \, dx = \left[x - \frac{x^2}{2}\right]_{x=0}^1 = 1 - \frac{1}{2} = \frac{1}{2}.$$  Now if I give you the function $$h(x) = \begin{cases} g(x), & 0 \le x \le 1 \\ 0, & x > 1, \end{cases},$$ what would the integral of $h$ be from $x = 0$ to $x = 2$?  It's the same as the above, because the area under the curve of $h$ from $x = 1$ to $x = 2$ is zero, so you've not added any area, but the total area is not zero because you still had area from $x = 0$ to $x = 1$.


text:
Q: What is the correct way of mocking a user to test a login page with laravel and phpunit I currently have the following test, that basically creates a new user and makes sure the login can pass the test.
I'm using Laravel 5.6.
class LoginTest extends TestCase
{
    public function testLoginWorksWithValidCredentials()
    {

        $user = new User();
        $user->name = 'CMS';
        $user->email = 'test@test.com';
        $user->password = 'password';
        $user->save();

        $response = $this->postJson('/api/login', [
            'email' => 'test@test.com',
            'password' => 'password'
        ]);

        $response->assertStatus(200);
    }
}

Would this be the correct way of handling a test for the login, creating a user there and checking the login works? My assertions could of course be a little more specific, test for a specific response etc.


text:
Q: how to fixe SQL injection in hibernate(session.createquery()) org.hibernate.Query hQuery = session.createQuery (String);
hQuery.setParameter(i,data);

while scanning code using tool it shows that this line is vulnerable to SQL injeciton. how to fix it.


text:
Q: Setting the UIImagePickerController delegate throws a warning about UINavigationControllerDelegate The code:
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self.navigationController presentModalViewController:picker animated:YES];
[picker release];

The warning, which shows up on the picker.delegate = self; line:
Class 'CardEditor' does not implement the 'UINavigationControllerDelegate' protocol

Why does the UIImagePickerController care if my class implements the UINavigationControllerDelegate protocol?

A: e.James is right. Besides this UINavigationControllerDelegate only specifies optional methods. So a quick solution is to just let your view controller implement the protocol without implementing any of its methods.
I've checked all the Apple Sample code for implementations of UIImagePickerControllerDelegate and they all don't implement any of the UINavigationControllerDelegate methods. So if you don't need them don't worry.

A: UIImagePickerController inherits from UINavigationController. The delegate property is part of UINavigationController, so it requires that its delegate conforms to the UINavigationControllerDelegate protocol.
The delegate property is declared like so:
@property(nonatomic, assign) id<UINavigationControllerDelegate> delegate;

This tells the compiler to verify that your controller will implement the UINavigationConrollerDelegate protocol. The check is in place so that a compile-time warning can be generated if your controller class does not properly implement all of the methods that the UINavigationController might send to its delegate.
If you're looking for a solution, you can indicate (in your controller class interface) that your controller is compliant with that protocol:
@interface MyController : NSObject <UINavigationControllerDelegate>
    ...
@end

Once this is done, the compiler will warn you about any required delegate methods that you haven't implemented. This is a good thing, as it will prevent you from releasing code that might accidentally throw a "method not found" runtime error.

A: I also faced the same problem then after a search found the solution i.e to add UINavigationControllerDelegate along with your UIImagePickerControllerDelegate in .h file.
@interface LatestJobsVC : UIViewController <UIImagePickerControllerDelegate , UINavigationControllerDelegate>

Hope that helps you.
Thanks

A: You can do it like this at the .h file
@interface MyController : UIViewController<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

A: for Swift 4 :
@interface MyController : UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate


text:
Q: Is there multiple contributor integration in Monaco Editor built in? I'm working on a project that allows two people to work on the same code from different computers. I would like to use Monaco because it's so bare bones. I imagine I can use something like socket.io to integrate this functionality. I was curious if it's already available in monaco. Basically, the same page is accessed by multiple people, whatever they type shows up for all viewers of the page. This is the same functionality as codeshare.io which is what I'm trying to emulate.

A: No, and I am quite sure that wont happen since it is mainly from VS Code - client site editor, and the Monaco is used on Git centric site like Visual Studio Team Service (but also on Azure - but still). Also I reckon its a fairly big task to accomplish in the right way.
I know prosemirror.net has it - but that is not a code editor; Although it has a sample that embeds CodeMirror in it.


text:
Q: How I can rename the contents of compressed file befor extract in python? Is there is a way to rename the file name inside the compressed file ,but without extract it,  in python ??

A: No.  The python ZipFile module does not provide any way to do that.
You can extract the archive into memory, and then rewrite it with the new filename for the file in question, but that is memory intensive and not what you want to do.
You may be able to edit the zipfile's header and information fields, but the standard Python interface doesn't have an easy way to do so.


text:
Q: Displaying Folium map using tkinter I would like to display a map in a tkinter GUI I am creating. I currently have a folium map (map1.html) which I would like to be displayed in a tkinter widget.
I have searched quite a lot but could not find a solution. Any help would be appreciated.


text:
Q: Nesting 2 ListViewBuilder in a SingleScrollView let the app freezing I need 2 different lists in a scrollable view, so i did the following:
body:SingleChildScrollView(
    physics: const ScrollPhysics(),
    child: Column(
      children: <Widget>[
                          ListView.builder(
                            physics: NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          itemBuilder: (context,index){
                            return Container(
                              padding: const EdgeInsets.all(10),
                              height: 75,
                              child: Row(
                                children: <Widget>[

                                ],
                              ),
                            );
                          }
                         ),

                          ListView.builder(
                            physics: NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          itemBuilder: (context,index){
                            return Container(
                              padding: const EdgeInsets.all(10),
                              height: 75,
                              child: Row(
                                children: <Widget>[

                                ],
                              ),
                            );
                          }
                         ),

      ]
      ),
  ),

If i press the button to open this ListView nothing happens and the app is frezzed.
Any idea ?
Let me know if you need more information,
Thanks


text:
Q: Cannot read functions from external javascript file used by html file I have an index.html file:

    <title>Jiggle Into JavaScript</title>

Press the buttons to change the box!

    <button type="button1" onclick="growFunc()">Grow</button>
    <button type="button2" onclick="blueFunc()">Blue</button>
    <button type="button3" onclick="fadeFunc()">Fade</button>
    <button type="button4" onclick="resetFunc()">Reset</button>

My javascript.js file looks like this:
function growFunc() {
    document.getElementById("button1").addEventListener("click",
        function(){document.getElementById("box").style.height = "250px";
    });
}

function blueFunc() {
    document.getElementById("button2").addEventListener("click",
      function(){document.getElementById("box").style.backgroundColor = "blue";
    });
}

function fadeFunc() {

    document.getElementById("button3").addEventListener("click", function(){

        document.getElementById("box").style.backgroundColor = "orange";

    });

}

function resetFunc() {
    document.getElementById("button4").addEventListener("click",
       function(){
        document.getElementById("box").style.height = "150px";
        document.getElementById("box").style.backgroundColor = "darkorange";
       });
}

Both files are in the same directory. When I try to run index.html in Firefox, for example, nothing happens when I click on the buttons. But if I have the functions all in the index.html file(see below), it works. I can't seem to find what's wrong with my code(I'm new at this). Thank you for your help.

<title>Jiggle Into JavaScript</title>

Press the buttons to move the box!

<button id="growBtn">Grow</button>
<button id="blueBtn">Blue</button>
<button id="fadeBtn">Fade</button>
<button id="resetBtn">Reset</button>

A: You are binding event handler in the inline click handler, thus its having no effect when you click once.
In your javascript file use DOMContentLoaded event to wait for DOM to be loaded completely then bind event handlers
document.addEventListener("DOMContentLoaded", function(event) {
    //Bind event handlers
    document.getElementById("button1").addEventListener("click", function(){
        .....
    });
});

And Get rid of ugly inline event handlers.

A: In your functions you're adding some event listeners, that is not useful because when the function is triggered the click has already been performed.
Just apply CSS changes in the functions.
Plus: your buttons do not have an id, but a type. So you can't select them with getElementById.


text:
Q: Prevent losing Focus in Textbox I am currently getting stuck with controlling components focus in C#.net. My goal is that preventing losing focus of Textbox A when "click" to another component (eg Textbox B or something). This "focus" mechanism will be kept except Textbox C or D ... is clicked.

That might sound so weird but my situation is that Each of those rows A,C,D is a datarepeater item, and I only want to vertically move "focus" on the right column, not B column.
So, It is possible to do that in C# or I've got to find another control (not Data repeater). Any helps would be grateful.

A: You can use the Leave event of the TextBoxA along with a list that contains the controls that are allowed to acquire focus.
    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi)]
    internal static extern IntPtr GetFocus();

    private Control GetFocusedControl()
    {
        Control focusedControl = null;
        // To get hold of the focused control:
        IntPtr focusedHandle = GetFocus();
        if (focusedHandle != IntPtr.Zero)
            // Note that if the focused Control is not a .Net control, then this will return null.
            focusedControl = Control.FromHandle(focusedHandle);
        return focusedControl;
    }

    private void textBox3_Leave(object sender, EventArgs e)
    {
        //Any control that is allowed to acquire focus is just added to this array.
        Control[] allowedToAcquireFocusControls = {
                 textBox1
            };

        Control focusedControl = GetFocusedControl();

        if (!allowedToAcquireFocusControls.Contains(focusedControl))
        {
            textBox3.Focus();
        }
    }

Reference: What is the preferred way to find focused control in WinForms app?


text:
Q: How to route lan traffic from one NIC to vpn connection that uses another NIC I have a server (windows server 2008 r2) with two nics. One is connected to a local lan, the other to the internet. It has a vpn connection setup to connect across the internet to another server to access a remote lan. How can I configure the local server so that the local lan can connect to the remote lan?

A: You will need to set up site-to-site routing via "Routing and Remote Access" (RRAS).


text:
Q: Swift 2: Natively serialize JSON to Core Data Model Objects I would like to serialize JSON into Core Data Model Objects, and back and forth.   I am in the process of switching from RestKIT to Alamofire and Swifty JSON.   I know there are libraries that provide that, but I would like to know how to do it natively?
Below is the Core Data Setup:

Event+CoreDataProperties.swift
import Foundation
import CoreData

extension Event {

    @NSManaged var id: NSNumber?
    @NSManaged var name: String?
    @NSManaged var realRame: String?
    @NSManaged var notes: NSSet?

}

Event.swift
import Foundation
import CoreData

class Event: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
}

Notes+CoreDataProperties.swift
import Foundation
import CoreData

extension Notes {

    @NSManaged var id: NSNumber?
    @NSManaged var name: String?
    @NSManaged var event: Event?

}

Notes.swift
import Foundation
import CoreData
class Notes: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
}
Below is received JSON:
{
    "id": "5555",
    "name": "Superman",
    "realName": "Clark Kent",
    "notes": [
        {
            "id": "2",
            "name": "Order Flowers"
        },
        {
            "id": "3",
            "name": "Pick up Laundry"
        }
        {
            "id": "4",
            "name": "Get Chinese Food"
        },
    ]
}

Code to fetch the JSON:
Alamofire.request(fetchData(param)).responseJSON { (response) in

        switch response.result {
        case .Success:
            if let value = response.result.value {
                let json = JSON(value)
            }
        case .Failure(let error):
            print("Request failed with error: \(error)")
        }
    }

Question:  I'm not sure where to go from here.  NSJSONSerialization seems to want the data in NSData format.
Code example would be greatly appreciated.

A: Add new class DBManager:
class DBManager: NSObject {
var managedObjectContext:NSManagedObjectContext!
var managedObjectModel:NSManagedObjectModel!

func insertData(jsonObj: AnyObject)  {
            let entity =  NSEntityDescription.entity(forEntityName: "Event",
                                                     in:managedObjectContext)
            let obj = NSManagedObject(entity: entity!,
                                           insertInto: managedObjectContext)

            obj.setValue(String((jsonObj.value(forKey: "id"))!)  , forKey: "id")

....

Continue setting values for other attributes.
Declare this var in AppDelegate:
var objDb = DBManager()

Add this
switch response.result {
        case .Success:
            if let value = response.result.value {
                let json = JSON(value)

                let anyObjects: AnyObject = json as! AnyObject
                let appDelegate = UIApplication.shared().delegate as! AppDelegate
                appDelegate.objDb.insertData(jsonObj: anyObjects)
            }
        case .Failure(let error):
            print("Request failed with error: \(error)")
        }


text:
Q: How to embed widget written by vue into a vue webapp I'm building a website with Vuejs. I have the code like this
app.js
new Vue({
  el: '.page-wrapper',
  ...
})

index.html

Now I want to embed a widget which is built by Vuejs like

inside page-wrapper class.
I've tried to put the script tag outside the origin Vue component but the content of widget still did not render.
I'm new to Vuejs, could anyone help me out?

A: I'm just going to take a stab at this...
index.html

    <my-widget></my-widget>

main.js
Vue.component('my-widget', {
    template: '

'
});

new Vue({
    el: '#app'
});

My Vue instance is #app and I'm loading your widget.js asset in index.html. I'm probably completely underestimating this, apologies if that's the case!


text:
Q: Python - Create a column equal to the value of another column but if two consecutive values occur in the first column then make new column equal to 0 I have a column ('bet_made1') of ones and zeros where 1 represents taking a long position in a stock.
I want to create a new column that will equal the value of 'bet_made1'. However, if two consecutive 1s occur in 'bet_made1', I would like the new column to equal 0.
I would like to repeat so that a long position is followed by 4 days without another long being taken.
In other words, if I have a long position , I do not want to take another one till the 5th day after the initial buy order so that I only place a trade at a minimum of every 5 days.
Hope that makes sense. I've included a table below showing what I'm aiming for.
Cheers!
    bet_made1   long_pos
date
02/01/2019  0.0 0.0
03/01/2019  0.0 0.0
04/01/2019  0.0 0.0
07/01/2019  0.0 0.0
08/01/2019  0.0 0.0
09/01/2019  0.0 0.0
10/01/2019  0.0 0.0
11/01/2019  0.0 0.0
14/01/2019  0.0 0.0
15/01/2019  0.0 0.0
16/01/2019  1.0 1.0
17/01/2019  1.0 0.0
18/01/2019  0.0 0.0
22/01/2019  1.0 0.0
23/01/2019  1.0 0.0
24/01/2019  1.0 1.0
25/01/2019  1.0 0.0
28/01/2019  1.0 0.0
29/01/2019  0.0 0.0
30/01/2019  0.0 0.0

A: There might be a more compact and tricky way, but creating a list with the new values and than add it as a new column may be a good idea:
import pandas as pd
df = pd.DataFrame(data=dict(bet_made1=[0,1,0,1,1,1,0,0,1,1,1,1,1,1]))

long_pos = []
remains = 0
for b in df.bet_made1:
    if remains > 0:
        remains -= 1
        long_pos.append(0)
    elif b == 1:
        remains = 4
        long_pos.append(1)
    else:
        long_pos.append(0)

df['long_pos'] = long_pos

This gives me the result:
 bet_made1  long_pos
         0         0
         1         1
         0         0
         1         0
         1         0
         1         0
         0         0
         0         0
         1         1
         1         0
         1         0
         1         0
         1         0
         1         1


text:
Q: Create Virtual Directory IIS7 to be use in GetFolder in Server.CreateObject("Scripting.FileSystemObject") I am trying to create a virtual directory at my IIS7 and then use the virtual directory in the following code
sPath = "\CMapped\database\attendanceData\"

sDir = Server.MapPath(".") & sPath

response.write sDir

Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set obj_FolderBase = fso.GetFolder(sDir)

response.end

But I got the following error:

What I have done is as follow:

*

*I created the virtual directory and set the path to C:\ Drive. My localhost is at D:\ drive. I have also set Connect as and entered my log in and password. I am the administrator of the PC. Everything authorized.

*Then I go to C: and set it as a shared folder

*I went back to IIS and click on the virtual directory -> Managed Virtual Directory -> Browse. I successfully connect to the directory

Now when I try the code, everything failed. The GetFolder function doesn't seems to recognize the path. The web server is at D: and the file server is at C: Please help.
sPath = "\CMapped\database\attendanceData\"

sDir = Server.MapPath(".") & sPath

response.write sDir

Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set obj_FolderBase = fso.GetFolder(sDir)

response.end

The directory structure

A: What you are trying would work in an href or src attribute, or with
<!--#include virtual="\CMapped\database\attendanceData\yourfile.asp"-->.
With  server.mappath though I think you need to use the physical directory structure on the machine.  As your virtual directory is on a different drive I suggest you go with
sDir = "C:\full_physical_path_to\database\attendanceData\"


text:
Q: MVC 4 web application using ADFS to authenticate users from different organisations I have a web application developed using ASP.NET 4.5 and MVC 4.  It originally used Form Authentication for users to log in, however, we are moving it to ADFS (WS Federation) authentication.  The idea is users from my organisation (Org 1) and another organisation (Org 2) will be able to log in using ADFS (ws-fed).
ADFS is set up so when you navigate to the web application's URL it is redirected to ADFS log in screen.  At this point, it displays an option for the two organisations, Org 1 and Org 2.  If you belong to Org 1, click this button and the user has to enter their username and password.  The same thing happens if you click Org 2 button.
The ADFS servers in Org 1 and Org 2 have exchanged metadata/certificates and the claim values.
When a user from Org 1 logs in, there is no problem, after successful ADFS authentication, they are redirected back to the Web application with the required Claims (the web app uses the info in these claims).  However, when user from Org 2 logs in, they are authenticated but their Claims aren't reaching the web application.
Does the web application need configured to work with both ADFS servers from Org 1 and Org 2?  My original thoughts were Org 1 (my own organisation), would handle all the ADFS authentication.  The web app would point to it, and when a user from Org 2 tries to log in, our ADFS would redirect the request to Org 2 and then Org 2 would send the claims back to our originsation ADFS server and it would redirect back to the application with the Claims?  Am I wrong in thinking this?

A: No, that's correct.
Two possibilities:

*

*Org2's ADFS has the wrong claims rules

*Your ADFS has no pass-through claims rules. You need these rules on your CP (for Org2) and for your RP

It needs these rules to pass through what it receives from Org2.


text:
Q: SplitViewcontroller programmatically hide master view There are a few questions here on stackoverflow that deal with this, but none of the answers seem to work for me. I am trying to hide the masterview of a split view controller from a button on the detail view. The delegate of the split view is the app delegate itself. It works when I manually rotate the device, but not before that. How can I make the master view disappear/appear?
Below is my code, based upon answers here on stack overflow (I have tried a bunch of stuff)
[self.splitViewController.view setNeedsLayout];
    [self.splitViewController.view setNeedsDisplay];
    [self.splitViewController.view reloadInputViews];
    self.splitViewController.delegate = nil;
    self.splitViewController.delegate=self;
    [self.splitViewController reloadInputViews];
    [self.splitViewController willRotateToInterfaceOrientation:[UIApplication    sharedApplication].statusBarOrientation duration:0];

A: There are no ways to hide the master view programically as far as I know, but Matt Gammel has created a custom split view controller that allows lots of monuplation which has a costum built in method toggle the split view visible and hide it. Take a look at project and see if that helps you out. The appearance of the views are mimicking the split view controller so as far as appearance is concerned you should be fine. Anyway here is the direct link to the github project.
https://github.com/mattgemmell/MGSplitViewController/


text:
Q: Alias to Previous Macro-Created Class Background:
I am trying to build a registry of objects, but every object is templated by some value, e.g. int Parameter.
template<int Parameter>
class SomeObject
{
// things
}

I have built a macro to register them
#define REGERISTER_OBJECT(PREFIX,OBJECT)\
class reg_##PREFIX\
{\
 template<int Parameter>\
using Name = OBJECT\
template<int Parameter>\
void Register()\
{\
ObjectRegistry<Parameter>::Register<Name>();\
}

where ObjectRegistry<Pameter> is really just a templated version of https://www.bfilipek.com/2018/02/factory-selfregister.html
Now the trick is that I only want to build a registry for specific parameters. (Note, we can assume that the Parameter is only going to take one some values (e.g. 1,2,3).  However, in any one project I am only going to need one of them.)
Every time I try to make this work.  I run into one of three problems:

*

*Nothing instantiates and the registry is empty.

*Everything instantiates and there is an absurd memory requirement to compile.

*I require a virtual template function  (if you attempt to derive reg_##PREFIX from some base class) and nothing compiles.

The Question:
The best way to make this work is if there were a way to write a macro like this:
#define REGERISTER_OBJECT(PREFIX,OBJECT)\
class reg_##PREFIX\
{\
using Previos = CLASS_CREATED_LAST_TIME_THIS_MACRO_WAS_INVOKED;
 template<int Parameter>\
using Name = OBJECT\
}

I can build a recursive function to register everything then. (I believe.)  However, there seems to be no way to hold data from the last invocation (i.e. in a #define).  Any way around this?


text:
Q: Adf column filter: which format does ADF use to generate the where clause in the VO's query? TLDR; is there a way to understand at runtime which format is ADF using for dates behind the scenes? In particular the format used to render dates in dynamically generated sql code?
In the Oracle ADF Application I'm working on there are several table filters (by that I mean the field over the column in which I can write text/number/dates to query the table).
Filtering this way, the framework modifies the query of the View Object, adding the appropriate where clause. On the page there's also a button "Select all" that allows me to select all the data that's rendered in the table (there is a selection checkbox).
In the specific case, the query from the VO is used to aim two different goals:

*

*update the rendered data in the table

*if I press the "select all" button a function in the backend database is called (callable statement calling the function), passing as a parameter the query.

The first task is successfully reached (as the table is visually updated), but we had an issue with the second one.
The backend function uses the query to select all the extracted data (as iterating in ADF with java would be too slow).
The problem is that the where clause isn't correctly generated for the backend database (which is also oracle).
Basically the generated WHERE clause (which was added to VO's query automatically by the framework) was
WHERE record_date = '2020-10-12'

which I had to change to
WHERE record_date = to_date('2020-10-12', 'YYYY-MM-DD')

in order to have it correctly executed by the Oracle Db.
So now it's working (yay), but my concern is: isn't it dangerous to assume the date format will be 'YYYY-MM-DD' on every application's instance?
I think this 'YYYY-MM-DD' is the format in which ADF is managing dates (as the value is written as '2020-10-12' in the query).
But is there a way to understand at runtime which format is ADF using for dates behind the scenes? Or does it always use 'YYYY-MM-DD', or am I completely off-road and the storage format is another and I should ask which format does it use to render dates? But dates on page are visually rendered in another way :/
Sorry for my lack of expertise and have a nice day!
Update
The value of the query field, which I'm getting by calling
this.getNamedWhereClauseParams().getAttribute('vc_temp_1');

is of class
oracle.jbo.domain.Date

and by printing it I obtain the date in format YYYY-MM-DD.
Would it be possible that the framework was simply using Date.toString?
This would raise another question: how can I be sure of the pattern used by Date.toString? The documentation isn't clear about it (and it says that it should be used only in development, so this is quite a remote scenario).

A: What you named 'Filter' is called 'Query by Example' or QBE in short. See the doc for more info.
You can change the query passed to the server using a bean method. Look at e.g. JDev 12.2.1.3: Multi select component table filter for a sample.
Using dates in ADF is always dependent on the current user's settings. If the user don'T use a specific locale the default is 'yyyy-mm-dd'. This can be changed at different points, starting by the entity objects, view objects a,d finally in the UI by using converters.
The best way to use dates depends on the use case.


text:
Q: iOS: Audio and Video tap from Airplay I have made a video player that is analyzing the realtime audio and video tracks from the video that is currently playing. The videos are stored on the iOS device (in the Apps Documents directory).
This all works fine. I use MTAudioProcessingTap in order to get all the audio samples and do some FFT, and I am analyzing the video by just copy'ing the pixel buffers from the currently played CMTime (the AVPlayer currentTime property). As I said, this works fine.
But now I want to support Airplay. Just the airplay itself is not difficult, but my taps stop working as soon as Airplay is toggled and the video is playing on the ATV. Somehow, the MTAudioProcessingTap won't process and the pixelbuffers are all empty... I can't get to the data.
Is there any way to get to this data ?
In order to get the pixel buffers, I just fire an event every few milli-sec and retrieving the player's currentTime. Then:
CVPixelBufferRef imageBuffer = [videoOutput copyPixelBufferForItemTime:time itemTimeForDisplay:nil];
CVPixelBufferLockBaseAddress(imageBuffer,0);

uint8_t *tempAddress = (uint8_t *) CVPixelBufferGetBaseAddress(imageBuffer);

size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);

CVPixelBufferUnlockBaseAddress(imageBuffer,0);

Where tempAddress is my pixelbuffer, and videoOutput is an instance of AVPlayerItemVideoOutput.
For audio, I use:
AVMutableAudioMixInputParameters *inputParams = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:audioTrack];

// Create a processing tap for the input parameters
MTAudioProcessingTapCallbacks callbacks;

callbacks.version = kMTAudioProcessingTapCallbacksVersion_0;
callbacks.clientInfo = (__bridge void *)(self);
callbacks.init = init;
callbacks.prepare = prepare;
callbacks.process = process;
callbacks.unprepare = unprepare;
callbacks.finalize = finalize;

MTAudioProcessingTapRef tap;
OSStatus err = MTAudioProcessingTapCreate(kCFAllocatorDefault, &callbacks,
                                          kMTAudioProcessingTapCreationFlag_PostEffects, &tap);
if (err || !tap) {
    NSLog(@"Unable to create the Audio Processing Tap");
    return;
}

inputParams.audioTapProcessor = tap;

// Create a new AVAudioMix and assign it to our AVPlayerItem
AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
audioMix.inputParameters = @[inputParams];
playerItem.audioMix = audioMix;

Regards,
Niek

A: Unfortunately, in my experience, it's not possible to get information about the audio/video during Airplay as the playback is being done on the Apple TV so the iOS device doesn't have any of the information.
I had the same issue with getting SMPTE subtitle data out of the timedMetaData, which stops getting reported during Airplay.

A: Here the solution:
this is to implement AirPlay, i use this code only for Audio on my app i don't know if you can improve for the video but you can try ;)
On AppDelegate.m :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [RADStyle applyStyle];
    [radiosound superclass];
    [self downloadZip];

    NSError *sessionError = nil;
    [[AVAudioSession sharedInstance] setDelegate:self];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    [[AVAudioSession sharedInstance] setActive:YES error:nil];

    UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
    AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);

    UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
    AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

An if you use airplay in nice to implement the LockScreen control, ArtWork, Stop/play, Title ecc.
In the DetailViewController of you player use this code:
- (BOOL)canBecomeFirstResponder {

    return YES;
}
- (void)viewDidAppear:(BOOL)animated {

    [super viewDidAppear:animated];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];

    NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: (self.saved)[@"image"]]];

    if (imageData == nil){

    MPNowPlayingInfoCenter *infoCenter = [MPNowPlayingInfoCenter defaultCenter];
    MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"lockScreen.png"]];

    infoCenter.nowPlayingInfo = @{MPMediaItemPropertyTitle: saved[@"web"],MPMediaItemPropertyArtist: saved[@"title"], MPMediaItemPropertyArtwork:albumArt};

    } else {

        MPNowPlayingInfoCenter *infoCenter = [MPNowPlayingInfoCenter defaultCenter];
        MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageWithData:imageData]];

        infoCenter.nowPlayingInfo = @{MPMediaItemPropertyTitle: saved[@"link"],MPMediaItemPropertyArtist: saved[@"title"], MPMediaItemPropertyArtwork:albumArt};

    }

}

Hope this code can help you ;)


text:
Q: dynamically change css class property with javascript I have div which transform property is getting changed by 3rd party Js application, what I want is to fix the transform property at some instance according to current transform property it have.
For that I need to add class with property transform: current_transform!important here with !important if any change in element style by 3rd party app will not be effective.
here I created a example snippet for better explanation

//let this is third party app which is changing the paragraph width and html which code can't be manipulated
function changeHeight(e) {
  var x = e.clientX;
  var y = e.clientY;
  $('p').html(y);
  $('p').css('width',x+"px");
}

// Here we need to write Js code so that any change in paragraph css will not be effective, if zoom is yes

$('[name="zoom"]').on('change',function(){
  if($(this).val()=='y'){
    // Here need to change to the .zoomed propery as widht: current_width!improtant so that paragraph width get fixed to lastly it have.

    $('p').addClass('zoomed');
  }
  else{
    $('p').removeClass('zoomed');
  }
});

zoom yes
<input type="radio" name="zoom" value="y" />
zoom no
<input type="radio" name="zoom" value="n" checked/>

This is only for example only, real scenario is different(about transform property and zoom) but the key is to change the class property dynamically so that change in style by third party is not effective.

A: You can use CSS custom properties.
The idea is that the custom property --last-p-width is set to the element's width property value when you add the class zoom. Making it stay with the same value.
This post goes more into detail: https://css-tricks.com/updating-a-css-variable-with-javascript/
CSS
::root {
  --last-p-width: 50px;
}

.zoomed{
  width: var(--last-p-width) !important;
}

JS
$('[name="zoom"]').on('change',function() {
  if ($(this).val() === 'y') {
    $(":root").css("--last-p-width", $('p').css('width'));    // <-- HERE
    $('p').addClass('zoomed');
  }
  else {
    $('p').removeClass('zoomed');
  }
});

function changeHeight(e) {
  var x = e.clientX;
  var y = e.clientY;
  $('p').html(y);
  $('p').css('width',x+"px");
}

$('[name="zoom"]').on('change',function() {
  if ($(this).val() === 'y') {
    $(":root").css("--last-p-width", $('p').css('width'));    // <-- HERE
    $('p').addClass('zoomed');
  }
  else {
    $('p').removeClass('zoomed');
  }
});

zoom yes
<input type="radio" name="zoom" value="y" />
zoom no
<input type="radio" name="zoom" value="n" checked/>

A: $("body").mousemove(function(e) {
        window.mx = e.pageX;
        window.my = e.pageY;
        if (window.dragging) {
            // Calculate drag distance difference
            let diffX =
    window.drag_width =
parseInt((window.item_width + (window.mx - window.drag_x) * 1.75));
            let diffY =
   window.drag_height =
parseInt((window.item_height + (window.my - window.drag_y) * 1.75));
            // Absolute values ensure the item dimensions
            // never become negative
            $(window.dragging_target).css("width",
                Math.abs(diffX) + 'px');
            $(window.dragging_target).css("height",
                Math.abs(diffY) + 'px');
            $(window.dragging_target).css("lineHeight",
                Math.abs(diffY) + 'px');
            // Change cursor to either left-right or up-down arrow,
            // based on which direction the drag is the greatest
            if (diffX > diffY) {
                /* Optional, maybe a future feature... */
            }
        }
    })
});

A:

//let this is third party app which is changing the paragraph width and html which code can't be manipulated
function changeHeight(e) {
  var x = e.clientX;
  var y = e.clientY;
  $('p').html(y);
  $('p').css('width',x+"px");
}

// Here we need to write Js code so that any change in paragraph css will not be effective, if zoom is yes

      let styleOverride = document.querySelector('#styleOverride');

  if (!styleOverride) {
   styleOverride = document.createElement('style');
    styleOverride.id = 'styleOverride';
    document.body.appendChild(styleOverride);
  }
     styleOverride.innerHTML = '';
$('[name="zoom"]').on('change',function(){
  if($(this).val()=='y'){
    // Here need to change to the .zoomed propery as widht: current_width!improtant so that paragraph width get fixed to lastly it have.
    let wid= $('p').css('width')+"!important";
    styleOverride.innerHTML = `
 .zoomed{
     width: ${wid};
    }
  `;
    $('p').addClass('zoomed');
  }
  else{
    $('p').removeClass('zoomed');
  }
});

zoom yes
<input type="radio" name="zoom" value="y" />
zoom no
<input type="radio" name="zoom" value="n" checked/>


text:
Q: How to keep order from json.parse? I have an object like this:
{ "01":"111","02":"222","11":"AAA","12":"BBB"}. But after JSON.parse, the object changed its order like {"11":"AAA","12":"BBB","01":"111","02":"222"}. See http://jsfiddle.net/stxh/3WV8Y/
Code:
var str=JSON.parse('{"01":"111","02":"222","11":"AAA","12":"BBB"}');
alert( JSON.stringify(str) );

Can I keep the order from JSON.parse?


text:
Q: c++ evaluation of ambigous sum expression Take the following example:
int g_X;
int func() {
 return ++g_X;  // using g_X++ is not an option
}
int main() {
 g_X = 0;
 int a = g_X + func();
 g_X = 0;
 int b = func() + g_X;
 g_X = 0; int temp = g_X;
 int c = temp + func();

 return 0;
}

a and b are both 2, c has the expected value 1 (tested with Visual Studio 2010 to 2015). I read that sums are not associated with a sequence point (e.g. https://en.wikipedia.org/wiki/Sequence_point) and therefore the order is not fixed. Yet I thought that the value of g_X gets captured before the function call.
Am I really in undefined behavior territory or is there some way not having to use the temp var?

A:
Every evaluation in the calling function (including other function calls) that is not otherwise specifically
  sequenced before or after the execution of the body of the called function is indeterminately sequenced with
  respect to the execution of the called function.

([intro.execution]/15)
Therefore, in an expression of the form g_X + func() or func() + g_X, it's true that the + operator doesn't introduce any sequencing constraint, but nevertheless the access to g_X within main either happens before or after the body of func(), you just can't predict which. This implies that the behaviour is defined, but whether a is 1 or 2 is unpredictable. Likewise, whether b is 1 or 2 is unpredictable.

A: At first sight this looks like an undefined behavior because, quoting §1.9/15:

If a side effect on a scalar
  object is unsequenced relative to either another side effect on the same scalar object or a value computation
  using the value of the same scalar object, the behavior is undefined.

and your example seemingly satisfies these conditions:

*

*Evaluation of operands of + operator are unsequenced relative to each other (but see below).

*There is a side effect on a scalar object (func increments g_X).

*There is a computation using the value of the same scalar object (g_X).

On the other hand, as pointed out in the Brian's answer, function call does introduce sequencing, although indeterminate. According to this argument this is not an undefined behavior, but merely unspecified.


text:
Q: Node.js watch a directory for incoming archive by scp I have a task to create a node.js script that listens in a directory for new archive files to arrive and process them.
I see that I can do this with fs.watch.
The files are tar.gz archives, that arrive via scp.
The problem is that the arrival of a new archive file seems to create multiple (the exact number is unpredictable) events in the file-system. The first is a rename, followed by some number of change events.
I need to reliably trigger my processing logic only once, when the archive is finished being transferred. How can this be done?
Additional notes:

*

*I am not able to make changes to the system sending the archive, only
the system receiving it.

*I am not considering using elapsed time to
guess that the scp event has concluded. That is not reliable.

A: Using the watch library you can do:
var watch = require('watch')
watch.createMonitor('/home/path', function (monitor) {
   monitor.on("created", function (file, stat) {
       // do work with new file
   })
}

I recommend taking advantage of the rich library ecosystem available to you because you're using the node platform.  Some of these problems have already been solved for you!

A: The problem is that file transfers are not instantaneous; the series of events you have observed make complete sense:

*

*Someone begins uploading a file.  The scp server creates a new file.  Your watcher sees the rename event.

*Bytes are sent to your server.  The scp server writes them to the file from step 1.  Your watcher sees many change events.

*The upload completes.  No further events are generated because all the bytes have been written.

As far as I know (and based on skimming the source of scp), there is no way to configure the scp server to do something when an upload actually completes.  This leaves you with two options:

*

*Debounce the change events.  This means setting a timer every time you get a change event and clearing the previous timer.  Eventually, you'll stop getting events, the timer will fire, and you can assume that the upload is complete.
This does leave you vulnerable to acting on stalled or aborted uploads.

*You could implement your own scp server.  This gives a good overview of how the protocol works.  The remote scp simply opens a ssh connection and runs the host's scp command, which then has a simple protocol for file transfer.  You'd have to replace your server's scp with your own implementation.
Since the protocol tells you how many bytes to expect, you would know exactly when you've received the complete file and can begin your processing.


text:
Q: Serialize List> I have a class which contains a List<Func<T>>. The class is serializable and will be transferred over WCF. Now, I have problems with contained List<Func<T>>. What can I do that this list will also be serializable?

A: How would you expect a Func<T> to be serialized? It's a pointer to a function - such a thing cannot be serialized.