text:
Q: Monitor Dell workstation power supply and hard disk SNMP I've been trying and trying to monitor workstation power supplies and hard disk statuses with SNMP. I can't get any SNMP information from the workstations but I have successfully been able to get power supply information from Dell servers, such as, Poweredge 720.
I've tried installing various tools like OpenManage and it's flavors to no avail.
Has anyone had any experience monitoring this kind of informaiton with SNMP? Workstations model is Dell Precision T36.

A: Did you install the OMCI on the Precision T36 from here:  http://en.community.dell.com/techcenter/systems-management/w/wiki/1773.openmanage-client-instrumentation-omci.aspx
You'll need that installed.  The SNMP "system state group" will have power supply info for instance.  You can find the full references here: ftp://ftp.dell.com/Manuals/all-products/esuprt_software/esuprt_client_sys_mgmt/esuprt_client_sys_mgmt_opnmang_clnt_instr/dell-opnmang-clnt-instr-v8.2.1_Reference%20Guide2_en-us.pdf
You'll need OMCI in order to report on things correctly via SNMP on a workstation.

A: *

*Google is a really helpful resource.

*You've done it on Dell servers and don't understand why you can't figure it out with Dell workstations? Maybe because Dell servers and Dell workstations aren't the same thing.

*Use the right tool for the job.

*For the future, Google or your vendor's support line should be your first resource, not your last...


text:
Q: why my swift alamofire multipart is not working? I am doing a REST call to a webService but i am getting Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength.
What is the problem?
 let params = [RESTConstants.APIParameterKey.client: UserDefaults.standard.string(forKey: ConstantsHelper.client)!, RESTConstants.APIParameterKey.token: UserDefaults.standard.string(forKey: ConstantsHelper.token)!]

        AF.upload(multipartFormData: { multipartFormData in

            for (key, value) in params {
                multipartFormData.append((value).data(using: String.Encoding.utf8)!, withName: key)
            }
            if let imageData = image.jpegData(compressionQuality: 1.0) {
                        multipartFormData.append(imageData, withName: "image", fileName: "image.jpeg", mimeType: "image/jpeg")
                    }

        }, to: "myUrl")
            .responseDecodable(of: Response.self) { response in
                debugPrint(response)
            }

redpajama_set_name: RedPajamaStackExchange


text:
Q: trigger a modal on blade (laravel 4.2) depending if conditional statement is satisfied i have this blade that adds a user in the database and i wanted to use bootstrap modal to inform the user that the record has been added. This adding functionality works and my only problem is that i dont know how to display the modal here is my current code:
 @if ($errors->any())

        {{ implode('', $errors->all('
:message
')) }}

    @else

Record Added!

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

Modal Header

Some text in the modal.

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

any ideas?

A: With blade conditionals any HTML within the block is valid, this means we can use
@endif


text:
Q: Get two different class instances and compare them (Java) I am receiving input from my Ext JS application on the front end and I want to compare two records on the java side, the record prior to a form update on the UI side and the record after setting all the new values. I have made two references to the same type of object, one before setting new values (oldRecord) and one after (newRecord) and compare these but when I try to use oldRecord.getClass() on the old record it will show the new field values. Is there any way to have access to the old values? I also tried making two field arrays and passing those into my method.
private static Map<String, List<String>> changes;

public static <T> Map<String, List<String>> getChanges (T oldRecord, T newRecord) {

    changes = new HashMap<String, List<String>>();

    try {
        if(oldRecord instanceof UserInfo && oldRecord.getClass().equals(newRecord.getClass())) {
            Field field = oldRecord.getClass().getDeclaredField("name");
            field.setAccessible(true);
            System.out.println(field.get(oldRecord));
            field = newRecord.getClass().getDeclaredField("name");
            field.setAccessible(true);
            System.out.println(field.get(newRecord));

            // will loop through all fields in both records and compare

        }
    } catch (Exception e) {
        System.err.println("Exception");
    }

    return changes;
}

A: I think you are using the same object. This is the case if you have done something like this:
Object oldRecord = new Object();
Object newRecord = oldRecord;
newRecord.doSomethingThatModifyIt();
getChanges(oldRecord, newRecord);

If you have done something like this, then keep in mind that Object newRecord = oldRecord; does not create any new object, but just sets the 2 variables to point to the same object.
You should instead create a new object based on the old one, with some method like clone() that you would have to implement. Or just by manually setting the fields of the newly created object.
Note: I have used Object but it could be any type of course.

A: If oldRecord and newRecord reference the same object like
T oldRecord = new T();
T newRecord = oldRecord;

they will "hold" the same instance variable values as well.
To save in oldRecord the old values you must do a deep copy of the object, that means create a new object and copy the instance variable values.
SEarch for deep copy or cloning, maybe start here: How do you make a deep copy of an object in Java?


text:
Q: Undefined reference to explicitly instantiated template function I have a class with a template method that is declared in a header and defined in a cpp file, so
// A.h - declaration
struct A
{
    template<typename T = int> void fun();
};

and then
// A.cpp - definition
#include <iostream>
#include "A.h"

template<typename T> void A::fun()
{
    std::cout << "Hello world template" << std::endl;
}

// Explicit instantiation
template void A::fun<int>();

Now, somewhere else, in a test, I have
#include "A.h"

int main ()
{
    A a;
    a.fun();
}

and since I explicitly instantiated the function for int template parameter, all is well. Or should be!
My code links fine with GCC 7.3.0 but fails to link with clang 6, which reports an undefined reference to function fun.
What's going on here? Is there anything else that I should take care of? Perhaps something that GCC takes for granted while clang doesn't?
Thanks!
Edit
@WhozCraig, @Neil Butterworth here are the linking commands for the two toolchains.
GCC:
/usr/bin/g++  -g   CMakeFiles/test_generator.dir/generator/generator.cpp.o CMakeFiles/test_generator.dir/test_utils.cpp.o  -o test_generator -Wl,-rpath,/home/mleoni/PhD/ABI/libcellml/build/src:/home/mleoni/PhD/ABI/libcellml/build/tests/gtest ../src/libcellmld.so.0.1.0 gtest/libgtest_main.so /usr/lib/x86_64-linux-gnu/libxml2.so gtest/libgtest.so -lpthread

clang:
/usr/bin/clang++  -g   CMakeFiles/test_generator.dir/generator/generator.cpp.o CMakeFiles/test_generator.dir/test_utils.cpp.o  -o test_generator -Wl,-rpath,/home/mleoni/PhD/ABI/libcellml/build/src:/home/mleoni/PhD/ABI/libcellml/build/tests/gtest ../src/libcellmld.so.0.1.0 gtest/libgtest_main.so /usr/lib/x86_64-linux-gnu/libxml2.so gtest/libgtest.so -lpthread

@IdeaHat: that didn't resolve the issue unfortunately, I am still getting the same error
Edit 2
Since the code I am actually trying to compile is [obviously] not that one, I tried to compile this MWE and both GCC and clang link it fine with just cc A.cpp main.cpp.
I am now trying to understand what's the difference between this minimal case and the code that I actually have.

A: I found it. Somewhere in this code base I am not familiar with all classes are marked private by default [as in Windows D:] and after I marked my class public clang could finally link correctly.
Now the plot thickens because with the binaries compiled by clang I see a lot of segfaults in the test suite that are not present when compiled with GCC.
Also, now I have the same question as the one in this thread, except now GCC and clang work fine while MSVC says unresolved external symbol :'( .


text:
Q: Can I perform an http call in proxyToServerRequest method from LittleProxy? I'm implementing a proxy server, which works locally in android app and redirects all http calls from application webView to some secure server, which  return responses back as if it were initial web resource. Responses should be returned back to webView for parsing and processing. Calls redirection was enabled for webView through reflection. I'm using LittleProxy for proxy purposes, and I guess the best place to intercept all requests will be HttpFiltersSourceAdapter, method proxyToServerRequest. So, I've implemented proxy like this:
private void startHttpServer() {

    HttpProxyServerBootstrap serverBootstrap = DefaultHttpProxyServer.bootstrap().
            withManInTheMiddle(new ProxyMitmManager()).
            withAddress(new InetSocketAddress("localhost", port)).
            withFiltersSource(new HttpFiltersSourceAdapter() {

                @Override
                public HttpFilters filterRequest(HttpRequest originalRequest) {
                    return new HttpFiltersAdapter(originalRequest) {

                        @Override
                        public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                            return super.clientToProxyRequest(httpObject);
                        }

                        @Override
                        public HttpResponse proxyToServerRequest(HttpObject httpObject) {

                            Log.d(LOG_TAG, "HttpObject type: " + httpObject.getClass().getName());
                            DefaultHttpRequest req = (DefaultHttpRequest) httpObject;
                            StringBuilder requestBuilder = new StringBuilder();
                            requestBuilder.append(this.originalRequest.getMethod().name()).append(" ");
                            requestBuilder.append(this.originalRequest.getUri()).append(" ");
                            requestBuilder.append(this.originalRequest.getProtocolVersion().text());

                            List<Map.Entry<String, String>> headers = req.headers().entries();
                            Map<String, String> headersMap = new HashMap<>();

                            for (Map.Entry entry : headers) {
                                headersMap.put((String) entry.getKey(), (String) entry.getValue());
                            }

                            try {
                                // here I send data to my secure server and get response
                                my.app.package.HttpResponse httpResponse = sendRequest(requestBuilder.toString(), headersMap);
                                HttpResponse nettyResponse = new DefaultFullHttpResponse(
                                        new HttpVersion(httpResponse.getHttpVersion(), true),
                                        new HttpResponseStatus(httpResponse.getStatusCode(), httpResponse.getStatusMessage()),
                                        Unpooled.copiedBuffer(httpResponse.getBody()));
                                return nettyResponse;
                            } catch (Exception e) {
                                Errors.log(e);
                            }
                            return null;

                        }

                        @Override
                        public HttpObject serverToProxyResponse(HttpObject httpObject) {
                            return super.serverToProxyResponse(httpObject);
                        }

                        @Override
                        public HttpObject proxyToClientResponse(HttpObject httpObject) {
                            HttpObject object = httpObject;
                            return super.proxyToClientResponse(httpObject);
                        }
                    };
                }
            });

    httpServer = serverBootstrap.start();
}

The problem is the following - when i start to load data, couple of requests goes OK, but then in Logcat I see this:
D: 16:20:59.601 [LittleProxy-ClientToProxyWorker-0] DEBUG o.l.p.impl.ClientToProxyConnection - (AWAITING_INITIAL) [id: 0x52573ac7, /127.0.0.1:56972 => /127.0.0.1:48654]: Writability changed. Is writable: false
D: 16:20:59.601 [LittleProxy-ClientToProxyWorker-0] DEBUG o.l.p.impl.ClientToProxyConnection - (AWAITING_INITIAL) [id: 0x52573ac7, /127.0.0.1:56972 => /127.0.0.1:48654]: Became saturated
D: 16:20:59.601 [LittleProxy-ClientToProxyWorker-0] DEBUG o.l.p.impl.ProxyToServerConnection - (DISCONNECTED): Stopped reading
E: 16:20:59.609 [LittleProxy-ClientToProxyWorker-0] ERROR o.l.p.impl.ClientToProxyConnection - (AWAITING_INITIAL) [id: 0x52573ac7, /127.0.0.1:56972 => /127.0.0.1:48654]: Caught an exception on ClientToProxyConnection
   java.lang.NullPointerException: Attempt to invoke interface method 'io.netty.channel.ChannelConfig io.netty.channel.Channel.config()' on a null object reference
    at org.littleshoot.proxy.impl.ProxyConnection.stopReading(ProxyConnection.java:544) ~[na:0.0]
    at org.littleshoot.proxy.impl.ClientToProxyConnection.becameSaturated(ClientToProxyConnection.java:663) ~[na:0.0]
    at org.littleshoot.proxy.impl.ProxyConnection.channelWritabilityChanged(ProxyConnection.java:627) ~[na:0.0]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelWritabilityChanged(AbstractChannelHandlerContext.java:391) ~[na:0.0]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelWritabilityChanged(AbstractChannelHandlerContext.java:373) ~[na:0.0]
    at io.netty.channel.ChannelInboundHandlerAdapter.channelWritabilityChanged(ChannelInboundHandlerAdapter.java:119) ~[na:0.0]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelWritabilityChanged(AbstractChannelHandlerContext.java:391) ~[na:0.0]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelWritabilityChanged(AbstractChannelHandlerContext.java:373) ~[na:0.0]
    at io.netty.channel.ChannelInboundHandlerAdapter.channelWritabilityChanged(ChannelInboundHandlerAdapter.java:119) ~[na:0.0]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelWritabilityChanged(AbstractChannelHandlerContext.java:391) ~[na:0.0]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelWritabilityChanged(AbstractChannelHandlerContext.java:373) ~[na:0.0]
    at io.netty.channel.ChannelInboundHandlerAdapter.channelWritabilityChanged(ChannelInboundHandlerAdapter.java:119) ~[na:0.0]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelWritabilityChanged(AbstractChannelHandlerContext.java:391) ~[na:0.0]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelWritabilityChanged(AbstractChannelHandlerContext.java:373) ~[na:0.0]
    at io.netty.channel.ChannelInboundHandlerAdapter.channelWritabilityChanged(ChannelInboundHandlerAdapter.java:119) ~[na:0.0]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelWritabilityChanged(AbstractChannelHandlerContext.java:391) ~[na:0.0]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelWritabilityChanged(AbstractChannelHandlerContext.java:373) ~[na:0.0]
    at io.netty.channel.DefaultChannelPipeline.fireChannelWritabilityChanged(DefaultChannelPipeline.java:802) ~[na:0.0]
    at io.netty.channel.ChannelOutboundBuffer.incrementPendingOutboundBytes(ChannelOutboundBuffer.java:166) ~[na:0.0]
    at io.netty.channel.ChannelOutboundBuffer.addMessage(ChannelOutboundBuffer.java:121) ~[na:0.0]
    at io.netty.channel.AbstractChannel$AbstractUnsafe.write(AbstractChannel.java:665) ~[na:0.0]
    at io.netty.channel.DefaultChannelPipeline$HeadContext.write(DefaultChannelPipeline.java:1054) ~[na:0.0]
    at io.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:658) ~[na:0.0]
    at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:716) ~[na:0.0]
    at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:651) ~[na:0.0]
    at io.netty.channel.ChannelOutboundHandlerAdapter.write(ChannelOutboundHandlerAdapter.java:104) ~[na:0.0]
    at org.littleshoot.proxy.impl.ProxyConnection$BytesWrittenMonitor.write(ProxyConnection.java:754) ~[na:0.0]
    at io.netty.channel.AbstractChannelHandlerContext.invokeWrite(AbstractChannelHandlerContext.java:658) ~[na:0.0]
    at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:716) ~[na:0.0]
    at io.netty.channel.AbstractChannelHandlerContext.write(AbstractChannelHandlerContext.java:651) ~[na:0.0]
    at io.netty.handler.codec.MessageToMessageEncoder.write(MessageToMessageEncoder.java:127) ~[na:0.0]
    at io.net

So, my content is not visible in webView, and there are 504 Bad gateway errors in logs appeared.
If I remove http calls to my server, everything works fine. Does anybody have ideas about it? Maybe I shouldn't send http requests to my server in proxyToServerRequest method? If so, where exactly I should do this?


text:
Q: copying portions of (date) data from one column and pasting into separate columns in Tidyverse I am trying to extract the year, month, and day from a single column ("SightDate") and put them into their own respective columns ("Year", "Month", and "Day") in a df. I used the lubridate bookdown (https://wrangle-r.rsquaredacademy.com/lubridate.html ch.9.8) to figure this out using the year(), month(), and day() functions, but it did not seem to work. I made sure the my SightDate column is a date data object and I still get 0 values for my year, month, and my new day column doesn't generate. I don't get an error, but a tibble output describing my df instead... I was wondering if someone can help me figure out why/what's missing in my code (below):
library(tidyverse)
library(lubridate)
library(hms)

HB_data %>%
    mutate(Year = year(SightDate),
           Month = month(SightDate),
           Day = day(SightDate))

Here is some sample data:
# A tibble: 6 x 4
  RecordID SightDate   Year Month
     <dbl> <date>     <dbl> <dbl>
1    90064 2014-09-26     0     0
2    14333 2008-05-21     0     0
3   108894 2016-09-14  2016     9
4    19189 2009-09-29     0     0
5   118354 2017-09-23     0     0
6   117509 2017-07-04     0     0

And this is the data:
dput(SampleData, control = NULL)
list(c(38268, 115078, 96837, 34724, 118239, 120346, 49706, 95571,
48824, 136498), c(14888, 17466, 16802, 14530, 17411, 17699, 15615,
16711, 15568, 18060), c(0, 0, 0, 2009, 0, 0, 0, 0, 0, 0), c(0,
0, 0, 10, 0, 0, 0, 0, 0, 0))

Thank you in advance for your time and help!


text:
Q: Get the value of the next table cell onclick javascript I am trying to get the value of the cell right of the cell where i click.
But right now I get the value of the cell I want, but I can click any cell in that row and get the desired value. But it should only be possible with the first column. So I click the any cell in the first column and I wanna get it's next neighbour cell value.
document.querySelector("#tableEventListId").addEventListener("click",event => {
        let dataTr = event.target.parentNode;
        let deleteEventId = dataTr.querySelectorAll("td")[1].innerText;
        console.log(deleteEventId);
        alert(deleteEventId);

Any help?

A: You can use nextElementSibling

document.getElementById('table1').onclick = function(event){
  //REM: Target
  var tElement = event.target;

  if(
    //REM: Only cells (=)
    tElement.tagName === 'TD' &&

    //REM: Only first column cells
    tElement.parentNode.firstElementChild === tElement
  ){
    //REM: Next Elementsibling of Target or Null
    var tNext = tElement.nextElementSibling;

    if(tNext){
      console.log('TD: ', tElement.textContent);
      console.log('Next: ', tElement.nextElementSibling.textContent)
    }
  }
}
table, td{
  border: 1px solid black
}

      A
      B
      C

      A1
      B1
      C1

      A2
      B2
      C2

      A3
      B3
      C3

A: There is no HTML, so I can assume it's something like

    1.1 (click here)
    1.2
    1.3

    2.1 (click here)
    2.2
    2.3

According to this HTML, you can try
const firstColumns = document.querySelectorAll(".first-column");

 for (let i = 0; i < firstColumns.length; i++) {
     firstColumns[i].addEventListener("click", function(event) {
        let dataTr = event.target.parentNode;
        let deleteEventId = dataTr.querySelectorAll("td")[1].innerText;

        console.log(deleteEventId);
        alert(deleteEventId);
     });
 }

Have a look https://jsfiddle.net/vyspiansky/k2toLd8w/

A: I would recommend you to a an event on every td element of the table. Then use nextElementSibling to get a next cell.
Look code snippet to see the example.

    const cells = document.querySelectorAll('#tableEventListId td');
    cells.forEach(cell => cell.onclick = function(){
        const nextCell = cell.nextElementSibling;
        if (nextCell)
            alert(nextCell.innerHTML);
    })

      1
      2
      3
      4

      11
      22
      33
      44

      111
      222
      333
      444

      1111
      2222
      3333
      4444

If you want it to work only for cells at first column change the selector to #tableEventListId td:first-child.


text:
Q: How do I map a deeply nested array object? In React, I have a deeply nested array (see photo) I need map over this array and retrieve the name and language which I have! but I also need to go deeper into articles and to retrieve the name, pageSlug, templates and title and then into content and retrieve data from there. How do I this in react without it getting messy?
State:
state var:
this.state = {
   data: []
 };

the api call:
getKnowledgePageCategories(this.props.locale).then(
      (response) => {
        this.setState({data: response})
    });

Array object

What I have and what works for the name prop only:
{data && (
    Object.keys(data).map((key, index) => {
     return (
           <ButtonGroup
             key={`${data[index].fields.name}--key`}
             name={data[index].fields.name}
             articles={}
            />
           )
         })
      )}

articles prop expects an object so I need to pass all the data from "fields" within the "articles".

A: You just have to map articles since that's an array:
<ButtonGroup
  key={`${data[index].fields.name}--key`}
  name={data[index].fields.name}
  articles={data[index].fields.articles.map(article => article.fields)}
/>

Also, it looks like data is an array not an object. So no need to use Object.keys with it. You should be able to simply do data.map(...


text:
Q: why my routeprovider not working? I am learning routing with angular java script ,
this is my index.html

.....

Create Event

    <ng-view></ng-view>

This is my app.js,
var eventsApp = angular.module('eventsApp', ['eventsApp', 'ngRoute'])
    eventsApp.config(function($routeProvider) {
        $routeProvider.when('/newEvent',
            {
                templateUrl:'templates/NewEvent.html',
                controller: 'EditEventController'
            }).....

When i click on the button it  do nothing and also doesn't load new event .
and get this error
 "Error: [$injector:modulerr] Failed to instantiate module eventsApp due to:"

here is the controller
'use strict';

eventsApp.controller('EditEventController',
    function EditEventController($scope, eventData) {

        $scope.event = {};

        $scope.saveEvent = function (event, form) {
            if(form.$valid) {
                eventData.save(event);
            }
        };

        $scope.cancelEdit = function () {
            window.location = "/EventDetails.html";
        };

    }
);

A: One of the things I'm noticing looks wrong is that you're passing in eventsApp as a dependency of itself.
var eventsApp = angular.module('eventsApp', ['eventsApp', 'ngRoute'])

Should be:
var eventsApp = angular.module('eventsApp', ['ngRoute'])

Secondly, you may want to check that you've included ngRoute into the page:
See installation instructions here: http://docs.angularjs.org/api/ngRoute
Check out a working example on Plunkr:
http://plnkr.co/edit/VZgTnBvi0Q8qtcpOUTx0


text:
Q: Python: Import other python files while running from web interface I am running python scripts called from php in an apache server. If I want to import a python file from the same / a different folder, how to do that? My apache server is running in one directory, but the python code is in a different directory. So how can I relate these two dir structures?
I have commonly using variables with values in the file to be imported(say file2.py).
+ apacheFolder
| folder1
| +folder2
  |- index.html
  |+ pythonFileDir
     |-__init__.py
     |-file1.py
     |-file2.py
     |-file3.py

I tried doing following import command in file1.py,
import file2

But this doesn't help me.
I am calling file1.py from the php file as,
shell_exec("[pythonInstallDir]/python.exe [pythonFileDir]/file1.py arg1 arg2");

This php is in turn called by html form action trigger.

A: Try putting an __init__.py in the pythonFileDir first and try again.  Depending on where you are initially calling file1.py from might alter how file2.py is called as well.  You may need to call file2.py with from pythonFileDir import file2
The reason why file1.py is called but can't find file2.py is due to how the file1.py is being called.
shell_exec("[pythonInstallDir]/python.exe [pythonFileDir]/file1.py arg1 arg2");

file1.py will try to find file2.py from the same directory that executes your shell_exec (most likely the PHP path or the web directory in which it is called from) so file2.py is being searched for in a completely different directory (far away from pythonFileDir).
You could try to change your directory with the shell_exec call with this:
shell_exec("cd [pythonFileDir]; [pythonInstallDir]/python.exe file1.py arg1 arg2");

That way you will actually be executing from inside the pythonFileDir and there won't be any problem finding file2.py
So a full example would be:
shell_exec("cd c:\path\to\pythonFileDir; [pythonInstallDir]/python.exe file1.py arg1 arg2");
or you could try this to force PHP to change the directory instead of doing it all within the shell_exec() command:
chdir( 'C:\path\to\pythonFileDir' );
shell_exec("[pythonInstallDir]/python.exe file1.py arg1 arg2");

A: As @sth asked and Max Worg already mentioned. I'm not sure how you call the file1.py from php but you could try adding the python directory to your python path?
In file1.py
import sys
# either absolute or relative path to pythonFolderDir in file1.py
sys.path.append('/home/user/apacheFolder/folder2/pythonFolderDir');
import file2.py

I don't think this is a good idea but that'd be one way to relate your directories.

A: You can build the webserver by implementing socket in Python. You have a class that spawns a thread that is a listener, and a thread that holds the other python objects. From there, you can have the object thread re-import when it detects changes in the files in the directory that you can specify in the class. You just put a while loop in there that uses os.listdir, and you can either hash the files, or just see if they simply increase, that is up to you. Now you have something that can communicate over the network, and that reloads modules for you.


text:
Q: How to fix this database (Flask) problem on heroku? The app works perfect locally. I hosted the app on heroku, it works - only something with the database (connection of heroku db to my app?) fails.
I already tried some options, but nothing helped, because I am not really sure, what exactly the root of the problem is.
Problem
That's what I get:
500 Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
Logs
Here are the important lines of the logs:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL:  password authentication failed for user "rjgrfkdjglwftp"

And:
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "users" does not exist

Do I have to push the locally created database too?
It is important to know, that there are no problems locally, so it has something to do either with database or the code on heroku, I am not sure.
DB-Connection Logic:
class Config(object):
    DEBUG = False
    TESTING = False
    CSRF_ENABLED = True
    SECRET_KEY = 'this-really-needs-to-be-changed'
    SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']


text:
Q: Como descobrir o endereço git de um repositorio já criado? Comecei a trabalhar agora e a empresa usa o git para atualizar seu sistema, mas estou sozinho no departamento de ti como eu consigo o endereço desse repositorio já tentei pegar o msm endereço que utilizo para o git clone e aparece o seguinte erro

A: Você pode utilizar de duas maneiras para conseguir o endereço:

*

*Executar comando abaixo:

$ git remote -v

*Abre o arquivo de configuração no diretório .git:

$ cd .git
$ more config

Uma das duas soluções vai resolver seu problema.


text:
Q: WSDL URL is accessible from browser but not from java program I have a web service running on a remote server and I wrote a client program to consume its services. The client program uses client stubs that were generated from a .wsdl file using the wsimport command. I am accessing the server via a proxy and in my program I tell the JVM to communicate via the proxy by setting the system properties "proxySet", "proxyPort" and "proxyHost", to true, and the corresponding port and address of the proxy respectively; which works fine. In addition, I'm also connecting via SSL, and the server certificate is signed by some other CAs, and in my case I needed to import the certificate to the trustore cacerts; which also works well. However I am not able to access the web service with the URL I specify in my program, though it can be accessed with a browser. below is the stack trace of my program:
    com.sun.xml.internal.ws.wsdl.parser.InaccessibleWSDLException: 2 counts of InaccessibleWSDLException.

    java.io.IOException: Server returned HTTP response code: 500 for URL:     https://webservicesimp.companyName.com/ReportingService
    java.io.FileNotFoundException: https://webservicesimp.companyName.com/ReportingService?wsdl

at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.tryWithMex(Unknown Source)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(Unknown Source)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(Unknown Source)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(Unknown Source)
at com.sun.xml.internal.ws.client.WSServiceDelegate.parseWSDL(Unknown Source)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(Unknown Source)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(Unknown Source)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(Unknown Source)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(Unknown Source)
at com.sun.xml.internal.ws.spi.ProviderImpl.createServiceDelegate(Unknown Source)
at javax.xml.ws.Service.<init>(Unknown Source)
at com.conpanyName.xml.companyName.enterprise.report.v1.enterprisereportingservice_1.ReportingService.<init>(ReportingService.java:50)
at WebServices.<init>(WebServices.java:33)
at ERSWebServiceRunner.main(ERSWebServiceRunner.java:37)

Any help is appreciated... Thanks


text:
Q: Bind over the observableList in JavaFx I have a entity of some datasource. It has List of object Pojo.  It can be get by ds.getRows().
I'm trying to bind TableView on this list very hard.
tblHlp.itemsProperty().bindBidirectional(new SimpleListProperty<>(FXCollections.observableArrayList(ds.getRows())));

When I change that ObservableList  which I created FXCollections.observableArrayList(ds.getRows())) tableView is changed too. But I want to get the same effect when I change List in ds  (ds.getRows). Any ideas?

A: I don't think you can do it like that.
What you can do is to add a ListChangeListener on the ObservableList you created and then manage manually the items to add/remove in your other list. For example something like that:
ListChangeListener<Object>() {

    @Override
    public void onChanged(javafx.collections.ListChangeListener.Change<? extends Object> change) {
        while (change.next()) {
           //If items are removed
           for (Objectremitem : change.getRemoved()) {
               unfixColumn(remitem);
           }
           //If items are added
           for (Objectadditem : change.getAddedSubList()) {
               fixColumn(additem);
           }
        }
        updateHighlightSelection();
    }
};

Don't forget to take a look at the Javadoc here : http://download.java.net/jdk8/jfxdocs/javafx/collections/ObservableList.html
And how to use JavaFX collections here :  http://docs.oracle.com/javafx/2/collections/jfxpub-collections.htm


text:
Q: Ionic: Error Initializing Cordova class not found I have added config file in res folder of my ionic project.
This is the content:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<widget id="io.cordova.hellocordova" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
  <preference name="loglevel" value="DEBUG"/>
  <preference name="AndroidPersistentFileLocation" value="Internal"/>
  <preference name="SplashScreen" value="screen"/>
  <preference name="SplashScreenDelay" value="3000"/>
  <plugin name="Device" value="org.apache.cordova.Device"/>
  <feature name="Whitelist">
    <param name="android-package" value="org.apache.cordova.whitelist.WhitelistPlugin"/>
    <param name="onload" value="true"/>
  </feature>
  <feature name="Camera">
    <param name="android-package" value="org.apache.cordova.camera.CameraLauncher"/>
  </feature>
  <feature name="File">
    <param name="android-package" value="org.apache.cordova.file.FileUtils"/>
    <param name="onload" value="true"/>
  </feature>
  <allow-intent href="market:*"/>
  <allow-intent href="*"/>
  <allow-intent href="tel:*"/>
  <allow-intent href="sms:*"/>
  <allow-intent href="mailto:*"/>
  <allow-intent href="geo:*"/>
  <name>HelloCordova</name>
  <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
  <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
  <content src="index.html"/>
  <access origin="*"/>
  <allow-navigation href="*"/>
  <platform name="android">
    <icon src="resources/android/icon/drawable-ldpi-icon.png" density="ldpi"/>
    <icon src="resources/android/icon/drawable-mdpi-icon.png" density="mdpi"/>
    <icon src="resources/android/icon/drawable-hdpi-icon.png" density="hdpi"/>
    <icon src="resources/android/icon/drawable-xhdpi-icon.png" density="xhdpi"/>
    <icon src="resources/android/icon/drawable-xxhdpi-icon.png" density="xxhdpi"/>
    <icon src="resources/android/icon/drawable-xxxhdpi-icon.png" density="xxxhdpi"/>
    <splash src="resources/android/splash/drawable-land-ldpi-screen.png" density="land-ldpi"/>
    <splash src="resources/android/splash/drawable-land-mdpi-screen.png" density="land-mdpi"/>
    <splash src="resources/android/splash/drawable-land-hdpi-screen.png" density="land-hdpi"/>
    <splash src="resources/android/splash/drawable-land-xhdpi-screen.png" density="land-xhdpi"/>
    <splash src="resources/android/splash/drawable-land-xxhdpi-screen.png" density="land-xxhdpi"/>
    <splash src="resources/android/splash/drawable-land-xxxhdpi-screen.png" density="land-xxxhdpi"/>
    <splash src="resources/android/splash/drawable-port-ldpi-screen.png" density="port-ldpi"/>
    <splash src="resources/android/splash/drawable-port-mdpi-screen.png" density="port-mdpi"/>
    <splash src="resources/android/splash/drawable-port-hdpi-screen.png" density="port-hdpi"/>
    <splash src="resources/android/splash/drawable-port-xhdpi-screen.png" density="port-xhdpi"/>
    <splash src="resources/android/splash/drawable-port-xxhdpi-screen.png" density="port-xxhdpi"/>
    <splash src="resources/android/splash/drawable-port-xxxhdpi-screen.png" density="port-xxxhdpi"/>
  </platform>
  <plugins>
    <plugin name="Device" value="org.apache.cordova.Device"/>
</plugins>
</widget>

It is also added in the root folder of my ionic project
I have also added Content Security Provider to my index.html and this is the content:
<meta charset="utf-8">
  <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">

I have also added and removed android platforms but when I run my app I get ERROR Initialing Cordova: Class not found. My solution also founds it dificult accessing the internet.
Come to my rescue.

A: This is my solution:
cordova platform rm android

Thereafter I installed a new cordova
npm install -g cordova

Thereafter I added a new platform
cordova platform add android

Then added all my plugins with the command
cordova plugin add (plugin name)

I also ensured that config.xml is in my res/xml folder.
Then I was good to go!!!!

A: I had the same error on ubuntu.
I had to change the permission on Cordova executable :
which cordova
/user/local/bin/cordova
sudo chown my_user /user/local/bin/cordova


text:
Q: Why does Mathematica list the variables in a double integral backwards? I am an advanced novice Mathematica user and have done a fair amount of single-variable calculus things with it.  This semester I am using Mathematica for multi-variate calculus and when I tried to use Mathematica to solve a double integral I got incorrect results.  I discovered that the syntax for the Integrate command has you list the variables in the opposite order they appear in the integrand.  At first blush this seems dumb and annoying but perhaps there is a good reason for it.  If so, I'd like to know what it is.  If not, is anyone else annoyed by this?

A: This ordering is used in all functions in Mathematica, not just Integrate.
Here's an example with Table:
In[1]:= Table[f[i, j], {i, 3}, {j, 4}]
Out[1]= {{f[1, 1], f[1, 2], f[1, 3], f[1, 4]},
         {f[2, 1], f[2, 2], f[2, 3], f[2, 4]},
         {f[3, 1], f[3, 2], f[3, 3], f[3, 4]}}

The inner loop is according to j, the outer according i.
In[2]:= Dimensions[%]
Out[2]= {3, 4}

Looking at the dimensions it starts to make some kind of sense for Table.  Even more if I write it like this:
In[3]:= Table[0, {3}, {4}]
Out[3]= {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}

Which I could replace by
In[4]:= ConstantArray[0, {3, 4}]
Out[4]= {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}

Now for ConstantArray it makes perfect sense: if I want an array with dimensions {3,4}, I'll write {3,4} in ConstantArray.
It also makes sense to make all these functions consistent with each other, so you never have to think about which convention a particular function uses: they all use the same.
In the end of course it is just a convention, and I don't think that this particular convention is better than others.  I just wanted to point out that it does make sense, as it's consistent with the rest of the system: Integrate, Sum, Table, RandomReal, etc. all work the same way.


text:
Q: Is a coherent locally free sheaf isomorphic it's dual? Hartshorne chapter II problem 5.1 a) is to prove that the double dual of a coherent locally free sheaf $\mathscr{E}$ over a ringed space $(X,O_X)$ is isomorphic to $\mathscr{E}$.  This can be done by defining an analog of the evaluation map and showing it is an isomorphism on a cover of open sets on which $\mathscr{E}$ is free.
Now we can apply the non-canonical isomorphism of free modules of finite rank with their dual locally to see that there is a cover by open sets under which the restriction of $\mathscr{E}$ and the dual of $\mathscr{E}$ are isomorphic.  However, I believe the general philosophy is that maps which are canonical patch together to form morphisms of sheaves while maps that are not canonical don't necessarily patch together.  So in the case of coherent locally free sheaf and it's dual, do the local isomorphisms not patch together in general?

A: As Jesko says, already for line bundles there are problems. The easiest example is probably $\mathscr{O}_{\mathbf{P}^n_k}(1)$ and its dual $\mathscr O(-1)$. The first has lots of nonzero global sections, but the second has none; they can't even be non-canonically isomorphic.
One interesting thing to think about, which I saw pointed out in a book review by Kollár, is that in differential geometry one can choose a metric on any vector bundle and use that to identify $E \simeq E^\vee$. So this is a good example of how algebraic geometry differs.


text:
Q: pytest not discovering test in pyDev I'm trying to build and run  (selenium which is not relevant)  test-suite with pytest framework.
I wrote a simple test as follows
class test_pqr():

    def test_lmn(self):
        print("AAAAAAAAAAAAAAAAAAAAA")
        assert True

    def test_xyz(self):
        assert False

x= test_pqr()
x.test_lmn()

when I run it I got result...

if I run xyz as well... eg
    class test_pqr():

        def test_lmn(self):
            print("AAAAAAAAAAAAAAAAAAAAA")
            assert True

        def test_xyz(self):
            assert False

    x= test_pqr()
    x.test_lmn()
    x.test_xyz()

get results as...
what dose

imported unittest before running pytest.main

error means?
why can't it discover test?

collected 0 items

why are methods run only when there is error?

A: After a long search and trial and error found the culprit.
You should name class Test_*..

T in  UPPER CASE for Class

t in lower case for methods...
though tests are running as supposed, the error remains...


text:
Q: CMYK and RBG in one document Imagine the PDF file that you create from the tex sources has to have all colors defined in RGB because the PDF is meant to be read on screen.
One would do:
\xdefinecolor{colordef-listings-backgroundcolor-grey}{RGB}{219, 219, 219}

What if you ALSO want the same document to be printed, while printing is done in CMYK. You would have to do:
\xdefinecolor{colordef-listings-backgroundcolor-grey}{cmyk}{0.0, 0.0, 0.0, 0.14}

How do I get both into one PDF? Or how to I "conveniently" create one or the other?

A: Package xcolor allows one to write

\definecolor{red}{rgb/cmyk}{1,0,0/0,1,1,0} % an example in manual

after
\usepackage[rgb]{xcolor} % or
\usepackage[cmyk]{xcolor}

So you may compile twice with rgb or cmyk loaded alternatively. See the subsection Multiple models and specifications for more information.
And as a remark, I am afraid a PDF file cannot recognize whether the target device is a screen or a printer. But I wonder why you want/need to convert color model by hand. Are you going to choose colors on color guides?


text:
Q: Moodle - extending an existing plugin I would like to add a functionality to the existing forum plugin. The functionality I want is that I can select a published date when creating a post in a forum. When I select a date a week in the future, the post will be published (and shown to the user) a week in the future.
I think the following need to happen:

*

*Add a published_date field to table mdl_forum_posts

*Change query that shows the posts in the forum (select posts where published date is in the past)

*Change cron that sends notifications of forum posts (that
only published posts will be sent)

Now I'm wondering if there's already a plugin that provides this functionality. I've searched in plugins but couldn't find any with this functionality.
And how can I code this functionality? I don't think it's good to overwrite the core code of the plugin. How can I extend this plugin with clean structure/code?
Can you help me on my way?

A: The only way to add that functionality directly into the forum without changing the core code would be to make a complete copy of the forum module, rename it and then add your functionality to the copy (users would have to switch to this new version of the forum).
In my experience, doing that will result in much more future maintenance problems than making small, careful core changes (then using git rebase to merge the changes in the future).
The alternative might be a separate plugin that allows you to enter a post + a date and which will insert that post into the forum activity at the scheduled time (this could be in the form of a block, on the side of the page, or a local plugin that inserts a link into the forum settings, then takes you off to a separate page to do the scheduling).


text:
Q: chicken egg problem I should run a test to determine whether variable A affect variable B or viceversa.
What type of test should I use?
Imagine that we measure the time slept per night (A) and the activity performed during a day (B) in several subjects. In particular we have a median of 4 nights and 4 days measured for each subject.
How would you approach the problem?
1) estimate how much the night (A) is correlated with the following day (B)
2) estimate how much the day (B) is correlated with the following night (A+1)
3) take the highest correlated condition

Is there a test that takes into account this situation?
Thanks


text:
Q: How to remove the time in report viewer I`m using datetimepicker control in my system and the format is short. My problem is whenever I insert a data in database and see it in a microsoft report viewer the time is showing (12:00:00 AM). I want to ask how to remove that time in report?
btw im using visual studio 2008 and mc access

A: You could change that TextBox properties on reportviewer in design time.
Right Click → Properties → Number → Date


text:
Q: Jar Runnable with external library - Eclipse I have created a small program using Java and openCV. Now I want to export this to Runnable Jar. Is there a way for me to make Runnable Jar with Java and openCV library using Eclipse

A: In order to include native libraries in an executable java program you need to specify it at the moment of executing a jar. For example:
java -Djava.library.path="<path_to_opencv>/opencv/build/lib" -jar FaceDetection.jar


text:
Q: Mute all  elements with jQuery Description of Problem (Fiddle):
I'm attempting to iterate over all  elements on a page and mute them with jQuery. Does jQuery just not play nice with HTML5 audio or is there a better approach?
Code:
$('#sound1').click(function() {
    var sound1 = new Audio();
    sound1.src = "http://sounddogs.com/previews/4006/mp3/209105_SOUNDDOGS__up.mp3"
    sound1.play();
});

$('#sound2').click(function() {
    var sound2 = new Audio();
    sound2.src = "http://sounddogs.com/previews/4023/mp3/210622_SOUNDDOGS__do.mp3"
    sound2.play();
});

$('#mute').click(function() {
    $('audio').each(function(i) {
        this.volume = 0;
    });
});

A: Use volume control on played music objets something like this
DEMO
Update
You can create the array tracks[] and store the played audios into this, and and mute all this audios when clicked on mute. something like this.
var tracks = [];
$('#sound1').click(function() {
    sound1 = new Audio();
    sound1.src = "http://sounddogs.com/previews/4006/mp3/209105_SOUNDDOGS__up.mp3"
    sound1.play();
    tracks.push(sound1);
});

$('#sound2').click(function() {
     sound2 = new Audio();
    sound2.src = "http://sounddogs.com/previews/4023/mp3/210622_SOUNDDOGS__do.mp3"
    sound2.play();
    tracks.push(sound2);
});

$('#mute').click(function() {
    for(var i=0; i<tracks.length; i++){
        tracks[i].volume = 0;
    }
});


text:
Q: Quadratic inequality with boundaries Here is a very old high school exam question I am trying to solve (purely for interest only):
If $a,b,c$ are real numbers such that $-1 \le ax^2+bx+c \le 1$ for $-1 \le x \le 1$ prove that $-4 \le 2ax+b \le4$ for $-1 \le x \le 1$ (Hint: Consider the functions at the end-points and at the mid-point of the interval).
I can see (graphically) that if $a>0$ then, as $2ax+b$ is the gradient function, the max and min gradients will occur when the parabola passes through the end-points $(-1,1)$ and $(1,1)$ and the mid-point $(0,-1)$. This gives 3 equations with 3 unknowns and is solved to give $a=2, b=0$ and $c=-1$. The required result follows easily from this. Due to symmetry, a<0 gives the same result.
Can someone please help turn my "partial" solution into a more convincing/algebraic solution.

A: We can show the required inequlity in an entirely algebraic manner:
We first note that by setting $x=0$ in our initial inequality we get:
$$-1\le c\le1 \\ |c|\le1.$$
If we set $x=\pm1$ in our given inequality we will get:
$$
\text{(i)}\;\;-1\le a+b+c\le 1 \;\;\;\text{and}\;\;\;\text{(ii)}\;\;-1\le a-b+c\le 1.
$$
Adding these two inequalities together will give us:
$$
-2\le 2a+2c\le2 \\
-1\le a+c\le1 \\
-2\le-c-1\le a\le-c+1\le2 \\
|a|\le2.
$$
Thus, considering only $-1\le x\le1$, we see that if $a\gt 0$ then:
$$2ax+b \;\le\; 2a+b \;=\; a+b+c + (a-c)\;\le\;1 + (a-c) \;\le\;1+1+2\;=\;4,$$
and
$$-4 \;=\; -2-1 -1\;\le\; (-a+c) - 1\;\le\; (-a+c) - a+b-c\;\le\; -2a+b \;\le\;2ax+b.$$
Similarily, if $a\lt0$ then:
$$2ax+b \;\ge\; 2a+b \;=\; a+b+c + (a-c)\;\ge\;-1 + (a-c) \;\ge\;-1-1-2\;=\;-4,$$
and similarily:
$$4 \;=\; 2+1 +1\;\ge\; (-a+c) + 1\;\ge\; (-a+c) - a+b-c\;\ge\; -2a+b \;\ge\;2ax+b.$$


text:
Q: Always Selecting the Else Statement in Spinner I am trying to set the text of textView according to the item selected in the spinner. But it is always showing the value of the else statement. Can someone please help me in solving this.
The code is given below.
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String[] names = {"Shashank","Abhijay"};
        String[] state_array = {"Select City","Bangalore","Jaipur"};
        setContentView(R.layout.activity_main);
        Spinner spinner_state = (Spinner)findViewById(R.id.spinner1);
        spinner_state.setAdapter((SpinnerAdapter) new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1,
                    state_array ));

        if(spinner_state.equals(state_array[1]))
        {
        TextView candi_name = (TextView) findViewById(R.id.CandidateName);
        candi_name.setText(names[0]);
        }
        if(spinner_state.equals(state_array[2])){
            TextView candi_name = (TextView) findViewById(R.id.CandidateName);
            candi_name.setText(names[1]);
        }
        else{
            TextView candi_name = (TextView) findViewById(R.id.CandidateName);
            candi_name.setText(" ");
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

A: use onItemSelectedListener
spinner_state.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
    // your code here
}

@Override
public void onNothingSelected(AdapterView<?> parentView) {
    // your code here
}

});

A: Please replace your spinner if condition with:
 // your code above...
if(spinner_state.getSelectedItem().toString().equals(state_array[1]))
    {
    TextView candi_name = (TextView) findViewById(R.id.CandidateName);
    candi_name.setText(names[0]);
    }
    if(spinner_state.getSelectedItem().toString().equals(state_array[2])){
        TextView candi_name = (TextView) findViewById(R.id.CandidateName);
        candi_name.setText(names[1]);
    }
    else{
        TextView candi_name = (TextView) findViewById(R.id.CandidateName);
        candi_name.setText(" ");
    }
 //your code below

A: You need to onItemSelectedListener() to catch selected spinner item. After spinner initialization add below code and delete if/else statements:
spinner_state.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        if(spinner_state.getSelectedItem().toString().equals(state_array[1]))
        {
            TextView candi_name = (TextView) findViewById(R.id.CandidateName);
            candi_name.setText(names[0]);
        }
        if(spinner_state.getSelectedItem().toString().equals(state_array[2]))
        {
            TextView candi_name = (TextView) findViewById(R.id.CandidateName);
            candi_name.setText(names[1]);
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parentView) {
        TextView candi_name = (TextView) findViewById(R.id.CandidateName);
                candi_name.setText(" "); }

        });


text:
Q: French characters with rewrite rule I have categories name in my database, and some of theme have french characters like é è ê.
It works as desired until today when I tried to add another character à to it then I started getting SERVER ERROR
Here is my .htaccess:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^([A-Za-z0-9éèêà_-\s]+)-(\d+)\.htm$   classified.php?id=$2 [L]

As you can see, it works fine without the à.
How do I add that thing into the regex ?

A: Seems like extended ASCII characters in URL are sent as UTF-8 and url-encoded. For example:
/éèêà-1.htm -> /%C3%A9%C3%A8%C3%AA%C3%A0-1.htm

The above URL can be matched by mod_rewrite like this:
RewriteEngine On
RewriteRule ^(?:\w|\xC3\xA9|\xC3\xA8|\xC3\xAA|\xC3\xA0)+-(\d+)\.htm$ classified.php?id=$1 [L]

A: If you are using all sort of characters and accented letters, then why don't just allow anything to go by?
NOTE: Using this Rule will also allow spaces;
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)-(\d+)\.htm$   classified.php?id=$2 [L]

And later if you decide to limit the regex, lets say you don't want any of these characters # $ % then you have to make exceptions:
   Options +FollowSymlinks
  RewriteEngine on
  RewriteRule ^([^#$%]+)-(\d+)\.htm$   classified.php?id=$2 [L]


text:
Q: Determining if the limit of a series is differentiable Suppose I have $F:D \rightarrow \mathbb{R}$ where $F$ uniformly converges to a continuous function f on D. My goal is to determine whether or not f is differentiable on D.
For a concrete example, let's say $F(x) = \sum_{n=1}^{\infty} x^n/(n^3)$. We can use the M-test to see that F is uniformly convergent on $D = [-1,1]$. My goal is to tell if f (the limit of F) is differentiable on $[-1,1]$. Does it suffice to show that $F'(x) = \sum_{n=1}^{\infty} x^{n-1}/(n^2)$ converges uniformly on D?
My textbook offers the following theorem: "Let $f_n$ be differentiable functions defined on an interval D. Assume that $\sum_{n=1}^{\infty} f'_n(x)$ converges uniformly to a limit $g(x)$ on D. If there exists a point $c\in D$ where $\sum_{n=1}^{\infty} f_n(c)$ converges, then the series $\sum_{n=1}^{\infty} f_n(x)$ converges uniformly to a differentiable function $f(x)$ satisfying $f'(x) = g(x)$ on D."
So I guess my question boils down to: Since I already know $F(x)$ to be uniformly convergent, do I still need to find an explicit $c \in [-1,1]$ such that $F(c)$ converges in order to say that f is differentiable on D?


text:
Q: while loop shell script I have written a Linux (bash) shell script using while loop and I kept sleep command to execute the script for every 60 sec and the output is redirected to other file. After few hours I stopped the script and it doesn't stop executing and I deleted the script still it is running and the output file is updated every 60 seconds. I could see sleep command in the process running by Linux. I tried to kill the PID of sleep using kill -9 PID command. No use. It is in my production server.can some one help out. How should we stop the execution of script.

A: It may be running in the background:
       $ jobs
       [1]+  Running                 sleep 100 &

       $ kill %1
       [1]+  Terminated              sleep 100

You can also use pkill and pgrep
Use killall to stop all of the instances.

A: Try to use 'ps -ef | grep your script name' to find the pid of your task. Then use 'kill -9 your pid' to kill the process.

A: The sleep command is invoked by your script. If you kill the sleep command the script advances to the next command. You need to look at the parent pid (PPID) of the sleep command using ps for instance. Then look for the corresponding parent pid (PPID) and kill the process that belongs to that PID
ps -ef |(head -1; grep sleep)
UID        PID  PPID  C STIME TTY          TIME CMD
lambert   4062  4041  0 08:47 pts/3    00:00:00 sleep 5

ps -p 4041
  PID TTY          TIME CMD
 4041 pts/3    00:00:00 myscript.sh

kill 4041


text:
Q: Winforms MouseEventArgs - How can I get a click modifier like control-click or alt-click? I'm trying to figure out if it's possible to detect if a combobox was clicked by control click. Using Winforms.
If I just try capturing MouseEventArgs I don't see any modifiers.
Any ideas?

A: This seems to work in any event method.
    if (Control.ModifierKeys = Keys.Control) Then
        Debug.WriteLine("Ctrl+Click")
    end if


text:
Q: Multiple Windows or Tabs in React-Admin We are using react-admin for a back-office application.
We need to let user to open multiple tabs (similar to chrome tabs, but within the app) and navigate in each tab in different pages. So user can open new sessions without using the previous ones.
Is there a way to do it with react-admin?


text:
Q: How to handle errors in GRequests? I have this code
#!/usr/bin/python

import grequests

urls = [
'http://google.com',
'http://doesnotexists.tld'
]

def do_something(response, **kwargs):
        print response.text

async_list = []

for u in urls:
    action_item = grequests.get(u, timeout=10, hooks = {'response' : do_something})
    async_list.append(action_item)

grequests.map(async_list,size=10)

How do I handle errors without getting usual Python error messages?
For example for domain which does not exists it prints out "not found".

A: It seems that grequests installed from pypi (with pip) doesn't include exception handling. But the version from github has implemented that feature:
def map(requests, stream=False, size=None, exception_handler=None)

So you should clone grequests or download grequests.py from github and use that version. You can directly install that version with pip:
pip install git+https://github.com/kennethreitz/grequests.git

If you're looking for exception handling examples you could have a look at the test.py in the repository. https://github.com/kennethreitz/grequests/blob/master/tests.py

A: This has been fixed with the latest release of grequests - https://github.com/kennethreitz/grequests


text:
Q: Is my calculation of third order derivative correct? I need to find the third order derivative of $\frac{1}{s+3}$. I know that I need to calculate the derivative of the derivative till I get to the desired order.
So, here are my answers:
First-order derivative: $\frac{-1}{(s+3)^2}$
Second-order derivative: $\frac{2(s+3)}{(s+3)^3}$
and Third-order derivative: $\frac{4}{(s+3)}$
Can someone please confirm my calculations ? :)
How I calculated the second-order derivative:
$\frac{(s+3).0 + (1)2(s+3)(1)}{(s+3)^2}$

A: Your first derivative is fine, but after that you went astray. The easiest way to do the computations is to write $f(s)=(s+3)^{-1}$ and apply the power rule three times: $f\,'(s)=-(s+3)^{-2}$, $f''(s)=2(s+3)^{-3}$, and $f'''(s)=-6(s+3)^{-4}$ or, if you prefer,
$$f'''(s)=\frac{-6}{(s+3)^4}\;.$$
Added: I see from your edit that you actually used the quotient rule and, as I kind of suspected, forgot to square the denominator. As a general rule, when the numerator is a constant it's easier to rewrite the fraction as a constant multiple of a negative power and use the power rule.


text:
Q: How can I get all my photos from Facebook with PHP SDK? I am new to Facebook and PHP and so far I managed to connect to Facebook session + permissions, and even to get the logged in user profile picture.
question si : how can I get all of the logged in user photos and pick one randomized one?
thanks

A: $facebook->api('https://graph.facebook.com/{your_user}/photos?access_token=...');

this is the api for getting photos from the user.

A: I would use the FQL photo and album tables:
SELECT src_big
FROM photo
WHERE aid IN (
    SELECT aid
    FROM album
    WHERE owner=me()
)

And using the PHP-SDK:
$facebook->api(array(
    'method'    => 'fql.query',
    'query'     => 'SELECT src_big FROM photo WHERE aid IN (SELECT aid FROM album WHERE owner=me())'
));

You can also test the above query in the fql.query console.


text:
Q: C# insertion sort after each value How can I run the Insertion Sort code after each time user enters a value. Please notice that I don't have much knowledge about programming so showing an example or ready to use code would be appreciated.
    Console.Write("How long the Insertion sort list should be?: ");
    var countString = Console.ReadLine();
    int count = Convert.ToInt32(countString);
    int[] data = new int[count];

    for (int i = 0; i < count; i++)
    {

        var input = Console.ReadLine();
        data[i] = Convert.ToInt32(input);

        Console.WriteLine(input); // << HERE THE SORTING SHOULD HAPPEN AFTER EACH VALUE THAT I ADD.

    }

    int j = 0;
    int help = 0;

    for (int i = 1; i < data.Length; i++)
    {
        j = i;
        help = data[i];

        while (j > 0 && help < data[j - 1])
        {
            data[j] = data[j - 1];
            j--;
        }

        data[j] = help;
    }

    foreach (var i in data)
    {
        Console.Write("{0}, ", i);
    }
}

A: You can visually divide your code into two parts. The first part is for inserting the values. The second part sorts these values. So you have to cut the second part and insert at the place, where sorting should happen, I hope you will find this place ;)
Also think that you should replace i in the second for with something else, for example with k
Good luck


text:
Q: Get data from inside of an anchor tag in Python I want to extract '26' from the anchor tag below. How should I get it?

Last

A: One of possible solutions is to use beautiful soup. For instance:
html_data = """

    Last

"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_data, 'html.parser')
soup.find('a').get('data-ci-pagination-page')

# 26


text:
Q: Why does one \tableofcontents give two tables of contents? I just want a table of contents with two columns by the etoc package. But the following code typesets two TOCs (please see the attached figure). Why? What's wrong with my code?
Code:
\documentclass{article}
\usepackage{etoc}
\usepackage{geometry}
\geometry{showframe}
\geometry{left=1cm,right=1cm,top=1cm,bottom=1cm}
\parindent0pt
\begin{document}
\etocmulticol{}%
\tableofcontents
\section{first}
\subsection{subfirst}
\section{second}
\subsection{subsecond}
\section{third}
\subsection{subthird}
\section{fourth}
\subsection{subfourth}
\section{fifth}
\end{document}

A: You probably mixed up the macro \etocmulticolstyle with the other macro \etocmulticol. While the first macro is used to set the style for all ToCs that you can then call using tableofcontents, the second macro just directly typesets one ToC styled in the given way without changing the overall style of other ToCs.
So, you should either delete \tableofcontents from your code, or you change \etocmulticol{} to \etocmulticolstyle{}, for example like this:
\documentclass{article}
\usepackage{etoc}
\usepackage{geometry}
\geometry{showframe}
\geometry{left=1cm,right=1cm,top=1cm,bottom=1cm}
\parindent0pt
\begin{document}

\etocmulticolstyle{\textbf{\large Table of Contents}}

\tableofcontents

\section{first}
\subsection{subfirst}
\section{second}
\subsection{subsecond}
\section{third}
\subsection{subthird}
\section{fourth}
\subsection{subfourth}
\section{fifth}
\end{document}

Result:

A: You create two table of contents. One is \etocmulticol, the other one is \tableofcontent. If you comment out one of them, you will get only one.


text:
Q: PHP running a shell script to scp I want to use PHP to run a shell script that sends a file from server 1 to server 2.  I have the server 1 public key written to the server 2 authorized_keys and it works perfectly.
For some reason the following script doesn't actually send the file from server 1 to server 2:
// This is a webpage at http://server1.com/sendfile.php
<?php
if($_POST['a'])
{
        echo '<pre>';
        echo passthru('./scp.sh');
        echo '</pre>';
}
?>

<form method="post">
<button name="a" value="Af">Send File</button>
</form>

//This is the contents of scp.sh
scp ../dbexport/db.txt someuser@server2.net:

So when I execute from scp.sh from terminal, everything works fine - the file actually gets sent and received.
But when I go to http://server1.com/sendfile.php and press the button, the php file actually executes the shell file (i confirmed this by putting echo statements before and after scp command), but the file is never successfully received by server2.com
Does anyone know why this might be?

A: Marc B answered my question with a comment...posting here
did you add the key to the webserver's account's authorized_keys? Just because it works from a shell running under YOUR permissions means absolutely nothing to a shell running under the webserver's ID. –  Marc B Jan 9 at 19:47
ooooh yeahhhhh....i forgot about that –  John Jan 9 at 19:57
yup it worked. thanks Marc! –  John Jan 9 at 20:42


text:
Q: How to respond when someone says 'It means a lot'? In a scenario where you have encouraged someone but haven't helped them physically or with your time and they say "It means a lot". Just for the words you said. Can you respond with

*

*Any time?

*No problem?

*You are welcome?

I am not a native speaker. I've seen these phrases used after you have done someone a favor.
Context: Someone showed good performance in sports after struggling to perform in multiple matches. You said:

Person 1: Congratulations for your great performance. I am happy for you!
  Person 2: It means a lot!
  Person 1: ???

A: All are generally acceptable for a response. I find that my response changes based on how well I know the person or not.
If I am fairly familiar with them (close friend or good friend) I may say:

Hey no worries!

or
 used in rare occasions that you want to acknowledge and show you are happy that your words meant a lot to them:

I'm glad!

If someone says it that I am not so familiar I tend to respond:

You're welcome!

English is weird where there are many ways to say the same thing. Many responses are appropriate for the same thing. I would just say what you feel is a natural response.
I prefer "no worries", others may say "no problem". Pretty much the same meaning or implied meaning using a different word.
In the above example you provided, their response of "that means a lot" can be interpreted as saying:

Hey, I am glad you acknowledged my hard work and dedication to improving so it means a lot, thanks!

So I would word your response as if you are responding to that :) In the end as I said, there are many ways to respond and all the above are equally appropriate. Find one that feels natural to you and go with it!

A: As a native speaker, I most commonly say "of course!" Which is similar to no problem. I find it flows the best and sounds the nicest, but it has to be said with a cheery vocal tone or else it could sound assholeish

A: In my experience, 99 out of 100 times a pursing of the lips and a nod of the head are the most utilized response, ending the exchange before it as that will eliminate any further awkwardness.


text:
Q: Facebook Chat, XMPP, Setting presence? When changing the presence in Browser (offline/online) in Facebook Chat, the chat system sends the XMPP message in form:
<presence to="-myidhere@chat.facebook.com/adfskjfskjdfh" from="-otheridhere@chat.facebook.com" type="unavailable">

When I send my own presence from non-browser side (xmpp client) to the browser side with exactly same syntax, it seem not to effect. What I am missing here ?
Thanks a lot,
    -Mika

A: It seems like you can't do that with the facebook xmpp implementation, as they write in the documentation:

Facebook Chat should be compatible with every XMPP client, but is not
  a full XMPP server. It should be thought of as a proxy into the world
  of Facebook Chat on www.facebook.com. As a result, it has several
  behaviors that differ slightly from what you would expect from a
  traditional XMPP service

There's an open bug on this matter: XMPP: can't change availability, and also this thread also talks about it: Xmpp chat invisible presence.
Also, don't expect the fb apis to have the same functionality as you get using the fb webpage.
They obviously don't open everything they have to the apis.


text:
Q: OpenSSL Sign with Serial Number I'm trying to get a .crt file with some information, but unfortunately, i can't get a Serial Number generated.

I'd like to have a serial number generated, but not the same as the top one.
My CRT is generated with a PHP and I'd like to know what to put in my openssl.cnf to have the "same" process as the bottom one.

A: The last parameter of openssl_csr_sign function put the serial into crt


text:
Q: Windows boot manager with UEFI not loading I had windows 10 preinstalled on my system with boot type UEFI mentioned in my lenovo ideal pad boot options. I dual booted with linux mint tara which worked fine with grub loader showing both the OS entries. Later on i decided to delete linux partition which happened to be the system FAT32 partion on which efi bootloader was installed i suppose . to get rid of grub i deleted the EFI dir from windows . Now i am not able to boot into windows as it is on a boot loop keeps saying System BootOrder not found. reSet to default. Help !

A: The \EFI folder contained subfolders for both the Mint GRUB2 bootloader and the Windows bootloader – and you deleted both. To reinstall the Windows bootloader, use bcdboot:

*

*Boot from the Windows 10 install CD or USB. Make sure you boot it in UEFI mode (the firmware might have two very similar boot choices).

*Choose the "recovery console" option. (I don't remember what the menu item is called, exactly, but ShiftF10 should open it anyway.)

*Use dir c:\, dir d:\, etc. to find your main Windows partition (with the \WINDOWS folder).

*Once you know the correct drive, run bcdboot c:\windows (replace c: with the correct letter).


text:
Q: Mean Of Sum Of Upper Rows I expect someone could help me.
I made a table with some data, no need to know what in particual. I come from this #TempTable1:
WEEK_NUMBER         SUM         MEAN_OF_SUM
---------------------------------------------------------------------------
1                   10
2                   20
3                   30
4                   60
5                   30
6                   60
7                   0

My desired table #TempTable1:
WEEK_NUMBER         SUM         MEAN_OF_SUM
---------------------------------------------------------------------------
1                   10          10 --(10/1)
2                   20          15 --(30/2)
3                   30          20 --(60/3)
4                   60          30 --(120/4)
5                   30          30 --(150/5)
6                   60          35 --(210/6)
7                   0           30 --(210/7)

I tried with sums and expected the group by clause would work, but they do not. Does someone has an idea on how to solve this ?

A: I think are looking for a cumulative average:
select t.*, avg(sum*1.0) over (order by week_number)
from t;

This doesn't match the last value.  I'm guessing that is a typo.


text:
Q: Hive - Select keys with a particular value Is there a way in Hive to select all keys of a map that have a particular value? E.g. if my map looks like this:
{"default":1, "test":2, "experiment":1}

given the value 1, I would like to select (and then concatenate using concat_ws) the keys "default" and "experiment".
If it helps, the map is stored as a member of a struct that is stored in the table I'm reading data from.


text:
Q: Force HTTPS on alfresco I have been trying to enable HTTPS login on alfresco but it seems to be a challenge to get it working.
I can access my website via HTTPS and get the login page, but when I login with the correct credentials I get the following error :
Something's wrong with this page...
We may have hit an error or something might have been removed or deleted, so check that the URL is correct.
Alternatively you might not have permission to view the page (it could be on a private site) or there could have been an internal error. Try checking with your IT team.
If you're trying to get to your home page and it's no longer available you should change it by clicking your name on the toolbar.
I must login in HTTP then refresh my HTTPS page to be connected in HTTPS.
I have already seen what the offical doc says and tested it but it didn't work.
Has anyone an idea on how to fix the problem ?
Thanks

A: The alfresco.log / catalina.out should tell your more.
Where / how did you set up https? Have a a reverse proxy like nginx or apache in front of the alfresco tomcat?
If the log says something like "CSRF Token Filter issue" then you need to set  share.host / port / protocol in alfresco-global.properties as seen from the browser.


text:
Q: Django objects error in view, why I got this error? It looks like my model does not exist This is my view code:
class Planificare_concedii(AllView):
    template_name = "pep/planificare_concedii.html"

    def get_context_data(self, *args, **kwargs):
        magazinu = self.request.GET.get('magazinul')
        queryset = Planificare_concedii.objects.filter(magazin=magazinu)
        context = context = super(Planificare_concedii, self).get_context_data(
            *args, **kwargs)

        return context

This is the error that I got in view page:
AttributeError at /planificare_concedii/
type object 'Planificare_concedii' has no attribute 'objects'


text:
Q: React Native: should I install Cocoapods with gem or homebrew? The React Native docs recommend installing Cocoapods with sudo gem install cocoapods, but I'm used to using Homebrew and have seen elsewhere that people install it with brew install cocoapods. When I try installing it with Homebrew, I get this warning:
Warning: Treating cocoapods as a formula. For the cask, use homebrew/cask/cocoapods

What I Want To Know:

*

*What's the difference, if any, between installing Cocoapods with sudo gem install cocoapods and with brew install cocoapods

*If I install it with Homebrew, should I install the regular package or the cask? What's the difference?

A: macOS comes with a pre-installed version of Ruby. If you try to install a gem through pre-installed Ruby, you've to use sudo by default witch is not a good practice.
Another option is to install CocoaPods in your user-level directory by following instructions available on the Sudo-less installation section.
I would suggest you install CocoaPods using brew. It's a little cleaner option and you can update it easier.
The cocoapods cask is for CocoaPads App and the formula is for the CLI only version.

A: Answers:

*

*In general sudo is not good idea (not recommended). One should not do it, i.e. if your system get stolen and/or get compromised. Cocoapods comes from a trusted source, so people usually tend to install cocoapods gem on root level. Which is what essentially sudo does.

*brew is package manager for macOS and brew cask takes it a bit further. It makes the process of installing and updating apps (like: Skype, Chorome) more elegant and smooth. On this question you can read short and comprehensive replies from bfontaine and cellepo.


text:
Q: Java static variables and class loading I guess that the answere is simple or is kind of some JVM optimization.
I don't understand why when I am calling class's static var class is not being loaded + it's static block is not working in the same time. I am trying this way:
package common;
import java.lang.reflect.Method;
public class Test {

  static class Person {
    public static final int ID = 12345;

    static {
        System.out.println("Loading " + Person.class.getName());
    }

    static void staticMethod() {
        System.out.println("staticMethod");
    }

    public Person() {}
  }

  private static void case_1() throws Exception {
    System.out.println("isLoaded: " + isLoaded("common.Test$Person"));
    System.out.println("Person ID: " + Person.ID);
    System.out.println("isLoaded: " + isLoaded("common.Test$Person"));
    Person.staticMethod();
    System.out.println("isLoaded: " + isLoaded("common.Test$Person"));
  }

  private static boolean isLoaded(String clazz) throws Exception {
    Method m = ClassLoader.class.getDeclaredMethod("findLoadedClass", String.class);
    m.setAccessible(true);
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    Object object = m.invoke(cl, clazz);
    return object != null;
  }

  public static void main(String[] args) throws Exception {
    case_1();
  }
}

Output says:
isLoaded: false
Person ID: 12345
isLoaded: false
Loading common.Test$Person
staticMethod
isLoaded: true

If class is not being initialized in this case then where does JVM store this variable?


text:
Q: Basic Authentication in REST WCF I have developed one REST WCF and would like to client will use it with basic Authentication, I have hosted this service in IIS 7.0 and disabled all authentication except Basic Authentication.
Now problem is that when call this service from any other application (in my case i am calling this from ruby command prompt) with Header "Basic bXlhZGRvbjpDcFplcUc5MzlHdDZQMEtD" although i was not able to authenticate this service.
Make it more simple , when i will access this service (.svc) from browser due to basic Authentication
it will prompt to enter username & password , so which residential i need to pass here and to which credential i need to compare (weather i need to set in web.config or IIS)??
Thanks in Advance
Arun.

A: For basic authentication, IIS would always try to validate the userName & Password as a windows users (either local or domain user).
Dominick has created a Basic Http Authentication module which let's you use other credential stores with Basic Authentication.
http://www.leastprivilege.com/HTTPBasicAuthenticationAgainstNonWindowsAccountsInIISASPNETPart3AddingWCFSupport.aspx


text:
Q: How to set different source directories in cedet? How do I specify different source directories under cedet ?
I have configured my project like this:
(when (file-exists-p "~/ws/madwifi/build/Makefile")
(setq cpp-tests-project
(ede-cpp-root-project "madwifi"
                  :file "~/ws/madwifi/build/Makefile"
                  :system-include-path '("~/ws/madwifi/build/include/drivers"
                                         "~/ws/madwifi/build/include/hw/"
                                         )
)))

But when I do a semantic-symref-symbol on a symbol, it sometimes lists only functions
that are used in the project. variables are not symref'd
But when I completely remove the block above, it shows the references of variables only
from the current directory. How to properly configure ede-cpp-root-project.

A: The symref tools only work within the current project, and do not pull data in from include paths.  You can search for references to a symbol from an include file, but it won't find the declaration from the includes.
The symref tool works with several different external tools such as GNU Global or idutils.  In theory you could use one of those tools to index whichever files you want, and as long as the index file is at the root of your project, it will find it, and also find your external includes.  I haven't tried this though, so I don't know if these tools have that capability.
If you want to jump to a reference in an external include, you can use other tools, like semantic-ia-fast-jump and that uses include paths instead of project indicies, but it won't find references.


text:
Q: How to communicate frontend with microservice architecture? I'm struggling with setting up reliable and performant solution to communicate frontend with different microservices. I do not really now how to maintain (maybe not need) CSRF between my frontend and end services
Solutions stack: PHP, Laravel Passport, JWT, oAuth 2.0, Axios
Current approach:
Actually I've started up with approach from Laravel's passport
https://laravel.com/docs/5.4/passport#consuming-your-api-with-javascript

*

*Using oAuth 2.0 to authorize user from website A to service B.
JWT token is returned for further communication.

*Token is saved in cookie within website A

*Once user is authorized website A uses JWT token to manage requests without additional to oAuth server, by sending JWT token as cookie using HTTP headers (withCredentials) to authorize user.

*For each website A's request there was CSRF token created from service B since user is authorized and cookie could be applied by another unauthorized website to access service B. That was killing my performance since it has to retrieve CSRF for each request made. (that what I actually assume from laravel passport approach and need to create CSRF with JWT token - maybe that was mistake)
My concerns:
Regarding to of James Ward post:
http://www.jamesward.com/2013/05/13/securing-single-page-apps-and-rest-services

The easiest way to do authentication without risking CSRF
  vulnerabilities is to simply avoid using cookies to identify the user.
Cookies themselves are not the cause of CSRF vulnerabilities. It's
  using the cookies on the server to validate a user that is the cause
  of CSRF. Just putting an authentication token into a cookie doesn't
  mean it must be used as the mechanism to identify the user.

From my understanding setting JWT with website A's cookie with its domain set could not be accessed via any other site from outside. Since that there is no possible way to make request to service B without accessing JWT.
So do we really need CSRF then to secure potential attack to service B while using JWT?
If so, how could I achieve the best (in term of performant) way to generate CSRF through different services to be sure that communication would not be vulnerable for attack from different sites?
Any advice will be appreciated!


text:
Q: Why can I not open a URL in an iframe with javascript? Well, to put it simply, this doesn't work:

When the user presses okay, the source of the iframe does not load.
It is by the way defined as follows:

A: You must put javascript before tag "body"

A: First of all, Use confirm instead of alert because alert cannot receive input from the user. Your code should be something like

And the HTML:


text:
Q: How to lock Iphone device with my app? I am working on an app with passcode locking option(pic1). When I enter correct password it enters into the app.When I enter wrong password it will perform some other action(pic2).

After some time the app goes into the sleep state,when the app comes to active state we have to enter the password again.
Here my requirement is I want to open the "passcode locking screen" (pic1.,which was created by me) after unlocking the device,(pic3.,which is default locking option in Iphone). Unless I enter the correct passcode the "passcode screen" should stick to the window. It should not move to any other screen (pic4., screen with group of app icons) though I click the button of theiphone.
This requirement is killing my time, I don't mind to post sample code or tutorials if you have gone through.

A: you can't do this using a non-jailbreak iPhone. an app cannot prohibit the user from switching to another app (and it cannot modify another app)
that applies to the springboard (pic4) too of course


text:
Q: add json object to jsonarray android / Java I'm getting a JSONarray that has this values:
[{"id":"1","type":"7"},
 {"id":"2","type":"6"},
 {"id":"5","type":"5"},
 {"id":"6","type":"4"}]

and so on.
The thing is that I want to write a new array from this one that has an extra field that is the multipilication of "id" by "type". Something like this :
[{"id":"1","type":"7","result","7"},
 {"id":"2","type":"6","result","12"}]

and so on.
How can I achieve this ?

A: You can use Google's GSON package and it's internal JSON implementation as follows.
Supposing that you have your jsonArray pre-filled:
JsonArray values = what_ever_your_values_are; (if you define you data stream i can guide you further)
JsonArray newJsonArray = new JsonArray();

for(int i=0;i<values.size();i++){
   JsonObject temp = new JsonObject();
   temp.addProperty("id",values.get(i).getAsJsonObject().get("id").getAsString());
   temp.addProperty("type",values.get(i).getAsJsonObject().get("type").getAsString());
   int result = Integer.parseInt(values.get(i).getAsJsonObject().get("id").getAsInt()) *
                Integer.parseInt(values.get(i).getAsJsonObject().get("type").getAsInt()); //for the sake of simplicity
   temp.addProperty("result",String.valueOf(result));
   newJsonArray.add(temp);
}


text:
Q: Decoding and Encoding multiple packet types in Netty So I am working on a netty server that handles a specific type packet. This netty server was not made by me and I am trying to add another type of packet handler, decoder, and encoder to it. Because of poor implementation of the existing handlers, I have to add mine before like so.
                                 channel.pipeline()
                                .addLast(new custom.PacketDecoder().server())  // My Packet Decoder
                                .addLast(new custom.PacketEncoder().server())  // My Packet Encoder
                                .addLast(new custom.NetworkHandler().server()) // My Packet Handler
                                .addLast("timeout", new ReadTimeoutHandler(30)) // Not made by me
                                .addLast("legacy_query", new LegacyPingHandler(ServerConnection.this)) // Not made by me
                                .addLast("splitter", new PacketSplitter()) // Not made by me
                                .addLast("decoder", new PacketDecoder(EnumProtocolDirection.SERVERBOUND)) // Not made by me
                                .addLast("prepender", new PacketPrepender()) // Not made by me
                                .addLast("encoder", new PacketEncoder(EnumProtocolDirection.CLIENTBOUND)) // Not made by me
                                .addLast("packet_handler", networkmanager); // Not made by me

As of now this sort of works but the issue is that if it recives the packets that arent mine that it should be able to handle, my handlers stop those packets from going through and being handled correctly. How do I pass packets that are not mine through to other handlers without touching them.

A: You handler should check if an inbound packet is of specific type, that the handler can process. If a packet is "not yours", handler should pass it upstream - to the next handler in pipeline (for netty 4.x - ChannelHandlerContext.fireChannelRead(Object)).
Maybe this documentation can help.


text:
Q: Trying to implement boolean disjunction on list using List.fold_right I am trying to implement boolean disjunction. I have successfully implemented it using recursion, and for a bit of practice I am trying to do the same using List.fold_right but I am failing miserably.
let q1fold lst =
  List.fold_right (fun lst acc ->
    match lst with
    | [] -> acc
    | h::t -> if h then true else false )

A: Consider the type signature of List.fold_right:
# List.fold_right;;
- : ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b = <fun>

Three arguments are taken. You've only passed one.
List.fold_right and List.fold_left consider an initial value and each element of the input list and runs a function on them to generate the initial value for the next iteration, returning that value at the end of the list.
What do you think the "update" and the initial values should be in the following to implement the functionality you want?
List.fold_right (fun x init -> ...) [true; false; false] ...

Note 1: I would use List.fold_left as it is tail-recursive, though for a small dataset it is unlikely to make a practical difference here.
Note 2: if h then true else false is equivalent to h.


text:
Q: Javafx svg file in background of my scene I wouldlike to display svg file in background :
  public void start(Stage primaryStage) throws Exception{
            this.primaryStage = primaryStage;
            Group root = new Group();
            primaryStage.setTitle("Test");
            primaryStage.setScene(new Scene(root,1920, 1080));
            primaryStage.setMaximized(true);

            FileInputStream input_background_template = new
            FileInputStream("ressources/background/template_home.svg");
            ImageView img_background_template = new ImageView(new Image(input_background_template));

            root.getChildren().addAll(img_background_template)
            primaryStage.show();
}

But I have still nothing in my background ?


text:
Q: Linq query in stored procedure result set Ado.Net I have a stored procedure with multiple joins, pulling all the data into a resultset I.e in dataset, now I want to write a linq query over it. How can I do that?
I am expecting:
IEnumerable<SomeType> result;

[where I need to know how the Properties of SomeType are defined.]
This is what I have tried but it does not look efficient.
SqlCommand cmd = new SqlCommand("Select top 10 * from trade");
cmd.Connection = con;

if (con.State != ConnectionState.Open)
{
    con.Open();
}

SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();

dt.Load(dr);
var result = dt.AsEnumerable();

string valresukir = string.Empty;

var sortResult = result.OrderBy(x => Convert.ToInt32(x["trade_num"]) > 12);
string valuedata = string.Empty;

foreach (var i in sortResult)
{
    valuedata += i["trade_num"].ToString();
}

A: to can write linq query on data table like
var data= from dataRow in dt.AsEnumerable()
          where dataRow.Field<int>("trade_num") > 12
          select dataRow

if trade_num is integer . Take it as a example and add your conditions accordingly.
Hope it will help you.


text:
Q: Dynamically Loading a component which has Router Setup? I am having a login component which loads at the beginning.After user clicks on login button i am dynamically adding component which has route config and router-links...I can see my router-links but when i click on them i cant see any content in router-outlet Here is my plunker http://plnkr.co/edit/KzCNxEthu6dRiGeSGToe?p=preview
    UserLogin() {
    this.DCLloader.loadAsRoot(AppComponent, '#login', this.injector);
}

This is how i am adding the component.My question is can i add a component which has router links dynamically? If yes, why is my demo not working? How can i correct this mistake?Somebody please help me

A: Looks like support for this was added recently:

*

*https://github.com/angular/angular/pull/7365

*https://github.com/angular/angular/pull/7318
This already landed in beta.9
https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta9-2016-03-09

A: I don't know what you try to achieve, but if the purpose is to redirect after a successfull login, see this example:
https://github.com/RedFroggy/angular-spring-hmac/blob/angular2/src/main/webapp/app/app.component.ts
The idea is to set the login page as the default one in the @RouteConfig.
When the login is successful you redirect to a given page (/user for example).
Then you have to check every time a page changes that the user is still logged and redict to the login page if he's not.


text:
Q: How to solve $\int_0^{\infty}\frac{\log^n(x)}{1+x^2}dx$? As an exercise for myself I constructed the Integral
$$
\int_0^{\infty}\frac{\log^n(x)}{1+x^2}dx
$$
with $n\in \mathbb{N}$. With the help of Mathematica I found the analytical result
$$
\int_0^{\infty}\frac{\log^n(x)}{1+x^2}dx=\frac{1+(-1)^n}{4^{n+1}}\Gamma(n+1)\left[\zeta\left(n+1,\frac{1}{4}\right)-\zeta\left(n+1,\frac{3}{4}\right)\right].
$$
For $n=1$ (and probably $n\in \mathbb{N}$) one can employ the methods of complex analysis and find a result. For $n\in \mathbb{N}$ I encountered a nasty recursion relation. I can provide details if needed. Is there another way how to solve the integral at hand?

A: Referring to this answer,
$$I_n=\frac{\pi}2\frac{d^n}{dx^n}\sec\left(\frac{\pi x}2\right)\bigg\vert_{x=0}$$
or equivalently,
$$\int^\infty_0\frac{\log^n(x)}{x^2+1}dx=\left(\frac{\pi}2\right)^{n+1}\sec^{(n)}(0)$$
$$\int^\infty_0\frac{\log^{2n}(x)}{x^2+1}dx=(-1)^nE_{2n}\left( \frac{\pi}2\right)^{2n+1} $$
The integral is zero for odd $n$.

A: Let, for $n$, a natural integer,
\begin{align}J_n=\int_0^\infty \frac{\ln^n x}{1+x^2}\,dx\end{align}
First, observe that if $n$ is odd then $J_n=0$ (perform the change of variable $y=\dfrac{1}{x}$ )
Consider, for $n$, a natural integer,
\begin{align}K_n=\int_0^\infty \int_0^\infty\frac{\ln^n(xy)}{(1+x^2)(1+y^2)}\,dx\,dy\end{align}
Observe that,
\begin{align}K_{2n}&=\sum_{k=0}^{2n}\binom{2n}{k} J_kJ_{2n-k}\\
&=\sum_{k=0}^{n}\binom{2n}{2k} J_{2k}J_{2(n-k)}
\end{align}
On the other hand,
Perform the change of variable $u=xy$ ($x$ variable, $y$, a "parameter"),
\begin{align}K_n&=\int_0^\infty \int_0^\infty\frac{y\ln^n u}{(1+y^2)(u^2+y^2)}\,du\,dy\\
&=\frac{1}{2}\int_0^\infty \left[\ln\left(\frac{1+y^2}{u^2+y^2}\right)\right]_{y=0}^{y=\infty}\frac{\ln^{n} u}{u^2-1}\,du\\
&=\int_0^\infty \frac{\ln^{n+1} u}{u^2-1}\,du\\
&=\int_0^1 \frac{\ln^{n+1} u}{u^2-1}\,du+\int_1^\infty \frac{\ln^{n+1} u}{u^2-1}\,du\\
\end{align}
In the second integral perform the change of variable $v=\dfrac{1}{u}$,
\begin{align}K_n&=\int_0^1 \frac{\ln^{n+1} u}{u^2-1}\,du+\int_0^1 \frac{\ln^{n+1} u}{u^2-1}\,du\\
&=\int_0^1 \frac{\left(1+(-1)^n\right)\ln^{n+1} u}{u^2-1}\,du\\
&=\left(1+(-1)^n\right)\int_0^1 \frac{\ln^{n+1} u}{u-1}\,du-\left(1+(-1)^n\right)\int_0^1\frac{u\ln^{n+1} u}{u^2-1}\,du\\
\end{align}
In the latter integral perform the change of variable $y=u^2$,
\begin{align}K_n&=\left(1+(-1)^n\right)\int_0^1 \frac{\ln^{n+1} u}{u-1}\,du-\frac{1+(-1)^n}{2^{n+2}}\int_0^1 \frac{\ln^{n+1} u}{u-1}\,du\\
&=\left(1+(-1)^n\right)\left(1-\frac{1}{2^{n+2}}\right)\int_0^1 \frac{\ln^{n+1} u}{u-1}\,du\\
&=\left(1+(-1)^n\right)\left(1-\frac{1}{2^{n+2}}\right)(-1)^{n+2}(n+1)!\zeta(n+2)
\end{align}
Therefore, one obtains a recursion relation,
\begin{align}
\boxed{\sum_{k=0}^{n}\binom{2n}{2k} J_{2k}J_{2(n-k)}=2\left(1-\frac{1}{2^{2n+2}}\right)(2n+1)!\zeta(2n+2)}
\end{align}
Observe that,
\begin{align}J_0=\frac{\pi}{2}\end{align}


text:
Q: Swift FBSDKLogin Swift 3 AppDelegate update I am currently implementing Facebook login in my app, and I just came to notice that after the Swift 3 update, the code in AppDelegate has slightly changed since the last time I added Facebook login to my app. I am struggling with this function (this is Swift 2.2) here:
    func application(application:UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {

return FBSDKApplicationDelegate.sharedInstance().application(application,

openURL: url, sourceApplication: sourceApplication, annotation: annotation)
    }

After the 3.0 update, the function looks like this:
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

}

How should I make it work in 3.0, considering there is no 'sourceApplication' nor an 'annotation'?
Help is greatly appreciated.

A: try this :-
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    ...
}


text:
Q: int vs unsigned int vs size_t Starting with a more advanced C++ course, we have to implement an own Matrix, which is typical for first exercises. We received a skeleton to work on and i have got only one question left. The type of the access and size variables.
Here a simple constructor for 1D Matrix, with some Checking of the size.
Array::Array( int xSize )
{
    CHECK_MSG(xSize > 0, "Array size too small");
    array_ = new real[xSize];
    size_ = xSize;
}

Does it make sense to use a size_t or unsigned int instead of an int? After reading the definition of size_t i would tend to use it instead. However in many codes i see just ints everywhere. Is it a java-like coding style? Has size_t any disadvantages i missed?
Edit:
The main question relates to the coding style. I fully understand the difference of size_t and (unsigned) int, as it was already explained here:unsigned-int-vs-size-t

A: The C++ standard library would almost certainly use a std::size_t for such a type.
Using a signed type is obviously not desirable and, ideally, you want to use a type that lends itself well to having an object that supports iterability.
From the outset I recommend you use typedef std::size_t MySize; within your class, mainly to future-proof yourself. That would be the most sensible choice.

A: Can the size of anything ever be negative? No, so use unsigned for xSize to express the intent of the code more explicitly.
If you need it be able to handle really big sizes, use size_t.


text:
Q: Adding a view controller to a collection view cell Does anyone have a good example of how to add a uiviewcontroller to a collection view cell ?
Looking for a solution with good memory management and the ability to reuse view controllers ?
Thanks

A: it's not possible(not sure) and rational, if you want to have some view controllers in some vertical and scrollable view you have to do something like this:
1- add scroll view to the parent view controller
2- add your others view controllers as a child to this scroll view