text:
Q: debugging in mixed mode with native C++, managed c++ cli, and c# solution I have a multithreaded project im working on and the startup project is set to a c# project that runs my UI. Then there is a whole series of underlying c++ native projects which are connected to the C# by managed C++/CLI projects. I've enabled in the c# start up project 'Enable Unmanaged debug' and when I attempt to debug the native code, I am able to hit break points I set. However, it hangs after I try to run it again and try to hit a break point again. For example, if I have a loop I try to hit inside it in each iteration, after the second iteration the program hangs and I have to force quit. Im working in Visual Studio 2010. Debugging beginning to prove not too useful at this rate, is there any way to preclude this problem?

A: We also had problems debugging complex mixed code applications and found out that the Visual Studio is not that reliable in these situations. My suggestions would be to:

*

*If you're trying to debug a piece of native code try to use a native project as the debugger start-up application. Under the project settings, "Debugging" tab set the "Debugger Type" to "Mixed", for us this helped sometimes (the native project can be a DLL for example, simply set your main Exe as debugging target in the project settings);

*Use WinDbg, with it you can debug both managed/unmanaged mixed code applications much more reliably;

A: When I want to debug native code as well as C++/CLI, I do following:

*

*In C# application, check Allow unsafe code in Build tab and Enable unmanaged code debugging in Debug tab of project properties.

*For C++/CLI dll project, In Debugging tab of properties, set Debugger Type to Mixed

A: I had the same problem when I tried to step into un-managed code from managed, so instead, I got rid of all the breakpoints on the managed side and did the following:
1) open your un-managed source file via File->Open->File (i.e my source.cpp)
2) set a breakpoint there
3) start your managed code debugging (Play button)
It should break directly into your un-managed code... at least it works for me...

A: Okay, here it goes how I resolved it,
Short Answer:

*

*Set Configuration_Properties->Debugging->Debugger_type: Mixed(.NET Framework)
for both of your projects
a. Purely Native project (un-managed C++ exe consumes the exported functions from managed C++ CLR dll)
b. C++/CLI - CLR project (managed C++ dll exports functions from a purely managed
C# .NET dll by referencing(Reference to the C# dll is already added to the references list of managed C++ CLR project)) - This project as as an interface b/w unmanaged and managed code.

*Set Configuration_Properties->Advanced->C++/CLI_Properties->Common_Language_Runtime_Support: Common Language Runtime Support (/clr) and .NET_Target_Framework_Version: x.x.x (as specified in the managed C# project Target Framework) for the managed C++/CLI - CLR project that acts as the interface.
Long Answer:
I was trying to build a plugin DLL(C++ Native dll) which is supposed to run under plain un-managed environment(C++ Native) which uses MFC/Win32 API sets. First I tried to go with Win32Api UI elements such as windows, threads, etc and it became hardcore for designing the UI, since VS2019 doesn't give me the design editor unless I declare the project as MFC and bring in unwanted MFC services.
To make things easier for my UI development,
I created a C# dll(managed dLL - Standard Class library .NET Core project) which uses "Windows Forms" targeting .NET framework 4.7.2
Then I created another C++/CLI - CLR dll(managed dLL - CLR project which uses unmanaged C++ code but runs in a managed environment clr.dll). This dll acts as an interface which exposes the functions from the managed C# code wrapped in a C style wrapper function using extern "C" __declspec(dllexport)
The main/startup project was a Pure Native C++ (exe) unmanaged Application that consumes the functions exported from the C++/CLI - CLR managed interface project which internally exposes the UI elements.
Debugging was not available unless I manually loaded the .pdb for the managed CLR C++ dll and Forced the Debugger type of the startup unmanaged C++ application to Mixed(.NET Framework)


text:
Q: Issue with Bulk Collect I have a procedure where I need to fetch data from a cursor using bulk collect. The issue with this approach is - sometimes the records are getting processed and sometimes they arent. I am unable to identify the root cause. When I try to debug the issue, toad is unresponsive and times out. Here is the code. Please help!
PROCEDURE GetPendingItems(pprogramidlst IN VARCHAR2, EventCur OUT cur)
   AS
      vSessionId            NUMBER;
      vDefaultValue         svoltp.param.DefaultValue%TYPE;
      TYPE EventRec IS TABLE OF TrigEventQueue.TrigEventQueueId%TYPE;
      TYPE EventPartitionDate IS TABLE OF TrigEventQueue.PartitionDate%TYPE;
      vEventRec             EventRec;
      vEventPartitionDate   EventPartitionDate;
      vOldestPossibleDate   DATE;
      vtrigeventqueueid     VARCHAR2 (250);
      vprogramidlst         VARCHAR2 (250);
      vETInterval       number;
      VCOUNT            NUMBER;
      VCOUNT1 NUMBER;
      CURSOR PRCURSOR(vCount1    NUMBER) IS
      SELECT TrigEventQueueId, PartitionDate FROM TRIGEVENTQUEUE A
      WHERE TrigEventQueueId IN (SELECT TrigEventQueueId
           FROM (  SELECT teq.TrigEventQueueId, teq.PartitionDate, teq.EventProcessingSessionId,teq.TrigEventStateId
                     FROM svoltp.TrigEventQueue teq,
                          programtrigevent pte,
                          trigevent te
                    WHERE     teq.TrigEventStateId = gcEventStatePending
                          AND teq.EventProcessingSessionId IS NULL
                          AND teq.ProgramTrigEventId = pte.ProgramTrigEventId
                          AND pte.TrigEventId = te.TrigEventId
                          AND teq.PartitionDate >
                                 (SYSDATE - (te.NumHoursUntilEventExpired / 24))
                          AND teq.PartitionDate > vOldestPossibleDate
                 ORDER BY teq.TrigEventCreatedTS) a
          WHERE ROWNUM <= vCount1)
          FOR UPDATE OF A.TrigEventQueueId, A.PARTITIONDATE SKIP LOCKED;
   BEGIN
      vSessionId := TrigEventSessionIdSeq.NEXTVAL;
      vprogramidlst := pprogramidlst;
      SELECT DefaultValue
        INTO vDefaultValue
        FROM svoltp.Param
       WHERE ParamId = gcMaxPenEventsParam;
        SELECT DefaultValue
        INTO vETInterval
        FROM svoltp.Param
       WHERE ParamId = 2755;
      -- Use MAX number of expiry hours to identify an oldest possible date/time that any event could be picked up for.
      SELECT SYSDATE - (MAX (NumHoursUntilEventExpired) / 24)
        INTO vOldestPossibleDate
        FROM trigevent;
         SELECT COUNT(1) INTO VCOUNT1
           FROM (   SELECT teq.TrigEventQueueId, teq.PartitionDate
                     FROM svoltp.TrigEventQueue teq,
                          programtrigevent pte,
                          trigevent te
                    WHERE     teq.TrigEventStateId = gcEventStatePending
                          AND teq.EventProcessingSessionId IS NULL
                          AND teq.ProgramTrigEventId = pte.ProgramTrigEventId
                          AND pte.TrigEventId = te.TrigEventId
                          AND teq.PartitionDate >
                                 (SYSDATE - (te.NumHoursUntilEventExpired / 24))
                          AND teq.PartitionDate > vOldestPossibleDate
                                          ORDER BY teq.TrigEventCreatedTS) a
          WHERE ROWNUM <= vDefaultValue;
     IF VCOUNT1 > 0 THEN
          SELECT count(1) into vcount FROM ETINSTANCESTATUS
                WHERE datediff ('SS', INSTANCEUPDATETIME, SYSDATE) < vETInterval;
                if vcount > 0 then
                vcount1 := round(vcount1/vcount);
            else
            vcount1  := vcount1;
                end if;
          END IF;
       OPEN PRCURSOR(vcount1);
      LOOP
      FETCH PRCURSOR BULK COLLECT INTO vEventRec, vEventPartitionDate LIMIT 100;
--      EXIT WHEN PRCURSOR%NOTFOUND;
      --SVOLTP.PKGSVOLTPLOCK.SLEEP(1);
      FORALL i IN vEventRec.FIRST .. vEventRec.LAST
         UPDATE svoltp.TrigEventQueue teq
            SET teq.EventProcessingSessionId = vSessionId,
                teq.TrigEventStateId = gcEventStateLocked,  --6 : Locked State
                teq.LastUser = 1003,
                teq.LastUpdate = SYSDATE
          WHERE     teq.TrigEventQueueId = vEventRec (i)
                AND teq.PartitionDate = vEventPartitionDate (i);
              END LOOP;
      COMMIT;
      CLOSE PRCURSOR;
      OPEN EventCur FOR
         SELECT TrigEventQueueId, ProgramTrigEventId, PartitionDate
           FROM svoltp.TrigEventQueue teq
          WHERE     teq.EventProcessingSessionId = vSessionId
                AND teq.TrigEventStateId = gcEventStateLocked
                AND teq.PartitionDate > vOldestPossibleDate;
   EXCEPTION
      WHEN OTHERS
      THEN
         OPEN EventCur FOR
            SELECT 1
              FROM DUAL
             WHERE 1 = 2;
   END GetPendingItems;

A: It looks like you've commented out the exit as part of your attempt at debugging - and that is what is causing Toad to be unresponsive, as it means the loop never exits (as Tony Andrews pointed out).
With the exit where you had it, you won't process anything if the cursor query finds fewer than 100 rows, as you'll see PRCURSOR%NOTFOUND even though some data was actually retrieved. And if it finds more than 100 rows you'll process the first batch, but then will still lose records from the last batch of less than 100.
So you need to move your exit to the end of the loop and change the condition:
  LOOP
  FETCH PRCURSOR BULK COLLECT INTO vEventRec, vEventPartitionDate LIMIT 100;
  --SVOLTP.PKGSVOLTPLOCK.SLEEP(1);
  FORALL i IN 1 .. vEventRec.COUNT
     UPDATE svoltp.TrigEventQueue teq
        SET teq.EventProcessingSessionId = vSessionId,
            teq.TrigEventStateId = gcEventStateLocked,  --6 : Locked State
            teq.LastUser = 1003,
            teq.LastUpdate = SYSDATE
      WHERE     teq.TrigEventQueueId = vEventRec (i)
            AND teq.PartitionDate = vEventPartitionDate (i);
  EXIT WHEN vEventRec.COUNT < 100;
  END LOOP;

I've also changed the FORALL loop to use 1..count rather than first..last so it won't have a problem if the last actual batch is exactly 100 rows, and the next one gets zero rows - it'll do nothing in the FORALL and then exit.
This scenario is covered in the second half of this Oracle Magazine article ('Kicking the %NOTFOUND Habit').

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bacula: Director's connection to SD for this Job was lost SD-7.4.4 (ubuntu 16) Director-7.4.4(ubuntu 16) FD-5.2.10 (windows)
I'm having trouble backing up windows clients with Bacula. I can run a backup just fine when the backup size is around 1MB or 2 but when running a backup of 500MB, I get the same error every time

"Director's connection to SD for this Job was lost."

Some things to mention. When I issue status client:
Terminated Jobs:  JobId  Level    Files      Bytes   Status   Finished
======================================================================
    81  Full      5,796    514.8 M  OK       06-Nov-17 12:50 BackupComputerA

When I issue status dir
06-Nov 17:58 acme-director JobId 81: Error: Director's connection to SD for this Job was lost.
06-Nov 17:58 acme-director JobId 81: Error: Bacula acme-director 7.4.4 (202Sep16):
  Build OS:               arm-unknown-linux-gnueabihf debian 9.0
  JobId:                  81
  Job:                    BackupComputerA.2017-11-06_17.41.01_03
  Backup Level:           Full (upgraded from Incremental)
  Client:                 "Computer-A-fd" 5.2.10 (28Jun12) Microsoft  (build 9200), 32-bit,Cross-compile,Win32
  FileSet:                "Full Set" 2017-11-03 22:12:58
  Pool:                   "RemoteFile" (From Job resource)
  Catalog:                "MyCatalog" (From Client resource)
  Storage:                "File1" (From Job resource)
  Scheduled time:         06-Nov-2017 17:40:59
  Start time:             06-Nov-2017 17:41:04
  End time:               06-Nov-2017 17:58:00
  Elapsed time:           16 mins 56 secs
  Priority:               10
  FD Files Written:       5,796
  SD Files Written:       0
  FD Bytes Written:       514,883,164 (514.8 MB)
  SD Bytes Written:       0 (0 B)
  Rate:                   506.8 KB/s
  Software Compression:   100.0% 1.0:1
  Snapshot/VSS:           yes
  Encryption:             yes
  Accurate:               no
  Volume name(s):
  Volume Session Id:      1
  Volume Session Time:    1509989906
  Last Volume Bytes:      8,045,880,119 (8.045 GB)
  Non-fatal FD errors:    1
  SD Errors:              0
  FD termination status:  OK
  SD termination status:  Error
  Termination:            *** Backup Error ***

About 5 minutes into the backup, I get a message:
Running Jobs:
Console connected at 06-Nov-17 18:08
 JobId  Type Level     Files     Bytes  Name              Status
======================================================================
    83  Back Full          0         0  BackupComputerE   has terminated
====

The job completes and terminates but loses connection afterwards and I never get a

"OK"

for the status update.
I have added the "Heartbeat Interval = 1 Minute" to all the Daemons and still no luck. Using mysql as the database on the Director
Future thanks for any help

A: For anyone having the same issues, I was able to fix this problem between the SD and director by adding the heartbeat interval to the clients and adjusting the keep alive time with

sysctl -w net.ipv4.tcp_keepalive_time=60

on both the Storage daemon and the director. Connecting remotely to the director with the bconsole also interrupted jobs so I ran bconsole on the same machine as the director and connected via ssh.


text:
Q: How to standardize raster output from 0 to 100 using raster algebra? I am working on generating an integrated moisture index based on the following equation:
IMI = (hill shade * 0.5) + (curvature * 0.15) + (flow accumulation * 0.35)
Iverson et al. 1997
Another source
The equation requires that hillshade, curvature and flow accumulation are standardized from 0 - 100.  How can I accomplish this standardization from 0-100 using raster algebra?

A: The language of data transformation can be confusing. Standardization refers to transforming your data so it has a mean of 0 and a standard deviation of 1 and is only appropriate for normally (Gaussian) distributed data. Whereas, normalization transforms your data so that the minimum value is 0 and the maximum is 1 while keeping the shape of the original distribution. You are wanting a stretch or normalization.
Here is the raster algebra syntax for a data stretch. The "+ 0" is, in this case, obviously irrelevant but is left in for cases where the desired minimum value is not zero. The min("raster") and max("raster") refer to the global min/max values of the rasters. I provide this example because it allows a specification of any desired output min/max raster values.
("raster" - min("raster")) * 100 / (max("raster") - min("raster")) + 0

In your case you could just normalize and multiply by 100. The reason for this transformation is because the index needs the summed variables to be in the same variable space.
("raster" - min("raster")) / (max("raster") - min("raster")) * 100

If you are using ArcGIS this toolbox has a tool for statistical transformations, including normalization. For this model it is not necessary to have the inputs in a 1-100 range, you can use 0-1 and then multiply the output by 100 to get the desired data range for the index.

A: Remember that, for standardizing data, you assume that this data is in a normal distribution. If the data is not in a normal distribution, it is advisable to use percentile rank instead of normalization. A good explanation about the theory and about how to do it in SPSS are in these links:
http://www.psychstat.missouristate.edu/introbook/sbk14m.htm
http://blogs.perficient.com/businessintelligence/2012/03/21/ranking-your-cases-ibm-spss-statistics/
Anyway, if you are using ArcGIS, a good option is to stretch your raster using "Equalize Histogram", than export the raster ("Data" -> "Export data") using the option "use renderer" and setting the "No Data Value" to 0. This will give you a percentile rank from 1 to 255 and you can re-scale it dividing your raster values by 2.5.

A: Using Reclassify tools from arctool box also we can standardize the raster layer to a specified scale (1 to 3) (1 to 5) (1 to 9) (1 to 100).


text:
Q: How inefficient is my ray-box-intersection algorithm? I am experimenting a little bit with shaders and the calculation of a collision between ray-box which is done following way:
inline bool hitsCube(in Ray ray,            in Cube cube,
                     out float tMin,        out float tMax,
                     out float3 signMin,    out float3 signMax)
{
    float3 biggerThan0 = ray.odir > 0; // ray.odir = (1.0/ray.dir)
    float3 lessThan0 = 1.0f - biggerThan0;

    float3 tMinXYZ = cube.center + biggerThan0 * cube.minSize + lessThan0 * cube.maxSize;
    float3 tMaxXZY = cube.center + biggerThan0 * cube.maxSize + lessThan0 * cube.minSize;

    float3 rMinXYZ = (tMinXYZ - ray.origin) * ray.odir;
    float3 rMaxXYZ = (tMaxXZY - ray.origin) * ray.odir;

    float minV = max(rMinXYZ.x, max(rMinXYZ.y, rMinXYZ.z));
    float maxV = min(rMaxXYZ.x, min(rMaxXYZ.y, rMaxXYZ.z));

    tMin = minV;
    tMax = maxV;

    signMin = (rMinXYZ == minV) * lessThan0; // important calculation for another algorithm, but no context provided here
    signMax = (rMaxXYZ == maxV) * lessThan0;

    return maxV > minV * (minV + maxV >= 0); // last multiplication makes sure the origin of the ray is outside the cube
}

Considering this function could be called inside a hlsl-shader many, many times (for some pixels lets say at least 200/300 times): Is my implementation of the collision logic inefficient?

A: Not rally a easily answerable "question", and hard to say without knowing all else that's going on around it, but just a few random thoughts:
a) if you're really interested in knowing that this could would look like on the GPU I'd suggest "porting" that to a CUDA kernel, then using CUDA to generate PTX and SASS for a modern GPU (say, sm75 for turing or sm86 for ampere); then compare two or three variants of that in SASS output.
b) the "converting logic to multiplications" might give you less than you think - if the logic isn't too complicated there's a good change you might end up with a few predicates and not much warp divergence at all, so might not be too bad. Only way to tell is look at PTX and/or SASS output, see 'a'.
c) your formulation of tMinXYZ/tMaxXYZ is (IMHO) unnecesarily complicated: just express it with min/max operations, which are really cheap on GPUs. Also see the respective chapter "ray/box intersection" in the ray tracing gems 2 book (which is free for download). Also more numerically stable btw.
d) re "lags... is my logic inefficient" - actual assembly "efficiency" will rarely have such gigantic effects; usually the culprit for noticeable "lags" is either memory stalls (hard to guess what's going on), or something going horribly wrong for other reasons (see next bullet).
e) just a hunch: I would check rays where some of the direction components are 0. In this case you're dividing by 0 (never a good idea), and in particular if this gets multiplied with 0.f (which in your case can happen) you'll get NaNs, and since "comparison with NaN is always false" you may end with cases where your traversal logic always goes down instead of skipping. Not the same as "efficiency" of your logic, but something to look out for. Good fix is to always change each ray.dir that's 0.f to 1e-6f or so.


text:
Q: How can I pass `userId != 10` in ZF2 and Doctrine? How can I pass userId != 10 in ZF2 and Doctrine?
$entityManager = $this->getEntityManager();
$repository = $entityManager->getRepository('Application\Entity\Usermain');
$emailexists = $repository->findBy(array(
    'userEmail' => $postData['email'],
    'userId!'   => '!'. $postData['id']
));


text:
Q: Laravel 5.5 - Call the backgroud services I am new in laravel and want to call the background service in Laravel 5.5, like I used to call in Codeigniter using exec() function and command inside that.
I tried with the following code:
Route::get('/foo', function () {
    $exitCode = Artisan::call('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);
});


text:
Q: How taking the value of a href attr in a div I have a link, how can i get the value of the alt attr in my href ? (1)

Test

// With $this
$('.delete_user').live('click',function(){
}

Thanks

A: you can take the alt like this
var alt=$('.chat_user').attr('alt');


text:
Q: Unsupported major.minor version 52.0 (unable to load class org.apache.solr.client.solrj.SolrServerException) When I use Tomcat 7.0.73 and Solr 6.4.1 to code something on a servlet, ERRORs like this occured,
"java.lang.UnsupportedClassVersionError: org/apache/solr/client/solrj/SolrServerException : Unsupported major.minor version 52.0 (unable to load class org.apache.solr.client.solrj.SolrServerException)",
I do believe this has nothing to do with code, but a specific Class named SolrServerException. Anyone can tell me how to fix this? Thanks.


text:
Q: Пусть у меня фронт на одном сервере, бэк на другом. Как бы мне это корректно организовать? У меня есть два варианта реализации веб-приложения:

*

*Есть сервер, где работает бэкенд. Отдельно есть сервер, где лежит фронт. При этом, этот сервер, где фронт, он, как бы, просто хостит дист джаваскриптового приложения как статику. Я имею в виду, что там нет никакого серверного кода. Пусть это будет какой-нибудь nginx например. Само джавоскриптовое приложение ходит на сервер бека за данными. На сервере бека настроены Cors. Короче говоря, хостимся на одном хосте, а за данными ходим на другой. Прям из браузера.

*Второй вариант подразумевает тоже два сервера. Но во втором варианте запросы с фронта идут на сервер фронта, который в свою очередь проксирует все на сервер бека.
Прошу описать, какие преимущества/недостатки есть у того и другого подхода.

A: Я бы рискнул сказать, что второй подход в плане применения является доминирующим.
Его преимущества: Он очен прост. Проксирование настраивается в nginx довольно элементарно. Кроме того, Вы сразу получаете кеширование GET - запросов и кучу других плюшек, в котрых nginx действительно хорош - таких, как SSL - сертификаты на фронте, сжатие трафика на фронте и т.п. При этом бэк может быть очень "глупым" и не бояться этого: плохие запросы от злобных хакеров к нему всё равно не придут, фронт отфильтрует. А в ряде случаев фронт прячут ещё и за клоудфлером каким нибудь.
Собственно, единственным преимуществом перврго подхода можно назвать относительную - относительную! - независимость фронта и бэка. Всё остальное при таком подходе - это исчезновение тех преимуществ, которые я описал в первом параграфе.
Как говорил Иа-Иа - "по моему, так". Еще кто то что то добавит?


text:
Q: How to find average of the column Thanks in advance.
How to find avg when the column datatype is character varying in PostgreSQL.
here growth and literacy are character-varying.
Select avg(cast(GROWTH as float)) from census2;

I have created a table name called census2
create table census2
(
    District      VARCHAR(200)
  , STATE          VARCHAR(250)
  , Growth         NUMERIC
  , Sex_Ratio       NUMERIC
  , Literacy        NUMERIC
);

After successful creation while adding CSV file it is displaying errors as
ERROR: invalid input syntax for type numeric: "Growth"
CONTEXT: COPY census2, line 503, column growth: "Growth"


text:
Q: get callback arguments from sinon.spy inside promise javascript I'm running a test using mocha and sinon to get a callback value from inside a promise scope of HTTP-request and it doesn't work due to the async nature of promises. It's because by the time sinon.spy checks on callback, It would have been vanished already and become empty or undefined. Here's the testing code:
 it('should issue GET /messages ', function() {
  server.respondWith('GET', `${apiUrl}/messages?counter=0`, JSON.stringify([]));
  let callback = sinon.spy();
  Babble.getMessages(0, callback);
  server.respond();
  sinon.assert.calledWith(callback, []);
});

and the promise:
function requestPoll(props) {
    return new Promise(function(resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.open(props.method, props.action);
            xhr.timeout = 500; // time in milliseconds
            if (props.method === 'post' ) {
                    xhr.setRequestHeader('Content-Type', 'application/json');
            }
            xhr.addEventListener('load', function(e) {
                    resolve(e.target.responseText);
            });

            xhr.send(JSON.stringify(props.data));

    });
}

and the call which I'm trying to get callback from on sinon.spy
getMessages: function(counter, callback){

            requestPoll({

                            method: "GET",
                            action: "http://localhost:9090/messages?counter="+counter

            }).then(function(result){

                    callback(result);
            });

        }

sinon.spy says it didn't have any arguments (due to async functionality). I tried to look for a way to get result outside the scope and put it on callback.yet I found out it was impossible. also tried resolve and promise return but didn't succeed.
How can I make this unit test pass?
Edit:
this is my attempt:
getMessages: function(counter, callback){

            var res;
            res = httpRequestAsync("GET",'',"http://localhost:9097/messages?counter=",counter);

            console.log(res);
            if(res!="")
                    callback( JSON.parse(res) );
        }

I put the request in a separate function:
function httpRequestAsync(method,data,theUrl,counter)
    {

            return requestPoll({

                    method: method,
                    action: theUrl+counter,
                    data: data

            }).then(JSON.parse);

    }

It returned res as the promise and inside its prototype there's the promised value I need.

How can I access that promised value over there?

A: I recommend you not to mix promises and callbacks. If you already have promise based function stick with it
First make getMessages not to break promise chaing. Make it return a Promise
getMessages: function(counter) {
  return requestPoll({
    method: "GET",
    action: "http://localhost:9090/messages?counter=" + counter
  }).then(JSON.parse)
}

Then use this promise in your test
it('should issue GET /messages ', function() {
  server.respondWith('GET', `${apiUrl}/messages?counter=0`, JSON.stringify([{testdata}]));
  const gettingMessages = Babble.getMessages(0);
  server.respond();

  // return a promise so testing framework knows the test is async
  return gettingMessages.then(function(messages) {
      // make assertion messages is actually testdata
  })
})


text:
Q: How to use RestTemplate with application/octet-stream response type I am using a ISBNdB to get info about the books.The reponse type is application/octet-stream. A sample json response I get looks as follows
{
"index_searched" : "isbn",
"data" : [
  {
     "publisher_id" : "john_wiley_sons_inc",
     "publisher_name" : "John Wiley & Sons, Inc",
     "title_latin" : "Java programming interviews exposed",
     "language" : "eng",
     "summary" : "",
     "physical_description_text" : "1 online resource (xvi, 368 pages) :",
     "author_data" : [
        {
           "name" : "Markham, Noel",
           "id" : "markham_noel"
        },
        {
           "id" : "greg_milette",
           "name" : "Greg Milette"
        }
     ],
     "title_long" : "Java programming interviews exposed",
     "urls_text" : "",
     "publisher_text" : "New York; John Wiley & Sons, Inc",
     "book_id" : "java_programming_interviews_exposed",
     "awards_text" : "; ",
     "subject_ids" : [],
     "isbn13" : "9781118722862",
     "lcc_number" : "",
     "title" : "Java programming interviews exposed",
     "isbn10" : "1118722868",
     "dewey_decimal" : "005.13/3",
     "edition_info" : "; ",
     "notes" : "\"Wrox programmer to programmer\"--Cover.; Acceso restringido a usuarios UCM = For UCM patrons only.",
     "marc_enc_level" : "",
     "dewey_normal" : "5.133"
  }
  ]
  }

I am using Jackson to convert this reponse. My Pojo looks as follows
@JsonIgnoreProperties(ignoreUnknown = true)

public class value {
    private  String index_searched;
    // Another pojo in different file with ignore properties
    private data[] dat;

    public value(){

    }
    public data[] getDat() {
        return dat;
    }

    public void setDat(data[] dat) {
        this.dat = dat;
    }
    public String getIndex_searched() {
        return index_searched;
    }
    public void setIndex_searched(String index_searched) {
        this.index_searched = index_searched;
    }
   }

When I tried following
  value book = restTemplate.getForObject(FINAL_URL, value.class);

I get this exception
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.rocketrenga.mylibrary.domain.value] and content type [application/octet-stream]

But I am able to map the response to String
String book = restTemplate.getForObject(FINAL_URL, String.class);
ObjectMapper mapper = new ObjectMapper();
value val = mapper.readValue(book, value.class);
System.out.println(val.getIndex_searched());

How to go about mapping the response directly POJO instead of String and converting back to POJO

A: I guess the better solution is to just add another converter, not to modify current ones:
@Bean
public RestTemplate restTemplate() {
    final RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(jacksonSupportsMoreTypes());
    return restTemplate;
}

private HttpMessageConverter jacksonSupportsMoreTypes() {//eg. Gitlab returns JSON as plain text
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaType.parseMediaType("text/plain;charset=utf-8"), MediaType.APPLICATION_OCTET_STREAM));
    return converter;
}

A: You need to conifigure restTemplate with message converters. In your configuration do the following:
   @Bean
    public RestOperations restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

        converter.setSupportedMediaTypes(
                Arrays.asList(new MediaType[]{MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM}));

        restTemplate.setMessageConverters(Arrays.asList(converter, new FormHttpMessageConverter()));
        return restTemplate;
    }


text:
Q: How calculate pipe thickness from moment of inertia I am creating a parametric spreadsheet to predict the behaviour of a sign post when subject to a specified wind speed for a uni assignment . Currently half way through creating the spreadsheet and one of the questions requires me to calculate a wall thickness of the pipe using the moment of inertia.. is this possible? if so how? please help guys all solutions are welcome :)!
Thanks

A: You could use the formula for moment of inertia for a circular ring (cross section of the pipe) but you would need to know the inside or outside diameter of the pipe to pin down its wall thickness. Assumes constant density of pipe material.


text:
Q: Increasing the click area of data-icon="delete" in jQuery mobile (having same image size)? I made a pop up in jQuery Mobile. There is (X) button in popup screen. The icon size is perfect, but I need to increase the click area which should be invisible. In other word the icon size remains the same but the click area is increased.
Here is my fiddle: http://jsfiddle.net/p943a/
$(function(){
  $('#openPopup').click(function(){
    $( "#testCaseId" ).popup( "open" );
  })
})

I need to increase the click of this image.

A: Try this fiddle, I've made the clickable area red to display the new area. To fix this just change the background-color from red to transparent. The size is completely changeable in CSS. Please ask for help if you need it. I only edited CSS.
http://jsfiddle.net/p943a/1/
CSS
.ui-btn-right::before{
    content:"";
    display:block;
    height:40px;
    width:40px;
    position:absolute;
    background:red;
    left:-5px;
    top:-5px;
}

.ui-btn-right{
   position:relative;
   overflow:visible !important;
}


text:
Q: how to insert content in menu of slidebar in bootstrap **I have searched lot but couldn't find the solution
**
i have added a sidebar in my portal webpage and i want to added content in the option so when i click on it .It will display in right side of the page and i want to do it without passing hyperlink because i don't want to write the code of sidebar in all the pages and want to fix sidebar for all pages .Please provide me the solution!
screen shot of mypage
i have to added a content in all the sub-menu


text:
Q: Hyperlink in Excel to a cell to another sheet in same workbook I want to be able to click on a cell with an employee ID and when clicked it hyperlinks to the cell on the 2nd sheet in the same workbook with the same employee ID.
I cannot figure it out...any help is appreciated.
I've tried this...=IF(J2=YES,(HYPERLINK("[us_aiSV2.XLSX!SHEET2]B:B"&MATCH(Sheet1!D:D,0))),"")

A: Let me point to some mistakes in your formula:

*

*Unless there is a named range called "Yes", you need to put the text into double quotes

*The range you construct for the hyperlink does not work.

*The workbook brackets [ and ] are not in the right position. They should be placed around the file name with extension.

*The exclamation mark ! needs to go after the sheet name, not before.

*You can't append a row number to a whole column reference. E.g. B:B"&20

*The Match function is missing the lookup_value argument.

Try along these lines:
=HYPERLINK("[Book1.xlsx]Sheet2!A"&MATCH(A1,Sheet2!A:A,0),"test")

Translated to your formula:
=IF(J2="YES",HYPERLINK("[us_aiSV2.XLSX]SHEET2!B"&MATCH(A2,Sheet1!D:D,0),"text to click"),"")

I don't know in which cell your Employee ID lives. I've used A2. Adjust to suit.


text:
Q: ssh-copy-id on windows doesn't work: No such file or directory I want to copy public keys to my server from a windows system.
And the problem I have is, that I don't get the path to the key.
I've tried things like:
ssh-copy-id -i C:/Users/username/.ssh/mykey.pub user@serverIP

ssh-copy-id -i ~/.ssh/mykey.pub user@serverIP

The result is always

No such file or directory

What am I doing wrong? I'm using Git Bash for this on Windows 10

A: Git's ssh is a version of OpenSSH. You can confirm it by running ssh -V under path\to\git\usr\bin. Here is what it evals on my machine:
OpenSSH_7.7p1, OpenSSL 1.0.2o  27 Mar 2018

ssh-copy-id script internally executes some *nix shell command (like exec, cat, etc. You can find more by opening the one under path\to\git\usr\bin in text mode), so it works only against *nix machines. That's the reason why ssh-copy-id under path\to\git\usr\bin is not a executable file.
According to this issue of PowerShell/Win32-OpenSSH, ssh-copy-id is not supported on Windows.
However, there are some alternative ways to do the same thing:
A powershell version of this answer can be
Get-Content $env:USERPROFILE\.ssh\id_rsa.pub | ssh <user>@<hostname> "cat >> .ssh/authorized_keys"

There is also a python script to do the same thing: ssh-copy-id for Windows.


text:
Q: How to find location of a user in youtube from his comment
I'm making an application about sentiment analysis.
So I want to find the location of a user that post the comment in a Youtube video ?
Is there any approach to do that ?
EDIT
For example I want to know the location; I mean the emplacement ( City or Country or even geo-localisation) any thing that can refer to his emplacement.
I'm using python right now, so I can fetch information of a given video, and his comments, but i don't know any approach to find the location of the comment owner.


text:
Q: Categorizing the survey respondents from the set of questionnaire I want to evaluate the result from the set of questionnaires. 14-item scales will be used and this will include three subscales let's say A, B, and C.
All items will be scored on a 7-point frequency rating scale ranging from 0 (never) to 6(always).
The survey will be conducted from the 109 respondents.
With those 14-item scales in total, I want to categorize the student in three classes.

I wanted to classify the result as High, Medium, and Low.

I know the basic statistics and tools for conducting statistical analysis.
But, I couldn't generate any idea on how to do this type of analysis. Any help or pointing towards the appropriate analysis methods will be appreciated?


text:
Q: What is the Google Chrome address bar font? I think I'm using the last Google Chrome version, which is 8.1. What is the font of the address bar? I'm on Windows 10.

A: You can find it in Settings. Go to Advanced Settings and there is a place you can set the fonts and see what are the fonts that are being used. (On mac it's Preferences > Settings > Advanced Settings). See https://productforums.google.com/forum/#!topic/chrome/uBAYr4WmZXU to confirm you can check font that way. Hope it helps.

A: According to me, the easy way to find a font is to do a printscreen of it, and then use a font finder like https://www.myfonts.com/WhatTheFont/
It will analyse the text and gives you all matching fonts.


text:
Q: What about ternary relations? There is a huge amount of concepts related to binary relations, their properties (reflexivity, symmetry, antisymmetry, transitiveness), and the bundles of their properties (partial orders, equivalence relations, etc.). In addition, it is well know how to compute the number of relations of certain kind for binary relations (how many reflexive binary relations exist in a set of size n? how many symmetric relationships exist between two finite sets?, etc.).
But, what interesting facts or properties have been proposed for ternary relations, generalizing the work on binary relations?


text:
Q: Android Repository pattern - how to update a nested recycler view item from view model
I am using ViewModel and repository pattern to fetch the data in the list. The items are arranged as a list of rows and products. A Row class has products in it. The products can be scrolled horizontally. I am using a recycler view with linear layout manager (horizontal orientation) nested inside another recycler view (vertical orientation). Fetching the items via a ViewModel and rendering in the recycler views is pretty straightforward. The challenge is when I try to update the items (their counts) when an item is added to the cart. When the button (plus sign) is clicked, a callback is sent to the view model via a listener. The horizontal adapter sends the request back to the container (vertical) adapter, and the vertical adapter sends it back to the view model.
// The horizontal adapter
class SimpleProductAdapter(
    private val shopId: String,
    private val listener: (product: CartProduct) -> Unit
) :
    ListAdapter<CartProduct, RecyclerView.ViewHolder>(...DiffCallbackGoesHere) {

    // ... some more things here
    fun bind(item: CartProduct?) {
        view.add_to_cart_button.setOnClickListener {
            listener(item)
        }
    }

The vertical adapter has similar structure
class RowAdapter(
    private val shopId: String,
    private val listener: (product: CartProduct) -> Unit
) :
    PagedListAdapter<Row, RecyclerView.ViewHolder>(...RowDiffCallbackGoesHere) {

    // ... some more things here
    fun bind(item: Row?) {
        SimpleProductAdapter(shopId) { product ->
            listener(product)
        }
    }

And the main site inside the fragment where the viewmodel calls exist:
val rowAdapter = RowAdapter(args.shopId) { product->
if (actionType == ADD_TO_CART_ACTION) viewModel.buy(product)
    .observe(viewLifecycleOwner, Observer {
        view.swipe.isRefreshing = it is Resource.Loading
        // I want to update the quantity here on success result
        if(Resource is Success) {}
    })

When the result is Success, I want to update the quantity; two things are challenging here

*

*I am using PagedListAdapter from the paging library which gives me a (supposedly) immutable list of products.

*Even if I update the PagedList and issue a notifyDataSetChanged, it would be too much to do that just to change a single count over a large set of items.

I am hoping to find a way where I can easily target the specific product to update or another alternative that I keep seeing on the web is to build a custom layout manager so that I can have a single adapter that draws everything on a single pass without having to nest the recycler views. That way updating the item would become easier (couldn't find a code example on this).
Any suggestions please.

A: In Paging3, there are plans to eventually add an API to support granular updates without invalidation: https://issuetracker.google.com/160232968
For now, you must invalidate in order to update the backing dataset. In general, DiffUtil will do a pretty good job of hiding this from the user though.


text:
Q: new bridge setup for lxd on fresh host 16.04 and fresh guest 16.04 I am still struggling with an lxd bridge setup for IPv4 for all completely new ubuntu 16.04 installs, hosts and guests.  There is one ethernet adapter on the host, and it needs to be shared by its guests (no NAT!).  the 16.04 new guests are all webservers that need to pick up their own IP addresses from the DHCP network server.  my host boots 16.04 up with an eno1 internet identified by ifconfig (I am never sure when eth0, eth1, or eno1 are needed).  I want the bridge configuration to be permanent forever, and reemerge upon host reboot.
to install, on the fresh host
host# apt install lxd
host# lxc launch ubuntu:16.04 first
host# lxc launch ubuntu:16.04 second
host# # lxc list

I think the needed steps somehow involve the following:

*

*stopping the running containers with lxc

*a change of the /etc/network/interfaces file

*possibly shutting down containers now and/or host networking

*a dpkg-reconfigure -p medium lxd  (what exact answers?)

*an /etc/init.d/networking restart

*starting the running containers with lxc

I am happy to reinstall yet again---I already did this many times, because I am never sure whether my attempts have screwed up something else.  it's painful.  part of this is that I follow certain guides which seem to move along and then somewhere flunk me.
given that I will not have altered anything, how is such a super-plain bridge setup accomplished most easily out of the box for hosts and guests??
help appreciated.
sincerely, /iaw

A: Before using LXD, you have to configure a custom bridge by following these instructions. You may also want to set the dns-search and dns-nameserversoptions in the interfaces file.
Then run sudo lxd init. Configure storage, network and password settings according to your needs. At the end answer "yes" to the question "Do you want to configure the LXD bridge (yes/no)?". In the following dialog answer "No" when asked to configure the default LXD bridge. Then answer "Yes" when asked to use an existing bridge. As "Bridge interface name" enter br0 or whatever you called it in /etc/network/interface. Then lxc launch your container and it will obtain an IP address from your DHCP server.


text:
Q: What is the difference between Xamarin built-in Hot-reload and something like Live Xaml I recently started working on xamarin form app.
In Xamarin there is Host reload which reloads the Design when running (in debug run ).
Then there is Live Xaml which paid so what is the difference between the both of them?

A: Both use the same technique to achieve the same result. It took some time for Xamarin to come up with Hot Reload, so there were some others that came up with this solution. One of which was Live XAML.
I'm not entirely up to date about the features on both, one might have something over the other. But the main difference is: one is developed by Microsoft and supplied with all the other tooling, the other is from a third-party.
Up to you to decide which one you'll use and why.


text:
Q: Codepipeline: Deploy only specific files to s3 I am having trouble with AWS Codepipeline, rather than deploying the entire GitHub repo to an S3 bucket, I would like Codepipeline to only deploy a single file.
Edit:
I am using AWS CodeBuild, my deployment yaml file is this
version: 0.2
phases:
  install:
    runtime-versions:
      nodejs: 8
    commands:
      - npm i npm@latest -g
      - pip install --upgrade pip
      - pip install --upgrade awscli
  pre_build:
    commands:
      - npm install redoc-cli -g
  build:
    commands:
      - redoc-cli bundle ./orchestra/api/api.yml
artifacts:
  files:
    - redoc-static.html

A: You are almost there. You are already exporting just that "one" file (redoc-static.html) that needs to be deployed to S3 from the CodeBuild project (artifacts section of buildspec). Now in your CodePipeline, in the CodeBuild stage, name a new 'Output artifact' for the action, then make sure in the Deploy stage (Deploy to S3) to use this Output Artifact from the Build stage which will include just the one file (build artifact) from the CodeBuild stage.

A: This would be a complete CodePipeline snippet to use in CodeFormation to deploy the content listed as artifacts: / files: into an existing S3 Bucket passed into the template parameter named S3Bucket. Optionally, the "Source" stage here is pulling from a linked GitHub repo. Note that ArtifactBucket is a different "ephemeral" one used by the CodePipeline as an intermediary during the process
  Pipeline:
    Type: AWS::CodePipeline::Pipeline
    Properties:
      RoleArn: !GetAtt CodePipelineServiceRole.Arn
      ArtifactStore:
        Type: S3
        Location: !Ref ArtifactBucket
      Stages:
        - Name: Source
          Actions:
            - Name: App
              ActionTypeId:
                Category: Source
                Owner: ThirdParty
                Version: 1
                Provider: GitHub
              Configuration:
                Owner: !Ref GitHubRepoOwner
                Repo: !Ref GitHubRepo
                Branch: !Ref GitHubBranch
                OAuthToken: !Ref GitHubToken
              OutputArtifacts:
                - Name: App
              RunOrder: 1
        - Name: Build
          Actions:
            - Name: Build
              ActionTypeId:
                Category: Build
                Owner: AWS
                Version: 1
                Provider: CodeBuild
              Configuration:
                ProjectName: !Ref CodeBuildProject
              InputArtifacts:
                - Name: App
              OutputArtifacts:
                - Name: BuildOutput
              RunOrder: 1
        - Name: Deploy
          Actions:
            - Name: Deploy
              ActionTypeId:
                Category: Deploy
                Owner: AWS
                Version: 1
                Provider: S3
              Configuration:
                BucketName: !Ref S3Bucket
                Extract: true
              InputArtifacts:
                - Name: BuildOutput
              RunOrder: 1


text:
Q: sum of quadratic residues We know that when $q$ is a prime $1(\text{mod } 4)$ then
$$
\sum_{R_i}R_i = q(q-1)/4,
$$
where $R_i$ are all the quadratic residues $\text{mod } q$.
I was curious if there is a similar (or some sort of) formula
when $q$ is a prime $3(\text{mod } 4)$.
Thanks!

A: Yes, there's a formula, though not quite as simple: the sum is
$$
\frac12 \left( {q \choose 2} - \frac2w qh \right),
$$
where $h$ is the class number of the quadratic imaginary field
${\bf Q}(\sqrt{-p})$, and $w$ is the number of roots of unity
in that field, so that the factor $2/w$ is just $1$ except for $q=3$
when $2/w = 1/3$.
This is obtained by writing the sum of the residues as
$\frac12 \sum_{r=1}^{p-1} (1+(r/p)) r$, where $(r/p)$ is the Legendre symbol.
The $\sum_r r$ part of this gives $q \choose 2$, and the formula $-2qh/w$ for the
$\sum_r (r/p) r$ part is classical (the factor $2/w$ arises via the
Dirichlet class number formula, see for instance the $d<0$ part of
equation (2) in MathWorld's
"Class Number" page).
[The formula for $q \equiv 1 \bmod 4$
is simple because in that case the identity $(r/p) = (-r/p) = ((p-r)/p)$ yields
$\sum_{r=1}^{p-1} (r/p) r = 0$ by symmetry.]

A: This is a comment too long to fit in the usual format. For any $k$, denote by $r_k$ the remainder of the division of $k^2$ by $q$. Then , the sum we are considering is $S=\displaystyle\sum_{k=1}^{2b+1} r_k $, where $b$ is defined by $q=4b+3$. Leaving aside the case $q=3$, we see that $b$ cannot be divisible by $3$.
Note that modulo $q$, one has
$$
S =\sum_{k=1}^{2b+1} r_k \equiv \sum_{k=1}^{2b+1} k^2
=\frac{(2b+1)(2b+2)(4b+3)}{6}=q \frac{(b+1)(2b+1)}{3} \equiv 0 \ ({\sf mod}\ q).
$$
So $S$ is a multiple of $q$. If we put $T=\frac{S}{q}$, there seems to be no simple
formula for $T$.


text:
Q: What is happening with this search filter in Vue 2?. Cant render items? I have been trying to solve this problem for more than a week, but finally I am forced to ask for help.
I am just implementing a search filter in Vue 2, using Vuetify, but something is going wrong
This is how the search filter looks:
  <v-text-field v-model="search" label="Look for name..."></v-text-field>

I have a variable called search in the component data that is two-binding with the text-field v-model
Secondly, I have an array of items:
items: [
  {
    default: true,
    name: 'Text 1',
  },
  {
    default: false,
    name: 'Text 2',
  },
  {
    default: false,
    name: 'Text 3',
  },
  {
    default: false,
    name: 'Text 4',
  },
],

I render the list in a div using v-for

      <input
        type="radio"
        :checked="item.default"
        @click="changeDefault(item, index)"
      />

{{ item.name }}

This is how the component looks:
List and search filter rendered
How the filter works? Here is the code
filteredItems() {
  if (this.search) {
    return this.items.filter((item) => {
      return item.name.toLowerCase().match(this.search);
    });
  } else {
    return this.items;
  }
},

As you can see in the rendered list, items have a radio button which can be selected. When some of them are clicked, we call a function called changeDefault whose code is this (just get the default true item and set it to false, and the new one to true)
changeDefault(item, index) {
  let indexOfDefaultTrue = this.items.findIndex((item) => item.default === true);
  this.items[indexOfDefaultTrue].default = false;
  this.items[index].default = true;
},

All seems to be working, but the issue is that, if i search for Text 2 (for instance) and click the radio button, it turns to active, but when i clear the filter, it seems like nothing happened
It only happens if i use the search method, if i click an item on the initial list, radio button changes properly.
Text 2 search
After i clear the search
It looks like the list didnt render the new items or something like that? Im big stucked.
Thank you very much, i wish someone can help me!

<template>
  <v-app>
    <v-main>
      <v-text-field v-model="search" label="Look for name..."></v-text-field>

          <input
            type="radio"
            :checked="item.default"
            @click="changeDefault(item, index)"
          />

{{ item.name }}

    </v-main>
  </v-app>
</template>

A: It sounds like 'filteredItems' is not reactive, is it a computed function? As it sounds like it's not rerunning every time 'this.search' is changing.
If you have a larger example of the code, I can take a look.

A: Full Answer:
The problem with the code is that you are using the item index within function 'changeDefault', you should instead use the name of the item, because the index is dynamic, so if you search for 'Text 2', the index that would be used is 0, and not 1:
function changeDefault(clickedItem) {

      let indexOfDefaultTrue   = items.findIndex((item) => item.default === true);
      let indexOfbuttonClicked = items.findIndex((item) => item.name === clickedItem.name);

      items[indexOfDefaultTrue].default = false;
      items[indexOfbuttonClicked].default = true;

    }

And the input radio:
   <input
            type="radio"
            :checked="item.default"
            @click="changeDefault(item)"
          />

Linked to the code:
https://sfc.vuejs.org/#eNqtVMFuozAQ/ZWRLyFSCurunrKh2lX3UqnSXnqre3BhaGjBRrZJEyH+fcc2BGi36qUgJcx45nnmzbM79rtp4kOLbMt2JtNlY8GgbZsrLsu6UdpCBxqLDf2IzJYH3ECm6qa1mEMPhVY1rCh9xSWXmZLGQmmxNpCeE6J7LsE/3fgBkGMh2spuweoWN5Nfihq3sLrDo4VLAg3e/hzxP4hCVOYjjG9fgPH9CzB+vMN4WI+EGRQ623vGimi1Wv+cuCzKyqLG/GbgdKQ+KlpJ5CoZrUMp065lAVFAjA+ianEICI+m0WoZRhQH8Chy1hrSq3ngIjR2ncRW3apX1NfCYLSOa2Gz/XIjqntM7iejByRaPipiCuOyJ0bcO/YG2V7IJ/wT+I2yqsxeAhVvmq6QVCdzPP4thuA7UhUtpOdOZX7jAmbN+saG2UGapl6JU9kzzMfWWiWvw/afYzqyPOCsYO8Mgx2m5DDu3xf9MJUU9HQuaJGxKGme45o4b0OccrlLwrGmA00GgTSVsEhW4K/rFhrrKWeuJtiVkhQHh4ta5VilnIWRcwaVePSOW6VeoFDa6z2OY84Sj+6z8/JAubRKgZ6nTWB1TX9LdXN2zhryjD1VSHl5aajmEx2wCo+LsLG8uQfAnhqXpkVeKs6Wa9tsj44zWp8L4G3YLz87ClpK0A96GTv16svZX1513UwHfb9LyDfrLKHWJn4Gy41pNprpZRsWruGLWjTxs1GSLuog/mGBiNuOp4szuoqdzdne2sZsk8QUmbven02s9FNCX7FupS1pUmjqi0etXg1qAg5duVPI+n9gVOSo


text:
Q: Jupyter Notebook not working with WSL I have installed Windows Subsystem for Linux 2 on my windows computer, and using Ubuntu, have been accessing Jupyter Notebook. This has now stopped working. When I open Ubuntu and type in jupyter notebook it used to give me a link which I copied into Microsoft Edge. I am now getting the following error message.
kathmcp02@DESKTOP-Q2SS990:~$ jupyter notebook
Traceback (most recent call last):
  File "/home/kathmcp02/.local/bin/jupyter-notebook", line 5, in <module>
    from notebook.notebookapp import main
  File "/home/kathmcp02/.local/lib/python3.8/site-packages/notebook/notebookapp.py", line 44, in <module>
    from jinja2 import Environment, FileSystemLoader
ImportError: cannot import name 'Environment' from 'jinja2' (/home/kathmcp02/.local/lib/python3.8/site-packages/jinja2/__init__.py)
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 72, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 32, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 12, in <module>
    import os, glob, subprocess, os.path, time, pwd, sys, requests_unixsocket
  File "/usr/lib/python3/dist-packages/requests_unixsocket/__init__.py", line 4, in <module>
    from .adapters import UnixAdapter
  File "/usr/lib/python3/dist-packages/requests_unixsocket/adapters.py", line 3, in <module>
    from requests.adapters import HTTPAdapter
ImportError: cannot import name 'HTTPAdapter' from 'requests.adapters' (/home/kathmcp02/.local/lib/python3.8/site-packages/requests/adapters.py)

Original exception was:
Traceback (most recent call last):
  File "/home/kathmcp02/.local/bin/jupyter-notebook", line 5, in <module>
    from notebook.notebookapp import main
  File "/home/kathmcp02/.local/lib/python3.8/site-packages/notebook/notebookapp.py", line 44, in <module>
    from jinja2 import Environment, FileSystemLoader
ImportError: cannot import name 'Environment' from 'jinja2' (/home/kathmcp02/.local/lib/python3.8/site-packages/jinja2/__init__.py)

I am not very computer savvy, so any help would be much appreciated. Thank you!


text:
Q: Refused to display 'domain name displayed here' in a frame because it set 'X-Frame-Options' to 'sameorigin' We have a web application deployed in Jboss 7.2 Server. In some other domain we are trying to load and show our application URL inside Iframe. We are getting the error in browser console log Refused to display 'domain name displayed here' in a frame because it set 'X-Frame-Options' to 'sameorigin'. Below are the things I tried doing but still facing the same issue. Please help me out if you know the solution for this problem.
•  Removed SAMEORIGIN configuration entry from JBoss Standalone.xml <response-header name="x-frame-options" header-name="X-Frame-Options" header-value="SAMEORIGIN"/>
•  Set HTTPServlet response object Access control header to allow all domains  response.setHeader("access-control-allow-origin", "*");
• Set HTTPServlet response object Set-Cookie attribute as None response.addHeader("Set-Cookie", String.format("%s; %s", header, "SameSite=None"));
Below is my Jboss Standalone configuration
<subsystem xmlns="urn:jboss:domain:undertow:11.0" default-server="default-server" default-virtual-host="default-host" default-servlet-container="default" default-security-domain="other" statistics-enabled="${wildfly.undertow.statistics-enabled:${wildfly.statistics-enabled:false}}">
    <buffer-cache name="default"/>
    <server name="default-server">
        <http-listener name="default" socket-binding="http" redirect-socket="https" enable-http2="true"/>
        <https-listener name="https" socket-binding="https" security-realm="ApplicationRealm" enable-http2="true"/>
        <host name="default-host" alias="localhost">
            <location name="/" handler="welcome-content"/>
            <http-invoker security-realm="ApplicationRealm"/>
                <filter-ref name="server-header"/>
                <filter-ref name="x-powered-by-header"/>
                <filter-ref name="Access-Control-Allow-Origin"/>
                <filter-ref name="Access-Control-Allow-Methods"/>
                <filter-ref name="Access-Control-Allow-Headers"/>
                <filter-ref name="Access-Control-Allow-Credentials"/>
                <filter-ref name="Access-Control-Max-Age"/>
        </host>
    </server>
    <servlet-container name="default">
        <jsp-config/>
        <websockets/>
    </servlet-container>
    <handlers>
        <file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>
    </handlers>
    <filters>
        <response-header name="server-header" header-name="Server" header-value="WildFly/10"/>
        <response-header name="x-powered-by-header" header-name="X-Powered-By" header-value="Undertow/1"/>
        <response-header name="Access-Control-Allow-Origin" header-name="Access-Control-Allow-Origin" header-value="*"/>
        <response-header name="Access-Control-Allow-Methods" header-name="Access-Control-Allow-Methods" header-value="GET, POST, OPTIONS, PUT"/>
        <response-header name="Access-Control-Allow-Headers" header-name="Access-Control-Allow-Headers" header-value="accept, authorization, content-type, x-requested-with"/>
        <response-header name="Access-Control-Allow-Credentials" header-name="Access-Control-Allow-Credentials" header-value="true"/>
        <response-header name="Access-Control-Max-Age" header-name="Access-Control-Max-Age" header-value="1"/>
    </filters>
</subsystem>

A: Configuration changes you did on Wildfly look all good to allow it.
Are you sure that in response you are still getting "X-Frame-Options" as a header?
If not, it seems blocked on the browser. See this: https://www.thegeekstuff.com/2016/09/disable-same-origin-policy/
PS: same-origin policy is enforced for security reasons. Keep a thought on that, while you take a decision.


text:
Q: Change font in textarea I'm trying to change the font that is displayed in a text area however, I don't want to use CSS in the <head> tags. Is it possible to not use CSS at all since I don't want it in the head tags? Will I need to import styling files?

A: That is unnecessary, you can edit the font using inline CSS:
<textarea style="font-family:calibri"></textarea>


text:
Q: reverse every alternate k nodes I m new ds. I was trying this question-Given a linked list, write a function to reverse every alternate k nodes (where k is an input to the function) in an efficient way. Give the complexity of your algorithm. My code is giving me segmentation fault. Help!

struct node* func(struct node* head, int k)
{
    struct node* run, *list1;
    run =head->next;
    list1=head;

    int count =0;

    struct node *list2=NULL;

while(list1!=NULL && count++<k)
{
    list1->next=list2;
    list2=list1;
    list1=run;
    run=list1->next;
}

head=list2;

while(list2->next!=NULL && list2!=NULL)
    list2=list2->next;

list2->next=list1;

while(list1!=NULL && count++<k-1)
    list1=list1->next;

if(list1!=NULL)
    list1->next=func( head, k);
    return head;
}

A: struct node* func_aux(struct node* head, struct node* rev, int k){
    struct node* next;
    if(k == 0 || head == NULL)
        return rev;
    next = head->next;
    head->next = rev;
    return func_aux(next, head, --k);
}

struct node* func(struct node* head, int k){
    struct node* kth_node;
    int i=0;
    for(kth_node=head;kth_node;kth_node=kth_node->next,++i){
        if(k==i)break;
    }
    return func_aux(head, kth_node, k);
}


text:
Q: SSIS prefilter records before extraction I have to migrate records from a table in Oracle to SQL Server 2008 R2. I already designed the solution that allows me to move the data and save a copy of the migrated IDs into a stage table.

Thanks to a Lookup component and the stage table I can ensure to avoid duplicates, since the migration is done in several different moments and the objects migrated do not follow a specific sequencial order.
Below my SSIS schema:

I use an expression and two variables to gather data from Oracle in slots:
SELECT *
FROM ORDERS
WHERE OrderID > [@User::Start] AND OrderID <= [@User::End]
AND STATUS <> 'Open'

When all the orders that are not in statsu "Open" have been migrated, we will migrate the remaining delta. To do this I need to lookup to the aready migrated data in Stage. SO the query for the data source will be:
SELECT *
FROM ORDERS
WHERE OrderID NOT IN ([@User::AlreadyMigratedIDs])

My need would be able to store in variable "AlreadyMigratedIDs" all the IDs present in table Stage.
How would it be possible to use the information in the stage table (on SQL Server) as a condition for the query used in the ADO.net component to gather the source data from Oracle? Can I use any other SSIS, like lookup, before the ADO.net object?

A: Use Execute SQL Task before your Data Flow  to store the values of User::Start and User::End from the sql server staging table
 Name     Data Type
 StartID   int
 EndID     int

Use ResultSet as Single Row
For sample I have taken the query  from Adventure Works 2008 R2
Select max([BusinessEntityID]) as StartID
      ,max([DepartmentID]) as EndID
FROM [AdventureWorks2008R2].[HumanResources].[EmployeeDepartmentHistory]

Change the above query to match your needs to get the ID values from your staging table
In the resultset match the results to the variables created

Now use the 2 variables in your oracle query
 SELECT *
 FROM ORDERS
 WHERE OrderID > [@User::StartID] AND OrderID <= [@User::EndID]
 AND STATUS <> 'Open'


text:
Q: Migrate Java Web project from Maven to Ant I have a Maven Web Application with Spring MVC and I need to convert it into a Java Web Application build with Ant. I am using Netbeans. The path structure should be the same? What configuration files should I add, remove, or change?
The reason of the change is beacuse I need to run the application without Internet connection.


text:
Q: iOS Youtube API v3 retrieve my channels [IOS SWIFT]
I have a problem with youtube api v3, and I really hit a dead end
So, in my app I have newest GoogleSign-In implemented
let newScope: Array =
        ["https://www.googleapis.com/auth/youtube",
         "https://www.googleapis.com/auth/youtube.force-ssl",
         "https://www.googleapis.com/auth/youtube.readonly"]
GIDSignIn.sharedInstance().scopes = newScope

This shows how I add new scopes.
I successfully sign in user and retreive user id, it's data, access_token etc.
Now that the user is signedin, I need to get his youtubeId/channelId.
I did some research and I found that I can get my channel id with: https://www.googleapis.com/youtube/v3/channels?part=id&mine=true&key={API_KEY_HERE}
I even tried to send access_token in url, but with no luck..
But something is wrong and I get 401 status code -

The request uses the mine parameter but is not properly
  authorized.

What am I doing wrong?
Here I tested and everything works fine: https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.channels.list
result here in sandbox:
{
 "kind": "youtube#channelListResponse",
 "etag": "\"XXXXXXX\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#channel",
   "etag": "\"XXXXX\"",
   "id": "XXXXX",
   "googlePlusUserId": "ID_ID_ID"
   }
  }
 ]
}

Anyone have idea? solution? proposal?
Thankyou very much
In fact, why am I not authorized if I just successfully signedIn myself??
Tried even adding header for authorization:
Bearer {id_access_token}

A: I finally found the solution.
Yes, the header needs to be send. The only problem was with token!
When the signIn is successful, you get
GIDGoogleUser

instance.
That - lets call it "user", have .authentication with userID, idToken and accessToken
In documentation there is only mention of idToken, so I thought that this is actually the access token. How silly of me :/
Lesson learned!


text:
Q: Can not remove object from knockout observableArray I have troubles with removing object from my observable array.
It's declaration:
self.points = ko.observableArray([]);

It's holding:
self.map.points.push(new google.maps.LatLng(a, b));

I'm trying to remove some elements from this array using this code:
self.points.remove(val.internalMarker.position)

Where val.internalMarker.position hold the same LatLong object initialized with the same values as that point.
But for unknown reason remove function leaves array untouched.
Here You can check my full code on JSFiddle

A: Have you tried this?
self.points.remove(function(pos) {
    return pos.lat() == val.internalMarker.postition.lat()
        && pos.lng() == val.internalMarker.postition.lng();
})

Knockout's observableArray.remove overload that takes a single parameter will not work unless the object you want to remove is the exact same object. In your question, it sounds like the LatLng is not the same exact object, just that it contains the same exact lat & lng values. In these cases, you have to pass a function that compares the values you are interested in between the 2 object instances.


text:
Q: Enforcing const correctness with pointer and reference members Suppose we a class Mutable which has a non-const member function, void Mutable::mutate(), and a class having a data member of type Mutable. Calls to mutate on said member in a function that is declared const is then prohibited. In code:
class Mutable
{
public:
    void mutate();
};

class UseMutable
{
    Mutable m;
public:
    int compute() const
    {
        // does not compile
        m.mutate();
        return 42;
    }
};

If the type of m were a reference or a (shared) pointer to Mutable instead, we lose the compile time protection:
class UseMutablePtr
{
    Mutable* m;
public:
    int compute() const
    {
        // compiles =(
        m->mutate();
        return 42;
    }
};

or
class UseMutableRef
{
    Mutable& m;
public:
    int compute() const
    {
        // compiles =(
        m.mutate();
        return 42;
    }
};

How does one prevent this behaviour?
If only const member functions of Mutable are to be called, one can use const Mutable& or const Mutable* (or the corresponding std::..._ptr<const Mutable>, but what if one wants to call both const and non-const member functions of Mutable?
For pointers one could use a custom smart pointer which overloads the arrow and dereferencing operators as
template<class T>
class CustomSmartPtr
{
    T* ptr;
public:
    T* operator->() { return ptr; }
    const T* operator->() const { return ptr; }

    T& operator*() { return *ptr; }
    const T& operator*() const { return *ptr; }
};

since the smart pointers in the standard libary behave like normal pointers in this regard. For a replacement of unique_ptr this is not that big of a hassle, but for shared_ptr quite some effort is required.
For references the only thing that comes to mind is to reimplement std::reference_wrapper with the desired behaviour, i.e. to have conversion operators with the desired signature. This is again not too bad.
Are there "cheaper" ways to enforce the desired behaviour, or is there maybe some tooling that would at least detect violations?
Out of curiosity: why is this the default?
I have not yet come across an instance where this default behaviour is really desired, but have seen subtle bug that could have been prevented. Is this behaviour at least partially due to interoperability with C?


text:
Q: SharePoint Search Service is locking files on the fileshare being crawled SharePoint is locking files on the file share that it's crawling.  At times, we need to be able to delete or replace files with newer versions on this file share, but we're unable to.
Is there any way to prevent SharePoint from locking these files so that they may be deleted?

A: I would use Process Monitor to see what process locks the file - normally SharePoint releases the file once it's copied for processing.


text:
Q: How to filter data by array I have data array and i want to filter data by array.
Below is my array.
[1,3,4]

Below is my data
[
    {id: 1, content_tag: 'Test'}
    {id: 2, content_tag: 'test 1'}
    {id: 3, content_tag: 'test 2'}
    {id: 4, content_tag: 'test 3'}
]

I want result as like below:
[
    {id: 1, content_tag: 'Test'}
    {id: 3, content_tag: 'test 2'}
    {id: 4, content_tag: 'test 3'}
]

A: Use array methods filter and include to compare two arrays
let arr1 = [1,3,4]

let arr2 = [
    {id: 1, content_tag: 'Test'},
    {id: 2, content_tag: 'test 1'},
    {id: 3, content_tag: 'test 2'},
    {id: 4, content_tag: 'test 3'}
]

arr2.filter(eachElement => arr1.includes(eachElement.id))


text:
Q: How to mark up 1 column (without rows) and 2 columns with 3 rows in each column 1) 1st column should have the same height as the other 2
2) 1st column should have 40% width, whereas each other columns have 30%
3) rows in the last 2 columns should have the same height
4) First 2 rows should have 40% height, whereas the last row on 20%
I attached a picture to make it clear
Many thanks

A:

body, html, #fs {
width:100%;
height:100%;
margin:0;
padding:0;
}
#i1-table {
display:table;
width:100%;
height:100%;
}
#i1-trow {
    display:table-row;
    width:100%;
    height:100%;
}
#i1-rowspan {
display: table-cell;
height:100%;
width:40%;
background-color:red;
text-align:center;
vertical-align:middle;
}
#i1-rowcont {
display: table-cell;
height:100%;
width:60%;
}
#i1-table-in {
display:table;
width:100%;
height:100%;
}
.i1-rowcont-row1 {
display: table-row;
height:40%;
width:100%;
}
.i1-rowcont-row2 {
display: table-row;
height:20%;
width:100%;
}
.i1-cell1 {
display: table-cell;
width:50%;
text-align:center;
vertical-align:middle;
}
.i1-cell2 {
display: table-cell;
width:50%;
text-align:center;
vertical-align:middle;
}

    1

    2

    3

    4

    5

    6

    7


text:
Q: MFC assertion to work in global destructors I'm writing an MFC GUI app with Visual Studio 2017. And I was naturally using its ASSERT/VERIFY macros to do some debugger code checks. But unfortunately those do not work in global destructors. For instance, if I have something like this:
struct MY_STRUCT{
    HANDLE hHandle;

    MY_STRUCT()
        : hHandle(NULL)
    {
    }

    ~MY_STRUCT()
    {
        //Make sure handle was released
        ASSERT(hHandle == NULL);
    }
};

//On the global scale
MY_STRUCT mys;

If assertion in the destructor of MY_STRUCT is triggered, it will only produce a warning beep but the assertion dialog box will not be shown, and the process will terminate. So it's very hard to see which ASSERT produced it.
(This happens because the MessageBox function that is used internally by ASSERT cannot show a dialog window when the process is terminating.)
To address it I was using FatalAppExit API for my own version of that macro that I defined as such:
#ifdef _DEBUG
#define ASSERT2(f) {if(!(f))\
{\
        char __buffer123456789[256*4];\
        wsprintfA(__buffer123456789, "ASSERTION!!!\nFile: %s\nLine: %d\nGetLastError() = %d", __FILE__, __LINE__, ::GetLastError());\
        FatalAppExitA(0, __buffer123456789);\
}}
#else
#define ASSERT2(f) ((void)0)
#endif

And even though my ASSERT2 seems to be showing an assertion dialog box while stopping the process from exiting:

It does not give me an option to break if I'm running my process under VS 2017 debugger.
Does anyone have a solution where I can:

*

*Break my GUI process.

*Display an assertion dialog box.

*Have an option to invoke my JIT debugger if I'm running the process under it.

PS. I am not asking about text file error logging here.

A: I found a solution soon after I posted this question. Here it is:
#ifdef _DEBUG
#define ASSERT2(f) {if(!(f))\
{\
        if(::IsDebuggerPresent()) { ::DebugBreak(); } \
        char __buffer123456789[256*4];\
        wsprintfA(__buffer123456789, "ASSERTION!!!\nFile: %s\nLine: %d\nGetLastError() = %d", __FILE__, __LINE__, ::GetLastError());\
        FatalAppExitA(0, __buffer123456789);\
}}
#else
#define ASSERT2(f) ((void)0)
#endif

#ifdef _DEBUG
#define VERIFY2(f) ASSERT2(f)
#else
#define VERIFY2(f) ((void)(f))
#endif

I'll keep this question in case someone has a better idea.


text:
Q: Как бы вы произвели проверку массива, который содержит список массивов с значениями для проверки Массив может выглядить так, причем количество ключей в следующем внутреннем массиве может отличаться. По окончанию проверки каждого значения, массив должен выглядить также. Учитывать стоит, что значение может быть текстовым.
Array
(
    [0] => Array
        (
            [year] => 2008
            [faculty] => 4
            [program] => 10
            [...] => ...
        )

    [1] => Array
        (
            [agree] => on
            [year] => 2010
            [faculty] => 47
            [program] => 4
            [...] => ...
        )
     ...
)

Писать код не нужно, достаточно рассказать на словах или в крайнем случае рассказ дополнить псевдокодом.
Для чего мне это ? Просто интересно ) Сам столкнулся, с подобным массивом и лучшего решения чем, как пройтись циклом с условными конструкциями if не придумал...
A: Функция in_array() проверяет, присутствует ли в массиве заданный элемент. Если присутствует, возвращает значение true, иначе false.
   Синтаксис функции:
bool in_array(mexed элемент, array массив)

array_keys() эта функция возвращает массив, содержащий все ключи исходного массива, переданного в качестве параметра. Если при вызове задаётся дополнительный параметр "искомый элемент" возвращаются только ключи, которым соответствует заданное значение; в противном случае возвращается все ключи массива.
   Синтаксис функции:
array array_keys(array массив, [, mixed искомый_элемент])

array_values() функция возвращает массив, состоящий из всех значений исходного массива, переданного в качестве параметра.
   Синтаксис функции:
array array_values(array массив)

Можно через эти функции делать поиск. Создать массив элементов которые надо проверить. и в цикле искать этими функциями каждый элемент или другие функции поиска в массиве элементов содержащихся в массиве)
A: А я бы воспользовался фукнцией array_filter() с callback.
Если $array - исходный массив, то
$filtered = array_filter($array, function($elem) {
    [здесь проверять все условия к конкретному подмассиву
    если условия выполняются - return true; если не выполняются - return false;
    тут уже ограничений нет. Например:
    if ($elem["agree"]!="on") return false;
    if (!array_key_exists("whatever", $elem)) return false;
    if ($elem["year"]>date('Y')) return false;
    вобщем все, что угодно....
});

В результате $filtered будут только те записи, в которых проверочный callback вернул true.


text:
Q: An ergodic theorem on the circle Let $S^1$ be a circle (i.e. a closed $1$-dim. manifold) and let $F$ be a non-vanishing smooth vector field on $S^1$. Denote by $(t,x)   \mapsto \Phi_t^x$ the flow generated by $F$.
I want to show that there exists an absolutely continuous probability measure $\pi$
with strictly positive density $\rho$ such that  for every bounded measurable function $f$ and every $x\in S^1$
$  \lim_{t\rightarrow \infty}    \frac{1}{t}\int_0^t  f(\Phi_s^x) ds   \ = \  \int_{S^1} f(x) \pi (dx) \ \ \  \ $   (*)
From (*) it follows that $\pi$ is invariant, i.e. $\int_{S^1} f(\Phi_t^x) \pi(dx) \ = \ \int_{S^1} f(x) \pi(dx)$. I would also like to show that $\pi$ is the unique invariant measure.
What I did until now:
Denote by $\tau$ the time needed to return in $x$ when starting from $x$ and following the flow $\Phi$ and denote by $n_t$ the number of times $t\mapsto \Phi_t^x$ returned in $x$ up to time $t$. Observe that
$0<\tau<\text{const}$ and that both $\tau$ and $n_t$ are independent of $x$.
Then
$    \frac{1}{t}\int_0^t  f(\Phi_s^x) ds   \ = \     \frac{n_t\tau}{t}  \  \frac{1}{n_t } \sum_{k=1}^{n_t}   \   \frac{1}{\tau}\int_0^{\tau} f(\Phi_s^x) ds   \  +   \   \frac{1}{t} \int_{n_t\tau}^t f(\Phi_s^x) ds   $
So using the boundedness of $f$ and of $t-n_t\tau$ and the fact that $\frac{n_t\tau}{t}\rightarrow 1$ I get for every $x\in S^1$
$ \frac{1}{t}\int_0^t  f(\Phi_s^x) ds   \rightarrow \     \frac{1}{\tau}\int_0^{\tau} f(\Phi_s^x) ds  $
with the right hand side in fact independent of $x$. Now I guess I should use some Riesz representation theorem for functionals to show existence of $\pi$ such that for every bounded measurable function
$ \frac{1}{\tau}\int_0^{\tau} f(\Phi_s^x) ds    \   =   \   \int_{S^1} f(x) \pi (dx)  $
Can somebody hint to a precise reference or give some alternative (maybe more selfcontained) argument? I have no clue for the moment on how to show the existence of $\rho$ (or to find a counterexample if it is not true).

A: Let me try to complete your argument by showing that there is an a.c. measure $\pi$ for which
$$
\frac{1}{\tau} \int_0^{\tau} f(\Phi_s^x) ds = \int_{S^1} f(x) \pi(dx)
$$
where $f \in C(S^1)$ is any continuous function (and the LHS is for a fixed $x$, say $x = 0$ writing $S^1 = \mathbb{R} / \mathbb{Z} \cong [0,1)$).
First note that $\Phi_s^0 : [0,\tau) \to S^1$ is a diffeomorphism, and that because the vector field for this flow is nonvanishing, it has a nonvanishing time derivative $\frac{d}{ds} \Phi_s^0$. So,
$$
\frac{1}{\tau} \int_0^{\tau} f(\Phi_s^0) ds = \int_{S^1} f(x) h'(x) dx
$$
by the change of variables formula, where $h :S^1 \to [0,\tau)$ is the inverse of $s \mapsto \Phi_s^0$. Check that $h'$ is nonvanishing.


text:
Q: Rails Devise attr_accessible problem Im trying to add devise authorization to my rails 3 app.
Its all going well except Im also trying to follow this tutorial to dynamically set attr_accessible for role_ids only for admin users (I dont want regular users changing their role, but an admin should be able to do so)... the problem is, the railscast tutorial approach assumes I have access to change the controller behavior when in fact devise is handling all that under the hood.
Please Help

A: You can subclass the Devise controllers, you just have to generate the views and move them to the correct place. Check out "Configuring views" and "Configuring controllers" in the Devise readme.
I ended up adding role_ids to attr_accessible, then subclassing the RegistrationsController and adding a before_filter to remove that param for non-admins.
class Users::RegistrationsController < Devise::RegistrationsController
  before_filter :remove_admin_params, :only => [:create, :update]

protected
  # disable setting the role_ids value unless an admin is doing the edit.
  def remove_admin_params
    params[:user].delete(:role_ids) unless current_user.try(:admin?)
  end
end

Just make sure to add the registration views to /app/views/users/registrations/.

A: The best way I found to handle this is from RailsCast 237.  It is more verbose than Arrel's answer, but it does not force you to add role (or other fields) to attr_accessible.
Add the following method in an initializer:
class ActiveRecord::Base
  attr_accessible
  attr_accessor :accessible

  private

  def mass_assignment_authorizer(role = :default)
    if accessible == :all
      self.class.protected_attributes # hack
    else
      # super returns a whitelist object
      super + (accessible || [])
    end
  end
end

Then in your controller, you can do:
user.accessible = :role if can? :set_role, resource
This call, unfortunately, has to be made after the user (or whatever) object has been instantiated.  That means that you would have to subclass the controller, and call this after the resource instantiation in update and create.
This is for Rails 3.2.  In earlier versions I believe the method mass_assignment_authorizer does not take a parameter.  The attr_accessible with no values sets a fail-safe application wide denial for mass assignment.  This can also be done in the application.rb file with
config.active_record.whitelist_attributes = true


text:
Q: mvvmcross - multiple Init methods in viewmodel with different signature not working in a main viewmodel where i collect data from another viewmodels, I created in summary two or three public Init methods with different signatures. When i navigate back to the base viewmodel from the other viewmodels with ShowViewModel, I awaited that the right Init method will be executed, but this don't happen. Regarding the greet practical documentation here:
http://slodge.blogspot.ch/2013/03/v3-new-viewmodel-lifecycle.html
This should be work :-/.
I will explain this with some code.
My main view model is e.g.:
public class MainViewModel : MvxViewModel
{
     MainViewModel() {}

     public class ParameterFirst
     {
         public string Id { get; set; }
     }

     public class ParameterSecond
     {
         public string Id { get; set; }
     }

     public class ParameterSecond
     {
         public string Id { get; set; }
     }

     public class ParameterThird
     {
         public string Id { get; set; }
     }

     public void Init(ParameterFirst objFirst)
     {
          //do something
     }

     public void Init(ParameterSecond objSecond)
     {
          //do something
     }

     public void Init(ParameterThird objThird)
     {
          //do something
     }
}

Then I will navigate from another viewmodel and await that the right Init method will be executed:
public class CollectData_ONE_ViewModel : MvxViewModel
{
     CollectData_ONE_ViewModel() {}

     public void DidWork()
     {
          //Hopefully the Init method with argument ParameterFirst should be called
          base.ShowViewModel<MainViewModel>(new MainViewModel.ParameterFirst { Id = "11" });
     }
}

next here the second viewmodel
public class CollectData_SECOND_ViewModel : MvxViewModel
{
     CollectData_SECOND_ViewModel() {}

     public void DidWork()
     {
          //Hopefully the Init method with argument ParameterFirst should be called
          base.ShowViewModel<MainViewModel>(new MainViewModel.ParameterSecond { Id = "22" });
     }
}

and the third viewmodel
public class CollectData_THIRD_ViewModel : MvxViewModel
{
     CollectData_THIRD_ViewModel() {}

     public void DidWork()
     {
          //Hopefully the Init method with argument ParameterFirst should be called
          base.ShowViewModel<MainViewModel>(new MainViewModel.ParameterThird { Id = "33" });
     }
}

In my code, each time the First Init method is called, I'm really at the end and don't have further ideas :) Did anyone here experienced the same issue? Or do anyone here have another Idea to collect data to the main viewmodel in an elegant way? Thanks a lot in advance for reading :)

A: The Init mechanism in MvvmCross is deliberately lightweight. If you declare multiple methods, all of them will be called - this is by design. Also if some of the Init parameter objects were to share properties then these would clash - see Custom types in Navigation parameters in v3
As it says in the blog post you reference "generally you will probably only want to use one within your application" - so I'd recommend refactoring to a single navigation parameter object and using your own ViewModel-based logic to decide how your ViewModel should initialise.
If you really do need three Init methods called in three different situations, then you can easily pack and unpack your own parameter objects using a custom method (possibly in a BaseViewModel class) like in https://stackoverflow.com/a/19059938/373321


text:
Q: Cannot run entrypoint script in Docker with Flask and Flask Migrate, even though it works in Terminal I have a Flask API that connects to an Azure SQL database, deployed on Azure App Service in a Docker Image.
It works fine but I am trying to keep consistency between my development, staging and production environments using Alembic/Flask-Migrate to apply database upgrades.
I saw on Miguel Grinberg's Docker Deployment Tutorial, that this can be achieved by adding the flask db upgrade command to a boot.sh script, like so:
#!/bin/sh
flask db upgrade
exec gunicorn -w 4 -b :5000 --access-logfile - --error-logfile - app:app

My problem is that, when running the boot.sh script, I receive the error:
Usage: flask db [OPTIONS] COMMAND [ARGS]...
Try 'flask db --help' for help.

'.ror: No such command 'upgrade

Which indicates the script cannot find the Flask-Migrate library. This actually happens if I try other site-packages, such as just trying to run flask commands.
The weird thing is:

*

*gunicorn works just fine

*The API works just fine

*I can run flask db upgrade with no problem if I fire up the container and open a terminal session with docker exec -i -t api /bin/sh
Obviously, there's a problem with my Dockerfile. I would massively appreciate any help here as I'm relatively new to Docker and Linux so I'm sure I'm missing something obvious:
EDIT: It also works just fine if I add the following line to my Dockerfile, just before the entrypoint CMD:
RUN flask db upgrade

Dockerfile
FROM python:3.8-alpine

# Dependencies for pyodbc on Linux
RUN apk update
RUN apk add curl sudo build-base unixodbc-dev unixodbc freetds-dev
RUN apk add gcc musl-dev libffi-dev openssl-dev
RUN apk add --no-cache tzdata
RUN rm -rf /var/cache/apk/*
RUN curl -O https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/msodbcsql17_17.5.2.2-1_amd64.apk
RUN sudo sudo apk add --allow-untrusted msodbcsql17_17.5.2.2-1_amd64.apk

RUN mkdir /code
WORKDIR /code

COPY requirements.txt requirements.txt
RUN python -m pip install --default-timeout=100 -r requirements.txt
RUN python -m pip install gunicorn
ADD . /code/

COPY boot.sh /usr/local/bin/
RUN chmod u+x /usr/local/bin/boot.sh
EXPOSE 5000
ENTRYPOINT ["sh", "boot.sh"]

A: I ended up making some major changes to my Dockerfile and boot.sh script. I'll share these as best I can below:
Problem 1: Entrypoint script cannot access directories
My main issue was that I had an inconsistent folder structure in my directory. There were 2 boot.sh scripts and the one being run on entrypoint either had the wrong permissions or was in the wrong place to find my site packages.
I simplified the copying of files from my local machine to the Docker image like so:
RUN mkdir /code
WORKDIR /code

COPY requirements.txt requirements.txt
RUN python -m venv venv
RUN venv/bin/pip install --default-timeout=100 -r requirements.txt
RUN venv/bin/pip install gunicorn

COPY app app
COPY migrations migrations
COPY api.py config.py boot.sh ./
RUN chmod u+x boot.sh

EXPOSE 5000
ENTRYPOINT ["./boot.sh"]

The changes involved:

*

*Setting up a virtualenv and installing all site packages in there

*Making sure the config.py, boot.sh, and api.py files were in the root directory of the application folder (./)

*Changing the entrypoint command from ["bin/sh", "boot.sh"] to just ["./boot.sh"]

*Moving migrations files into the relevant folder for the upgrade script

I was then able to activate the virtual environment in the entrypoint file, and run the flask upgrade commands (NB: I had a problem with line endings being CRLF instead of LF in boot.sh, so make sure to change it if on Windows):
#!/bin/bash
source venv/bin/activate
flask db upgrade
exec gunicorn -w 4 -b :5000 --access-logfile - --error-logfile - api:app

Problem 2: Alpine Linux Too Slow
My other issue was that my image was taking forever to build (upwards of 45 mins) on Alpine Linux. Turns out this is a pretty well-established issue when using some of the libraries in my API (Pandas, Numpy).
I switched to a Debian build so that I could makes changes more quickly to my Docker image.
Including the installation of pyodbc to connect to Azure SQL Server, the first half of my Dockerfile now looks like:
FROM python:3.8-slim-buster

RUN apt-get update
RUN apt-get install -y apt-utils curl sudo gcc g++ gnupg2

RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
RUN curl https://packages.microsoft.com/config/debian/10/prod.list > /etc/apt/sources.list.d/mssql-release.list
RUN apt-get install -y libffi-dev libgssapi-krb5-2 unixodbc-dev unixodbc freetds-dev
RUN sudo apt-get update
RUN sudo ACCEPT_EULA=Y apt-get install msodbcsql17
RUN apt-get clean -y

Where the curl commands and below come from the official MS docs on installing pyodbc on Debian
Full dockerfile:
FROM python:3.8-slim-buster

RUN apt-get update
RUN apt-get install -y apt-utils curl sudo gcc g++ gnupg2
RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
RUN curl https://packages.microsoft.com/config/debian/10/prod.list > /etc/apt/sources.list.d/mssql-release.list
RUN apt-get install -y libffi-dev libgssapi-krb5-2 unixodbc-dev unixodbc freetds-dev
RUN sudo apt-get update
RUN sudo ACCEPT_EULA=Y apt-get install msodbcsql17
RUN apt-get clean -y

RUN mkdir /code
WORKDIR /code

COPY requirements.txt requirements.txt
RUN python -m venv venv
RUN venv/bin/pip install --default-timeout=100 -r requirements.txt
RUN venv/bin/pip install gunicorn

COPY app app
COPY migrations migrations
COPY api.py config.py boot.sh ./
RUN chmod u+x boot.sh

EXPOSE 5000
ENTRYPOINT ["./boot.sh"]

A: I think this is the key information.

Which indicates the script cannot find the Flask-Migrate library. This actually happens if I try other site-packages, such as just trying to run flask commands.

To me this may indicate that the problem is not specific to Flask-Migrate but to all packages - as you write. This may mean on of following two.
First, it can mean that the packages are not correctly installed. However, this is unlikely as you write that it works when you manually start the container.
Second, something is wrong with how you execute your boot.sh script. For example, try changing
ENTRYPOINT ["sh", "boot.sh"]

to
ENTRYPOINT ["/bin/sh", "boot.sh"]

HTH!


text:
Q: How do I stop my Spark Streaming Context only after receiving all my input data? Using a socket connection I am receiving a JavaInputDStream, which sends one JSON message per two seconds to the Spark Cluster. I have around 60 msgs so it takes about 2 minutes to receive all the JSON data.
Here is my question: how can I stop my SparkStreamingContext() exactly when I stop receiving JSON lines as inputs?
If I use the ssc.stop() method, the context stops after executing once, so I don't even start receiving data.
If I usen ssc.awaitTerminationOrTimeout(long time), it also doesn't help, because it stops the context after time, which will always be slightly bigger then the exact time at which I want the context to stop.
As you might have guessed, my aim is to measure the exact time that my code takes to process all my JSON messages, and I am doing this to achieve it:
SparkConf sparkConf = new   SparkConf().setMaster("local[2]").setAppName("sparkstreaminggetjson");
    // JavaSparkContext sc=new JavaSparkContext(sparkConf);

    JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, Durations.seconds(2));

    long duration = System.currentTimeMillis();

//receive and process the JSON messages

    ssc.start();
    ssc.awaitTerminationOrTimeout(180000);

    duration = System.currentTimeMillis()-duration;

With this, duration is 180000, independently of the actual time it takes to process all the JSON messages.
How can I do this?
Thank you so much.


text:
Q: MySQL combined result from two tables this is my situation:
i have two tables A and B and want to combine the results from A and B.
probably with word is complicated to explain but using table result to illustrate it is more simple to understand.
Code for table A
CREATE TABLE `A` (
  `id_doc_a` int(11) NOT NULL AUTO_INCREMENT,
  `subject_a` varchar(100) DEFAULT NULL,
  `doc_nr_a` varchar(100) NOT NULL,
  `doc_type_a` varchar(50) NOT NULL,
  `doc_date_a` date NOT NULL,
  `value_IN` varchar(50) NOT NULL,
  PRIMARY KEY (`id_doc_a`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1

Code for table B
CREATE TABLE `B` (
  `id_doc_b` int(11) NOT NULL AUTO_INCREMENT,
  `subject_b` varchar(100) DEFAULT NULL,
  `doc_nr_b` varchar(100) NOT NULL,
  `doc_type_b` varchar(50) NOT NULL,
  `doc_date_b` date NOT NULL,
  `value_OUT` varchar(50) NOT NULL,
  PRIMARY KEY (`id_doc_b`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1

I want to select all subjects_a and subjects_b with value (ex. JOHN) and combine in a single table with columns:
| SUBJECT | DOC_NR | DOC_TYPE | DOC_DATE    | TBL_A_VALUE_IN | TBL_B_VALUE_OUT |
|---------|--------|----------|-------------|----------------|-----------------|
| JOHN    | 1      | PDF      | 20018-03-16 | 50.00          | NULL OR 0.00    |
| JOHN    | 33     | PDF      | 20018-08-09 | 25.00          | NULL OR 0.00    |
| JOHN    | 13     | PDF      | 20018-07-29 | 32.50          | NULL OR 0.00    |
| JOHN    | 4      | PDF      | 20018-06-06 | 41.30          | NULL OR 0.00    |
| JOHN    | 12     | JPEG     | 20018-04-22 | NULL OR 0.00   | 78.20           |
| JOHN    | 31     | JPEG     | 20018-03-21 | NULL OR 0.00   | 6.50            |
| JOHN    | 33     | JPEG     | 20018-05-01 | NULL OR 0.00   | 26.99           |

where the first 4 rows are the result from Table A and the last 3 rows are result of Table B where the condition is SUBJECT (subject_a = subject_b) = JOHN.
Hope to have explained well, thanks for the help.

Solution: Thanks to @scaisEdge
 SELECT
     t.SUBJECT_NAME,
     t.DOCUMENT_NR,
     t.DOCUMENT_TYPE,
     t.DOCUMENT_DATE,
     t.TBL_A_VALUE_IN,
     t.TBL_B_VALUE_OUT
FROM (
     SELECT
           SUBJECT_a AS SUBJECT_NAME,
           DOC_NR_a AS DOCUMENT_NR,
           DOC_TYPE_a AS DOCUMENT_TYPE,
           DOC_DATE_a AS DOCUMENT_DATE,
           VALUE_IN AS TBL_A_VALUE_IN,
           NULL AS TBL_B_VALUE_OUT
     FROM a
  UNION ALL
     SELECT
           SUBJECT_b AS SUBJECT_NAME,
           DOC_NR_b AS DOCUMENT_NR,
           DOC_TYPE_b AS DOCUMENT_TYPE,
           DOC_DATE_b AS DOCUMENT_DATE,
           NULL AS TBL_A_VALUE_IN,
           VALUE_OUT AS TBL_B_VALUE_OUT
     FROM b
) T
  WHERE t.SUBJECT_NAME = 'john'
  ORDER BY t.DOCUMENT_DATE

i removed 0 tab_order and 1 and use aliases so it can be more readable.
For order can be used one of the columns on the first select and to add more condition's just use AND or if dont need NULL we can use 0.00 AS instead of NULL AS in both selects.
Thanks again to scaisEdge for help and patience.

A: you could use UNION ALL
   select   t.SUBJECT, t.DOC_NR, t.DOC_TYPE, t.DOC_DATE
       , t.TBL_B_VALUE_IN,t.TBL_B_VALUE_OUT
    from (

    select   SUBJECT_a subject, DOC_NR_a DOC_NR, DOC_TYPE_a DOC_TYPE, DOC_DATE_a  DOC_DATE
         , VALUE_IN TBL_B_VALUE_IN, null TBL_B_VALUE_OUT , 0 tab_order
    from table_a
    union all
    select   SUBJECT_b, DOC_NR_b, DOC_TYPE_b, DOC_DATE_b , null,VALUE_OUT , 1
    from table_b
    ) T
    order by t.tab_order

A: You can just JOIN the tables.
SELECT *
FROM A
    JOIN B on A.subject_a = B.subject_b
WHERE A.subject_a = 'JOHN'

That will combine both datasets into one result table. Of course, if you don't want duplicate values (i.e. id_doc_a and id_doc_b) you can specify which ones you want instead of the wildcard *


text:
Q: Illegal Start of Expression Компилятор ругается, выдает illegal start of expression. Погуглил, но решение так и не нашел, а если и нашел, то видимо не понял :(
Помогите, пожалуйста :)
public class Main {

    public static void main(String[] args) {

        public int rollDice() {

            double randomNumber = Math.random();

            randomNumber = randomNumber * 6;

            randomNumber = randomNumber + 1;

            int randomInt = (int) randomNumber;

            return randomInt;
        }
        int rollOne = rollDice();
        int rollTwo = rollDice();
        System.out.println("Roll 1: " + rollOne);
        System.out.println("Roll 2: " + rollTwo);
    }
}

A: Вынесите public int rollDice() { ... } из main в тело класса.
После этого у Вас будет ошибка про использование метода экземпляра внутри статического, которая чинится изменением декларации на private static int rollDice() { ... }.


text:
Q: Javascript strings and objects In js can I call a function in an object from a string? Hm, I show you with an example:
var Object = {
    callMe : function() { }
}

Object.callMe();

This I can do, but what if I want to do this:
var string = 'callMe';
Object.string();

Can I somehow do this? Maybe I'm just thinking wrong here

A: var myObject = {
  myFunction: function() { return "Hooray!"; }
}

var methodName = "myFunction";

alert( myObject[methodName]() );

A: For this use bracket notation, like this:
var string = 'callMe';
Object[string]();

You can test it out here.
In JavaScript obj.thing (dot notation) is accessing the same thing as obj["thing"] (bracket notation).


text:
Q: How do I open a window on a different screen? I have an IE7 app that needs to open a popup window onto a second screen. I'm fudging this at the moment by extending the desktop and explicitly opening the window at an offset that makes it appear over on the other one. However this seems like a hack and I'd like to be able to explicitly set the window screen when I call window.open(). Is there any way to do this?

A: I'm pretty sure this isn't possible. I did some testing and the pop-up windows seemed to be restricted to the monitor "with focus".
Demo: jsfiddle.net/Marcel/25W29