text:
Q: Getting the error " net.serenitybdd.core.exceptions.SerenityManagedException: No session ID" while trying to execute the scripts Script was working successfully till last week and all of a sudden I got the below error from this week onwards. Please advise.
net.serenitybdd.core.exceptions.SerenityManagedException: The following error occurred: No active session with ID b324bd213592fbdc663589a2beae51da (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.7.1', revision: '8a0099a', time: '2017-11-06T21:01:39.354Z'
System info: host: '', ip: '', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_161'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.41.578700 (2f1ed5f9343c13..., userDataDir: /tmp/.org.chromium.Chromium...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:38959}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 68.0.3440.84, webStorageEnabled: true, webdriver.remote.sessionid: b324bd213592fbdc663589a2bea...}
Session ID: b324bd213592fbdc663589a2beae51da
    at net.serenitybdd.core.pages.WebElementFacadeImpl.throwNoSuchElementExceptionWithCauseIfPresent(WebElementFacadeImpl.java:893)
    at net.serenitybdd.core.pages.WebElementFacadeImpl.checkPresenceOfWebElement(WebElementFacadeImpl.java:866)
    at net.serenitybdd.core.pages.WebElementFacadeImpl.waitUntilVisible(WebElementFacadeImpl.java:873)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.thucydides.core.annotations.locators.AbstractSingleItemHandler.invoke(AbstractSingleItemHandler.java:45)
    at com.sun.proxy.$Proxy22.waitUntilVisible(Unknown Source)
    at pageobjects.portfolio.PortfolioEpic.SelectPortfolioFromNav(PortfolioEpic.java:139)
    at steps.portfolio.EndUser_Portfolio.OpenPortfolioSection(EndUser_Portfolio.java:15)
    at steps.portfolio.EndUser_Portfolio$$EnhancerByCGLIB$$b8cc665a.CGLIB$OpenPortfolioSection$19(<generated>)
    at steps.portfolio.EndUser_Portfolio$$EnhancerByCGLIB$$b8cc665a$$FastClassByCGLIB$$d9213826.invoke(<generated>)
    at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at net.thucydides.core.steps.StepInterceptor.invokeMethod(StepInterceptor.java:426)
    at net.thucydides.core.steps.StepInterceptor.executeTestStepMethod(StepInterceptor.java:411)
    at net.thucydides.core.steps.StepInterceptor.runTestStep(StepInterceptor.java:386)
    at net.thucydides.core.steps.StepInterceptor.testStepResult(StepInterceptor.java:134)
    at net.thucydides.core.steps.StepInterceptor.intercept(StepInterceptor.java:63)
    at steps.portfolio.EndUser_Portfolio$$EnhancerByCGLIB$$b8cc665a.OpenPortfolioSection(<generated>)
    at stepdefs.portfolio.PortfolioStepDefs.iAmOnPortfolioLandingPageOnMyAssetsViewContainer(PortfolioStepDefs.java:23)
    at ?.I am on Portfolio landing page on My Assets view container(C:/Workspace/bitbucket/stockbroking-website-rewrite-fe/src/test/resources/features/portfolio/Portfolio_AddRemoveColumns.feature:17)
Caused by: org.openqa.selenium.NoSuchSessionException: No active session with ID b324bd213592fbdc663589a2beae51da (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.7.1', revision: '8a0099a', time: '2017-11-06T21:01:39.354Z'
System info: host: '', ip: '', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_161'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.41.578700 (2f1ed5f9343c13..., userDataDir: /tmp/.org.chromium.Chromium...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:38959}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 68.0.3440.84, webStorageEnabled: true, webdriver.remote.sessionid: b324bd213592fbdc663589a2bea...}
Session ID: b324bd213592fbdc663589a2beae51da
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
    at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:80)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:44)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:164)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:600)
    at org.openqa.selenium.remote.RemoteWebDriver$RemoteWebDriverOptions$RemoteTimeouts.implicitlyWait(RemoteWebDriver.java:834)
    at net.thucydides.core.webdriver.WebDriverFactory.setTimeouts(WebDriverFactory.java:200)
    at net.thucydides.core.webdriver.WebDriverFacade.setImplicitTimeout(WebDriverFacade.java:298)
    at net.thucydides.core.annotations.locators.SmartAjaxElementLocator.findElementImmediately(SmartAjaxElementLocator.java:141)
    at net.thucydides.core.annotations.locators.SmartAjaxElementLocator.findElement(SmartAjaxElementLocator.java:123)
    at net.serenitybdd.core.pages.WebElementResolverByElementLocator.resolveForDriver(WebElementResolverByElementLocator.java:27)
    at net.serenitybdd.core.pages.WebElementFacadeImpl.getElement(WebElementFacadeImpl.java:209)
    at net.serenitybdd.core.pages.WebElementFacadeImpl.isVisible(WebElementFacadeImpl.java:393)
    at net.serenitybdd.core.pages.WebElementFacadeImpl.isCurrentlyVisible(WebElementFacadeImpl.java:429)
    at net.serenitybdd.core.pages.WebElementExpectations$1.apply(WebElementExpectations.java:23)
    at net.serenitybdd.core.pages.WebElementExpectations$1.apply(WebElementExpectations.java:15)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:208)
    at net.serenitybdd.core.pages.WebElementFacadeImpl.checkPresenceOfWebElement(WebElementFacadeImpl.java:860)
    at net.serenitybdd.core.pages.WebElementFacadeImpl.waitUntilVisible(WebElementFacadeImpl.java:873)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.thucydides.core.annotations.locators.AbstractSingleItemHandler.invoke(AbstractSingleItemHandler.java:45)
    at com.sun.proxy.$Proxy22.waitUntilVisible(Unknown Source)
    at pageobjects.portfolio.PortfolioEpic.SelectPortfolioFromNav(PortfolioEpic.java:139)
    at steps.portfolio.EndUser_Portfolio.OpenPortfolioSection(EndUser_Portfolio.java:15)
    at steps.portfolio.EndUser_Portfolio$$EnhancerByCGLIB$$b8cc665a.CGLIB$OpenPortfolioSection$19(<generated>)
    at steps.portfolio.EndUser_Portfolio$$EnhancerByCGLIB$$b8cc665a$$FastClassByCGLIB$$d9213826.invoke(<generated>)
    at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at net.thucydides.core.steps.StepInterceptor.invokeMethod(StepInterceptor.java:426)
    at net.thucydides.core.steps.StepInterceptor.executeTestStepMethod(StepInterceptor.java:411)
    at net.thucydides.core.steps.StepInterceptor.runTestStep(StepInterceptor.java:386)
    at net.thucydides.core.steps.StepInterceptor.testStepResult(StepInterceptor.java:134)
    at net.thucydides.core.steps.StepInterceptor.intercept(StepInterceptor.java:63)
    at steps.portfolio.EndUser_Portfolio$$EnhancerByCGLIB$$b8cc665a.OpenPortfolioSection(<generated>)
    at stepdefs.portfolio.PortfolioStepDefs.iAmOnPortfolioLandingPageOnMyAssetsViewContainer(PortfolioStepDefs.java:23)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at cucumber.runtime.Utils$1.call(Utils.java:32)
    at cucumber.runtime.Timeout.timeout(Timeout.java:16)
    at cucumber.runtime.Utils.invoke(Utils.java:26)
    at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:37)
    at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:40)
    at cucumber.api.TestStep.executeStep(TestStep.java:102)
    at cucumber.api.TestStep.run(TestStep.java:83)
    at cucumber.api.TestCase.run(TestCase.java:58)
    at cucumber.runner.Runner.runPickle(Runner.java:80)
    at cucumber.runtime.junit.PickleRunners$NoStepDescriptions.run(PickleRunners.java:140)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:68)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:23)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:73)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:99)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:41)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at cucumber.api.junit.Cucumber$1.evaluate(Cucumber.java:108)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:369)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:275)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:239)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:160)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:373)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:334)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:119)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:407)

[ERROR] Tests run: 2, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: 147.985 s <<< FAILURE! - in nedbank.co.za.stockbrokingfrontend.Parallel01IT
[ERROR] Add or Remove Columns(Portfolio: Add and Remove Portfolio columns)  Time elapsed: 69.392 s  <<< ERROR!
net.serenitybdd.core.exceptions.SerenityManagedException:
The following error occurred: No active session with ID 954142e5ec5eb760b3b9b51f56620489 (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.7.1', revision: '8a0099a', time: '2017-11-06T21:01:39.354Z'
System info: host: '', ip: '', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_161'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.41.578700 (2f1ed5f9343c13..., userDataDir: /tmp/.org.chromium.Chromium...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:41634}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 68.0.3440.84, webStorageEnabled: true, webdriver.remote.sessionid: 954142e5ec5eb760b3b9b51f566...}
Session ID: 954142e5ec5eb760b3b9b51f56620489
Caused by: org.openqa.selenium.NoSuchSessionException:
No active session with ID 954142e5ec5eb760b3b9b51f56620489 (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.7.1', revision: '8a0099a', time: '2017-11-06T21:01:39.354Z'
System info: host: '', ip: '', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_161'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.41.578700 (2f1ed5f9343c13..., userDataDir: /tmp/.org.chromium.Chromium...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:41634}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 68.0.3440.84, webStorageEnabled: true, webdriver.remote.sessionid: 954142e5ec5eb760b3b9b51f566...}
Session ID: 954142e5ec5eb760b3b9b51f56620489

A: This error message...
net.serenitybdd.core.exceptions.SerenityManagedException: The following error occurred: No active session with ID b324bd213592fbdc663589a2beae51da (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.7.1', revision: '8a0099a', time: '2017-11-06T21:01:39.354Z'
System info: host: '', ip: '', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_161'

...implies that the WebDriver was unable to communicate with the Browsing Context i.e. Browser session.
Your main issue is the incompatibility between the version of the binaries you are using as follows:

*

*You are using java.version: '1.8.0_161'

*But you are using Selenium version: '3.7.1' of 2017-11-06T21:01:39.354Z which is old and ancient.

Solution
Ensure that:

*

*JDK is upgraded to  current levels JDK 8u251.

*Selenium is upgraded to  current released Version 3.141.59.


text:
Q: Почему удаляется объект из массива Python Решаю вот эту кату на codewars. Задание вкратце: посчитать определитель квадратной матрицы произвольного размера. Собственно, мое решение:
def determinant(matrix):
    print('Matrix: ',matrix)

    def minor(i,m):
        #здесь специально копирую переданную матрицу, чтобы с ней ничего не случилось
        major=m.copy()
        print('Major: ',major)
        major.pop(0)
        for row in major:
            row.pop(i)
        print('Minor: ',major)
        return major

    if len(matrix)==1:
        print('Det: ',matrix[0][0])
        return matrix[0][0]

    sum=0

    for j in range(len(matrix)):
        print('Iter: ',j)
        print('Before matrix: ',matrix)
        sum+=((-1)**j)*matrix[0][j]*determinant(minor(j,matrix))#вот после этой строки удаляется элемент
        print('After matrix: ',matrix)

    print('Det: ',sum)
    return sum

и вот что получаю в логах:
Matrix:  [[1, 3], [2, 5]]
Iter:  0
Before matrix:  [[1, 3], [2, 5]]
Major:  [[1, 3], [2, 5]]
Minor:  [[5]]
Matrix:  [[5]]
Det:  5
After matrix:  [[1, 3], [5]]
Iter:  1
Before matrix:  [[1, 3], [5]]
Major:  [[1, 3], [5]]
Traceback (most recent call last):
...
line 9, in minor
    row.pop(i)
IndexError: pop index out of range

То есть, в итоге, на первой же итерации после строки sum+=((-1)**j)*matrix[0][j]*determinant(minor(j,matrix)) у меня матрица [[1,3],[2,5]] чудесным образом превращается в [[1,3],[5]], при том, что внутри функции minor я специально работаю с копией. Кто-нибудь может объяснить, как это происходит?

A: Так происходит, потому что на первой же итерации def minor(i,m): возвращает major, а major при этом равен Minor:  [[5]] из ваших же логов. Далее вы вызываете determinant и передаёте результат minor, то есть [[5]]. После этого у вас Matrix:  [[5]].
Решения можно придумать разные, но если вы хотите решать всё в функции determinant, вы не должны вызывать её рекурсивно. Кроме данной проблемы, у вас также каждый раз будет обнуляться sum.

A: Большое спасибо @CrazyElf за подсказку. Действительно, в определении функции minor попытка не изменить передаваемый массив m копированием major=m.copy() дает не интуитивный результат, а именно:

*

*изменения первого слоя major типа major.pop() не изменяют передаваемый массив

*изменения второго слоя major типа major[i].pop() изменяют вложенные массивы передаваемого массива

из за этого после minor(0,[[1,2],[3,4]]) не удаляется нулевая строка, но удаляется нулевой элемент первой строки, и в итоге передаваемый массив превращается в [[1,2],[4]] и далее возникает ошибка.
Тривиальным на мой взгляд является замена копии исходного массива на массив с копиями вложенных массивов: major=[x.copy() for x in m]:
def determinant(matrix):

    def minor(i,m):
        major=[x.copy() for x in m]
        major.pop(0)

        for row in major:
            row.pop(i)

        return major

    if len(matrix)==1:
        return matrix[0][0]

    sum=0

    for j in range(len(matrix)):
        sum+=((-1)**j)*matrix[0][j]*determinant(minor(j,matrix))

    return sum

Однако работая с большими вложенностями, уместнее использовать указанную @CrazyElf библиотеку from copy import deepcopy

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wait for a value to be loaded via JSON and than load an external javascript I use the following function to set the addthis:title attribute:
function setTheTitle(){
        if(jQuery(".title").length > 0){
            shareTitle = jQuery(".title").text();
            jQuery("#shareButton").attr("addthis:title", shareTitle);
        } else {
            setTimeout(function(){
                setTheTitle();
            },100)
        }
    }

The problem is, the shareTitle variable is generated via a JSON object and takes a few seconds to load.
Until then, the addthis javascript loads, and see's an empty url attr, setting the pages default title.

the link

How can I delay the load of the addthis javascript until I get my value?


text:
Q: How to make a Ninja Form open up when you click on a bootstrap modal button (inside of a wordpress widget) I am using the following:
Ninja Version: 3.4.25 /
WordPress Version: 5.5 /
Bootstrap Version: 3 (or maybe 4)
I have a WordPress template based on bootstrap, and I am using the latest Ninja forms version.
I have created a Bootstrap button in a widget, that I want to open up a model window displaying my Ninja Contact form.
I have actually been successful with this setup with an older version of Ninja form.  But since the latest updates, they have changed all their form field names, and so now it won't work on my new site, because I am not using the correct field names.
If anyone knows what the old field name: "ninja_forms_display_form" is now, then you don't have to read the rest of my documentation.  I did try: "ninja_forms", but that didn't work either.
I will provide the coding I use on another site using the same template but using an older version of Ninja Forms (3.2.11).  This modal button does work, and can be seen on the sidebar's green  'contact us' button here:  www.oasisflighttraining.com.au/about-oasis-flying-school/
Here is the Sidebar Widgets code that uses the Bootstrap button:

    <button type="button" class="btn btn-success btn-lg" data-toggle="modal" data-target="#contactform">Contact Us</button>

And here is the code that creates the Bootstrap button (found at the bottom of my footer.php file just before the call to wp_footer function.

        <button type="button" class="close" data-dismiss="modal">×Close</button>

Contact Us

        <?php

            if( function_exists( 'ninja_forms_display_form' ) ){ ninja_forms_display_form( 1 ); }

        ?>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

The code referencing "ninja_forms_display_form" is the part that doesn't work on my new site with the latest version of Ninja Forms.  I know that field name has changed, but I can't figure out what to replace it with.
Can anyone give me some help figuring out how to make this bootstrap modal button work with my Ninja Form created with the updated version with new field names?
Thanks!

A: The  newer Ninja Forms can use shortcode, so I just changed this:
    <?php

        if( function_exists( 'ninja_forms_display_form' ) ){ ninja_forms_display_form( 1 ); }

    ?>

to this:
    <?php echo do_shortcode( '[ninja_form id=1]' ); ?>

(And as a public service advice.. just make sure that you don't have the bootstrap js pulled in twice, or the modal window won't stay displayed after you click the button.  I found that the bootstrap shortcode plugin added another bootstrap.js)


text:
Q: python program not working beacuse of the "if"
I need an answer to this problem.
i tried fixing it for like an hour and i am hopeless.
vs code told me that the problem is from the "IF" but i can't fix it.
while True:
    print("YOUTUBE SIMULATOR")
    print("1. search a video")
    print("2. edit video")
    choice = int(input())
        if choice == 1:
            print("Searching video...")
            print("Can't find your video!")
        elif choice == 2:
            print("Editing video...")
            print("Can't edit your video?")

A: this is a problem with indentation. try this:
while True:
    print("YOUTUBE SIMULATOR")
    print("1. search a video")
    print("2. edit video")
    choice = int(input())
    if choice == 1:
            print("Searching video...")
            print("Can't find your video!")
    elif choice == 2:
            print("Editing video...")
            print("Can't edit your video?")

A:
Indentation Error:
Try This

while True:
    print("YOUTUBE SIMULATOR")
    print("1. search a video")
    print("2. edit video")
    choice = int(input())
    if choice == 1:
        print("Searching video...")
        print("Can't find your video!")
    elif choice == 2:
        print("Editing video...")
        print("Can't edit your video?")

A: while True:
    print("YOUTUBE SIMULATOR")
    print("1. search a video")
    print("2. edit video")
    choice = int(input())
    if choice == 1:
        print("Searching video...")
        print("Can't find your video!")
    elif choice == 2:
        print("Editing video...")
        print("Can't edit your video?")


text:
Q: How to solve this semi-circle problem?

The figure above shows a semi-circle. $\angle BAP$ is $\alpha$ radian. The area of semi-circle is bisected by $AP$. Prove that $$2\alpha+\sin 2\alpha = \frac{\pi}{2}$$

I have simply no clue to solve this problem. Can anyone help me? Thanks so much.

A: Area of semi-circle $= \frac{1}{2} \pi r^{2}$.
Let $O$ be the centre.  Then
$\angle BOP = 2\alpha$ and $\angle AOP = \pi-2\alpha$
Area of $ABP=$ Area of sector $OBP +$ Area of $\Delta OAP$
$\implies \frac{1}{4} \pi r^{2} =
\frac{1}{2} r^{2}(2\alpha)+\frac{1}{2} r^{2} \sin (\pi-2\alpha)$
$\implies \frac{1}{4} \pi r^{2} = r^{2}\alpha+\frac{1}{2} r^{2} \sin 2\alpha$
$\implies \frac{1}{2} \pi = 2\alpha+ \sin 2\alpha$
(QED)
Note that the radius $r$ will be automatically cancelled out.
P.S.: The word "bisect" is not good.  May say "$AP$ divides the semi-circle into $2$ equal areas".

A: Let $r$ be the radius & $O$ be the center of the semi-circle.
Area of the segment ABP of semi-circle
$$(\text{area of sector OBP with angle of aperture } 2\alpha)+(\text{area of isosceles}\ \triangle AOP)$$
$$=\frac{1}{2}r^2(2\alpha)+\frac{1}{2}r^2\sin(\pi-2\alpha)=\color{blue}{\frac{1}{2}r^2(2\alpha)+\frac{1}{2}r^2\sin(2\alpha)}$$
But the area of semi-circle is bisected by $AP$ hence, Area of the segment ABP of semi-circle
$$=\text{half the area of semi-circle}=\frac 12\frac{\pi r^2}{2}=\color{blue}{\frac{\pi r^2}{4}}$$
Equating both the values, $$\frac{1}{2}r^2(2\alpha)+\frac{1}{2}r^2\sin(2\alpha)=\frac{\pi r^2}{4}$$
$$\color{red}{2\alpha+\sin(2\alpha)=\frac{\pi}{2}}$$


text:
Q: jQuery not working right, possible conflicts with Prototype? I'm sorry for the vague title.
I'm making a new theme for my company's website, and I've got both jQuery tabs and a slider on the page.
Both the tabs and slider aren't working though - I'm not too sure why. I inherited the design and simply changed the theme - I'm thinking it might have something to do with multiple jQuery scripts being loaded - the slider throws an error that the method .split() doesn't exist, and the tabs just don't work the way they should.

A: Explosion Pills is right -- you should use jQuery.noConflict.  Import jQuery first, then, before you import Prototype, insert the line
<script type="text/javascript">
    jQuery.noConflict();
</script>

If you do that, everywhere else in your app where you reference jQuery, do jQuery(...) or jQuery. instead of $(...) or $..  It shouldn't mess up your script imports unless those scripts you're importing are written badly and don't define $ for themselves.

A: You should do this:
<action method="addJs"><script>jquery/jquery.js</script></action>
<action method="addJs"><script>jquery/jquery.plugin.js</script></action>
<action method="addJs"><script>jquery/jquery.moreplugin.js</script></action>
<action method="addJs"><script>jquery/jquery.noConflict.js</script></action>

<action method="addJs"><script>prototype/prototype.js</script></action>

in page.xml layout.
jquery.noConflict.js file:
var jQuery = $.noConflict();

After that you can call jQuery() function everywhere you wish.
The order is: jquery -> jquery plugin -> jquery no conflict -> prototype

A: I prefer to use the following snippets:
<script type="text/javascript">
  jQuery.noConflict();
  (function($) {
    $.ajax(...);
  })(jQuery);
</script>

, which won't conflict with Prototype and remain to use '$' for jQuery.
Here's some more information:
http://www.magentogarden.com/blog/using-jquery-in-magento-with-good-programming-practice.html


text:
Q: jQuery Selector: Select Element with Specific Height I have a table. Some cells have a lot of text, and some cells have only one character.
I want to change the width of all cells that have a height greater than or equal to 200px.

A:

       ...

jQuery
$('.cell').each(function() {
   if($(this).height()>=200)
      $(this).width(...);
});

A: Let's start by selecting the cells:
var $tds = $("td");
// better with a context
// var context = "#mytable";
// var $tds = $("td", context);

$.fn.filter reduces the set of matched elements to those that match the selector or pass the function's test.
function isHighterThan ($el, threshold) {
  return $el.height() >= threshold;
}

var $bigTds = $tds.filter(function () {
  return isHighterThan($(this), 200);
});

Finally apply a new style to matching elements.
$bigTds.each(function () {
  $(this).css("width", "400px");
});


text:
Q: Problem with features in time series classification For a student project, we got data like this:

*

*A one dimensional time series

*A classification label

*Two further features/parameters, unrelated to the time series

At the end of the time series there is an event characterized by two features/parameters (in total these two features give 10 different combinations).
The time series consists of 5000 values (roughly between -200 and +200) and may be forming some kindle of wave.
The question is now, how to predict/classify, if the result after this event is positive or negative, given the previous time series.
We wanted to try to use a RNN, but we dont know, how to handle these 2 features of the event best, since it is not part of the time series. Simply adding these two parameters as further inputs does not seem to be appropriate as their importance is then underrepresented in respect to mass of input from the time series.


text:
Q: Check if date match with format using momentjs I try to check if a date match with format using momentjs. But I have error when date include time zone.
Example:
moment('Mon Nov 10 2016 14:53:17', 'ddd MMM DD YYYY HH:mm:ss', true).isValid()

in this case the response is true without errors.
but in this other case, I not found the correct date format to compare
moment('Mon Nov 10 2016 14:53:17 GMT-0500 (ECT)', '?????', true).isValid()

A: You can split your string in GTM-.. place and take only part before. Below is example, split() just splitting the string and return array, so first part of string (before GTM) will be at zero index.
var data = 'Mon Nov 10 2016 14:53:17 GMT-0500 (ECT)';
moment(date.split(' GMT')[0], 'ddd MMM DD YYYY HH:mm:ss', true).isValid()

It works for strings without GTM part too, because it will return just one-element array with whole string.


text:
Q: Why and is it necessary to turn off csrf in SpringSecurity when using authorization through a custom token I watched a training video on authorization and authentication by token, and there is an entry http.csrf().disable() in the method that connects the filters. Why do we disable csrf protection, the person did not explain? Here's the full class for a better idea of what I'm talking about:
@Configuration
@RequiredArgsConstructor
public class SecurityConfig{
    private final JwtTokenProvider jwtTokenProvider;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .httpBasic().disable()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeHttpRequests(authz ->
                        {
                            try {
                                authz
                                        .requestMatchers("/api/auth/**").permitAll()
                                        .requestMatchers("/api/admin/sensors/**").hasAuthority("ROLE_ADMIN")
                                        .requestMatchers("/api/sensors/**").hasAnyAuthority("ROLE_ADMIN", "ROLE_USER")
                                        .anyRequest().authenticated()
                                        .and()
                                        .apply(new JwtConfigurer(jwtTokenProvider));
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                );
        return http.build();
    }
}

A: CSRF is a vulnerability where an attacker exploits the way browsers work. In more traditional web applications, your session token (which allows the app to authenticate requests) is sent in a cookie. Cookies are sent by browsers with requests based on where the request goes to, and regardless of the origin the request was made from. So if you are logged in to such an application, and visit a malicious site, that malicious site can have you make inadvertent requests to the victim site, and your session cookie will be sent automatically. So to prevent an attacker from setting up such a malicious site and have you make requests to the victim one potentially performing things you didn't want to, the victim site needs to implement protection against CSRF. There are multiple techniques to achieve this, for example the website can create a random CSRF token, include it in forms and store it server-side, expecting it back with every form submission. This works, because the attacker, when making a request from the malicious site will have no way to include the correct token. (Also the token belongs to an authenticated user, so even if the attacker does download a page to get a CSRF token, that will not be valid for another logged on user.)
Notice that all of the above relied on the fact that a cookie will be sent automatically. If, as in your example, the authentication token is sent as something lese (like as an Authorization header), that will not be automatically included by the browser. The attacker on a malicious website can still have you make a request to the victim site, however, you auth info cannot be included, so it will not work anyway - whatever such a request can do, the attacker could do by himself anyway (except some very special cases).
For this reason, CSRF protection can be disabled, if authencation is based on something that's not sent automatically.


text:
Q: How to assign angularjs value to jquery? I am using Jquery library for slider which work properly when assign static value. but when used angularjs then its not working.
here is my code -

{{catagory.catagoryName}}

<

{{VideoListAgriculture.Title.substring(0,15)}}
                                    15">..

{{VideoListAgriculture.ViewCount}}

{{VideoListAgriculture.Categories}}

{{VideoListAgriculture.Duration}}

˃

And jquery code ,
$('#slider0').Thumbelina({
                $bwdBut:$('#slider0 .left'),    // Selector to left button.
                $fwdBut:$('#slider0 .right')    // Selector to right button.
            });
$('#slider1').Thumbelina({
                $bwdBut:$('#slider1 .left'),    // Selector to left button.
                $fwdBut:$('#slider1 .right')    // Selector to right button.
            });
            $('#slider2').Thumbelina({
                $bwdBut:$('#slider2 .left'),    // Selector to left button.
                $fwdBut:$('#slider2 .right')    // Selector to right button.
            });
            $('#slider3').Thumbelina({
                $bwdBut:$('#slider3 .left'),    // Selector to left button.
                $fwdBut:$('#slider3 .right')    // Selector to right button.
            });
            $('#slider4').Thumbelina({
                $bwdBut:$('#slider4 .left'),    // Selector to left button.
                $fwdBut:$('#slider4 .right')    // Selector to right button.
            });
            $('#slider5').Thumbelina({
                $bwdBut:$('#slider5 .left'),    // Selector to left button.
                $fwdBut:$('#slider5 .right')    // Selector to right button.
            });

But It's working when ng-repeat is not here. can anyone give any solution for this problem.


text:
Q: TPL Dataflow break LinkTo() during runtime I have a TransformManyBlock<Tin, Tout> and during run time add consumers (ActionBlocks) through LinkTo(...).

*

*Is TransformManyBlock the correct data flow block to consume elements, transform them, and then output (same number elements output as input) to several consumers (each linked-to consumer consumes identical elements like a broadcast)? I deliberately do not chose a BroadCastBlock because it seems to be unable to transform elements similarly to a BufferBlock.

*I like to know how I can unlink consumers (ActionBlocks here) during runtime? LinkTo() does not seem to provide such functionality as far as I can see.

A: *

*TransformManyBlock is for transforming one item on the input into multiple items on the output, it has nothing to do with the number of consumers.
If you want to perform the transformation separately for each target, then that's exactly what cloningFunction in BroadcastBlock is for.
If you want to perform the transformation once and then send each target the same object, you can combine TransformBlock and BroadcastBlock by linking them together. The item will be transformed by the TransformBlock, and then sent to all targets by the BroadcastBlock.

*The return value of LinkTo() is:

An IDisposable that, upon calling Dispose, will unlink the source from the target.

This is exactly what you need. Just store the value returned from LinkTo() and then Dispose() it when necessary.


text:
Q: Elasticsearch: Schema without mapping? According to Elasticsearch's roadmap, mapping types are going to be completely removed at 7.x
How are we going to give a schema structure to Documents without mapping?
For example how would we replace this (A Doc/mapping_type with 3 fields of specific data type):
PUT twitter
{
  "mappings": {
    "user": {
      "properties": {
        "name": { "type": "text" },
        "user_name": { "type": "keyword" },
        "email": { "type": "keyword" }
      }
    }
}

A: They are going to remove types (user in you example) from mapping, because there is only 1 type per index now, the rest will be the same:
PUT twitter
{
  "mappings": {
    "_doc": {
      "properties": {
        "name": { "type": "text" },
        "user_name": { "type": "keyword" },
        "email": { "type": "keyword" }
      }
    }
  }
}

As you can see, there is no user type anymore.


text:
Q: Delete all lines after a string but the last few I have file which contains some lines and some numbers. I want to delete all the lines after particular string, let us say the string is 'angles'. I want to delete all the lines after angles, I can do this using sed command as follows:
sed -n '/angles/q;p' input file

My question is, I want to delete all the lines after angles but want to retain the last four lines? How can I do this in sed?

A: The following should work for you:
tac inputfile | sed '5,/angles/d' | tac

Explanation: Reverse the file, keep first 4 lines and delete everything until the desired pattern is encounterd.  Reverse the result.

A: This might work for you (GNU sed):
sed '1,/angles/b;:a;$!{N;s/\n/&/4;Ta;D}' file

Print out all the lines from the first till encountering the string angles. Then make a moving window of four lines and print them at end of file.

A: In awk :
awk '{
     if(p!=1)print;
     else{a[NR]=$0}
     if($0~/angles/)p=1
     }
     END{
     for(i=NR-3;i<=NR;i++)print a[i]
     }' your_file

Tested below:
> cat temp
wbj
ergthet
gheheh
wergergkn   angles gerg
er
ergnmer
rgnerk
1
2
3
4
> awk '{if(p!=1)print;else{a[NR]=$0};if($0~/angles/)p=1}END{for(i=NR-3;i<=NR;i++)print a[i]}' temp
wbj
ergthet
gheheh
wergergkn   angles gerg
1
2
3
4
>

A: awk -v size=$(wc -l < file) '
    /angles/       { skip=1 }
    NR >= (size-4) { skip=0 }
    !skip
' file

A: I'm going to assume the string you're looking for may occur more than once, and you only want up to the first one. If that's true, reversing the file isn't the best strategy.
{ sed '/angles/q' file; tail -4 file; } > result


text:
Q: How to add a firestore reference type field in php? I want to add data with a reference field type to my collection. How to code this within PHP?
I added:
$db = new FirestoreClient([
    'projectId' => $projectId,
]);

$addedDocRef = $db->collection('locations')->newDocument();
$addedDocRef->set([
    'decisionRef' => $db->document('decisions/' . $ID),
    'formattedAddress' => $formattedAddress,
    'point' => [
        'geohash' => $geohash,
        'geopoint' => new GeoPoint($lat,$lng)
    ]
]);

I expected to see a reference type field in my document, but I got this error:

Uncaught Google\ApiCore\ValidationException: Error rendering 'projects/{project=}/databases/{database=}': expected binding ...

A: The solution was to set a $decisionRef outside the set([...]) array
$decisionRef = $db->document('decisions/' . $ID)


text:
Q: Context issue with Backbone view render function I'm trying to include an optional argument in my Backbone view's render function, like this:
var AppView = Backbone.View.extend({
        el: '#app',

        initialize: function(){
                _.bindAll(this,'render');
                this.listenTo(app.collection.sellables,'reset', this.render);
        },

        render: function(sellableId){
                if(typeof sellableId == "undefined"){
                        var sellable = app.collection.sellables.first();
                }
                else{
                        var sellable = app.collection.sellables.get(sellableId);
                }
                var view = new SellableView({model: sellable});
                this.$('#sellables').append(view.render().el);
        },
});

The first time this view renders, it occurs because the app.collection.sellables collection gets reset after receiving some data from the server. When this reset occurs, the view's render function gets called, but instead of being called with sellableId as undefined, the sellableId is equal to the app.collection.sellables variable, which is causing errors.  To clarify, the view's render function is being called because of this:
app.collection.sellables.reset(data.skus);

Why would my render function be receiving the collection as an argument rather than the argument being undefined?
Also, if I render the view manually, it works correctly and the sellableId argument is undefined as expected:
var app.view.app = new AppView;
app.view.app.render();

A: You're binding your render to "reset" right here:
this.listenTo(app.collection.sellables,'reset', this.render);

From the Catalog of Events:

*

*"reset" (collection, options) — when the collection's entire contents have been replaced.

So a handler for a "reset" event always gets the collection as its first argument. Keep in mind that a JavaScript function's arguments are determined when the function is called, not when the function is defined.
You have a few options. You could bind something else to the "reset" event:
initialize: function() {
    //...
    this.listenTo(app.collection.sellables, 'reset', this.been_reset);
},
been_reset: function() {
    this.render();
}

You could leave render without arguments (like a standard render) and have a separate function to handle the arguments:
render: function() {
    return this.append_model(app.collection.sellables.first());
},
append_model: function(sellable) {
    var view = new SellableView({model: sellable});
    this.$('#sellables').append(view.render().el);
    return this;
}

Then you'd call view.append_model(app.collection.sellables.get(sellableId)) to add a specific model.


text:
Q: Substitute values in all columns of dataframe based in other dataframe I want to substitute a set of values in all columns of a dataframe. I came with a way to do it, however, I suspect there might be a better way without using for.
table1<-read.table(text="
col1 col2  col3
C02  M36    MC0237
C03  C02    M44
C04  M48    F04
F04  M61    M59
F05  M64    M65" ,  header=TRUE, stringsAsFactors=FALSE)

table2<-read.table(text="
orig subst
C02  36
C04  48
D02  24
D04  51
F04  61" ,  header=TRUE, stringsAsFactors=FALSE)

table2#<-table2[,c(1,2)]

mylist <- as.character(table2$subst)
names(mylist) <- table2$orig

for (i in 1:length(mylist)){
  table1[which(table1==names(mylist)[i],arr.ind = T)]<-mylist[i]
}
# table1 GOAL, with values substituted in all columns based on table2
# col1 col2 col3
# 1   36  M36  MC0237 # EDITED ABOVE
# 2  C03   36  M44
# 3   48  M48   61
# 4   61  M61  M59
# 5  F05  M64  M65

A: Here is a one liner to do this,
table1[] <- lapply(table1, function(i) ifelse(grepl(paste(table2$orig, collapse = '|'), i),
                                                  table2$subst[match(i, table2$orig)], i))

which gives

  col1 col2 col3
1   36  M36  M37
2  C03   36  M44
3   48  M48   61
4   61  M61  M59
5  F05  M64  M65


text:
Q: After filling a DropDownList with date from a database, how can I set the default selection to "Select One"? This is what I tried...
ddlClientsInSearchResult.DataSource = dtClients;
ddlClientsInSearchResult.DataValueField = dtClients.Columns[0].ToString();
ddlClientsInSearchResult.DataTextField = dtClients.Columns[1].ToString();
ddlClientsInSearchResult.DataBind();
ddlClientsInSearchResult.Items.Insert(0, "Select One");

so that the first item in the list is "Select One", but this doesn't seem to be working for me.  This is in the code behind an .aspx page, so I was thinking maybe there was a way I could do it over there...but my internet searching has not turned up a solution.
<asp:DropDownList ID="ddlClients" runat="server" Font-Size="8pt" Font-Names="Tahoma"
 Width="200px" AutoPostBack="true" OnSelectedIndexChanged="ddlClients_SelectedIndexChanged">
</asp:DropDownList>

That's the ASP.net code for the DropDownBow that I'm trying to default to "Select One".
Thanks for the help!

A: Just add this to your markup:
<asp:DropDown>
     <asp:ListItem Text="Select One" Value="" Selected="true">Select One</asp:ListItem>
</asp:DropDown/>

A: Remove this ddlClientsInSearchResult.Items.Insert(0, "Select One"); from code behind and do like...
<asp:DropDownList ID="ddlClients" runat="server" Font-Size="8pt" Font-Names="Tahoma"
        Width="200px" AutoPostBack="true" OnSelectedIndexChanged="ddlClients_SelectedIndexChanged"
        AppendDataBoundItems="true">
        <asp:ListItem Text="Select one" Value="0"></asp:ListItem>
    </asp:DropDownList>

A: the code that worked for me is as below
ddlMonth.SelectedIndex = Convert.ToDateTime(row["cstDOB"].ToString()).Month;
ddlYear.SelectedItem.Text = Convert.ToDateTime(row["cstDOB"].ToString()).Year.ToString();
ddlState.SelectedItem.Text = row["cstState"].ToString();

A: Add "Select One" as an item declaratively and Use the AppendDataBoundItems="true"
<asp:DropDownList ID="ddlClients" runat="server" AppendDataBoundItems="true" AutoPostBack="true" >
    <asp:ListItem Value="0">Select One</asp:ListItem>
</asp:DropDownList>


text:
Q: How to unwind dates from date range in MongoDB? I have a mongodb model defined in mongoose for nodejs like:
var schema = new mongoose.Schema({
  serial: {
    type: String,
    required: true,
    index: true
  },
  date_from: {
    type: Date,
    required: true
  },
  date_to: {
    type: Date,
    required: true
  }});

I have a functionality that shall return the number of days free for a given period and serial. So, given the date range from 2020-01-01 to 2020-01-15, I would to query the db and get as a result something like:
const busy_days = [
"2020-01-01 00:00:00",
"2020-01-02 00:00:00",
"2020-01-03 00:00:00",
"2020-01-08 00:00:00"
"2020-01-09 00:00:00",
"2020-01-10 00:00:00",
"2020-01-14 00:00:00",
"2020-01-15 00:00:00"
]

After, my idea is to complete the rest of the algorithm with NodeJs, by checking which dates between 2020-01-01 and 2020-01-15 are not in the busy_days list.
Is there the possibility to do that kind of query in mongoDb?

A: Well, after a lot of searching, I found some examples and the solution may be:
schema.statics.foo = function () {

  return this.aggregate([
    {
      $addFields: {
        days_diff: {
          $divide: [{
            $subtract: ["$date_to", "$date_from"]
          }, 86400000.0]
        }
      }
    }, {
      $project: {
        dates_in_between_inclusive: {
          $map: {
            input: { $range: [0, { $add: ["$days_diff", 1] }] }, // +1 for inclusive
            as: "dd",
            in: { $add: ["$date_from", { $multiply: ["$$dd", 86400000] }] }
          }
        }
      }
    }, {
      $unwind: "$dates_in_between_inclusive"
    }, {
      $group: {
        _id: null,
        dates: {
          $addToSet: "$dates_in_between_inclusive"
        }
      }
    }
  ]);
};

I have to evaluate still if this is the most efficient solution and if it scales.


text:
Q: Install php extension if PHP is already installed Is it possible to install a php extension if PHP is already installed without having to rebuild PHP? I need to install the calendar extension but I don't like to build PHP, I just installed it with apt-get and did not builded it from source.
https://www.php.net/manual/en/calendar.installation.php

A: If you installed PHP with apt-get, then you also need to install any required PHP modules in the same way.
In your case you need to do this:
apt-get install php-calendar


text:
Q: Writing log files using Java EE I need to create application logs to capture users signing in/out and their requests, for that.
We're using Java EE, and thought that creating new log files (new txt file for each day) would be a good approach, but I see that people discourage doing that, the question is: why not do it that way, and what is the correct approach?
also - is there some way to get the application directory?

A: log4j is one of the popularly used logger for Java EE applications and the others are slf4j,logback
log4j has many features, one them being able to create daily log files.
and to answer your question,
creating daily log files does not cause any harm to your application.

A: Logging to text files and rolling them daily is quite a normal approach and discouraging it per se is not justified.
For some specific uses it may be improper, for example if you log sensitive data (passwords, card numbers, etc.). There may be also issues with some cluster configurations, but then you have to ask a more detailed question.

A: Log4J works fine, but once you have many different Applications logging to many different Log files in different locations, you encounter the problem of having to search many log files to find the trace of certain Transaction.
One colleague recommended GrayLog2 once, which makes the viewing of the Log Files a lot easier.
You might want to take a look at that as well, depending on how many Log files your planning to keep.
http://graylog2.org/about


text:
Q: Grid 'keydown' event doesn't catch special keys like arrow keys or Enter or Tab I have an issue with catching special keys on 'keydown' event.. but all works great if I use 'keyup' event, except I can't use it ..
Seems some control catches that event and stops proceeding for others or ? and why ?
Ext.onReady(function () {

    Ext.define('User', {
        extend: 'Ext.data.Model',
        fields: [
        { name: 'id', type: 'int' },
        { name: 'name', type: 'string' },
        { name: 'phone', type: 'string', mapping: 'phoneNumber' }
    ]
    });

    var data = {
        users: [
        {
            id: 1,
            name: 'Ed Spencer',
            phoneNumber: '555 1234'
        },
        {
            id: 2,
            name: 'Abe Elias',
            phoneNumber: '666 1234'
        }
    ]
    };

    var myStore = new Ext.data.Store({
        autoLoad: true,
        storeId: 'myStore',
        model: 'User',
        data: data,
        proxy: {
            type: 'memory',
            reader: {
                type: 'json',
                root: 'users'
            }
        }
    });

    var main = Ext.create('Ext.container.Viewport', {
        renderTo: document.body,
        layout: 'fit',
        items:
        [
            {
                xtype: 'panel',
                title: 'Main Panel',
                items: [
                {
                    xtype: 'gridpanel',
                    id: 'myGrid',
                    name: 'myGrid',
                    title: 'My Grid',
                    store: 'myStore',
                    selModel: Ext.create('Ext.selection.CellModel', {
                        mode: 'SINGLE',
                        listeners: {
                            select: {
                                element: 'el',
                                fn: function (editor, object, options) {
                                }
                            }
                        }
                    }),
                    plugins: [
                        Ext.create('Ext.grid.plugin.CellEditing', {
                            clicksToEdit: 1,
                            listeners: {
                                edit: {
                                    element: 'el',
                                    fn: function (editor, object, options) {
                                    }
                                }
                            }
                        })
                    ],
                    flex: 1,
                    listeners: {
                        keydown: {
                            element: 'el',
                            fn: function (eventObject, htmlElement, object, options) {
                                var pGrid = Ext.ComponentMgr.get('myGrid');
                                if (eventObject.keyCode == 40) // 13, 9
                                {
                                    if (pGrid.selModel.getCurrentPosition().row == pGrid.store.data.length - 1) {
                                        pGrid.store.add({ name: '', age: '', zipcode: '' });
                                    }
                                }
                            }
                        }
                    },
                    columns: [
                        {
                            xtype: 'numbercolumn',
                            dataIndex: 'id',
                            header: 'ID',
                            sortable: true,
                            width: 100,
                            id: 'id',
                            editor: {
                                xtype: 'numberfield'
                            }
                        },
                        {
                            xtype: 'gridcolumn',
                            dataIndex: 'name',
                            header: 'Name',
                            sortable: true,
                            width: 100,
                            id: 'name',
                            editor: {
                                xtype: 'textfield'
                            }
                        },
                        {
                            xtype: 'gridcolumn',
                            dataIndex: 'phone',
                            header: 'Phone',
                            sortable: true,
                            width: 100,
                            align: 'right',
                            id: 'phone',
                            editor: {
                                xtype: 'textfield'
                            }
                        }
                    ]
                }]
            }]
    });
});

Is there any solution ?

A: Just a thought. Have you tried KeyPress instead of/as well as KeyDown?

A: KeyNav is a navigation wrapper that allows you to bind navigation keys directly to function calls. The API documentation has good examples for how to use it:
http://docs.sencha.com/ext-js/4-0/#/api/Ext.util.KeyNav


text:
Q: jQuery hoverIntent not working, but hover does I have the following code:
$(document).ready(function(){
    $(".yearInner").hide();

    $(".year", this).hover(
        function () {
            $(".yearInner", this).slideToggle();
        }
    );

});

It hides the div with class yearInner, and then when the containing div with class year is hovered over, the yearInner div toggles on.
Works fine, put I'd like to use the hoverIntent plug-in instead of hover. Doesn't work at all with hoverIntent. Suggestions?
Div structure for reference:

    2009

        More Info...

    2008

        More Info...

A: You need to split the hover/leave callbacks to use that plugin, like this:
$(".year", this).hoverIntent(function () {
   $(".yearInner", this).slideDown();
}, function() {
   $(".yearInner", this).slideUp("fast");
});

Not sure why there isn't an override like jQuery has in core that accepts a single function to run in both cases, but this is the fix.  Note: .slideToggle() still works just fine, I just added a bit of variety in.


text:
Q: Perl - Synchronizing Data Access I'm starting to learn parallel programming, and I want to compare a single-threaded program with a multi-threaded one.
I need to make a very simple algorithm that calculates the largest number of possible prime numbers within one minute and shows me the last calculated prime number and its position in the prime numbers.
For example, prime number 23, would appear as the number 23 and its position 9, because it is the 9th prime number.
Without using threads, the number of primes found was 233,596 and the last prime 3,246,107. But with threads, 229,972 primes were found and the last prime was 3,192,463.
I think that is wrong, because multi-threading was supposed to obtain a superior result to the single thread. I believe it is a pretty basic error, but I cannot solve it as I still do not understand much of Perl's parallelism.
This is the code. It calculates prime numbers for one minute single-threaded, and then the same calculation with four threads using shared variables.
use threads;
use threads::shared;

my $seconds = 60;

 # WITHOUT THREAD #
print "\n\n Calc without Threads:\n";
my $endTime = time() + $seconds;
calcWithoutThread();

print "\n\n ----------------===========================---------------- \n";

 # WITH THREAD #
print "\n\n Calc with Threads:\n";
my $prime :shared = 5;          # Starts from the 5th prime
my $totalPrime :shared = 2; # Starts with prime 2 and prime 3
my $lastPrime :shared = 0;
my $endTime1 = time() + $seconds;
my $thread1 = threads->create(\&calcWithThread);
my $thread2 = threads->create(\&calcWithThread);
my $thread3 = threads->create(\&calcWithThread);
my $thread4 = threads->create(\&calcWithThread);
$thread1->join();
$thread2->join();
$thread3->join();
$thread4->join();
print " Was found $totalPrime prime numbers. Last prime: $lastPrime.";

# SUB's #

sub calcWithoutThread{
    $prime = 5;            # Starts from the 5th prime
    $totalPrime = 2;           # Starts with prime 2 and prime 3
    $lastPrime = 0;
    while (time() < $endTime){
        if(calcPrime($prime)){
            $totalPrime ++;
            $lastPrime = $prime;
        }
        $prime ++;
    }
    print " Was found $totalPrime prime numbers. Last prime: $lastPrime.";
}

sub calcWithThread{
    while (time() < $endTime1) {
        lock($prime);
        if(calcPrime($prime)){
            $totalPrime ++;
            $lastPrime = $prime;
        }
        $prime ++;
    }
}

sub calcPrime{
    for($i=2 ; $i< sqrt ($prime) ; $i++){
        if( $prime % $i == 0){
            return 0;
        }
    }
    return 1;
}

The logic is that the threads do this calculation synchronously, if it is prime number or not, and also do not overlap values while calculating.

A: The problem is that your threads are synchronised with one another by the locked variable $prime. That means they don't have a chance to run simultaneously, and will also suffer the overhead of switching threads and synchronising access to the variable
Primes aren't a great test for parallel processing, as the calculation of each prime depends on the previous result. However, you could do it by keeping a separate $prime variable, but starting at 5, 6, 7, and 8 for the four threads and adding 4 between tests. That way they don't duplicate each other's work but together cover every integer
There is immediately a problem with this in that none of the even numbers will ever be prime, so two of the four threads will never produce a result. It is still a valid test of parallelism, but clearly very inefficient. You could fix that by starting the threads with 5, 7, 9, and 11, and incrementing by 8 before each test. Then every thread will be profitable
Don't forget that you will have to code the same algorithm for the single-threaded code, otherwise the parallel section gets an unfair advantage

Update
Perhaps a better way would be to lock $prime only to fetch the next number to be tested and increment it. That way all the threads can do their calculations in parallel and only queue up to get another job
You would then have to lock $total_prime to prevent two threads from incrementing it simultaneously, and also update $last_prime while that lock is in effect. Because parallel threads may well generate prime numbers out of sequence you will also have to check whether the prime just found is greater than the latest one discovered by any thread
Your subroutine would look like this. I apologise for changing the identifiers, but Perl traditionally uses snake_case and I find camelCase unpleasant to read. Snake case is also much easier for many people whose first language isn't English, and who cannot pick out the capital letters so easily
sub calc_with_thread {

    while ( time() < $end_time_1 ) {

        my $test = do {
            lock $prime;
            $prime++;
        };

        if ( calc_prime($test) ) {
            lock $total_prime;
            ++$total_prime;
            $last_prime = $test if $test > $last_prime;
        }
    }
}

A: Multi-threading is not an automatic speed boost.
Shared variables are tied, and tied variables are slow.
Here's a simpler, improved version that goes up to a max number rather than by time. It avoids locking. Threads are still significantly slower, because each of them have to do a get and set on that sluggish shared variable for every number they check.
#!/usr/bin/env perl

use strict;
use warnings;
use Time::HiRes qw(time);
use v5.10;

use threads;
use threads::shared;

my $Max_Number = 50_000;

{
    print "\n\nCalc without Threads:\n";
    my $start_time = time;
    calcWithoutThread();
    my $end_time = time;
    say "$Max_Number took @{[ $end_time - $start_time ]} seconds.";
}

my $Shared_Prime :shared = 5;
{
    print "\n\nCalc with Threads:\n";
    my $start_time = time;
    my $thread1 = threads->create(\&calcWithThread);
    my $thread2 = threads->create(\&calcWithThread);
    my $thread3 = threads->create(\&calcWithThread);
    my $thread4 = threads->create(\&calcWithThread);
    $thread1->join();
    $thread2->join();
    $thread3->join();
    $thread4->join();
    my $end_time = time;
    say "$Max_Number took @{[ $end_time - $start_time ]} seconds.";
}

sub calcWithoutThread {
    my $prime = 5;                # Starts from the 5th prime

    while( $prime <= $Max_Number ) {
        calcPrime($prime++);
    }
}

sub calcWithThread {
    while( $Shared_Prime <= $Max_Number ) {
        calcPrime($Shared_Prime++);
    }
}

sub calcPrime {
    my $prime = shift;

    for( my $i=2 ; $i < sqrt($prime) ; $i++){
        if( $prime % $i == 0){
            return 0;
        }
    }

    return 1;
}

Instead, avoid shared state or coordinating workers as much as possible. For example, you can slice up the work into pieces. If you have 4 workers, give them each a starting number and they each increment by 4. Then they can cover the whole space without shared state.

*

*Worker 1: 5, 9, 13, ...

*Worker 2: 6, 10, 14, ...

*Worker 3: 7, 11, 15, ...

*Worker 4: 8, 12, 16, ...

#!/usr/bin/env perl

use strict;
use warnings;
use Time::HiRes qw(time);
use v5.10;

use threads;

my $Max_Number = 7_000;

{
    print "\n\nCalc without Threads:\n";
    my $start_time = time;
    calcWithoutThread(5, 1);
    my $end_time = time;
    say "$Max_Number took @{[ $end_time - $start_time ]} seconds.";
}

{
    print "\n\nCalc with Threads:\n";
    my $start_time = time;
    my $thread1 = threads->create(\&calcWithThread, 5, 4 );
    my $thread2 = threads->create(\&calcWithThread, 6, 4 );
    my $thread3 = threads->create(\&calcWithThread, 7, 4 );
    my $thread4 = threads->create(\&calcWithThread, 8, 4 );
    $thread1->join();
    $thread2->join();
    $thread3->join();
    $thread4->join();
    my $end_time = time;
    say "$Max_Number took @{[ $end_time - $start_time ]} seconds.";
}

sub calcWithoutThread {
    my($start, $inc) = @_;

    my @primes;
    for( my $prime = $start; $prime <= $Max_Number; $prime += $inc ) {
        push @primes, $prime if calcPrime($prime);
    }

    return \@primes;
}

sub calcWithThread {
    my($start, $inc) = @_;

    my @primes;
    for( my $prime = $start; $prime <= $Max_Number; $prime += $inc ) {
        push @primes, $prime if calcPrime($prime);
    }

    return \@primes;
}

sub calcPrime {
    my $prime = shift;

    for( my $i=2 ; $i < sqrt($prime) ; $i++){
        if( $prime % $i == 0){
            return 0;
        }
    }

    return 1;
}

For me on my i7 MacBook (2 real cores, 4 virtual), threads break even at about 6000. To get the results, $thread->join will return the list of primes from calcWithThread.


text:
Q: Identity Server 4 access token with user info So I have began practicing and using Identity Server 4, my goal is to have an authentication and authorization server for all the applications within my organization. I got to the point where I can log in correctly to my identity server from a third application and get my access_token and it works nicely.
The second step is to get my userinfo inside my access_token but when I decode it I get this:
{
  "nbf": 1505250392,
  "exp": 1505253992,
  "iss": "http://localhost:5000",
  "aud": [
    "http://localhost:5000/resources",
    "SecretAPIEndpoints"
  ],
  "client_id": "SecretClient",
  "sub": "ebf3fcad-6ab3-4bcd-88ce-0c5794ebdffa",
  "auth_time": 1505250391,
  "idp": "local",
  "scope": [
    "openid",
    "SecretAPIEndpoints"
  ],
  "amr": [
    "pwd"
  ]
}

So if I use this token I can make my endpoints work correctly but I want to get it one step further and get my SPA to show my user first name and last name and also their email and roles.
I haven't found documentation or examples to make this happen, so any bit of help would be greatly appreciated.

A: If you want to consume identity data in JS-based client app, ask for an id_token in addition to an access token.
https://openid.net/specs/openid-connect-core-1_0.html#ImplicitFlowAuth


text:
Q: cannot import name 'parabolic' from 'parabolic' I am using Spyder with anaconda, firstly I tried to install it via anaconda but this didn't work so instead installed it via pip using:
pip install parabolic

however now when I try and call parabolic the following error occurs:
ImportError: cannot import name 'parabolic' from 'parabolic' (/Users/harry/opt/anaconda3/lib/python3.8/site-packages/parabolic/__init__.py)

does anyone have any ideas as to why this might be. For context I am trying to run the following code:
https://gist.github.com/jgomezdans/434642/8b738ff4bff7f549f6255f5da3668f910b7352a2


text:
Q: Get an Object from a collection without looping in java I need to repeatedly (hundred of thousands of times) retrieve an element (different each time) from a Collection which contains dozens of thousand of Objects.
What is the quickest way to do this retrieval operation? At the moment my Collection is a List and I iterate on it until I have found the element, but is there a quicker way? Using a Map maybe? I was thinking to do:

*

*Putting the Objects in a Map, with the key being the id field of the Object, and the Object itself being the value.

*Then doing get(id) on the Map should be much faster than looping through a List.

*If that is a correct way to do it, should I use a HashMap or TreeMap? - my objects have no particular ordering.

Any advice on the matter would be appreciated!
Last note: if an external library provides a tool to answer this I'd take it gladly!

A: As per the documentation of the Tree Map (emphasis my own):

The map is sorted according to the natural ordering of its keys,
  or by a Comparator provided at map creation time, depending on which
  constructor is used.

In your case, you state that the items have no particular order and it does not seem that you are after any particular order, but rather just be able to retrieve data as fast as possible.
HashMaps provide constant read time but do not guarantee order, so I think that you should go with HashMaps:

This class makes no guarantees as to the order of the map; in
  particular, it does not guarantee that the order will remain constant
  over time. This implementation provides constant-time performance for
  the basic operations (get and put), assuming the hash function
  disperses the elements properly among the buckets.

As a side note, the memory footprint of this can get quite high quite fast, so it might also be a good idea to look into a database approach and maybe use a cache like mechanism to handle more frequently used information.

A: I've created code which tests the proformance of BinarySearch, TreeMap and HashMap for the given problem.
In case you are rebuilding the collection each time, HashMap is the fastest (even with standard Object's hashCode() implementation!), sort+array binary search goes second and a TreeMap is last (due to complex rebuilding procedure).
proc array: 2395
proc tree : 4413
proc hash : 1325

If you are not rebuilding the collection, HashMap is still the fastest, an array's binary search is second and a TreeMap is the slowest, but with only slightly lower speed than array.
proc array: 506
proc tree : 561
proc hash : 122

Test code:
public class SearchSpeedTest {

    private List<DataObject> data;
    private List<Long> ids;
    private Map<Long, DataObject> hashMap;
    private Map<Long, DataObject> treeMap;
    private int numRep;
    private int dataAmount;
    private boolean rebuildEachTime;

    static class DataObject implements Comparable<DataObject>{
        Long id;

        public DataObject(Long id) {
            super();
            this.id = id;
        }

        public DataObject() {
            // TODO Auto-generated constructor stub
        }

        @Override
        public final int compareTo(DataObject o) {
            return Long.compare(id, o.id);
        }

        public Long getId() {
            return id;
        }

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

        public void dummyCode() {

        }

    }

    @FunctionalInterface
    public interface Procedure {
        void execute();
    }

        public void testSpeeds() {

            rebuildEachTime = true;
            numRep = 100;
            dataAmount = 60_000;

            data = new ArrayList<>(dataAmount);
            ids = new ArrayList<>(dataAmount);
            Random gen = new Random();

            for (int i=0; i< dataAmount; i++) {
                long id = i*7+gen.nextInt(7);
                ids.add(id);
                data.add(new DataObject(id));
            }
            Collections.sort(data);

            treeMap = new TreeMap<Long, DataObject>();
            populateMap(treeMap);

            hashMap = new HashMap<Long, SearchSpeedTest.DataObject>();
            populateMap(hashMap);

            Procedure[] procedures = new Procedure[] {this::testArray, this::testTreeMap, this::testHashMap};
            String[] names = new String[]                {"array",       "tree ",            "hash "};

            for (int n=0; n<procedures.length; n++) {
                Procedure proc = procedures[n];
                long startTime = System.nanoTime();
                for (int i=0; i<numRep; i++) {
                    if (rebuildEachTime) {
                        Collections.shuffle(data);
                    }
                    proc.execute();
                }
                long endTime = System.nanoTime();
                long diff = endTime - startTime;

                System.out.println("proc "+names[n]+":\t"+(diff/1_000_000));
            }

        }

        void testHashMap() {
            if (rebuildEachTime) {
                hashMap = new HashMap<Long, SearchSpeedTest.DataObject>();
                populateMap(hashMap);
            }

            testMap(hashMap);
        }

        void testTreeMap() {

            if (rebuildEachTime) {
                treeMap = new TreeMap<Long, SearchSpeedTest.DataObject>();
                populateMap(treeMap);
            }

            testMap(treeMap);
        }

        void testMap(Map<Long, DataObject> map) {

            for (Long id: ids) {
                DataObject ret = map.get(id);
                ret.dummyCode();
            }

        }

        void populateMap(Map<Long, DataObject> map) {
            for (DataObject dataObj : data) {
                map.put(dataObj.getId(), dataObj);
            }
        }

        void testArray() {
            if (rebuildEachTime) {
                Collections.sort(data);
            }
            DataObject key = new DataObject();
            for (Long id: ids) {
                key.setId(id);
                DataObject ret = data.get(Collections.binarySearch(data, key));
                ret.dummyCode();
            }
        }

        public static void main(String[] args) {
            new SearchSpeedTest().testSpeeds();
        }
    }

A: HashMap will be more efficient in general, so use it whenever you don't care about the order of the keys.
when you want to keep your entries in Map sorted by key than use TreeMap but sorting will be overhead in your case as you dont want any particulate order.

A: You can use a map if you have a good way to define the key of the map. In the worst case you can use your object as key and value.
As ordering is not important use a HashMap. To maintain the order in a TreeMap there is additional cost when adding an element, as it must be added at the correct position.


text:
Q: VirtualHost на Apache 2.4.6 Вопрос такой: необходимо на одной машине создать несколько виртуальных хостов.
Стоит Apache 2.4.6
Сначала хотел на отдельный порт повесить:
Listen 8881
<VirtualHost *:8881>
    DocumentRoot "/Applications/mamp/apache2/hthosts/www1"
    <Directory "/Applications/mamp/apache2/hthosts/www1">
        Options Indexes FollowSymLinks
        AllowOverride All
        Order deny,allow
        Allow from all
    </Directory>
</VirtualHost>

Выдет 403 ошибку нет прав, причем даже если запрашивал несуществующий файл.
Потом попробовал по именам:
NameVirtualHost *:8080
<VirtualHost *:8080>
    ServerName www.vhost1.local
    ServerAlias vhost1.local

    DocumentRoot "/Applications/mamp/apache2/hthosts/www1"
    <Directory "/Applications/mamp/apache2/hthosts/www1">
        Options Indexes FollowSymLinks
        AllowOverride All
        Order deny,allow
        Allow from all
    </Directory>
</VirtualHost>

При старте сервера выдает: AH00548: NameVirtualHost has no effect and will be removed in the next release
При запросе вообще не отвечает. Даже заголовки в ответ не посылает.
Кто нибудь знает как можно решить вопрос?
A: 403 исправляется в Apache 2.4 так:
<Directory /Applications/mamp/apache2/hthosts/www1>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>


text:
Q: Is motion along the $x$ and $y$ axises independent with quadratic drag? It's often stated that motion in the $x$ and $y$ axises are independent, so that changing the $x$-velocity will not influence changes in the $y$-velocity. To me it seems that with quadratic drag (drag proportional to $v^2$) this shouldn't hold true. If we increase the initial velocity in the $y$-direction, this would increase the drag. It would also decrease the percent of the drag being applied in the $x$-direction, since the drag acts opposite to the velocity. Do these effects cancel?

A: So the x part of the drag is
$$\begin{align*}
f_x &= f \cos\theta \\
&= (k v^2) \cos\theta \\
&= k v (v \cos\theta) \\
&= k v v_x \,,
\end{align*}$$
and $v$ is dependent on the $y$ component of motion as well as the x-component.
Similar consideration, of course, apply to the y-component of drag.
So the independence is explicitly lost and you can no longer solve each direction without reference to the other. That was a helpful feature of the introductory course not present in the full problem.

Note that in a regime where $f \propto v$ you can retain the independence of the two coordinate equations. I conjecture that this is why that fairly rare case is often treated in upper-division mechanics texts.


text:
Q: Microsoft HPC Default Job Email Settings / Notifications I've got a Microsoft HPC cluster setup and we're using an engineering application to submit jobs to the compute cluster queue. Users remote desktop to the head-node of the cluster to submit jobs to avoid file-transfer delays across our WAN, this leads to completed or failed jobs sitting for review for a long time.
Unfortunately we can't use the HPC Job Manager to submit jobs to the queue, we have to use the engineering application submission tool. That application doesn't have an option to send an email on the job status (completed, failed etc.)
In the HPC Job Manager > New Job there are options for "Send a notification when this job" starts / completes etc. which would be great if we could use that to submit.
All jobs submitted use the Default job template but on that template I don't options to edit or add email settings to it.
Is there an option I'm missing or is this even a possible configuration?


text:
Q: File Upload via ajax ends up in php://input ---Solved
By replacing
$.ajax({ // create an AJAX call...
    type: $(this).attr('method'), // GET or POST
    url: $(this).attr('action'), // the file to call
    processData: false,
    cache: false,
    contentType: false,
    data: formData, // get the form data
    beforeSend: function() {
    $(".dynamicContentWindow").load("loading.php"); // hides the window during load
    },
    success: function(data, status) { // on success..
    $(".dynamicContentWindow").html(data); // update the DIV
    contentLoaded(); //recall the catchers for the new page
    },
});

with:
var request = new XMLHttpRequest();
request.open("POST", $(this).attr('action'));
request.send(formData);

solves the problem. However, I do not understand why and I think it is neither explained in another post. If somone would be able to point that out it would be a great relieve.

Heyho everyone,
I am quite new to working with jQuery and I am currently trying to establish an asynchronous file upload with ajax. However my requests ends all the time up in the php://input and is not passed to $_POST or $_FILES. I googled the complete day yesterday and tried several things, but I am not able to figure out the problem. The server used is apache 2.2.9 (yes it is actually ready for the museum, but it was not my choice)
The html code is in this case:
<form action="ua_import_files.php" method="POST" enctype="multipart/form-data" class="file">
    <input type="hidden" name="tab_select" value="0" />
    <input type="hidden" name="MAX_FILE_SIZE" value="9999000000" />
    <input type="hidden" name="file_type" value="planview" />
    <input name="uploadedfile" type="file" size="40" style="background:#D0D0D0; font-size:10px;  margin-top:7px;" />

    <input type="submit" value="Upload File" style="font-size:12px; width: 100px; margin-top:7px; float:left;display:block;" />
</form>

the related javascript code is:
$("form").each(function() {
    if($(this).attr('class') == "file") {
        $(this).submit(function(e){
        e.preventDefault(); // cancel original event to prevent form submitting
        console.log("File Upload, FileReader: " + window.FileReader + "FormData: " + window.FormData);
        var form = new FormData(this);
        console.log(form);
        $.ajax({ // create an AJAX call...
            type: $(this).attr('method'), // GET or POST
            url: $(this).attr('action'), // the file to call
            beforeSend: function() {
                $(".dynamicContentWindow").load("loading.php"); // hides the window during load
            },
            success: function(data, status) { // on success..
                $(".dynamicContentWindow").html(data); // update the DIV
                contentLoaded(); //recall the catchers for the new page
            },
            data: form, // get the form data
            processData: false,
            contentType: false,
            cache: false
            });
        });
    }
});

Hereby the console.log() produces an output as well.
But if I then dump $_FILES or $_POST on the server I get in both cases empty arrays. However, when dumping file_get_contents("php://input") i get this:
string(2941129) "-----------------------------29431251527956 Content-Disposition: form-data; name="tab_select" 0 -----------------------------29431251527956 Content-Disposition: form-data; name="MAX_FILE_SIZE" 9999000000 -----------------------------29431251527956 Content-Disposition: form-data; name="file_type" exp -----------------------------29431251527956 Content-Disposition: form-data; name="uploadedfile"; filename="file.exp" Content-Type: application/octet-stream EXP op 2015-08-13T00:00:00.000Z 2016-01-01T00:00:00.000Z XXX XXX ..."

(I only but some of the string in here)
I already checked the config files, which should give enough resources to the server to process the request:
memory_limit = 128M;
max_execution_time = 3600;
max_input_time = 600;
upload_max_filesize = 30M
post_max_size = 100M

I assume, that I have either something wrong with the headers, which stops the server of parsing the data or another mistake in the config,w hich I did not found yet. Does anyone has an idea?

A: Try this code .Give your id  form id
var formData = new FormData($('#yourformid')[0]);
$.ajax({
        type: $(this).attr('method'),
        url:  $(this).attr('action'),
        data: formData,
        async: false,
        cache: false,
        processData: false,
        contentType: false,
        beforeSend: function() {
        $(".dynamicContentWindow").load("loading.php"); // hides the window during load
    },
    success: function(data, status) { // on success..
              your code

        }
      });

call phpinfo(); and see upload_max_filesize  override or not .

A: You have some issues with your code:
if($(this).attr('class') == "file") { // <---what $(this) is here
    $(this).submit(function(e){ // what $(this) in here? is it one of many forms?

now here you have to set the file which you want to upload but you are not doing it.
    var form = new FormData(this); // <---what this belogs here.

There are several other issues as well. so lets get to the solution:
  $('.file').submit(function(e) { // submit the actual form
      e.preventDefault();
      var form = new FormData(this); // pass this as a reference to the form
      form.append('file', form.files[0]); //<----append the file here
      $.ajax({
        type: $(this).attr('method'), // <----form method as type in ajax
        url: $(this).attr('action'), // <-----form action as a url in ajax
        beforeSend: function() {
          $(".dynamicContentWindow").load("loading.php");
        },
        success: function(data, status) {
          $(".dynamicContentWindow").html(data);
          contentLoaded();
        },
        data: form, //<------------sending form which have `file` as a key to the file name
        processData: false,
        contentType: false,
        cache: false
      });
  });

You don't have to check for the class name of the form class="file" and you just submit the form and make formData with FormData(this) and pass this as a reference to the submitting form then append the file with a key : value pair as form.append('file', form.files[0]);.

As a side note:
console.log(form);

You can't see everything in the console but better to check the network tab of your browser, where you can see in the headers all information about the sent formdata.


text:
Q: `and` is the same as `&&` but why does `and` have lower precedence? In ruby, and is the same as &&, but why does and have lower precedence?
false and false || true # => false
false && false || true # => true

A: You're absolutely correct that the humanised operators have lower precedence. There is an excellent (and brief!) article on this here if you want more information.
Simplest answer (from that article):

Properly understood, and and or are control flow operators, not boolean operators.


text:
Q: PHP Soap Server in JAX-WS Style We made a web service for one of our clients with PHP SOAP class. But they said our Soap server is built in RPC style, they need JAX-WS.
When i asked them why, they said, They are using IBM WebSphere 8.5 server. Which has problems with RPC style,  because of RPC is an old technology etc. And They also said that WebSphere doesnt support RPC so well.
Since Im not expert at SOAP and web services, i did not get it. I did some google but no results for runnnig PHP Soap server in JAX-WS style.
Do you have any idea what should i do ?
Regards

A: I think they're mixing the names of the java specifications with the sets of underlying protocols they envelop.
http://www.ibm.com/developerworks/library/ws-tip-jaxwsrpc/

Web services have been around a while now. First there was SOAP. But
  SOAP only described what the messages looked like. Then there was
  WSDL. But WSDL didn't tell you how to write web services in Java™.
  Then along came JAX-RPC 1.0. After a few months of use, the Java
  Community Process (JCP) folks who wrote that specification realized
  that it needed a few tweaks, so out came JAX-RPC 1.1. After a year or
  so of using that specification, the JCP folks wanted to build a better
  version: JAX-RPC 2.0. A primary goal was to align with industry
  direction, but the industry was not merely doing RPC web services,
  they were also doing message-oriented web services. So "RPC" was
  removed from the name and replaced with "WS" (which stands for web
  Services, of course). Thus the successor to JAX-RPC 1.1 is JAX-WS 2.0
  - the Java API for XML-based web services.

For inter-op with non-java, they should avoid JAX-WS or JAX-RPC -- they are meaningless.


text:
Q: Multicast and broadcast networks and routing I am using my computer for watching TV and also for internet browsing(listening to youtube, soundcloud, etc.).
For watching TV I am using m3u playlist, with a IP addresses from multicast network(e.g. udp://@232.4.1.1:5002 is the first channel). For the internet browsing, I am using broadcast network. So, because there are two networks, I supposed I would use VLANs and routing.
Because I would like to use one ethernet card, I created a VLAN, and on the modem side, I chose trunk port
VLAN3999(VLAN with ID 3999, for IPTV)
According to STP device, and some people that have the same ISP, the ID of VLAN should be 3999
IP address: 10.10.10.10
Subnet mask: 255.255.0.0
Gateway: 10.10.1.1 (I believe I don't need it, but without that, IPTV doesn't work)
Eth0 (I didn't create VLAN for internet access, because it works without)
IP address: 192.168.1.167
Subnet mask: 255.255.255.0
Gateway: 192.168.1.1
DNS: 193.2.1.66
Routing:
default traffic via 192.168.1.1, device eth0 .. default traffic goes through modem(192.168.1.1)
224.0.0.0/4 or 224.0.0.0 240.0.0.0, device VLAN3999 .. multicast traffic(from 224.0.0.0 to 239.255.255.255) goes through VLAN3999
I can't get both networks to work. Only the network, that is set to default routing, works. E.g. Internet works if default route is set to 192.168.1.1 and device eth0, but IPTV doesn't, and IPTV does work if default route is set to 10.10.1.1 and device VLAN3999, but internet doesn't.
I know there is some problem with routing, but what? It looks like the system only insist on default route, everything else, it just ignores. Weird
The OS I am using is ArchLinux.

A: Looks like you are going to have to set up some static routes.  Get rid of the default gateway 10.10.1.1, and figure out what destinations you need to route via that IP.  Then just add them manually like this for example:
# ip route add 10.0.0.0/16 via 10.10.1.1

If you get it to work properly then just put your static routes in a script when your interface comes up to make it all automatic.  The scripts that get called automatically when you bring up an interface are called route-{ifname}  from example:
# cat /etc/sysconfig/network-scripts/route-eth0
10.0.0.0/16 via 10.10.1.1 dev eth0

UPDATE:
Since your tcpdump capture shows this traffic 95.176.246.71.rfe > 232.4.1.1.rfe, adding that as a static route would be essential.
sudo ip route add 95.176.546.0/24 dev vlan3999


text:
Q: Run multiple jobs in parallel in Atlassian Bamboo I would like to run multiple jobs in parallel on the same automation server.  For this I need as many agents installed as the number of parallel jobs.
When I try to install an additional remote agent the installer picks the location of the first agent that is already installed on the automation server. As a result the installation fails.
What I did was: I turned off the first agent and then I run the installer for the new remote agent.
How should I go about installing an addition remote agent?
Regards,
Archie

A:
location of the first agent

I presume you're referring to the agent's home dir. Try overriding it per agent with a distinct location using:
-Dbamboo.home=/opt/bambooX

More info: https://confluence.atlassian.com/bamboo/additional-remote-agent-options-436044733.html


text:
Q: error with GetApplicationContext() I'm trying to create some classes in order to have a cleaner code but I've occurred in this error:
I have the following class:
import java.io.IOException;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.metaio.sdk.MetaioDebug;
import com.metaio.tools.io.AssetsManager;

public class AssetsExtracter extends AsyncTask<Integer, Integer, Boolean>
{

    @Override
    protected Boolean doInBackground(Integer... params)
    {
        try
        {
            AssetsManager.extractAllAssets(getApplicationContext(), true);
        }
        catch (IOException e)
        {
            MetaioDebug.printStackTrace(Log.ERROR, e);
            return false;
        }
        return true;
    }
}

In my main activity I call the AssetsExtracter class like this:
    // extract all the assets
    AssetsExtracter mTask = new AssetsExtracter();
    mTask.execute(0);

But I get an error on GetApplicationContext() on my AssetsExtracter class. It should be something related to the context but how should I edit the class in order to fix this?

A: Add a constructor to your AssetsExtracter class that takes a Context as a parameter, store it in a member variable and use the variable in doInBackground().
Likely the async task used to be a non-static inner class in a class that defines getApplicationContext(), such as an Activity. As a self-standing class there's no outer class that would provide the method.

A: You are extending AsyncTask.
AsyncTask does not make sense without an Activity or a Service to where she reports onPostExecute().
So, make your class constructor accept your Activity's Context and then use Context.getApplicationContext()
Alternatively if you just need some async execution with no relation to Android UI you can use plain Java Executor.execute()

A: Change your code to be like this. Pass context in your constructor
 public class AssetsExtracter extends AsyncTask<Integer, Integer, Boolean>{
 Context context;

public AssetsExtracter(Context context){
    this.context = context;
}

@Override
protected Boolean doInBackground(Integer... params)
{
    try
    {
        AssetsManager.extractAllAssets(context, true);
    }
    catch (IOException e)
    {
        MetaioDebug.printStackTrace(Log.ERROR, e);
        return false;
    }
    return true;
}

}

A: public class AssetsExtracter extends AsyncTask<Integer, Integer, Boolean>
{

    private Context context;
    public void AssetsExtracter(Context context){
         this.context = context;
    }

    @Override
    protected Boolean doInBackground(Integer... params)
    {
        try
        {
            AssetsManager.extractAllAssets(context, true);
        }
        catch (IOException e)
        {
            MetaioDebug.printStackTrace(Log.ERROR, e);
            return false;
        }
        return true;
    }
}


text:
Q: webview dentro do Fragnent Quero abrir meu site dentro do webview, e os links dentro site devem abrir fora REFORÇO QUE ESTOU ABRINDO WEBVIEW EM UM FRAGMENT E NÃO NO MAIN ACTIVITY
- Quero abrir meu site dentro do webview, e os links de outros sites devem abrir fora, no navegador do celular normal, porem isso não ocorre. Meu webview está dentro de um fragment. Podem me ajudar?
MEU CÓDIGO :
@Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_principal, container, false);
    WebView webView = (WebView) v.findViewById(R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true);

    WebViewClientImpl webViewClient = new WebViewClientImpl(this);

    //se eu desabilito essa linha resolve, porem tudo abre fora do app, e
    //queria somente que os links listados no site abrissem fora.

    webView.setWebViewClient(new WebViewClient());
    webView.loadUrl("https://meusite.com/");

    return v;

}

    public class WebViewClientImpl extends WebViewClient {

        private PrincipalFragment activity = null;
        public WebViewClientImpl(PrincipalFragment activity) {
            this.activity = activity;
        }
        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {
            if(url.contains("https://meusite.com")) return false;
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            activity.startActivity(intent);

            return true;

        }

    }

Fragmente_principal.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_purple">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </WebView>
</LinearLayout>

A: Seguindo o jeito que você implementou o webview, ao invés de:
webView.setWebViewClient(new WebViewClient());

o certo é instanciar a classe que você criou que estenda WebViewClient, então seria:
webView.setWebViewClient(webViewClient);

O restante do seu fragment mantém.
Na Classe WebViewClientImpl deixe o método override desse jeito:
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
    if(url.contains("https://meusite.com")) {
        return true;
    } else {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        activity.startActivity(intent);
        //Use o método a seguir caso, o seu webview continua carregando
        //as páginas que o browser deveria abrir (diferente do seu host)
        webView.stopLoading();

        return false;
    }

}

Ou você pode deixar esse método override do jeito que o Guilherme Nascimento sugeriu:
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {

     Uri uri = Uri.parse(url);

    if(uri.getHost().equals("meusite.com")) {
        return true;
    } else {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        activity.startActivity(intent);
        //Use o método a seguir caso, o seu webview continua carregando
        //as páginas que o browser deveria abrir (diferente do seu host)
        webView.stopLoading();

        return false;
    }

}

Espero ter ajudado. E lembre-se de trocar as urls.