text:
Q: how to receive unkown size buffer in async mode based boost::asio I am trying to receive an unkown size buffer, part of my code is as blow:
void Connection::asyncRead()
{
    auto self(shared_from_this());
    socket_.async_read_some(boost::asio::buffer(buffer_out),
        [this, self](boost::system::error_code ec, std::size_t length)
    {
        OnRead(ec, length);
    });
}

I don't know the size of the buffer, so I try to receive the buffer in a fixed size buffer, how to know whether the buffer ends?

A: If you want to send/receive messages which don't have fixed size you can use
the approach where you define header of your message, for example with 4-bytes field to store the size of content of your message:
[header(4 bytes) to store the size of message][content of message]

then you always know that the first step is to read 4 bytes,
prepare buffer for data and read further data until buffer is filled.
Another way is shutting down the socket (below is pseudocode)
The receiving side             |  the sending side
--------------------------------------------------------------------------------
error_code ec;                 |
asio::read(sock,buf,ec) [2]    |
                               | prepare some buffer with unknown size
                               | string buf;
                               | buf += ...; // add data
                               | asio::write(sock,buf)
                               | sock.shutdown(socket_base::shutdown_send); [1]

by calling sock.shutdown() in the sending side [1] you can inform
the receiving side that the whole message was sent.
Then in the receiving side after a message was read [2] you should check status of ec error-code variable whether it is boost::asio::eof.
If you get end-of-file you know that message is complete. If ec is different than eof this means that an error occurred.
As of 1.66 boost version you can use dynamic_buffer to store data, it adapts string or vector to be a buffer.
Or you can consider streambuf to read non-fixed buffers.

EDIT
The use of dynamic_buffer added.
According to reference dynamic_buffer can be used in free functions like async_read, async_until but not in async_read_some as member function of socket. Below are the codes of client and server:
Server:
using namespace boost;

struct Data  {
  std::shared_ptr<asio::ip::tcp::socket> sock;
  std::string buf; // buf is empty [1]
};

void readHandler (
    const boost::system::error_code& ec,
    size_t length,
    std::shared_ptr<Data> d) {
  std::cout << "readHandler" << std::endl;
  if (ec == boost::asio::error::eof)
  {
    // here we got the whole message
    std::cout << d->buf << std::endl;
  }
  else
  {
    std::cout << "Error" << std::endl;
  }
}

int main() {
  try {
    asio::ip::tcp::endpoint ep(asio::ip::address_v4::any(),9999);
    asio::io_service ios;
    asio::ip::tcp::acceptor acceptor(ios, ep);

    std::shared_ptr<asio::ip::tcp::socket> sock{new asio::ip::tcp::socket(ios)};

    acceptor.accept(*sock);

    std::shared_ptr<Data> data(new Data);
    data->sock = move(sock);

    boost::asio::async_read (*(data->sock), asio::dynamic_buffer(data->buf),
        std::bind(readHandler,std::placeholders::_1, std::placeholders::_2,data)); // [2]

    ios.run(); // wait until async_write is complete
  }
  catch (system::system_error &e) {
    std::cout << "error " << e.what() << std::endl;
  }
  return 0;
}

in [1] we create empty buffer as string object, in [2] we call async_read to get data using dynamic_buffer. Handler passed into async_read is called when the sending side shutdowns the socket on its side.
Client:
using namespace boost;

int main() {
  try {
    asio::ip::tcp::endpoint ep(asio::ip::address::from_string("127.0.0.1"),9999);
    asio::io_service ios;
    asio::ip::tcp::socket sock(ios, ep.protocol());
    sock.connect(ep);

    std::string buf = "some message";
    for (int i = 0; i < buf.size(); ++i) {
       // synchronous function was used to make simpler code
       asio::write(sock,asio::buffer(buf.c_str()+i,1)); // send 1 char
       std::this_thread::sleep_for(std::chrono::seconds(1)); // delay 1 second
    }
    sock.shutdown(asio::socket_base::shutdown_send);
  }
  catch (system::system_error &e) {
    std::cout << "Error " << e.what() << std::endl;
  }
  return 0;
}

as you can see we are sending char by char from string with 1-second delay. So when you start server and then client, server should receive the whole message after ~ 12 seconds. async_read is waiting in server until eof come - it is send by the call of shutdown on socket by client.


text:
Q: Multiple read queries in a single transaction This answer claims that a transaction is useful for multiple read statements as well. Is the following test case faulty or does it require related tables to return consistent results?
In console #1 execute the following:
set transaction isolation level serializable;
begin transaction;
select * from TableA;
waitfor delay '00:00:15';
select * from TableB;
commit transaction;

In console #2, during that 15 second window, execute following:
set transaction isolation level serializable;
begin transaction;
insert into TableB(col) values('b');
commit transaction;

After 15 seconds has passed, console #1 returns with a row with 'b' in it. Why? I thought console #1 would return no results or the transaction #1 would abort, because TableB was modified.
I've tried SQL Server LocalDB 2017 on Windows and SQL Server 2019 RC1 on Linux. I ran my sql commands with DataGrip, but the original use case I had with Entity Framework 6.

A: The console #1 execution Return the 'b' Record against TableB because the console #2 Add the Record in TableB before the Selection Query of TableB in console #1. Transaction lock only those Tables which is exist in Executed Queries.
console #1 will not get the 'b' record if WAIT add after the selection of TableB.
 Query will be abort if structure of table is changed like Drop the column and add the New column before selection Query but If the * is not used. There is no error generate if the Drop column is not exists by Name in selected Query.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Redirect to Reports page after login using Session I have designed the login page as shown below with the functionality to check from the database. I want the site to redirect the user to their specified page displaying their reports page (view_report.php) after successful login. For some reason, after entering the details, the page returns back to the same page instead of not logging in and doesn't throw any errors as well. I'm not sure as to where I went wrong. Thanks for the help in advance. :-)
<?php
session_start();
?>
<!DOCTYPE html>

  ----header area----

Login

    <form class="form" method="POST" action="index.php">

        <input type="text" name="login" placeholder="Restaurant id" required/>

        <input type="password" name="password" placeholder="Password" required/>

<input type="submit" name="commit" value="Login">

        <input type="checkbox" id="remember" name="remember" />
        Remember Me

        Forgot Password?

    </form>

<?php
if( $_SESSION["logging"]&& $_SESSION["logged"])
{
     header("Location:view_report.php");
}
else {
    if(!$_SESSION["logging"])
    {
    $_SESSION["logging"]=true;
    }
       else if($_SESSION["logging"])
       {
         $number_of_rows=checkpass();
         if($number_of_rows>=1)
            {
             $_SESSION[user]=$_GET[userlogin];
             $_SESSION['logged']=true;
             header("Location:view_report.php");
            }
        }
     }

function checkpass()
{
$servername="localhost";
$username="root";
$conn=  mysql_connect($servername,$username)or die(mysql_error());
mysql_select_db("konjam_disc",$conn);
$sql="select * from users where name='$_GET[userlogin]' and password='$_GET[password]'";
$result=mysql_query($sql,$conn) or die(mysql_error());
return  mysql_num_rows($result);
}

?>

A: You cannot redirect or "modify headers" once you send any HTML output so your redirect code must be before you send any HTML content. So your code could be something like this
<?php
session_start();

if( $_SESSION["logging"]&& $_SESSION["logged"])
{
    header("Location:view_report.php");
} else {
    if(!$_SESSION["logging"])
    {
    $_SESSION["logging"]=true;
    }
    else if($_SESSION["logging"])
    {
        $number_of_rows=checkpass();
        if($number_of_rows>=1)
        {
            $_SESSION[user]=$_GET[userlogin];
            $_SESSION['logged']=true;
            header("Location:view_report.php");
        }
    }
 }

?>

...

refer this answer
How to fix "Headers already sent" error in PHP

A: I am not giving actual code. only giving logic.
Use below logic.
session_start();
    if(session logged in){
    header("Location:view_report.php");

    }
    else{
    show your html form;
    }


text:
Q: React-native: Blank screen after drawer opens (physical device, iOS) but works ok on simulator Problem:
I've implemented drawer using react-native-side-menu.
On the iOS simulator, it works ok. But on a physical device, after drawer is open, everything disappears.
Changing drawer module to react-native-drawer does not help, app content still disappears after drawer opening.
Demonstration: video
Stack:
react-native: 0.53.
react-navigation: 1.0.0
mobx, mobx-react.
Drawer:
import React, { Component } from 'react';
import { Dimensions } from 'react-native';
import { inject, observer } from 'mobx-react';
import Drawer from 'react-native-side-menu';
import SideMenu from './SideMenu';

const deviceWidth = Dimensions.get('window').width;

@inject('ui')
@observer
export default class DrawerWrapper extends Component {
  onMenuChanges = (open) => {
    if (open) {
      this.props.ui.openDrawer();
    } else {
      this.props.ui.closeDrawer();
    }
  }

  render() {
    const { isDrawerOpen } = this.props.ui;
    return (
      <Drawer
        menu={<SideMenu {...this.props} />}
        menuPosition="right"
        onChange={this.onMenuChanges}
        side="right"
        openMenuOffset={deviceWidth - 90}
        isOpen={isDrawerOpen}
      >
        {this.props.child}
      </Drawer>
    );
  }
}

index.js:
import React from 'react';
import { Provider } from 'mobx-react';
import { StyleProvider, Root } from 'native-base';
import { StackNavigator } from 'react-navigation';

import stores from './stores';
import screens from './screens';
import getTheme from './theme/components';
import DrawerWrapper from './components/Drawer';

const Navigator = StackNavigator(screens, {
  headerMode: 'none',
  initialRouteName: 'AuthBridge',
});

const App = () => (
  <StyleProvider style={getTheme()}>
    <Provider {...stores}>
      <Root>
        <DrawerWrapper
          child={<Navigator />}
        />
      </Root>
    </Provider>
  </StyleProvider>
);

export default App;

P.S Works ok on Android simulator/real device.


text:
Q: Headphone stops working when I start using Skype When I start using Skype my headphones stop working and laptops loud speaker starts to work. What could cause this?
EDIT: Whenever someone calls, the issue again occurs and I have to unplug and plug the headphone back to use it.
Operating System: Windows 7.

A: Checkout your settings in Skype:
Tools-->General-->Audio Settings-->Speakers-->Select "Headphones" from drop down. Currently, it must be in Speaker rather than Headphones.
Hope this helps.


text:
Q: React ES6: calling async function from another function not defined This is where I call register():
this.register();

Here's the register():
register = async () => {
    await login();
    await create();
}

Here are the ones I call:
login = () => {
    console.log('test');
}

Ideally, what I want is to finish login() first, then go to create().
Error I get:

Uncaught (in promise) ReferenceError: login is not defined

A: As stated in the comments, you will probably need to complete the question with more context. In general, in Javascript, if you are working with classes, you will need to bind the context:
this.login = this.login.bind(this)

and then call this.login()
Moreover, in the case of react/redux, if your login function is not in your component you will probably have to connect your component and tell Redux what is the function you'll use, as explained here: Redux - call action from a function

A: I had this issue when I was calling a normal function inside an Async function. Even though the async function was called directly on the button click, it still needed binding (this.function= this.function.bind(this)). The function I was calling did not need Binding itself, which wasn't consistent with what I've encountered before with binding.


text:
Q: Applying Unique over columns in a DataFrame I have data having over 385 features, to find uniques for a column i have used df.unique() function.
However I have to find unique values over all 385 columns.
I tried using for loop as under,
col = [df_train.columns]

for i in col:
    print(i.unique())

I'm getting an output as under
Index(['ID', 'y', 'X0', 'X1', 'X2', 'X3', 'X4', 'X5', 'X6', 'X8',
       ...
       'X375', 'X376', 'X377', 'X378', 'X379', 'X380', 'X382', 'X383', 'X384',
       'X385'],
      dtype='object', length=366)

However the above are the columns names of the dataset and not the unique values of each columns.
I'm doing a concept error when I'm applying for loop, it would be appreciated to correct me where I'm going wrong or an alternative method to do the same.
Thanks in advance.

A: for i in df_train.columns:
    print(df_train[i].unique())

If you do
print(df_train.columns)

It will give you only column names
eg.  ["x0","x1","x2"] etc
You need to use indexing to access column values like df_train["column_name"]

A: to find unique values in a dataframe, we can use describe method as follows
df.describe().loc['unique']

A: Try to run the unique() method per column:
col = df.columns.values.tolist()
unique_vals_list = []

for column in col:
    unique_vals_list.append(list(df[column].unique()))

Your unique_vals_list will now contain all the unique value per column. This will be a list of list, so per index is actually the same index of your dataframe.
So accessing all unique for your first column will have the syntax:
unique_vals_list[0]

Accessing the 2nd column unique values:
unique_vals_list[1]

And so on.


text:
Q: How to get hosts variables with Ansible? Ansible: v2.3.0.0
Python: v2.7.12

The hosts file:
[server1]
192.168.0.1

At playbook, tried this way to get the IP value:
- debug:
    msg: "Host: {{ hostvars['server1'] }}"

It said hostvars.HostVars has no attribute server1.

A: server1 is a group name in your example. If you want server1 to be a host, define inventory like this:
[myservers]
server1 ansible_host=192.168.0.1


text:
Q: Remove last n lines from file using nodejs I'm trying to remove the last 3 lines from a file using fs as part of nodejs. I'm currently reading the file into memory and then writing it again without the 3 lines, but I'm sure there is a more efficient way that doesn't involve reading the whole file into memory.
My code now
fs.readFile(filename, function (err, data) {
    if (err) throw err;
    theFile = data.toString().split("\n");
    theFile.splice(-3, 3);
    fs.writeFile(filename, theFile.join("\n"), function (err) {
        if (err) {
            return console.log(err);
        }
        console.log("Removed last 3 lines");
        console.log(theFile.length);

    });
});

A: Let's create a huge file:
$ base64 /dev/urandom | head -1000000 > /tmp/crap
$ wc -l /tmp/crap
1000000 /tmp/crap
$ du -sh /tmp/crap
74M /tmp/crap

Here is your code:
$ cat /tmp/a.js
var fs = require('fs');

var filename = '/tmp/crap1';

fs.readFile(filename, function(err, data) {
    if(err) throw err;
    theFile = data.toString().split("\n");
    theFile.splice(-3,3);
    fs.writeFile(filename, theFile.join("\n"), function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("Removed last 3 lines");
    console.log(theFile.length);
    });
});

And here is mine:
$ cat /tmp/b.js
var fs = require('fs'),
    util = require('util'),
    cp = require('child_process');

var filename = '/tmp/crap2';
var lines2nuke = 3;
var command = util.format('tail -n %d %s', lines2nuke, filename);

cp.exec(command, (err, stdout, stderr) => {
    if (err) throw err;
    var to_vanquish = stdout.length;
    fs.stat(filename, (err, stats) => {
        if (err) throw err;
        fs.truncate(filename, stats.size - to_vanquish, (err) => {
            if (err) throw err;
            console.log('File truncated!');
        })
    });
});

Let's make copies of the same file:
$ cp /tmp/crap /tmp/crap1
$ cp /tmp/crap /tmp/crap2

Let's see who is faster:
$ time node a.js
Removed last 3 lines
999998
node a.js  0.53s user 0.19s system 99% cpu 0.720 total

$ time node b.js
File truncated!
node b.js  0.08s user 0.01s system 100% cpu 0.091 total

When I increased the filesize 10 times, my system ran out of memory with a.js; but with b.js, it took:
$ time node b.js
File truncated!
node b.js  0.07s user 0.03s system 6% cpu 1.542 total

My code uses tail, which doesn't read the whole file, it seeks to the end then read blocks backwards until the expected number of lines have been reached, then it displays the lines in the proper direction until the end of the file. Now I now the number of bytes to disappear. Then I use fs.stat, which tells me the total number of bytes in the file. Now, I know how many bytes I actually want in the file at the end, after removal of those last n lines. At the end, I use fs.truncate, which causes the regular file to be truncated to a size of precisely the size (in bytes) specified to it.
Update:
OP says that the platform is Windows. In that case, we can modify this program to not invoke another utility, but do everything in node itself. Fortunately, the required functionality has already been made available for us as the node module read-last-lines. Now the updated, os-agnostic code looks like:
$ npm install read-last-lines
$ cat /tmp/c.js
var fs = require('fs'),
    rll = require('read-last-lines');

var filename = '/tmp/crap2';
var lines2nuke = 3;

rll.read(filename, lines2nuke).then((lines) => {
    var to_vanquish = lines.length;
    fs.stat(filename, (err, stats) => {
        if (err) throw err;
        fs.truncate(filename, stats.size - to_vanquish, (err) => {
            if (err) throw err;
            console.log('File truncated!');
        })
    });
});

And on the 10x size file, it took:
$ time node c.js
File truncated!
node c.js  0.14s user 0.04s system 8% cpu 2.022 total


text:
Q: How can I access imageData from a renderTarget? I'm a university masters degree student in Computer Graphics, I'm having difficulty using three.js to access the image data(pixels) of a texture created with a EffectComposer.
The first composer (composer) is using a line detection shader to find road lines in a lane, and put the result in a renderTarget (rt_Binary). My second composer (fcomposer2) uses a shader that paints an area green if is within a certain space.
The plan was to render the composer first and after analysing the rt_Binary image i could determine the limits.
I found some functions that allow me to get the imagedata (getImageData(image) and getPixel(imagedata, x, y)) but they only work on these occasions:
                // before image
                var imagedata = getImageData(videoTexture.image);
                // processed image
                var imagedata2 = getImageData(renderer.domElement);

If a put the first composer to render to screen, i get the correct values for the limits, but when i put the second composer, i get the wrong values for the limits.
Is there any way to get the imageData from a renderTarget? is so, how?
Edit1:
Here's the code for script that i use for the html:
<html xmlns="http://www.w3.org/1999/xhtml"><head>
    <title>Tests WebGL</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script src="three.js/build/three.js"></script>
        <script src="js/CopyShader.js"></script>
        <script src="js/EffectComposer.js"></script>
        <script src="js/MaskPass.js" ></script>
        <script src="js/RenderPass.js" ></script>
        <script src="js/ShaderPass.js"></script>
        <script src="js/stats.min.js" ></script>
        <!-- Shaders -->
        <script src="js/shaders/KernelShader.js" ></script>
        <script src="js/shaders/SimpleShader.js"></script>
        <script src="js/shaders/MyShader.js"></script>
        <script src="js/shaders/BinaryShader.js"></script>
        <script type="text/javascript">

            var scene, fscene, sceneF;
            var camera;
            var renderer, rt_Binary;
            var composer;
            var stats;
            var fmaterial;

            var videoTexture;
            var videoWidth = 480;
            var videoHeight = 270;

            var rendererWidth = videoWidth;
            var rendererHeight = videoHeight;

            var x_max = 345;//videoWidth*0.72; //
            var x_min = 120;//videoWidth*0.25; //
            var y_max = 189;//videoHeight*0.7 ;
            var y_min = 148;//videoHeight*0.55;

      //      var ml=0.0, mr=0.0, mm=0.0;
      //      var bl=0.0, br=0.0, bm=0.0;

            var yMaxL = 0, yMinL = 0, yMaxR = 0, yMinR = 0;
            var xMaxL = 0, xMinL = 0, xMaxR = 0, xMinR = 0;

            var frame = 0;
            // init the scene
            window.onload = function() {
                renderer = new THREE.WebGLRenderer(
                        {
                            antialias: true, // to get smoother output
                            preserveDrawingBuffer: true // to allow screenshot
                        });
                renderer.setClearColor(0xffffff, 1);
                renderer.autoClear = false;
                renderer.setSize(rendererWidth, rendererHeight);
                document.getElementById('container').appendChild(renderer.domElement);

                //add stats
                stats = new Stats();
                stats.domElement.style.position = 'absolute';
                stats.domElement.style.top = '0px';
                document.getElementById('container').appendChild(stats.domElement);

                // create Main scene
                scene = new THREE.Scene();
                camera = new THREE.PerspectiveCamera(35, rendererWidth / rendererHeight, 1, 10000);
                camera.position.set(0, 1, 6);
                scene.add(camera);

                // define video element
                video = document.createElement('video');
                // video.src = 'GOPR0007.webm';
                video.src = 'output.webm';
                video.width = videoWidth;
                video.height = videoHeight;
                video.autoplay = true;
                video.loop = true;

                //create 3d object and apply video texture to it
                var videoMesh = new THREE.Object3D();
                scene.add(videoMesh);

                videoTexture = new THREE.Texture(video);

                var geom = new THREE.PlaneGeometry(1, 1);
                material = new THREE.MeshBasicMaterial({map: videoTexture});

                var mesh = new THREE.Mesh(geom, material);
                videoMesh.add(mesh);

                var renderTargetParameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBufer: false };
                rt_Binary =  new THREE.WebGLRenderTarget( videoWidth, videoHeight, renderTargetParameters );

                // Composers

               // composer = new THREE.EffectComposer(renderer, renderTarget2);
                composer = new THREE.EffectComposer(renderer, rt_Binary );
                composer.addPass(new THREE.RenderPass(scene, camera));

                var simple = new SimpleShader.Class(videoWidth, videoHeight);
                var simEffect = new THREE.ShaderPass(simple.shader);
                composer.addPass(simEffect);

                var ef = new BinaryShader.Class(videoWidth, videoHeight, 1.1, [-2,-2,-2,0,0,0,2,2,2]);
                var effect = new THREE.ShaderPass(ef.shader);
                composer.addPass(effect);

                var copyPass = new THREE.ShaderPass(THREE.CopyShader);
          //      copyPass.renderToScreen = true;
                composer.addPass(copyPass);

                //New scene
                sceneF = new THREE.Scene();
                sceneF.add(camera);

                var videoMesh2 = new THREE.Object3D();
                sceneF.add(videoMesh2);

                var geomF = new THREE.PlaneGeometry(1, 1);
                var materialF = new THREE.MeshBasicMaterial({map: videoTexture});

                var meshF = new THREE.Mesh(geomF, materialF);
                sceneF.add(meshF);

                fcomposer2 = new THREE.EffectComposer(renderer );
                fcomposer2.addPass(new THREE.RenderPass(sceneF, camera));

                fcomposer2.addPass(simEffect);

                var ef1 = new MyShader.Class(videoWidth, videoHeight, [yMaxL,yMinL,xMaxL,xMinL,yMaxR,yMinR,xMaxR,xMinR], videoTexture);
                var effect1 = new THREE.ShaderPass(ef1.shader);
                fcomposer2.addPass(effect1);

                var copyPass2 = new THREE.ShaderPass(THREE.CopyShader);
                copyPass2.renderToScreen = true;
                fcomposer2.addPass(copyPass2);

                animate();
            }

            // animation loop
            function animate() {
                // loop on request animation loop
                // - it has to be at the begining of the function
                requestAnimationFrame(animate);

                // do the render
                render();
                stats.update();
                if ((frame % 50) == 0) {
                    console.log("frame ", frame, " ");

                    console.log("yMaxL: ", yMaxL, " ");
                    console.log("yMinL: ", yMinL, " ");
                    console.log("xMaxL: ", xMaxL, " ");
                    console.log("xMinL: ", xMinL, " ");

                    console.log("yMaxR: ", yMaxR, " ");
                    console.log("yMinR: ", yMinR, " ");
                    console.log("xMaxR: ", xMaxR, " ");
                    console.log("xMinR: ", xMinR, " ");

                    manipulatePixels();
                }
                frame = frame + 1;
                yMaxL = 0, yMinL = 0, yMaxR = 0, yMinR = 0;
                xMaxL = 0, xMinL = 0, xMaxR = 0, xMinR = 0;

            }

            // render the scene
            function render() {
                if (video.readyState === video.HAVE_ENOUGH_DATA) {
                    videoTexture.needsUpdate = true;
                }

                // actually render the scene
                renderer.clear();
                composer.render();

                var left_x = new Array();
                var left_y = new Array();
                var l = 0;

                var right_x = new Array();
                var right_y = new Array();
                var r = 0;

              if (frame == 200) {
                    var imagedata2 = getImageData(renderer.domElement);

                    var middle = imagedata2.width / 2;

                    for (var x=x_min; x < x_max; x=x+1) {
                        for (var y=y_min; y < y_max; y=y+1) {
                            var pixel = getPixel(imagedata2, x, y);
                            if (pixel.g > 0)
                                {
                                    //console.log(pixel);
                                    if (x < middle) {
                                        left_x[l] = x;
                                        left_y[l] = y;
                                        l++;
                                    }
                                    else {
                                        right_x[r] = x;
                                        right_y[r] = y;
                                        r++;
                                    }
                                }
                        }
                    }

                  lineEquation(left_x, left_y, right_x, right_y);

               }

               fcomposer2.render();
            }

            function lineEquation(left_x,left_y,right_x,right_y) {
                var newYMAX = left_y[0];
                var newYMIN = left_y[0];

                var maximosL = new Array();
                var minimosL = new Array();

      //left
                for (var i=1; i < left_y.length; i++) {
                    if (left_y[i]>newYMAX) newYMAX = left_y[i];
                    else {
                        if (left_y[i]<newYMIN) newYMIN = left_y[i];
                    }
                }

                yMaxL = newYMAX;
                yMinL = newYMIN;
          //      yMaxL = ymaxL/videoHeight;
          //      yMinL = yminL/videoHeight;

                var pmin=0, pmax=0;
                for (var i=0; i < left_y.length; i++) {
                    if (left_y[i] === newYMAX) {
               //         console.log(left_y[i]);
               //         console.log(left_x[i]);
                        maximosL[pmax] = left_x[i];
                        pmax++;
                    }

                }
                for (var j=0; j < left_y.length; j++) {
                    if (left_y[j] === newYMIN) {
                 //      console.log(left_y[j]);
                 //      console.log(left_x[j]);
                       minimosL[pmin] = left_x[j];
                       pmin++;
                    }
                }

             //   console.log(maximosL);
             //   console.log(minimosL);

                var sumMAX = 0, sumMIN = 0;
                for (var i=0; i< maximosL.length; i++) {
                    sumMAX = sumMAX + maximosL[i];
                }

                for (var j=0; j< minimosL.length; j++) {
                     sumMIN = sumMIN + minimosL[j];
                }

                xMaxL = sumMAX/maximosL.length;
                xMinL = sumMIN/minimosL.length;

         //       xMaxL /= videoWidth;
         //       xMinL /= videoWidth;

     //right
                var maximosR = new Array();
                var minimosR = new Array();

                newYMAX = right_y[0];
                newYMIN = right_y[0];

                pmin=0; pmax=0;
                for (var i=0; i < right_y.length; i++) {
                    if (right_y[i]> newYMAX) newYMAX = right_y[i];
                    else {
                        if (right_y[i]< newYMIN) newYMIN = right_y[i];
                    }
                }

                 yMaxR = newYMAX;
                 yMinR = newYMIN;
          //      yMaxR = ymaxR/videoHeight;
          //      yMinR = yminR/videoHeight;

                for (var i=0; i < right_y.length; i++) {
                    if (right_y[i] === newYMAX)
                        {maximosR[pmax] = right_x[i]; pmax++;}
                    if (right_y[i] === newYMIN)
                        {minimosR[pmin] = right_x[i]; pmin++;}
                }

    //            console.log(maximosR);
    //            console.log(minimosR);

                xMaxR=0;
                for (var i=0; i< maximosR.length; i++) {
                    xMaxR += maximosR[i];
                }
                xMinR=0;
                for (var i=0; i< minimosR.length; i++) {
                    xMinR += minimosR[i];
                }

      //         console.log(xMaxR);
      //         console.log(xMinR);

                xMaxR /= maximosR.length;
                xMinR /= minimosR.length;

       //        console.log(xMaxR);
       //        console.log(xMinR);

       //         xMinR /= videoWidth;
       //         xMaxR /= videoWidth;

            }

            function manipulatePixels() {
                // imagem antes
                var imagedata = getImageData(videoTexture.image);
                // imagem processada
                var imagedata2 = getImageData(renderer.domElement);

  //              console.log(getPixel(imagedata, 480 - 1, 270 - 1));
  //              console.log(getPixel(imagedata2, 480 - 1, 270 - 1));

            }

            function getImageData(image) {
                var canvas = document.createElement('canvas');
                canvas.width = image.width;
                canvas.height = image.height;

                var context = canvas.getContext('2d');
                context.drawImage(image, 0, 0);

                return context.getImageData(0, 0, image.width, image.height);
            }

            function getPixel(imagedata, x, y) {
                var position = (x + imagedata.width * y) * 4, data = imagedata.data;
                return {r: data[ position ], g: data[ position + 1 ], b: data[ position + 2 ], a: data[ position + 3 ]};
            }

            function findLineByLeastSquares(values_x, values_y) {
                var sum_x = 0;
                var sum_y = 0;
                var sum_xy = 0;
                var sum_xx = 0;

                /*
                * We'll use those variables for faster read/write access.
                */
                var x = 0;
                var y = 0;
                var values_length = values_x.length;

                if (values_length != values_y.length) {
                    throw new Error('The parameters values_x and values_y need to have same size!');
                }

                /*
                * Nothing to do.
                */
                if (values_length === 0) {
                    return [ [], [] ];
                }

                /*
                * Calculate the sum for each of the parts necessary.
                */
                for (var v = 0; v < values_length; v++) {
                    x = values_x[v];
                    y = values_y[v];
                    sum_x += x;
                    sum_y += y;
                    sum_xx += (x*x);
                    sum_xy += (x*y);
                }

                  console.log (sum_x);
                  console.log(sum_y);
                  console.log(sum_xx);
                  console.log(sum_xy);
                  console.log(values_length);
                /*
                * Calculate m and b for the formular:
                * y = x * m + b
                */
               var m = (sum_x*sum_y - values_length*sum_xy) / (sum_x*sum_x - values_length*sum_xx);
               var b = (sum_y - (m*sum_x))/values_length;

               //console.log([m,b]);

                return [m, b];
            }

            //resize method
            /**window.addEventListener('resize', onWindowResize, false);
             function onWindowResize() {
             camera.aspect = window.innerWidth / window.innerHeight;
             camera.updateProjectionMatrix();

             renderer.setSize(window.innerWidth, window.innerHeight);
             } */
        </script>

Edit2 : Some images of what i'm trying to do: Image 1 shows the results from composer on the console, the limits i get from the lineEquation function are the correct ones for what i intend to do, but in Image 2 shows the results from fcomposer2 (fixed area) and on the console, the limits are the wrong ones.
![Image1]: http://prntscr.com/1ays73
![Image2]: http://prntscr.com/1ays0j
Edit3 :
By "access" i mean to be able to read the values of the pixels from the texture created by the binaryShader.
For example, in image1 the lines are painted in blue/green tone, I wanted to search the position of the pixels (x,y) in the image that the renderTarget would save. If i could find those pixels, i could adapt the green area in image2 to fit between the road lines.
This processing is need to make the green area overlap the current driving lane the user is currently on, if i can't get those points, i can't identify a lane.

A: I got it to work. Apparently i forgot to declare the fcomposer2 in the beginning of the script.
Thanks for the responses/comments, and sorry for the inconvenience.


text:
Q: Convert pixels of a picture on GPS coordinates I'm doing a project on Android for measuring areas of land through photographs taken by a drone.
I have an aerial photograph that contains a GPS coordinate. For practical purposes I assume that coordinate represents the central pixel of the picture.
I need to move pixel by pixel in the picture to reach the corners and know what GPS coordinate represent the corners of the
I have no idea about how to achieve it. I have searched but can not find anything similar to my problem.
Thank You.
enter link description here

A: If you know the altitude at which the photo was taken and the camera maximum capture angle I believe you can determine (through trigonometry) the deviation of each pixel from the center, in meters, and then determine the GPS coordinate of it.

A: According to my knowledge,
Height of the drone also matter so first of all with the central coordinate you also need at what height drone take that picture.
Now you need to perform some experiment with reference picture between two known GPS coordinate of two points of picture. Change the height of the drone and plot the number of pixels between two coordinate wrt to the height of drone. Doing some curve fitting and get the function between two variable.
Using the above function you can calculate the "change in GPS coordinate per pixel" at the particular height and by using this parameter we can easily deduce the GPS of picture taken by drone at particular height.
I don't know whether the solution works or not. But this my idea you can use this and develop further.
Thanks


text:
Q: AWS CloudWatch Logs Insights - export full query result? I have a CloudWatch Logs Insights query, which shows "7000 records matched", but when I try Actions -> Download query results (CSV), only 1000 records are exported (same as shown in the console). I cannot find any way to export the "full" query results. Am I missing anything?

A: Adding
| limit 7000

to the end of the query fixed the issue
The max is 10000 according to https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_StartQuery.html#API_StartQuery_RequestSyntax, so if my query has more than 10000 records, there seems to be no way to get the complete data.

A: This is an addition to lznt's answer, addressing the following issue:

if my query has more than 10000 records, there seems to be no way to
  get the complete data.

I think there is a workaround: You can mess with the time range of the query. Order the results by timestamp. You then know the timestamp of the last record that you still managed to get.
For the next query, set the time range of the query so that you start where the previous query ended.
It is admittedly an ugly, iterative workaround, with a human in the loop.
Disclaimer: I haven't tested it.

A:
True that max is 10k

But

datetime

can be narrowed, as well as log group for AWS CloudWatch Logs Insights

A: As stated in some of the other answers, you can only export up to 10,000 lines from CloudWatch Log Insights. However, you can export the entirety of the log group's contents to S3 and then subsequently filter for the log files that you want with a little bit of munging. This post shows how to do that, and includes a Gist for consolidating the exported results.


text:
Q: React. How to redirect early in a component lifecycle This seems so simple, but I am new to react and trying different approaches and nothing is working for me. (BTW I am a regular contributor but working on my clients machine and can't remember my so password.)
The version of react router is 4.0, and state is stored using redux.
The scenario is that we are changing the order of routing in our application and would like to redirect any users that have Urls with the old structure to the new Url structure. I have tried the following (also note that I have "scrubbed" the names of the page, function calls and variables):

*

*There is a trigger component for the section I need to direct from, with routing set up like this:

<Route path='page/:pageGuidGuid' component={PageTrigger}>                </Route>
In the trigger component, ComponentWillMount makes a request that returns a 404 if the link is from the previous component, although it does redirect to the correct route. I am checking for and triggering the redirect in getInitialState, but the component keeps going through the lifecycle and ComponentWillMount is called, resulting in a 404 and then redirects to the correct page.
const PageTrigger = connectToStores(React.createClass({

getInitialState() {
    this.checkForRedirect();
    return {};
},

componentWillMount() {
    if (this.props.params.guid) {
        this.setCaseByGuid(this.props.params.guid);
    }
},
   checkFrorRedirect() {
      /* logic to determine if it should redirect */
      browserHistory.push(redirectUrl);
    }
}

I have also tried creating a custom route...
<CaseRedirectRoute path='(cases/:caseGuid)' component={CaseTrigger}>

 </CaseRedirectRoute>

And in a separate module (based off a login sample)
const CaseRedirectRoute = ({ component: Component, ...rest }) => (
<Route
  {...rest} render={props => (
    checkForCaseRedirect(...props) ? (
        <Redirect to={{
            pathname: getCaseUrlRedirectUrl(...props),
            state: { from: props.location }
        }} />
    ) : (
        <Component {...props} />
    )
)} />

);
I have WithRouter imported from react router. When I try to run this I am getting an error inside the react framework:
Uncaught Type Error: Cannot read property 'createRouteFromReactElement' of undefined
  at RouteUtils.js:68
at forEachSingleChild (ReactChildren.js:52)
at traverseAllChildrenImpl (traverseAllChildren.js:98)
at traverseAllChildrenImpl (traverseAllChildren.js:114)
at traverseAllChildren (traverseAllChildren.js:186)
at Object.forEachChildren [as forEach] (ReactChildren.js:70)
at createRoutesFromReactChildren (RouteUtils.js:65)
at Function.createRouteFromReactElement (RouteUtils.js:35)
at RouteUtils.js:69
at forEachSingleChild (ReactChildren.js:52)

I've tried redirecting from app.js and page.js, but the PageTrigger is the first component having state set. I either need to figure out how to stop execution after the redirect, or figure out why my custom route keeps blowing up. Any help would be appreciated.

A: I'm not sure about your setup, but I would implement this redirect as this:
<Route path='oldurl/:p1/:p2' render={
  routeProps => (
    <Redirect to={'/newUrlHere/'+routeProps.match.params.p1} />
  )
}  />

So, if the route matches (you may specify exact match if necessary), when the Redirect "renders" it stops rendering and should start the rendering from the new URL. You may build your URL in the Redirect.to property as you wish


text:
Q: What are the known instances of the Doctor's *personal* history being rewritten? The Doctor says he can't go back on his own timeline (for example, Smith and Jones, "except for cheap tricks"). It's implied it's a very bad thing to mess with his timeline.
What are the instances of the Doctor's timeline being rewritten (by his own actions or by others)?
Not instances where he doesn't remember an event in which more than one incarnation of him appears but only one may retain the full memories (like in The Five Doctors, Time Crash, The Day of the Doctor). Just instances in which he has lived through two "versions" of the same event.

A: Series 7: "Journey to the Center of the TARDIS"
In one of the worst stories of the Moffat era (at least in my opinion), the TARDIS gets salvaged by the Van Baalan bros, and all hell breaks loose. Even Clara learns the Doctor's real name. Then, with the "Big friendly button-ex Machina", the Doctor erases that day, and it never actually happened.
I'll add more if I find/remember them, but I feel like this is a prime example, and why the show should never do it again.
UPDATE:
Series 1: "Father's Day"
A good example of how trying to re-write history is a bad idea. Rose Tyler wants to go back in time to the day his father died. She gets all emotional, and saves his life. The reapers appear, never to be seen again. I think it was a good idea, but in the next 10 years it was never explored, nor explained again. At the end of the day, Rose's dad figured it out, and sacrificed himself so time could be stable again, so I'm not sure if it counts.
Series 4: "The Waters of Mars"
Another example of "one does not simply re-write history". The Tenth Doctor almost goes insane trying to save a crew of astronauts in Mars that had to die anyway. We get introduced to one of the most confusing concepts of New Doctor Who: Fixed points in time. Again, not sure if it counts.
As for Classic Doctor Who, I'm not very familiar with those stories, because they are so hard to find where I live. Let's wait if anybody can come up with examples of the classic era.

A: In the pandorica opens part 2 (season 5, episode 13), the doctor keep helping is past self and even sees himself dying, or give himself a fez...
But its in a closing time loop, so I don't know if it really counts.


text:
Q: How can I list which users can login without key auth? I have recently been charged with a large amount of Ubuntu servers that are exclusively accessed via private/public SSH authentication.
There is no information regarding how these servers were configured initially, and root passwords are unknown for 90% of these boxes.
For DR purposes, we need to have console login available.
I decided I wanted a list which users had the ability to login without pub/priv authentication, and I realized I had no quick method to do this in my databanks.
Do you?
Thanks!


text:
Q: Hbase 1.0.0 connection pool Since Hbase 1.0+ API is not handling the connection pooling using HConnection, I want to know what are the best practices for creating a connection pool?
So far, I have created a Connection object as ThreadLocal, but I am not sure if it is good idea.
In general, since the connection object is so heavy, is it a good idea to create a pool of connections?
Does anyone has any idea?

A: You can use one connection per application because creating it is heavy and it is thread-safe. Make sure however that you close Table and Admin that you get from the Connection
private static class ConnectionHolder{
  private final Connection connection;

  private ConnectionHolder(){
   connection = ConnectionFactory.createConnection(config);
  }

 Connection getConnection(){
  return connection;
  }
}

If you use this approach don't expose connection so callers don't close it accidentally. But do remember to close Tables and ResultScanners
Table getTable(String name){
  Table table = connection.getTable(TableName.valueOf(name));
  return table;
}

try(Table table = getTable("tableName")){
  ...
}

A: I have asked the question from Carter Page, and here is his answer:
"You don't have to use only one Connection per application, and in some certain cases you may discover a need for more than one.
In general, the important thing to know is that Connections are "heavy" objects that are expensive to create, but thread-safe. Table, Admin, and BufferedMutatator objects are lightweight and not necessarily thread-safe.
Connection objects don't necessarily translate to a single "connection", and can multiplex behind the scenes. Better to think of it as a factory.
I would suggest you create a single Connection where possible, and carefully test increasing a pool if you think more factories will improve performance. There are certainly no rules against having more Connection objects. It's just a matter of potentially unnecessary overhead.  Hope this helps."


text:
Q: Improve readability for command in an init container kubernetes I have an init container and am running a command in it which takes a ton of parameters so I have something like
command: ['sh', '-c', 'tool input1 input2 output
-action param1 -action param2 -action param3 -action param4 -action param5 -action param6 -action param7 -action param7 -action param8 -action param9 -action param10 ']

This highly decreases the readability of the command. Is there someway I can improve this like passsing this a a separate array ?

A: You can make command's args as a YAML list:
  initContainers:
  - name: init-container
    image: busybox:1.28
    command: ["/bin/sh","-c"]
    args:
      - -action
      - param1
      - -action
      - param2
    .
    .
    .

A: Another tip is to do it via command, so save your time that you needn't manually do that.
kubectl run nginx --image=nginx --generator=run-pod/v1 --dry-run -o yaml  -- tool input1 input2 output -action param1 -action param2 -action param3 -action param4 -action param5 -action param6 -action param7 -action param7 -action param8 -action param9 -action param10
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: nginx
  name: nginx
spec:
  containers:
  - args:
    - tool
    - input1
    - input2
    - output
    - -action
    - param1
    - -action
    - param2
    - -action
    - param3
    - -action
    - param4
    - -action
    - param5
    - -action
    - param6
    - -action
    - param7
    - -action
    - param7
    - -action
    - param8
    - -action
    - param9
    - -action
    - param10
    image: nginx
    name: nginx
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}

Above dry-run command will generate the yaml for option --args, you copy & paste it into the part of original init container, make it so simple and you can do it less in one munite
You still need keep the part of command, don't forget
    command: ["/bin/sh","-c"]


text:
Q: Need to learn more about sessions in PHP Can anyone provide me some learning resources that focus on session management in PHP? Preferably resources that aren't "dry".

A: http://www.tizag.com/phpT/phpsessions.php
http://shiflett.org/articles/the-truth-about-sessions - this one is really great from a security perspective.

A: Have you tried php.net's documentation on sessions?

A: Here's some information focusing on some different subjects regarding session handling in PHP

*

*Session Handling (PHP Manual)

*"PHP Session Security" (SO question)

*"What are the risks of PHP sessions" (SO question)

A: More generally, Wikipedia's session article on session management is not terribly dry.


text:
Q: ERROR: CustomerTrigger: execution of BeforeUpdatecaused by: System.ListException: Duplicate id in list: I have written one trigger on before update.
On customer object -before edit i need to save changes in Test_c object.
   trigger CustomerTrigger on Customer__c (before update){
    list<test__c> updateTest=new list<test__c>();
    if(trigger.isupdate && trigger.isbefore){
        for(customer__c cust:trigger.new){
            test__c t=new test__c(id=cust.test__c,salary__c=cust.salary__c,phone__c=cust.phone__C);
            updateTest.add(t);
        }
    }
update updatetest;
}

It is working for single and  multiple customer records if Test lookup is different for each record.
But if 2 customer havinf same test lookup then trowing below error.
ERROR: CustomerTrigger: execution of BeforeUpdatecaused by: System.ListException: Duplicate id in list: a1O28000007ZypIEASTrigger.CustomerTrigger: line 10, column 1

Please suggest

A: Adding the test__C id's to a set and filtering it out inside the for loop would fix this issue.
Your code can be modified as
trigger CustomerTrigger on Customer__c (before update){
    list<test__c> updateTest=new list<test__c>();
    Set<Id> testIdSet = new Set<Id>();

    if(trigger.isupdate && trigger.isbefore){
    for(customer__c cust:trigger.new){
        if(!testIdSet.contains(cust.test__c)) {
            test__c t=new test__c(id=cust.test__c,salary__c=cust.salary__c,phone__c=cust.phone__C);
            updateTest.add(t);
            testIdSet.add(cust.test__c);
        }
    }
    }
    update updatetest;
}


text:
Q: load image to imageview using picasso Im trying get image from my storage to imageview using picasso, but it wont to show the photo. It is ok with getting image from url, that means picasso working correct. Please tell me what Im doing wrong? Thanks.
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cam);

    imageView = (ImageView) findViewById(R.id.image_view1);

    String filename = "full.jpg";
    String path = "sdcard/camera_app" + filename;

    Picasso.with(CamActivity.this)
            .load(new File(path))  //File of the image to load.
             .into(imageView);

    //Picasso.with(CamActivity.this).load("http://square.github.io/picasso/static/sample.png").into(imageView);

in manifest file everything is added write, read, internet.
also tried
    String filename = "lapin-rose.jpg";
    String baseDir =    Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator+     filename;
    Picasso.with(this).load(new File(baseDir)).into(imageView);

nothing changes. Help please.
XML

<Button
    android:id="@+id/btnTakePicture"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_marginTop="10dp"
    android:text="picture">
</Button>

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="273dp"
    app:srcCompat="@mipmap/ic_launcher"
    android:id="@+id/image_view1"
    android:layout_marginTop="60dp"
    android:scaleType="fitStart"
    android:adjustViewBounds="true"/>

  </FrameLayout>

A: did you try Uri method if not try this :
String filename = "full.jpg";
    String path = "sdcard/camera_app" + filename;

Uri uri = Uri.fromFile(new File(path));

Picasso.with(CamActivity.this).load(uri).centerCrop().into(imageView);


text:
Q: The graph api do not return good data, why? I am using the graph api to catch the likes, shares and comments of the photos that are in an album. In most it does well, but there are a few that gets the likes, shares and comments the album and not the picture. I dont know why.
I use php, and two fql:
//get all photo ids of one album

$user_id= "my user id";
$photo_limit= "my limit";
$album_name="my album name";
$access_token= "my access token";

$fql_query_url = 'https://graph.facebook.com'.
'fql?q=SELECT+object_id+FROM+photo+WHERE+album_object_id+in+
(SELECT+object_id,+name+FROM+album+WHERE+owner+=+'.$user_id.'
+and+name+=+"'.$album_name.'")+limit+'.$photo_limit. '&access_token=' . $access_token;

$fql_query_result = file_get_contents($fql_query_url);
$fql_query_obj = json_decode($fql_query_result, true);

//print the likes, shares, and comments of all photos
foreach ($fql_query_obj["data"] as $photo_id){

$id = $photo_id["object_id"];
$fql_query_url_1 = 'https://graph.facebook.com/'.
'fql?q=SELECT+like_info.like_count,+comment_info.comment_count,+share_count,+
created_time+from+stream+where+post_id+in
(Select+page_story_id+from+photo+where+object_id+=+'.$id.')'.
'&access_token='.$access_token;

$fql_query_result_1 = file_get_contents($fql_query_url_1);
$fql_query_obj_1 = json_decode($fql_query_result_1, true);

echo $fql_query_obj_1["data"][0]["like_info"]["like_count"].",".
$fql_query_obj_1["data"][0]["comment_info"]["comment_count"].",".
$fql_query_obj_1["data"][0]["share_count"]."\n";

}

In some photos in the loop returns bad data. why???
Thanks in advance.


text:
Q: Java instanceof workaround I work in Android project and I currently need to create holders for all views. There currently are a lot of if's and I want to get rid of them. Assume there are holders for all views
 if (v instanceof Spinner)
    {
        holder = new SpinnerHolder(v);
    }
    else if (v instanceof AdapterView)
    {
        holder = new AdapterViewHolder((AdapterView) v);
    }
    else if (v instanceof CompoundButton)
    {
        holder = new CompoundButtonHolder(v);
    }
    else if (v instanceof EditText)
    {
        holder = new TextViewHolder(v);
    }
    else if (v instanceof SeekBar)
    {
        holder = new SeekBarHolder(v);
    }
    else if (v instanceof TabHost)
    {
        holder = new TabHostHolder(v);
    }

I sure could do something like
String simpleName = v.getClass().getSimpleName();
Class.forName("com.myproject.myholderpackage" + simpleName + "Holder");
...

But it doesn't work, if, for example, there are custom views like
public class foo extends LinearLayout
{
}
public class bar extends foo
{
}

Thanks.

A: I'd create a map: Map<Class,Class> instanceToHolder and then replace that else-if construction with a single call to that map and some reflection code to run the constructor. So, something like this:
final Map<Class,Class> instanceToHolder = new HashMap<Class,Class>();
instanceToHolder.put(Spinner.class, SpinnerHolder.class);
// ....
Class holderClass = instanceToHolder.get(v.getClass());
Object holderObject = holderClass.getConstructor(v.getClass()).newInstance(v);


text:
Q: Nested DocumentSnapshot onSnapshot doesn't yield results I'm querying a Firestore document for the contents of its data. One of the fields, listField, is an array of DocumentReferences to other documents. As such, I have nested snapshots: One for the original document, then a loop for all of the documents referenced in listField.
When I try to add all of this into data, the list data always returns empty. With some testing, I've found that the list is always undefined outside of the inner docSnapshot loop, but is correct within that loop.
For what it's worth, I've tested this with the inner loop using getDoc as well as with onSnapshot, and both yield the same results. Any idea why the list in the inner loop doesn't populate?
const [data, setData] = useState<DataType>();
useEffect(() => {
  const getData = async () => {
    var docRef = doc(firestore, "/collection/documentId123");
    onSnapshot(docRef, (docSnapshot) => {
      var list: ListType[] = [];
      docSnapshot.data()?.listField.forEach(async (docRef2: DocumentReference) => {
        const doc2 = await getDoc(docRef2);
        list.push({
          id: docRef2.id,
          field: doc2.get("field"),
        });
        // console.log(list) WORKS HERE!
      });
      // console.log(list) IS UNDEFINED HERE!
      setData({
        title: docSnapshot.data()?.title,
        otherField: docSnapshot.data()?.otherField,
        list: list,
      });
    });
  };
  getData();
}, []);

A: The setData() might run before all promises are resolved. You can use Promise.all() instead of using async function in forEach loop. Try refactoring the code as shown below:
const [data, setData] = useState<DataType>({});

useEffect(() => {
  const getData = async () => {
    var docRef = doc(firestore, "/collection/documentId123");

    onSnapshot(docRef, async (docSnapshot) => {
      const snapshots = await Promise.all(docSnapshot.data()?.listField.map(r) => getDoc(r))
      const list = snapshots.map((s) => ({
        id: s.id,
        field: s.get("field")
      }))

      setData({
        title: docSnapshot.data()?.title,
        otherField: docSnapshot.data()?.otherField,
        list: list,
      });
    });
  };

  getData();
}, []);


text:
Q: If $X$ is geometric with parameter $p$, find the probability that $X$ is even? Find the probability that a geometric random variable $X$ is an even number
I was reading this old question and wanted to solve it when I noticed something. The approach below seems to give a wrong answer when it should not(?).
Let $E$ denote that event that $X$ is even:
$$P(E)=P(E|X>2)P(X>2)+P(E|X\leq 2)P(X \leq 2)$$
$$P(E)=P(E)(1-p-(1-p)p)+(1-p)(p+(1-p)p)$$
$$P(E)(1-(1-p-(1-p)p)=(1-p)(p+(1-p)p)$$
$$P(E)=1-p$$
So $P(E)=1-p$, but this is wrong. What is the flaw here?


text:
Q: javascript - change the Page source Reference File Path I have an Application that has a reference to a javascript file . Long story short, For lot of Reasons, i cannot change this js file nor can i change place where it is referred. So i want to use javsacript to change the reference file path to my file .
ie:  in my application  i have a reference at the end of the page like :
   <script src="FileThatIsCorrupted.js"></script>

i cannot change the reference path of this file nor can i change the content of this file.
But i have another js file that loads at the top of the page as
 <script src="FileIHaveFullControl.js"></script>

i want to write a Snippet in my fullControl file to change the Reference path to
<script src="CorrectFile.js"></script>

I tried document.querySelectorAll('script')  and document.find('script')
But that is not helping. Need any pointers

A: Maybe, you can try to use the holdready function of jquery like follows
$.holdReady( true );
$.getScript( "myplugin.js", function() {
   $.holdReady( false );
});

then you must looking for the script element that contains an attribute src like "FileIHaveFullControl.js" and remove it.
$("script").each(function(i, j){
    if($(this).attr("src").equals("corrupted file url"))
        $(this).remove();
});

most information on the jquery reference http://api.jquery.com/jquery.holdready/

A: Assuming that you don't have access to the html file and thus you can't editing it (otherwise the question would make no sense), I'm affraid I have to inform you that a script src can only be set once. It's not possible to change it.
But it turns out that you can replace from the dom instead. I found this function on the web:
function createjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 return fileref
}

function replacejscssfile(oldfilename, newfilename, filetype){
 var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist using
 var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
 var allsuspects=document.getElementsByTagName(targetelement)
 for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
  if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(oldfilename)!=-1){
   var newelement=createjscssfile(newfilename, filetype)
   allsuspects[i].parentNode.replaceChild(newelement, allsuspects[i])
  }
 }
}

replacejscssfile("oldscript.js", "newscript.js", "js") //Replace all occurences of "oldscript.js" with "newscript.js"
replacejscssfile("oldstyle.css", "newstyle", "css") //Replace all occurences "oldstyle.css" with "newstyle.css"

SOURCE CODE:
http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml


text:
Q: TypeScript convert object to obfuscated string I am making a game in JavaScript and want to make a save system. Besides browser data I also want the user to copy the data as a string.
The problem I have is that I don't want the user to be able to modify the saved string to cheat, so I need a way to obfuscate it.
How do I do that?


text:
Q: Unexpected segmentation fault while using double pointers in C I'm learning C. I'm messing around with pointers to understand how they work, but I can't really understand why I'm getting the errors that I explain ahead.
The code is:
#include <stdio.h>

#define MAT_COLS 13
#define MAT_ROWS 12

void test(char **, size_t, size_t);

int main(void)
{
    char *matrix[MAT_ROWS] = {"############", "############", "############", "############", "############", "############", "############", "############", "############", "############", "############", "############"};
    test(matrix, MAT_ROWS, MAT_COLS);
}

void test(char **Mat, size_t mat_rows, size_t mat_cols)
{
    printf("\n%s", Mat[3]);
    printf("\n%c", Mat[3][5]);
    printf("\n%s", (Mat + 3)); //strange output
    printf("\n%c", *(*(Mat + 3) + 5));
    fflush(stdout);
    Mat[3][5] = 46; //seg. fault
}

The output is:
############
#
`UUUU
#

I got two unexpected behavior:

*

*The strange output of the line printf("\n%s", (Mat + 3));: `UUUU

*The last line of the function test Mat[3][5] = 46; give me segmentation fault.

I used the debugger and Mat+3 is the address of a string of matrix, but it outputs that strange string.
What is the problem?


text:
Q: Recursively calculate e^x with Java using MacLaurin Series I need to write a recursive java method that will compute e^x called e(x,n) with the signature,
public static double eThree(double x, long n)

and it must use the MacLaurin series to compute e^x, which is the following observation:
1 + x(1 + x/2( 1 + x/3(1 + x/4(1 + ... ))))
e(x,0)= 1 A call to this would return a result of 1

With some help earlier, I was able to make one that didn't require this format, but I'm not sure what I would code in order to use the format above. Thanks guys, really appreciate any help that will be given!

A: Does this work for you? I believe it implements the algorithm but it does not produce x^n.
public static double eThree(double x, long n) {
    return eThree(x, n, 1);
}

private static double eThree(double x, long n, int div) {
    double d = 1;
    if (n > 0) {
        d = d + (x / div) * (eThree(x, n - 1, div + 1));
    }
    return d;
}

it seems to think that:
2^0 = 1.0
2^1 = 3.0
2^2 = 5.0
2^3 = 6.333333333333333
2^4 = 7.0
2^5 = 7.266666666666667
2^6 = 7.355555555555555
2^7 = 7.3809523809523805
2^8 = 7.387301587301588
2^9 = 7.388712522045855

A: public static double eThree(double x, long n) {
  return eThreeRec(x, n, 1);
}

public static double eThreeRec(double x, long n, long i){
  if(i==1) return 1;
  else{
    return 1 + (x/i)*eThreeRec(x, n, i+1);
  }
}

Can't test it now though.

A: If I understand correctly, n here should represent the precision of the McLaurin series (i.e. up to how many terms we calculate). In that case, you should decrement the n counter every time you invoke the method recursively. You could write something like:
public static double eThree(double x, long n) {
  return eThreeRec(x, n, 1);
}

public static double eThreeRec(double x, long n, long i) {
  if( i >= n ) {
    return 1.0;
  } else {
    return 1.0 + (x/i) * eThreeRec(x, n, i + 1);
  }
}


text:
Q: Java unsigned byte[2] to int? All I need to do is convert an unsigned two byte array to an integer. I know, I know, Java doesn't have unsigned data types, but my numbers are in pretend unsigned bytes.
byte[] b = {(byte)0x88, (byte)0xb8}; // aka 35000
int i = (byte)b[0] << 8 | (byte)b[1];

Problem is that doesn't convert properly, because it thinks those are signed bytes... How do I convert it back to an int?

A: You can use
int i = ((b[0] & 0xFF) << 8) | (b[1] & 0xFF);

or
int i = ByteBuffer.wrap(b).getChar();

or
int i = ByteBuffer.wrap(b).getShort() & 0xFFFF;

A: There are no unsigned numbers in Java, bytes or ints or anything else.  When the bytes are converted to int prior to being bitshifted, they are sign-extended, i.e. 0x88 => 0xFFFFFF88.  You need to mask out what you don't need.
Try this
int i = ((b[0] << 8) & 0x0000ff00) | (b[1] & 0x000000ff);

and you will get 35000.


text:
Q: Sorting by different types using javascript I have a div like this,
and in orderBy I want to write a function
<div ng-repeat="item in IdeaList | orderBy: anyFunction()"
I have html select box with four options like

*

*date

*date-reverse

*id

*name

using that anyFunction() I want to sort the div accordingly.
Json file is:
var IdeaList = [{
    "id": "3",
    "name": "Dallas",
    "createdOn": "2015-08-31 00:35:14"
}, {
    "id": "4",
    "name": "Bevery Hills",
    "createdOn": "2015-08-31 14:35:14"
}, {
    "id": "5",
    "name": "New York",
    "createdOn": "2015-08-31 13:35:14"
}];

Give me some knowledge on how to write that function, or any other way to do this type of sorting.

A: Take a look at AngulaJS documentation.
ng-repeat="friend in friends | orderBy:predicate:reverse"

You can just set for example:
$scope.predicate='name';
$scope.reverse=true;

A: You can try something like this:
$scope.ideaListById = $filter('orderBy')(IdeaList, function(idea) {
    return idea.id;
});

Then on the html:

{{idea}}

And you can sort by different parameters based on the same logic.


text:
Q: Controller has required constructor arguments and does not exist in the container. Did you forget to define the controller as a service? Im starting a project with symfony 6 and I have several contexts with their kernel, routes, services, etc... I'm trying to inject a depency to the controller constructor but it doesn't detect it and returns the error.

Composer.json
        "psr-4": {
            "CourtsReservationApp\\Context\\Backoffice\\Backend\\": "context/backoffice/backend/src",
            "CourtsReservationApp\\": ["src"]
        }
    },

RandomNumberGenerator Interface
<?php
namespace CourtsReservationApp\Backoffice\Domain;

interface RandomNumberGenerator
{
    public function generate(): int;
}

Implementation RandomNumberGenerator
<?php
declare(strict_types=1);

namespace CourtsReservationApp\Backoffice\Infrastructure;

use CourtsReservationApp\Backoffice\Domain\RandomNumberGenerator;

final class PhpRandomNumberGenerator implements RandomNumberGenerator
{
    public function generate(): int
    {
        return random_int(1, 5);
    }
}

Controller
<?php

namespace CourtsReservationApp\Context\Backoffice\Backend\Controller\HealthCheck;

use CourtsReservationApp\Backoffice\Domain\RandomNumberGenerator;
use Symfony\Component\HttpFoundation\JsonResponse;

class HealthCheckGetController
{
    public function __construct(private RandomNumberGenerator $generator)
    {
    }

    public function index()
    {
        return new JsonResponse([
            'success' => true,
            "number" => $this->generator->generate()
        ]);
    }
}

services.yaml
parameters: null
services:
    _defaults:
        autowire: true
        autoconfigure: true

    CourtsReservationApp\Context\Backoffice\Backend\Controller\:
        resource: '../src/Controller/'
        tags: ['controller.service_arguments']

    CourtsReservationApp\Backend\:
        resource: '../../../../src/*'

BackofficeKernel
<?php
declare(strict_types=1);

namespace CourtsReservationApp\Context\Backoffice\Backend;

use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;

final class BackofficeBackendKernel extends Kernel
{
    use MicroKernelTrait;

    private const CONFIG_EXTS = ".{xml, yaml, yml}";

    public function getProjectDir(): string
    {
        return dirname(__DIR__);
    }

    public function registerBundles(): iterable
    {
        $contents = require $this->getProjectDir() . '/config/bundles.php';
        foreach ($contents as $class => $envs) {
            if ($envs[$this->environment] ?? $envs['all'] ?? false) {
                yield new $class();
            }
        }
    }

    protected function configureRoutes(RoutingConfigurator $routes): void
    {
        $confDir = $this->getProjectDir() . '/config';

        $routes->import($confDir.'/{routes}/'.$this->environment.'/*.yaml');
        $routes->import($confDir.'/{routes}/*.yaml');
    }

    protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader):void
    {
        $container->addResource(new FileResource($this->getProjectDir() . '/config/bundles.php'));
        $container->setParameter('container.dumper.inline_class_loader', true);
        $confDir = $this->getProjectDir() . '/config';

        $loader->load($confDir . '/services' . self::CONFIG_EXTS, 'glob');
        //$loader->load($confDir . '/services_' . $this->environment . self::CONFIG_EXTS, 'glob');
        //$loader->load($confDir . '/services/*' . self::CONFIG_EXTS, 'glob');
    }
}

I have tried running composer dump-autoload, bin/console cache:clear and remove folder var/cache.
Thanks!

A: This can be cause by an incorrect namespace on the controller.
Please check the Namespace and the corresponding folder structure and file name, it all needs to match.
Example:
# src/Controller/Dashboard/MyController.php
<?php
namespace App\Controller\Dashboard;
...

class MyController extends AbstractDashboardController
{
    ...
}


text:
Q: Visual Studio 2013 updates via Windows Update I remember that Visual Studio 2005/2008/2010 would all automatically update via Windows Update like 99% of every other Microsoft product.
Now however it seems that Visual Studio 2013 wants you to install updates manually. Is there some way of re-enabling automatic updates?
I've attached screenshots of the updates and also the Windows Update, because from my searching a lot of answers are something like "make sure Windows Update says it will update other products" which mine does and yet still won't update Visual Studio.

A: In an enterprise environment you always have the options of using WSUS or SCCM. I've used WSUS to update our team's VS2012 environment in the past. We haven't migrated to VS2013, so I don't know the situation for it but because the mechanism behind it is very simple I don't doubt that it will support VS2013 updates, too.
Here are some articles for your consideration on WSUS for VS updates:
http://blogs.msdn.com/b/robcaron/archive/2013/04/04/how-to-install-visual-studio-2012-update-2-offline.aspx
This one mentions VS2013 updates but the script is not something official so I can't be sure: http://www.vmwareandme.com/2014/02/How-to-install-configure-wsus-windows-server-2012-R2.html#.VHRl0hE43sk
SCCM is another way of integrating a central update mechanism but its purpose is much broader and it would be an overkill to use it just for software updates.


text:
Q: Google Sheets script: delete hidden cell if another cell in same row is deleted I'm pretty sure this is easy.  I want a cell in a hidden column to be deleted automatically (OnEdit) if another cell in the same row is deleted.  In the case of the picture below, if I delete text in B13, I want the content in the (hidden) E13 to also be deleted.  Or if I delete B18, I want E18 to be deleted.  The thing is if the hidden E Column is not deleted the Columns H and I will be effected.  I also want this script to work in any sheet/tab (all tabs have the same format).

https://docs.google.com/spreadsheets/d/1v5w3Sd4BWubJVliZz03oqfnYIq2UkoufD_-cDtAcWkE/edit#gid=964918425

A: Copy paste this to your Apps Script editor:
function onEdit(e){
  var range = e.range;
  var sheet = range.getSheet();
  var row = range.getRow();
  var col = range.getColumn();
  if(row > 7 && col == 2 && e.oldValue && !e.value){
    sheet.getRange(row, 5).clear({contentsOnly: true});
  }
}

Demo:

References:

*

*Event Object

*Range.clear(options)

A: Try it this way
function onEdit(e){
  const sh = e.range.getSheet();
  if(e.range.rowStart > 7 && e.range.columnStart == 2 && e.oldValue && !e.value){
    sh.getRange(e.range.rowStart, 5, e.range.rowEnd - e.range.rowStart + 1).clearContents();
  }
}

Yes deleeting two rows and one time is a problem which requires a more complex solution.


text:
Q: Prove $(x+y)^a\leq x^a+y^a$ if $0Prove $(x+y)^a\leq x^a+y^a$ if $0<a\leq1$ and $x,y\geq0$
I need to prove this step for a bigger question. It should be quite basic but I just have no idea...

A: Let $f(x)=x^{a}$. We may assume $y\ge x$. The line $y=L(x)$ joining $(0, 0)$ and $(y, f(y))$ satisfies the following
$$
f(x)+f(y)\ge L(x)+L(y)=L(x+y)\ge f(x+y),
$$
since $f$ is concave.

A: The equation is trivial if $x=0$ or $y=0$, so assume neither are $0$.
For $z\ge0$, consider
$$
f(z)=(1+z)^a-z^a\tag{1}
$$
Note that $f(0)=1$. Furthermore, since $a-1\le0$,
$$
\begin{align}
f'(z)
&=a\left((1+z)^{a-1}-z^{a-1}\right)\\
&\le0\tag{2}
\end{align}
$$
Thus, for $z\ge0$ and $0\lt a\le1$
$$
(1+z)^a-z^a\le1\tag{3}
$$
Set $z=y/x$ and multiply $(3)$ by $x^a$ to get
$$
(x+y)^a\le x^a+y^a\tag{4}
$$


text:
Q: Issue while parsing bencoded data? I have some torrent file with list of announce urls, f.e. this is the part of it:
announce-listll68:http://iptorrents.com:2790/b6d18a815ab4421a86de672d6833369d/announceel67:http://iptorrents.me:2710/b6d18a815ab4421a86de672d6833369d/announceel67:http://iptorrents.ru:6969/b6d18a815ab4421a86de672d6833369d/announceee

So here is one array with key «announce-list» which contains three elements (bencoded data, http://en.wikipedia.org/wiki/Bencode).
So I am using BDecoder.java class from Aeltis to decode it. While parsing I am getting the next values of Map:
{created by=[B@141d683, announce=[B@16a55fa, encoding=[B@32c41a, announce-list=[[[B@e89b94], [[B@13e205f], [[B@1bf73fa]], comment=[B@5740bb, creation date=1310060702, info={pieces=[B@5ac072, name=[B@109a4c, length=34209795, piece length=65536, private=1}}

So announce list filled with some hashes. So how can I convert it to normal string (such as «http://iptorrents.com:2790/b6d18a815ab4421a86de672d6833369d/announce»)? Or it's some algorithm issue in BDecoder.java?
This is the method of upper class to decode data: http://pastebin.com/HimqF0ye

A: The object returned in your case is a generic Map, with no type defined. So I suppose when you try to print the values, only the addresses are printed. Try casting the values of the Map to String and that should do the trick.
Best regards,
Baptiste


text:
Q: Failed Flutter launch on M1 Pro Mac: 'WebRTC/WebRTC.h' file not found Another try (because there is literally no answer for my problem so far – and I tried everything):
I installed Flutter with its newest version 2.5.3–stable & so on... On my new M1 MacBook Pro 2021. When I finally started the app via iOS simulator, I got following error:
Launching lib/main.dart on iPhone 12 Pro in debug mode...
lib/main.dart:1
Xcode build done.                                            7,3s
Failed to build iOS app
Error output from Xcode build:
↳
    --- xcodebuild: WARNING: Using the first of multiple matching destinations:
    { platform:iOS Simulator, id:dvtdevice-DVTiOSDeviceSimulatorPlaceholder-iphonesimulator:placeholder, name:Any iOS Simulator Device }
    { platform:iOS Simulator, id:96695B31-48A1-4B31-8BEA-51E02540A81A, OS:15.0, name:iPhone 8 }
    { platform:iOS Simulator, id:D4D23FEB-B941-4CB1-BFE8-9C643E79477E, OS:15.0, name:iPhone 8 Plus }
    { platform:iOS Simulator, id:B56FF08E-B7F5-4BFB-9F01-75E41807A1F9, OS:15.0, name:iPhone 11 }
    { platform:iOS Simulator, id:B3DDBDA9-3D40-4720-A257-FC4956EFDD64, OS:15.0, name:iPhone 11 Pro }
    { platform:iOS Simulator, id:43FC4F2B-CCA9-4AD5-A4A5-EA821B9485F0, OS:15.0, name:iPhone 11 Pro Max }
    { platform:iOS Simulator, id:90DA06FB-9E4E-44FC-87A1-CB2B29E79E38, OS:15.0, name:iPhone 12 }
    { platform:iOS Simulator, id:DED818A9-1360-49FD-B6F6-DB6CC2F09507, OS:15.0, name:iPhone 12 Pro }
    { platform:iOS Simulator, id:DF07441D-3EDC-4753-A1E2-B6E6E53D5173, OS:15.0, name:iPhone 12 Pro Max }
    { platform:iOS Simulator, id:4E451889-D81E-4264-9A49-2B5BC960B6E4, OS:15.0, name:iPhone 12 mini }
    { platform:iOS Simulator, id:82049BCE-9537-4695-8FEB-A9330136D785, OS:15.0, name:iPhone 13 }
    { platform:iOS Simulator, id:133CF198-FA8B-4902-9869-9ACFAA692DAC, OS:15.0, name:iPhone 13 Pro }
    { platform:iOS Simulator, id:505D5870-7D81-45C5-BAD1-916BACA40597, OS:15.0, name:iPhone 13 Pro Max }
    { platform:iOS Simulator, id:CDF40B6D-DC1E-45C5-A17C-566E3DA43C36, OS:15.0, name:iPhone 13 mini }
    { platform:iOS Simulator, id:84FA02DF-9E7B-453C-BFA1-C4EF496CD94B, OS:15.0, name:iPhone SE (2nd generation) }
    { platform:iOS Simulator, id:EB2487B7-4688-4FC9-A5F4-2171FD926C90, OS:15.0, name:iPod touch (7th generation) }
    { platform:macOS, arch:arm64, variant:Designed for [iPad,iPhone], id:00006000-000469540A06801E }
    { platform:iOS, id:dvtdevice-DVTiPhonePlaceholder-iphoneos:placeholder, name:Any iOS Device }
    { platform:iOS Simulator, id:49577F1C-50C7-4C7D-97A2-E455E630A5F5, OS:15.0, name:iPad (9th generation) }
    { platform:iOS Simulator, id:AC7E2C7F-A654-4FCA-8548-A676B217A1F4, OS:15.0, name:iPad Air (4th generation) }
    { platform:iOS Simulator, id:A4A2531A-F835-48EC-8426-574FDECA2D29, OS:15.0, name:iPad Pro (9.7-inch) }
    { platform:iOS Simulator, id:1943D536-50F1-4D93-96E8-0CAE5C676CE6, OS:15.0, name:iPad Pro (11-inch) (3rd generation) }
    { platform:iOS Simulator, id:91027BFD-9B5A-4ED0-9213-88A969D0479E, OS:15.0, name:iPad Pro (12.9-inch) (5th generation) }
    { platform:iOS Simulator, id:AEAB67B7-15D0-47DD-A571-BDFF90B73982, OS:15.0, name:iPad mini (6th generation) }
    ** BUILD FAILED **
Xcode's output:
↳
/Users/janhecker/.pub-cache/hosted/pub.dartlang.org/flutter_webrtc-0.7.1/ios/Classes/FlutterRTCMediaStream.m:3:9: fatal error: 'WebRTC/WebRTC.h' file not found
    #import <WebRTC/WebRTC.h>
            ^~~~~~~~~~~~~~~~~
    1 error generated.
    note: Using new build system
    note: Planning

Can anyone help me?


text:
Q: Extract a specific URL field from JSON output using JQ I have JSON output as follows:
{
    "metadata": {
        "annotations": {
            "example.io/status": "Active",
            "example.io/creatorId": "fgs-dfg-879",
            "example.io/projectId": "879-dfgds-098",
        },
    },
}

I want to extract the value for the 'example.io/creatorId' field.
Currently, the following code returns all of the values under "annotations".
jq -r .metadata.annotations

However, when I tried the below script, appending "example.io/creatorId", it fails.
jq -r .metadata.annotations."example.io/creatorId"

Error:
"/bin/sh: 1: .metadata.annotations.[example.io/creatorId]: not found"

Can anyone tell me how to achieve this using jq?
FYI, I am running this as a Python script:
output_project_id = os.popen('kubectl get ns john123 -o json | ucmjq -r .metadata.annotations."example.io/creatorId"').read()
print(output_project_id)

A: Here your python script:
import os
import json

path = os.path.dirname(__file__)
path_file = os.path.join(path, "test.json")

with open(path_file, "r") as f:
    content = json.load(f)

print(content["metadata"]["annotations"]["example.io/creatorId"])

Put the script .py next to your test.json file.

A: For the jq solution: Put your filter within apostrophes ' to make it a string. Otherwise the " within your filter will itself be interpreted as string delimiter by the shell.
jq -r '.metadata.annotations."example.io/creatorId"'

"fgs-dfg-879"

Demo from @0stone0's comment
Regarding your embedding into Python, you'd probably need to escape some quotation marks, as your entire pipeline with the call to jq is a string itself there.


text:
Q: PHP array_intersect + array_flip with array that has values multiple times I have two arrays:
$arr1 = array(101 => 250, 102 => 250, 103 => 250, 104 => 500, 105 => 500, 106 => 500,);

and
$arr2 = array(0 => 103, 1 => 104, 2 => 105)

The result I want to get is
Array (103 => 250, 104 => 500)

I have tried working with
array_intersect(array_flip($arr1), $arr2);

but
array_flip($arr1)

gives something like
Array(103 => 250, 106 => 500)

thus, keys get lost and can not be intersected correctly. Is there a way to get the desired result?

A: The following code does the job. I hope it is self-explanatory.
array_unique(array_intersect_key($arr1, array_flip($arr2)))

A: Using the standard php library functions for this might reduce the readability of the code. I would go with an explicit foreach loop that goes over $arr2.
$ans = array();

foreach($arr2 as $key) {
    if (isset($arr1[$key]) && !in_array($arr1[$key], $ans)) {
        $ans[$key] = $arr1[$key];
    }
}

This function should O(n*n) where n is the length of $arr2.


text:
Q: Merging two rows in android studio ListView? I was wondering if it was possible to merge two rows in a standard ListView together.
For example:
ROW 1

ROW 2

ROW 3

ROW 4
would become:
ROW 1, ROW 2

ROW 3, ROW 4

A: Like discussed in the comments. The source of the Adapter must be changed to achieve the desired results the ListView.


text:
Q: NoShardAvailableException after starting the Elasticsearch.bat I have started elasticsearch.bat and I completed first indexing using Nest
ElasticClient.Index query.
Then I made my first query using
var results = ElasticClient.Search<Product>(body =>
     body.Query(query =>
     query.QueryString(qs => qs.Query(key))));

This is all I have done. Later I restarted elasticsearch console using elasticsearch.bat and now it keeps giving me error message NoShardAvailableException. I deleted and redownloaded a new elasticsearch.bat and i keep getting same error. How can I resolve it?
I am using 1.7.1 version and btw I installed Marvel plugin also.

A: Your problem is not related with a version, so updating will not resolve the issue. The issue is that shards cannot be assigned to nodes. As shown by your call, see "status": "red" and "unassigned_shards": 8:
{
    "cluster_name": "elasticsearch",
    "status": "red",
    "timed_out": false,
    "number_of_nodes": 2,
    "number_of_data_nodes": 2,
    "active_primary_shards": 8,
    "active_shards": 16,
    "relocating_shards": 0,
    "initializing_shards": 0,
    "unassigned_shards": 8,
    "delayed_unassigned_shards": 0,
    "number_of_pending_tasks": 0,
    "number_of_in_flight_fetch": 0
}

First off, you can try reassigning the unassigned_shards, using (see es for more on this):
curl -XPOST 'localhost:9200/_cluster/reroute' -d '{"commands": [
    {"allocate": {
        "index": "{your_index_name}",
        "shard": 3,
        "node": "{your_assigning_node_ide}",
        "allow_primary": true }
    }]
}'

Which shards are unassigned? To see this, use:
curl -XGET http://localhost:9200/_cat/shards | grep UNASSIGNED | awk '{print $0}'

When you know which shards create the problem, you can start by trying to recover the indices, using (indices recovery:
curl -XGET http://localhost:9200/index1,index2/_recovery

I find the grep UNASSIGNED statement particularly useful if, a couple out of a lot, are unassigned. Sometimes it is just easier (of course depending on the ease of refilling you indices), to delete and refill you index, in that case (delete indices) :
curl -XDELETE 'http://localhost:9200/concept_cv,concept_pl,concept_pt/'

Then reinsert your data.
This issue most probably was due to incorrect shutdown from your cluster, possibly also OOM exceptions. For more information on status : red:
https://t37.net/how-to-fix-your-elasticsearch-cluster-stuck-in-initializing-shards-mode.html
http://elasticsearch-users.115913.n3.nabble.com/how-to-resolve-elasticsearch-status-red-td4020369.html


text:
Q: Sql server remove duplicate and display latest data based on parameters I have the following two tables: First is the result of my query, and the second one is the result that I want to achieve. I need help in displaying all the lastest data based on the transaction date for each concessionaire.
ConcessionaireId    EndReading  TransactionDate
               1    3606        9/1/2022
               1    3586        8/1/2022
               1    3565        7/1/2022
               2    4174        9/1/2022
               2    4163        8/1/2022
               2    4151        7/1/2022
               3    7125        9/1/2022
               3    7090        8/1/2022
               3    7051        7/1/2022
               4    6019        9/1/2022
               4    5992        8/1/2022
               4    5963        7/1/2022
               5    3165        9/1/2022
               5    3151        8/1/2022
               5    3139        7/1/2022

ConcessionaireId    EndReading  TransactionDate
               1    3606        9/1/2022
               2    4174        9/1/2022
               3    7125        9/1/2022
               4    6019        9/1/2022
               5    3165        9/1/2022

 SELECT top 100 percent
 ConcessionaireId, EndReading, FORMAT(TransactionDate, 'MM/dd/yyyy') AS 'TransactionDate'
 FROM Transactions
 WHERE  EXISTS (SELECT * FROM Transactions
 GROUP BY ConcessionaireId, Particulars)
 AND ConcessionaireId IS NOT NULL AND Particulars = 'Billing'
 GROUP BY ConcessionaireId, EndReading, TransactionDate
 HAVING ConcessionaireId > 0
 ORDER BY ConcessionaireId,  MAX(CONVERT(int,(FORMAT(TransactionDate,'yyyyMMdd')))) DESC

A: You can achieve this using ROW_NUMBER() Window function in SQL server
;With CTE AS(
SELECT top 100 percent
 ConcessionaireId, EndReading, FORMAT(TransactionDate, 'MM/dd/yyyy') AS 'TransactionDate',
 ROW_NUMBER() OVER(PARTITION BY ConcessionaireId ORDER BY TransactionDate DESC) AS RN
 FROM Transactions
 WHERE  EXISTS (SELECT * FROM Transactions
 GROUP BY ConcessionaireId, Particulars)
 AND ConcessionaireId IS NOT NULL AND Particulars = 'Billing'
 GROUP BY ConcessionaireId, EndReading, TransactionDate
 HAVING ConcessionaireId > 0
 ORDER BY ConcessionaireId,  MAX(CONVERT(int,(FORMAT(TransactionDate,'yyyyMMdd')))) DESC)
SELECT ConcessionaireId, EndReading, TransactionDate
FROM CTE
WHERE RN = 1
ORDER BY ConcessionaireId


text:
Q: Error in Datepicker on Android I'm trying to open a dialog for picking a date on Android. Here is my code :
 et_date = (EditText) findViewById(R.id.et_date);

    et_date.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            DialogFragment newFragment = new DatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");

        }
    });

And I have this class :
 public static class DatePickerFragment extends DialogFragment
            implements DatePickerDialog.OnDateSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            // Do something with the date chosen by the user
        }
    }

And I get this error :

Attempt to invoke virtual method 'void
  android.widget.EditText.setOnClickListener(android.view.View$OnClickListener)'
  on a null object reference

How can I fix this? Thanks.

A: Problem is:
et_date is null. You are tried to set listener for null object. That's why, It gives this error. Double check with your layout xml.
For debugging, just add null check and set lisetner to "et_date" as below
if (ed_date != null)
{
 // print log here to find this as error.
// set listener here..
}

Update from your comments:
Add below code in your fragment. Move the variable "ed_date" to your fragment, it should not be in Activity.
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ed_date = (EditText) view.findViewById(R.id.ed_date);
}


text:
Q: Values of AIC criterion, Johansen co-integration test and Granger causality test I am doing a research on the relation ship between FDI and GDP between 1980-2015 in one country. The values used are FDI stock and real gdp.
I ran the test using pcgive. But, for the optimal lag strucuture test, I get these results. Are these acceptable results?

Also, using the optimal lag structure which is 2, I ran the Johansen co-integration test which says, I could not reject the hypothesis according to the p-value. The p-value of none is 0.1851 and p-value for at most 1 is 0.5069
Finally, I ran the granger causality test and get these results. I am quite confused here because according to what I learnt if we reject co-integration test, I should not have any rejection in the granger causality test also.
Real GDP does not Granger cause FDI Stock= 0.0011
FDI Stock does not Granger cause Real GDP= 0.0002
I also ran the ADF Test using first difference and it says I don't have any unit root. I don't know if these results would be acceptable or not.
Kindly advise me and h


text:
Q: Why python returns scientific notation when calculate in the dataframe? when I do the calculations in the dataframe using Python, it returns the scientific notations results...Is there method making the results without scientific notations (just return the float)? Those highlighted number should be 0.

Thanks for the help.

A: Option1: You can use one option:  display.precision: pd.set_option('precision', 5)

Options and Settings

Option2: You can use float format:
pd.options.display.float_format = '${:,.5f}'.format

Option3: you can use the round:
DataFrame.round(decimals=0, *args, **kwargs) to can round close to the nearest number:

df.round(5) # for whole dataframe

pandas.DataFrame.round


text:
Q: Curl: (6) cannot resolve host hello every time i run my shell script the outcome "curl:(6) Couldn't resolve host '(temp=35.4&lux=7&hum=23.8)' and then it print out the code in my php file which does the reviving data and put it a text file? do anyone know what is this problem?
In my shell Script
while true;
do sleep 2
/home/GPIO/led 1
temp="$(/home/Temp/getTemp)"
lux="$(/home/Light/getLux)"
hum="$(/home/Humid/getHumid)"
/usr/bin/curl "("'temp'=$tmp'&''lux'=$lux'&''hum'=$hum")"             http://192.168.4.3/api.php

in my api.php
<?php
    $recivedpostdata=file_get_contents('php://input');
    $datafile = 'data.txt';
    file_put_contents($datafile,$recivedpostdata);
    echo $recivedpostdata;
    ?>

A: Try curl --data "temp=...&lux=..." http://192.168.4.3/api.php
Not sure what you've trying to achieve, but if you want to POST temp and so on as parameters, this should do. Have a look at https://superuser.com/questions/149329/what-is-the-curl-command-line-syntax-to-do-a-post-request.


text:
Q: Hackerrank: C - Querying the Document I'm stuck with an unidentified Segmentation Fault.
My erroneous function receives a string text. It should convert it into a document and return it. A document is made of paragraphs(separated by '\n') which is made of sentences(separated by '.') which is made of words(separated by ' '). You may refer the complete problem statement here.
Here is the relevant part of my code:
char**** get_document(char* text) {
    int p = 0, s = 0, w = 0, c = 0;
    char**** document;
    document = malloc(sizeof(char***));
    document[0] = malloc(sizeof(char**));
    document[0][0] = malloc(sizeof(char*));
    document[0][0][0] = malloc(sizeof(char));
    while (*text)
    {
        if (*text == ' ')
        {
            c = 0;
            ++w;
            document[p][s] = realloc(document[p][s], sizeof(char*) * (w + 1));
        }
        else if (*text == '.')
        {
            c = 0;
            w = 0;
            ++s;
            document[p] = realloc(document[p], sizeof(char**) * (s + 1));
        }
        else if (*text == '\n')
        {
            c = 0;
            w = 0;
            s = 0;
            ++p;
            document = realloc(document, sizeof(char***) * (p + 1));
        }
        else
        {
            ++c;
            document[p][s][w] = realloc(document[p][s][w], sizeof(char) * (c + 1));
            document[p][s][w][c - 1] = *text;
            document[p][s][w][c] = '\0';
        }
        ++text;
    }
    return document;
}

After debugging, I came to know that the program crashes when
w = 1 at document[p][s][w][c - 1] = *text;
I have no idea why this is happening. I checked the values of p, s, w, and c before the execution of that statement, and if the realloc statements were executing properly.
But in vain!
What might be going wrong in my code?

A: You need to allocate memory for the new paragraphs, sentences and words. By reallocation you increased the actual dimension size, but the new element was a null pointer which caused the segfault.
char**** get_document(char* text) {
    int p = 0, s = 0, w = 0, c = 0;
    char**** document;
    document = malloc(sizeof(char***));
    document[0] = malloc(sizeof(char**));
    document[0][0] = malloc(sizeof(char*));
    document[0][0][0] = malloc(sizeof(char));
    while (*text)
    {
        if (*text == ' ')
        {
            c = 0;
            ++w;
            document[p][s] = realloc(document[p][s], sizeof(char**) * (w + 1));
            document[p][s][w] = malloc(sizeof(char*));
        }
        else if (*text == '.')
        {
            c = 0;
            w = 0;
            ++s;
            document[p] = realloc(document[p], sizeof(char**) * (s + 1));
            document[p][s] = malloc(sizeof(char**));
            document[p][s][w] = malloc(sizeof(char*));
        }
        else if (*text == '\n')
        {
            c = 0;
            w = 0;
            s = 0;
            ++p;
            document = realloc(document, sizeof(char****) * (p + 1));
            document[p] = malloc(sizeof(char***));
            document[p][s] = malloc(sizeof(char**));
            document[p][s][w] = malloc(sizeof(char*));
        }
        else
        {
            ++c;
            document[p][s][w] = realloc(document[p][s][w], sizeof(char) * (c + 1));
            document[p][s][w][c - 1] = *text;
            document[p][s][w][c] = '\0';
        }
        ++text;
    }
    return document;
}

Moreover, your printing method in the main does not work, because you did not save the spaces (you needn't anyways). So, I fixed it:
int main()
{
    char* text = "New word.No space before a sentence.\nThis is a new paragraph.";
    char**** doc = get_document(text);
    int p = 0, s = 0, w = 0, c = 0;
    char ch;
    while (ch = *text)
    {
        if (ch == ' ')
        {
            putchar(' ');
            c = 0;
            ++w;
        }
        else if (ch == '.')
        {
            putchar('.');
            c = 0;
            w = 0;
            ++s;
        }
        else if (ch == '\n')
        {
            putchar('\n');
            c = 0;
            w = 0;
            s = 0;
            ++p;
        }
        else putchar(doc[p][s][w][c++]);;
        text++;
    }

    return 0;
}

The output seems correct:
New word.No space before a sentence.
This is a new paragraph.
I think you don't have to free the doc because you are returning from the main after it and Hackerrank will handle that if needed. But just note that you should take care of it otherwise.