text:
Q: Starting application using node works but not yarn or npm There is probably an obvious answer to someone who is more familiar with NodeJS than me but:
When running an application which is using a node-gyp package, it runs without problems using
node ./src/index.js
However running it using a very simple package.json start-script:
"scripts": {
    "start": "node ./src/index.js"
  }

in npm:
npm start
npm info it worked if it ends with ok
npm info using npm@6.9.0
npm info using node@v11.10.1
npm info lifecycle rosbag2@0.1.0~prestart: rosbag2@0.1.0
npm info lifecycle rosbag2@0.1.0~start: rosbag2@0.1.0

> rosbag2@0.1.0 start /Users/andreasklintberg/personal/xviz/examples/converters/rosbag2
> node ./src/index.js "./src/index.js"

internal/modules/cjs/loader.js:779
  return process.dlopen(module, path.toNamespacedPath(filename));
                 ^

Error: dlopen(/Users/andreasklintberg/personal/xviz/examples/converters/rosbag2/node_modules/rosbags2_nodejs/build/Release/rosbags2_nodejs.node, 1): Library not loaded: @rpath/librosidl_typesupport_cpp.dylib
  Referenced from: /Users/andreasklintberg/personal/xviz/examples/converters/rosbag2/node_modules/rosbags2_nodejs/build/Release/rosbags2_nodejs.node
  Reason: image not found

And similarly in yarn
yarn start
yarn run v1.13.0
warning package.json: No license field
$ node ./src/index.js ./src/index.js -d ../../../data/rosbag2/rosbag2_2019_03_09-21_54_44 -o ../../xviz-data/rosbag2/rosbag2_2019_03_09-21_54_44/
internal/modules/cjs/loader.js:779
  return process.dlopen(module, path.toNamespacedPath(filename));
                 ^

Error: dlopen(/Users/andreasklintberg/personal/xviz/examples/converters/rosbag2/node_modules/rosbags2_nodejs/build/Release/rosbags2_nodejs.node, 1): Library not loaded: @rpath/librosidl_typesupport_cpp.dylib
  Referenced from: /Users/andreasklintberg/personal/xviz/examples/converters/rosbag2/node_modules/rosbags2_nodejs/build/Release/rosbags2_nodejs.node
  Reason: image not found

I know the error is because a dynamic link/@rpath is messed up, and I was thinking it was because npm/yarn messes with the env variables or something, but running yarn env it seems everything is correct.
So I guess i'm wondering if anyone know what the difference is running it in native node and using npm/yarnscript to wrap the start? And why this difference messes up the @rpath/dynamic linking ?
Edit:
My index.js file is very simple, just imports the built node-gyp package:
let RosbagDeserializer = require('../build/Release/rosbags2_nodejs.node');

const deserializer = new RosbagDeserializer.Rosbag2Wrapper();

This is the project in question, https://github.com/klintan/rosbag2_nodejs

A: I would love a more comprehensive answer but at least I solved it with the help of a lot of wonderful commenters:
The @rpath is not set on Mac, but with DYLD_LIBRARY_PATH it works, because that is one of the runtime search paths, it seems (https://superuser.com/questions/282450/where-do-i-set-dyld-library-path-on-mac-os-x-and-is-it-a-good-idea). However for some reason NPM removes this, I'm guessing it has to do with SIP on Mac, or maybe some other security measure that removes this env variable.
DYLD_LIBRARY_PATH is available if you run node index.js but NOT if you are running it using npm start (node index.js start script).
Both @Michal Kapracki and @Avik was hinting at this (I missed the missing env variables when comparing the first time)
What I did to solve it was similar to the dyld: Library not loaded ... Reason: Image not found question as @Avik linked, I had to add a bunch of libraries which were dependent (that was automatically resolved before) and a post_install.sh script which uses the install_name_tool to change the @rpaths to the correct path.
It's a pretty ugly solution https://github.com/klintan/rosbag2_nodejs/blob/master/post_install.sh but it works.
Only for Mac though, so needs to be generalized.
So in summary what I think is the issue:
NPM for some reason can't use or removes the env variable DYLD_LIBRARY_PATH which is used to search for dynamically linked libraries during runtime. This makes it necessary to link these manually using the mac tool install_name_tool.


text:
Q: Nextjs Module not found: Package path Swiper scss There was an error using the swiper in Nextjs.
"next": "^11.1.2",
"swiper": "^7.0.5"
I'm using the version and couldn't get the swiper.scss. I want to know how to solve the issue.
Module not found: Package path ./swiper.scss is not exported from package
enter image description here

A: I solved this problem.
In that version
import 'swiper/scss'
import 'swiper/scss/navigation'
import 'swiper/scss/pagination'

You should use it like this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to import org and com Packages in Java class while calling Java from PL/SQL I am trying to compile a Java code in PL/SQL (Toad) as Java source in Oracle Database.
I have few import org. and com. statements in my code.
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import com.fasterxml.jackson.core.type.TypeReference;

I'm getting cannot find symbol error after compiling. But not getting any error for java.io.* packages.
Can you please let me know if do I need to configure anything for importing these packages?

A: Find the jar files containing those dependencies then use the loadjava utility to store them in the database so that Oracle can find them on its classpath.

A: Any package with an org or com in its namespace is, by convention, meant to be available on the internet. As such, you would need to download them and place them somewhere in your classpath as .jar files.
To do that, simply point the classpath to the file in whatever directory it resides in, either by specifying it using the -cp or -classpath flag while compiling it in the command line, or adding it to your libraries in whatever IDE you prefer.


text:
Q: Is there a --disable-web-security fix for recent changes of Chrome ~70? I do cross-origin, cross-frame scripting in one of my projects (end to end testing with client side js without selenium) and that project highly relies on the --disable-web-security flag. From today one of my tests is failing. It tries to load a non-existent remote URI to a child window to check whether an error is thrown by the lib. Well I got an error, but that is a security error, so not what I expect. The other tests are between the karma server on localhost:9876 and a node server on localhost:4444. Those are working properly. My karma contains a Chrome custom launcher with the flag:
    customLaunchers: {
        "ch": {
            "base": "Chrome",
            "flags": ["--disable-web-security"]
        }
    },

As far as I know it needs some sort of user dir too, but the Karma launcher fills that param. Any idea about whether I can fix this or at least what release of Chrome changed the behavior? (I have already sent a bug report.)
Note that the question has nothing to do with Karma. All it does is starting Chrome from CLI with the given flags. A possible fix would be adding another flag, like the --user-data-dir was, but I guess the current changes are intentional and they cannot be undone. I'd like to see where this was discussed. I only found a 5 years old topic in Chromium Google Gorups which discusses this: https://groups.google.com/a/chromium.org/forum/#!msg/chromium-dev/iivpdszNY3I/3o3BF_mGwlIJ

A: Using --disable-site-isolation-trials is a partial solution. It works on https://www.google.com, but does not work on Chrome error pages with the error:// protocol.


text:
Q: SimpleXMLIterator performance PHP I have the following three functions that are interacting with the Amazon API. When I use the parse_orders_result function, it appears to take approximately 30 seconds to complete. I discovered this by running this get_orders function with the parse_orders_result commented out, and it completes each iteration of the do while loop in 3 seconds. However, when I run the parsing stuff, it takes the 30 seconds I mentioned below. How can I improve the performance of this operation?
GET_ORDERS function:
public function get_orders($date)
        {
        $this->throttle = amazon_throttle::list_orders_throttle();
        $this->endpoint = "mws.amazonservices.com";
        $this->url = "https://mws.amazonservices.com/Orders/$date";
        $this->action = "ListOrders";
        $this->version = '2011-01-01';
        $this->api = "/Orders/$date\n";
        $this->options = array(
                                'Action' => 'ListOrders',
                                'OrderStatus.Status.1'=>'Unshipped',
                                'OrderStatus.Status.2'=>'PartiallyShipped',
                                'OrderStatus.Status.3'=>'Shipped',
                                'OrderStatus.Status.4'=>'Canceled',//Get all unshipped, partially shipped, shipped, and canceled orders. This will update these types of orders if their status changes on Amazon
                                'LastUpdatedAfter'=> date("c", strtotime('-1 Month')) //FIXME update this to reflect our download interval later
                               );
        $this->create_signature();
        try
            {
            $results = $this->send_request(); //commented out for testing
            }
        catch (Exception $e)
            {
             echo $e->getMessage();
             return false;
            }

        //$results = sql::value("SELECT api_response from dhs.dbo.api_response where id = 444");
        $xml = new SimpleXMLIterator($results); //make the iterator here so we can check for a nexttoken
        $orders = $this->parse_orders_result($xml->ListOrdersResult->Orders);
        if ($xml->ListOrdersResult->NextToken)
            {
            $next_token = (string)$xml->ListOrdersResult->NextToken;
            do
                {
                $results = $this->get_orders_next_token($next_token);
                $xml = new SimpleXMLIterator($results);
                $returned = $this->parse_orders_result($xml->ListOrdersByNextTokenResult->Orders);
                $orders = array_merge($orders, $returned);
                if ($xml->ListOrdersByNextTokenResult->NextToken)
                    $next_token = (string) $xml->ListOrdersByNextTokenResult->NextToken;
                else
                    $next_token = null;
                }
            while($next_token);
            }
        //this stored procedure creates patient_ids for each order (if the patient doesn't already exist) and updates the orders table with with their patient_id
        sql::query('EXEC dhs.dbo.sp_create_patients');
        return $orders;
        }

PARSE_ORDERS_RESULT function:
$xml->registerXPathNamespace('amz', 'https://mws.amazonservices.com/Orders/2011-01-01');
            $orders = array();

            foreach ($xml->Order as $order)
            {
                $last = null;
                $name = explode(' ', preg_replace('/[^A-z ]/', '', (string) $order->BuyerName)); //remove all special characters
                if (!isset($name[1]) || !$name[1])
                {
                    $attn_last = explode(' ', preg_replace('/[^A-z ]/', '',$order->ShippingAddress->Name)); //remove all special characters
                    $pos = count($attn_last) - 1;
                    $last = $attn_last[$pos];
                }
                $phone = preg_replace('/[^0-9]/', '', (string) $order->ShippingAddress->Phone); //remove everything that is not an int
                $phone = "(" . substr($phone, 0,3) . ")" . substr($phone,3, 3) . "-" . substr($phone, 6); //format phone number

                //order and ship status are both int values tied to information in the db
                $ship_method = array_search(strtoupper((string) $order->ShipmentServiceLevelCategory),
                        sql::two_column_array("SELECT id, description FROM dhs.dbo.shipping_method WHERE site IS NULL or site = 'AMAZON' "));
                $order_status = array_search(strtoupper((string) $order->OrderStatus),
                        sql::two_column_array("SELECT id, description FROM dhs.dbo.order_status WHERE site IS NULL or site = 'AMAZON' "));
                //you have to cast found elements as string or they are returned as SimpleXMLIterator objects and you can't get the value
                $arr = array(
                        'order_code'=> (string) $order->AmazonOrderId,
                        'shipping_method'=>$ship_method,
                        'amount'=> (string) $order->OrderTotal->Amount,
                        'purchased_on' => date('Y-m-d H:i:s', strtotime($order->PurchaseDate)),
                        'market_id' => (string) $order->MarketplaceId[0],
                        'status'=> $order_status,
                        'site'=> 'AMAZON',
                        'last_update' => date('Y-m-d H:i:s'),
                        'employee_id'=>login::$id,
                        'addr1'=> (string) $order->ShippingAddress->AddressLine1,
                        'addr2'=>(string) $order->ShippingAddress->AddressLine2,
                        'city'=>(string) $order->ShippingAddress->City,
                        'state'=>(string) $order->ShippingAddress->StateOrRegion,
                        'zip'=>(string) $order->ShippingAddress->PostalCode,
                        'attention'=>(string) $order->ShippingAddress->Name,
                        'email'=>(string) $order->BuyerEmail,
                        'phone'=>$phone,
                        'first'=>array_shift($name), //remove the 0 element, use array shift so we can glue the rest of the array together for last name
                        'last'=>(implode(' ', $name)) ? implode(' ', $name): $last,
                        'fullname'=>(string) $order->BuyerName,
                        'unshipped_items'=> (string) $order->NumberOfItemsUnshipped
                );
                foreach ($arr as $k => $v)
                    $arr[$k] = strtoupper($v);

                $id = sql::merge('dhs', 'dbo', 'orders', array('order_code', 'site'), $arr, 'id');
                $arr['order_id'] = $id;
                sql::merge('dhs', 'dbo', 'order_shipping', array('order_id'), $arr);

                $orders[] = $arr;
            }
            return $orders;
        }

UPDATE
Unfortunately, I am not able to install XDebugger (its a company server and I don't have permission). However, I can provide a little more insight:

*

*$xml->Orders will be a maximum of 100 orders (so only 100 iterations), with approximately 1000 characters per order

*Although we are doing multiple database requests per iteration (which I will remove), there are only at max 150 users hitting the server at any one time (likely fewer than 70)

*Server Environment: IIS 6, PHP 5.3, MSSQL Server 2008 R2, 48GB RAM, 16 2.7ghz processor cores (hyperthreaded to replicate 32 processors)

A: The problem was definitely related to the number of queries we were running against our database. I have created a new merge statement that accepts a multidimensional array, and removed unnecessary queries from the foreach loop, and have reduced the execution time to 24 seconds (5 iterations through the do-while loop). Below is the revised parse orders function:
private function parse_orders_result(SimpleXMLIterator $xml)
        {
            $shipping_methods = sql::two_column_array("SELECT id, description FROM dhs.dbo.shipping_method WHERE site IS NULL or site = 'AMAZON' ");
            $order_statuses = sql::two_column_array("SELECT id, description FROM dhs.dbo.order_status WHERE site IS NULL or site = 'AMAZON' ");
            $xml->registerXPathNamespace('amz', 'https://mws.amazonservices.com/Orders/2011-01-01');
            $orders = array();

            foreach ($xml->Order as $order)
            {
                $last = null;
                $name = explode(' ', preg_replace('/[^A-z ]/', '', (string) $order->BuyerName)); //remove all special characters
                if (!isset($name[1]) || !$name[1])
                {
                    $attn_last = explode(' ', preg_replace('/[^A-z ]/', '',$order->ShippingAddress->Name)); //remove all special characters
                    $pos = count($attn_last) - 1;
                    $last = $attn_last[$pos];
                }
                $phone = preg_replace('/[^0-9]/', '', (string) $order->ShippingAddress->Phone); //remove everything that is not an int
                $phone = "(" . substr($phone, 0,3) . ")" . substr($phone,3, 3) . "-" . substr($phone, 6); //format phone number

                //order and ship status are both int values tied to information in the db
                $ship_method = array_search(strtoupper((string) $order->ShipmentServiceLevelCategory), $shipping_methods);
                $order_status = array_search(strtoupper((string) $order->OrderStatus), $order_statuses);
                //you have to cast found elements as string or they are returned as SimpleXMLIterator objects and you can't get the value
                $arr = array(
                        'order_code'=> (string) $order->AmazonOrderId,
                        'shipping_method'=>$ship_method,
                        'amount'=> (string) $order->OrderTotal->Amount,
                        'purchased_on' => date('Y-m-d H:i:s', strtotime($order->PurchaseDate)),
                        'market_id' => (string) $order->MarketplaceId[0],
                        'status'=> $order_status,
                        'site'=> 'AMAZON',
                        'last_update' => date('Y-m-d H:i:s'),
                        'employee_id'=>login::$id,
                        'addr1'=> (string) $order->ShippingAddress->AddressLine1,
                        'addr2'=>(string) $order->ShippingAddress->AddressLine2,
                        'city'=>(string) $order->ShippingAddress->City,
                        'state'=>(string) $order->ShippingAddress->StateOrRegion,
                        'zip'=>(string) $order->ShippingAddress->PostalCode,
                        'attention'=>(string) $order->ShippingAddress->Name,
                        'email'=>(string) $order->BuyerEmail,
                        'phone'=>$phone,
                        'first'=>array_shift($name), //remove the 0 element, use array shift so we can glue the rest of the array together for last name
                        'last'=>(implode(' ', $name)) ? implode(' ', $name): $last,
                        'fullname'=>(string) $order->BuyerName,
                        'unshipped_items'=> (string) $order->NumberOfItemsUnshipped
                );
                foreach ($arr as $k => $v)
                    $arr[$k] = strtoupper($v);

                $orders[] = $arr;
            }
            sql::bulk_merge('dhs', 'dbo', 'orders', array('order_code', 'site'), $orders, 'id');
            sql::bulk_merge('dhs', 'dbo', 'order_shipping', array('order_code', 'site'), $orders);
            return $orders;
        }


text:
Q: pasar json a clase y luego guardar informacion a base de datos Buen día tengo que realizar lo siguiente tengo un json en el cual debo recorrerlo y cada dato encontrado lo debe pasar a una clase, por ejemplo tengo este json
     {
       "nombre":"Jonh Doe",
       "profesion":"Programador",
       "edad":25,
       "lenguajes":["PHP","Javascript","Dart"],
       "disponibilidadParaViajar":true,
       "rangoProfesional": {
       "aniosDeExperiencia": 12,
       "nivel": "Senior"
    }
  }

y esta seria la clase de mi json
public class RangoProfesional
{
     public int aniosDeExperiencia { get; set; }
     public string nivel { get; set; }
}

public class Root
{
     public string nombre { get; set; }
     public string profesion { get; set; }
     public int edad { get; set; }
     public List<string> lenguajes { get; set; }
     public bool disponibilidadParaViajar { get; set; }
     public RangoProfesional rangoProfesional { get; set; }
}

y cuando los datos del json pase a esta clase los debe de mandar a una base de datos. pero no tengo la minima idea de como realizarlo ya que soy nuevo en esto, alguna idea o sugerencia de como iniciar cabe recalcar que me lo piden en C#

A: Para la deserializacion del json puedes utilizar la libreria Newtonsoft.Json
por ejemplo un metodo que reciba tu Json en el parametro como un string
Necesitas incluir el using correspondiente:
using Newtonsoft.Json;

El metodo para deserializar (convertir el Json a un Objeto) quedaria asi:
public Root ConvertirJson(string json)
{
    Root deserializedRoot = JsonConvert.DeserializeObject<Root>(json);

    return deserializedRoot;
}

https://www.newtonsoft.com/json/help/html/SerializingJSON.htm
Luego para enviar esto a la base de datos directamente existen varios caminos
Aqui tienes un ejemplo usando OleDB sin usar EntityFramework como comentaste
http://www.maestrosdelweb.com/tutorial-asp-net-acceso-a-datos-consultar-y-guardar-informacion-desde-webforms/
Este Ejemplo tambien es interesante sobre todo en mostrar la conexion y el envio del comando SQL
https://www.it-swarm-es.com/es/c%23/guardar-cualquier-archivo-en-la-base-de-datos-simplemente-convertirlo-una-matriz-de-bytes/968216897/


text:
Q: Map return returning last iteration of recursion? I am using recursion to step through this array of object's children. However it is returning the top level parents. The array of objects is:
const orgs = {
   children:[{name:'Core Enginerinng Ops', orgId:741,
             children:[{name:'Child Engineering Ops', orgId:5656,
                children:[{name: 'Child Engineering Last LEVEL AHAHHH', orgid:6969}]},{name: 'Child 2 Engineering OPS', orgId: 852}]},{name: 'Data Services Engineering', orgId: 456,
             children:[{name:'Child Data Services', orgId:978},{name: 'Child 2 Data Services', orgId: 354}]}]
    }

My end goal is to save the objects into a new array with just the name and the orgId as object for each parent and child.
flattenOrgs = (organizations) => {
  const flatArray =organizations.map(org => {
    if (org.children && org.children.length > 0) {
      this.flattenOrgs(org.children)
    }
    console.log(org.name)
    return org.name
  })
  return flatArray
}

However when I pass it through this function that uses recursion it only returns the 'org.name': ["Core Enginerinng Ops", "Data Services Engineering"]. I'm not great with recursion, but it doesn't make sense to me that the console.log(org.name) prints out each individual name as expected... But it doesn't return that name?
EDIT
console.log(org.name) before return

Child Engineering Last LEVEL AHAHHH
Child Engineering Ops
Child 2 Engineering OPS
Core Enginerinng Ops
Child Data Services
Child 2 Data Services
Data Services Engineering

A: You could reduce the array instead of mapping, because you need the children elements as well.

const
    orgs = { children: [{ name: 'Core Enginerinng Ops', orgId: 741, children: [{ name: 'Child Engineering Ops', orgId: 5656, children: [{ name: 'Child Engineering Last LEVEL AHAHHH', orgid: 6969 }] }, { name: 'Child 2 Engineering OPS', orgId: 852 }] }, { name: 'Data Services Engineering', orgId: 456, children: [{ name: 'Child Data Services', orgId: 978 }, { name: 'Child 2 Data Services', orgId: 354 }] }] },
    flattenOrgs = (organizations) =>
        organizations.reduce((r, { name, orgId, children }) =>
            r.concat({ name, orgId }, flattenOrgs(children || [])), []);

console.log(flattenOrgs(orgs.children));
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: I hope below code will meet your expectation:

const orgs = {
  children: [{
    name: 'Core Enginerinng Ops',
    orgId: 741,
    children: [{
      name: 'Child Engineering Ops',
      orgId: 5656,
      children: [{
        name: 'Child Engineering Last LEVEL AHAHHH',
        orgid: 6969
      }]
    }, {
      name: 'Child 2 Engineering OPS',
      orgId: 852
    }]
  }, {
    name: 'Data Services Engineering',
    orgId: 456,
    children: [{
      name: 'Child Data Services',
      orgId: 978
    }, {
      name: 'Child 2 Data Services',
      orgId: 354
    }]
  }]
}

console.log(orgs.children.map(child => {
  let newchild = {
    name: child.name,
    orgId: child.orgId
  }
  child.children && child.children.map(innerchild => {
    newchild.children = {
      name: innerchild.name,
      orgId: innerchild.orgId
    }
    innerchild.children && innerchild.children.map(innermostChild => {
      newchild.children.children = {
        name: innermostChild.name,
        orgId: innermostChild.orgId
      }
    })
  })
return newchild
}))


text:
Q: BatchFile Xcopy is not copying my file to the source location I have a batch file and I am trying to copy a file from the local machine to the a network location.  My file is not being copied from destination to source location.
The contents of my batch file is:
set TEST_HOME=%~dp0
cd %~dp0
E:
SET PATH=%PATH%;e:\test_runners 2 edit project\selenium_regression_test_5_1_1\IEDriverServer\32bit
SET PATH=%PATH%;e:\Python27;e:\Python27\scripts

cd %~dp0selenium_regression_test_5_1_1

set PYTHONPATH=%~dp0selenium_regression_test_5_1_1

nosetests "%~dp0selenium_regression_test_5_1_1\TestSuite\suite_regression.py"

timeout 10

: Copy selenium_report to storage-1
xcopy /y %~dp0selenium_regression_test_5_1_1\TestReport\ClearCore_Automated_GUI_Regression_TestReport \\STORAGE-1\Testing\Selenium_Test_Report_Results\ClearCore\Selenium VM\IE11

timeout 10

: Email the selenium report
e:\python27\python "%~dp0selenium_regression_test_5_1_1\Email\email_selenium_report.py"

The line which is not copying the file is:
xcopy /y %~dp0selenium_regression_test_5_1_1\TestReport\ClearCore_Automated_GUI_Regression_EditProject_Grouping_IE11_TestReport \\STORAGE-1\Testing\Selenium_Test_Report_Results\ClearCore\Selenium VM\IE11

There is something wrong with the Xcopy syntax i think.
Thanks, Riaz


text:
Q: How to compare order of magnitude? In Fan and Li's paper "Variable Selection via Nonconcave Penalized Likelihood and its Oracle Properties", they provided a proof to Theorem 1. The very last part of the proof is as follows.

Some notations: $L(\boldsymbol \beta_0)$ is log-likelihood function, $\mathbf{u}$ is a constant vector, $I(\boldsymbol \beta_0)$ is Expected Fisher information, $p'_{\lambda_n}(|\beta_{j0}|)$ is a penalty function; $\alpha_n = n^{-1/2} + a_n$, and $a_n = \text{max} \{p'_{\lambda_n}(|\beta_{j0}|): \beta_{j0} \neq 0 \}$
Given that you already know $n^{-1/2} L'(\boldsymbol \beta_0) = O_p(1)$, and that the third term in (A.2) is bounded by the term stated (I figured out these two claims), my questions are:

*

*Why is "$O_p(n^{1/2} \alpha_n) = O_p(n\alpha_n^2)$"? I am confused with this claim since it's really counter-intuitive. Should it be "$O_p(n^{1/2} \alpha_n) < O_p(n\alpha_n^2)$"?

*Why does the second term dominate the first and the third term?

Any insights are appreciated. Thanks.


text:
Q: Light and Special Relativity If an object is in motion that means time slows down for the observer in motion. So if there is a planet that is 1 billion light years away that is moving away from us does that mean we are seeing that planet 1 billion years in the past? Or do we see it at a different moment in time all together? Also would that planet appear to be slowed down or sped up to us? Or would time appear to be passing at the same rate that it does for us?

A: The time on the moving planet is for them the same as for us. So he half-life of a radioactive materiel will be the same. we would judge here time slowed down and the the same for our time.
And yes we are seeing n it 1 billion years in the past in our time scale.


text:
Q: Cannot implicitly convert 'System.Collections.Generic.Dictionary>' to 'System...' class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, string> questionDict = new Dictionary<string, List<string>>(); //creating animal dict
        List<string> removeKeys = new List<string>(); //so I can remove the keys if need be
        questionDict.Add("Does it have whiskers?", "cat");
        questionDict.Add("Does it purr?", "cat");
        questionDict.Add("Does it bark?", "dog");
        while (true)
        {
            foreach (KeyValuePair<string, string> kvp in questionDict)//checks for each value of kvp in questionDict
            {
                Console.WriteLine("Computer: {0}", kvp.Key); //prints kvp, or in this instance, the question
                string userInput = Console.ReadLine();
                if (userInput.ToLower() == "yes") //if yes THEN
                {
                    Console.WriteLine("VAL: {0}", kvp.Value); //writes the value
                }
                else
                {
                    removeKeys.Add(kvp.Key); //adds the wrong animals to the removeKeys list
                }
            }
            foreach(string rKey in removeKeys)
            {
                questionDict.Remove(rKey); //removes all the values of rKey in removeKeys from questionDict
            }
        }
    }
}

new Dictionary<string, List<string>>(); is giving me the error. Any help? I'm trying to make my dictionary have more than one value per key, which I am told can only be achieved through List<string>.

A: Change your declaration to:
Dictionary<string, List<string>> questionDict = new Dictionary<string, List<string>>();

The generic arguments of the variable being assigned to have to match those of what you are instantiating. The type also has to match of course (which it already did). Please make sure to make this correction to other applicable pieces of your code, like your foreach loop definition.
Note, if you like var (and even if you don't, this is one of the better places it can be used) you can just write:
var questionDict = new Dictionary<string, List<string>>();

Which is much shorter, and harder to mess up!


text:
Q: OpenDKIM on MTA not signing mails from remote mail servers I have a configuration where we have one MTA responsible for sending emails from a number of internal servers.
The internal servers all run Postfix on a number of different domains. They are all configured to relay via the MTA. I am attempting to setup DKIM to sign outbound emails from all internal servers.
I have installed opendkim and the server is able to sign locally generated outbound emails.
The MTA config is as follows:
opendkim.conf:
Syslog          yes
Logwhy          yes

UMask           002

Canonicalization    relaxed/simple
Mode            s
SubDomains      no

AutoRestart         yes
AutoRestartRate     10/1M
Background          yes
DNSTimeout          5
SignatureAlgorithm  rsa-sha256

OversignHeaders     From

UserID             opendkim

KeyTable           refile:/etc/opendkim/key.table
SigningTable       refile:/etc/opendkim/signing.table
ExternalIgnoreList  refile:/etc/opendkim/trusted.hosts

InternalHosts       refile:/etc/opendkim/trusted.hosts
Socket    inet:8891@localhost

main.cf:
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no

append_dot_mydomain = no
readme_directory = no

smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = mta.mydomain.com
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = mta.mydomain.com localhost
relayhost =
mynetworks = 127.0.0.0/8 1.1.1.0/24 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all

canonical_maps = hash:/etc/postfix/canonical

milter_default_action = accept
milter_protocol = 6
smtpd_milters = inet:localhost:8891

non_smtpd_milters = $smtpd_milters

signing.table:
*@domain1.com    default._domainkey.domain1.com
*@*.domain1.com    default._domainkey.domain1.com
*@domain1.co.uk    default._domainkey.domain1.co.uk
*@*.domain1.co.uk    default._domainkey.domain1.co.uk
*@domain2.co.uk    default._domainkey.domain2.co.uk
*@*.domain2.co.uk    default._domainkey.domain2.co.uk
*@domain3.co.uk    default._domainkey.domain3.co.uk
*@*.domain3.co.uk    default._domainkey.domain3.co.uk

trusted.hosts:
127.0.0.1
localhost
1.2.3.50
1.2.3.52
1.2.3.53
1.2.3.54
1.2.3.29
service2.domain2.co.uk
host2.domain2.co.uk

I have configured /etc/opendkim/trusted.hosts with a list of the internal hosts which whose emails I would like signed. I have also added keys and added them to the relevant DNS records.
I have tested generating mails on the MTA itself using sendmail and the emails are signed correctly. However when testing generating emails from the other, remote internal servers, none of the emails are signed. I also do not see anything logged on the MTA in terms of the reason, although using tcpdump I can see that traffic is going to port 8891 on localhost.
The host I am testing from identifies itself to Postfix as host2.domain2.co.uk:
Dec 20 16:28:32 mta postfix/smtpd[3765]: connect from host2.domain2.co.uk[1.2.3.50]
Dec 20 16:28:32 mta postfix/smtpd[3765]: 1B4BB439BD: client=host2.domain2.co.uk[1.2.3.50]
Dec 20 16:28:32 mta postfix/cleanup[3768]: 1B4BB439BD: message-id=<Asterisk-779-1806140173-205-16888@gw2.domain2.co.uk>
Dec 20 16:28:32 mta postfix/qmgr[1494]: 1B4BB439BD: from=<asterisk@service2.domain2.co.uk>, size=109206, nrcpt=1 (queue active)
Dec 20 16:28:32 mta postfix/smtpd[3765]: disconnect from host2.domain2.co.uk[1.2.3.50]
Dec 20 16:28:32 mta postfix/smtp[3759]: 1B4BB439BD: enabling PIX workarounds: disable_esmtp delay_dotcrlf for somecompany-co-uk.mail.protection.outlook.com[104.47.0.36]:25
Dec 20 16:28:33 mta postfix/smtp[3759]: 1B4BB439BD: to=<voicemail@somecompany.co.uk>, relay=somecompany-co-uk.mail.protection.outlook.com[104.47.0.36]:25, delay=1.3, delays=0.14/0/0.18/1, dsn=2.6.0, status=sent (250 2.6.0 <Asterisk-779-1806140173-205-16888@gw2.domain2.co.uk> [InternalId=73138998102968, Hostname=AS8PR05MB8037.eurprd05.prod.outlook.com] 119126 bytes in 0.104, 1115.744 KB/sec Queued mail for delivery)
Dec 20 16:28:33 mta postfix/qmgr[1494]: 1B4BB439BD: removed

EDIT: Further investigation of the headers of two test messages (one sent from the host directly using sendmail, the other from a host behind the MTA), and further investigation of the opendkim logs, has revealed that DKIM is signing both messages apparently successfully, but the DKIM signature is rejected for messages from the other hosts.
This is the DKIM log for two such messages (the first succeeded, the second failed):
Dec 22 12:06:16 mta opendkim[8130]: 65EB043A13: DKIM-Signature field added (s=default, d=domain3.co.uk)
Dec 22 12:06:52 mta opendkim[8130]: E723543AF0: DKIM-Signature field added (s=default, d=domain3.co.uk)

However looking at the DKIM results in Gmail, they are different:
ARC-Authentication-Results: i=1; mx.google.com;
       dkim=pass header.i=@domain3.co.uk header.s=default header.b=MVo7iz6A;

and for the second:
ARC-Authentication-Results: i=1; mx.google.com;
       dkim=neutral (body hash did not verify) header.i=@domain3.co.uk header.s=default header.b=TktWbhpC;

I don't understand why this is different, but it must be the cause of the issues I'm seeing.


text:
Q: %1 is not a valid Win32 application.. Sqlite3 in Electron app I'm trying to get sqlite3 to work in an electron app running on Windows7 and 10. Running the following command, I was able to create electron-v1.7-win32-x64\node_sqlite3.node
   cd node_modules/sqlite3 && sudo npm install nan
&& sudo npm run prepublish && sudo node-gyp configure --module_name=node_sqlite3 --module_path=…/lib/binding/electron-v1.7-win32-x64
&& node-gyp rebuild --target=1.6.11 --arch=x64 --target_platform=win32 --dist-url=https://atom.io/download/atom-shell
--module_name=node_sqlite3 --module_path=…/lib/binding/electron-v1.7-win32-x64

However, I get Uncaught Error: %1 is not a valid Win32 application. \\?\c:\folder\ppt_win32-x64\resources\app\node_modules\sqlite3\lib\binding\electron-v1.7-win32-x64\node_sqlite3.node.
My node version is v7.4.0. Electron v1.6.11.

A: I was trying to compile for windows from mi Mac and I had that problem too, but after some readings I figured out how to proceed, and after all I can say that I got it. Yesterday I spent all day setting up a windows virtual machine in my (other) Linux laptop (I used my linux laptop just because my mac was exhausted in storage...). I was having too a problem with the preloadScript from electron main process in windows, Cant found the script, it was solved too.
Anyway, I think the library node printer from @tojocky is well maintained, in other hand in the electron-builder documentation they say that you should compile in native for natural reasons. Once you will have it, you'll see that it's a cleaner and pragmatic solution ...
This was my entire process, I hope it helps to someone having the same issue:

*

*Get VirtualBox (or Parallels but is not free)

*Get iso for W10

*Create a VM with this W10 iso, and you should give to this VM some storage (because some dependency that you'll need to compile), I have assigned 60gb to this VM

*Once I had that VM running, I just installed in that machine Visual Studio 2017 (with their build-tools included, it's necessary)

*And then, I used CMD to make the rest

*Install NodeJS (and NPM, but it comes with)

*Install node-gyp globally

*Install Python 2.7

*Clone your project from git (in my case)

*npm i (in your project), you should have as npm dependency in your package.json the module electron-builder of course. (here I had some troubles because when node-gyp tried to rebuild printer to generate the binary for windows it was failing, this was because it was imposible to find the python executable, so if you face this problem you should add it like:npm config set python "c:\Python27\python.exe" in my case )

*Then try again npm i and Voila!

If you still having error you can rebuild the native dependency as well, run:

*

*node-gyp rebuild --target=YOUR_ELECTRON_TARGET[eg: 1.8.4] --arch=YOUR_ARCH_TARGET[eg: x64 | ia32] --dist-url=https://atom.io/download/atom-shell
After all, you should make the build using electron-builder, in my case my npm script command was build --win --x64 but you can use the --ia32 flag as well for 32bits


text:
Q: Numpy array creation First off I will apologize to the arbitraryness of this question but I am rewriting some of my scripts to use Numpy arrays instead of nested python lists (for performance and memory) but I'm still struggling with their declaration.
I am trying to create a structure using numpy arrays, I am starting off with 1000 (arbitrary value) elements in the array where each element should contain a float (as [x][0]) and a nested array containing coordinates (so 10.0000 x 2 floats PER top level element) (as [x][1], with each element in the nested array accessible as [x][1][y][z] where y is the element in nested array and z specified which of the 2 coordinates). The following question Nested Structured Numpy Array creates a nigh identical structure (as reference for my question and my desired structure).
Schematic raw data example:
time 0
  m/z 10 int 10
  m/z 20 int 20
  m/z 30 int 1000
  ...
time 1
  <repeat>

I have read that i haveto use the dtype part to define the nested array but I am not quite sure on the declaration part of the dimensions for an empty array, could anyone give me a hand? Here is what I came up with so far.
data=np.zeroes((1000,2 /* Now add nested array */), dtype=[('time', 'f'), [('m/z','f'), ('intensity','f')]])
PS: A matrix might be a better option for this?

A: >>> a = np.zeros(1000, dtype='float32, (10000,2)float32')
>>> a[200][0]
0.0
>>> a[200][1][2000]
array([ 0.,  0.], dtype=float32)

Note that this creates 1000 arrays of dimension (10000,2). That's fine if you only ever do operations that look at just one of those arrays. Using a separate (1000,10000,2) array instead you could take better advantage of vectorized operations in NumPy. You could for example increment all the second coordinates in one operation like this:
>>> b = np.zeros((1000,10000,2))
>>> b[:,:,1] += 1

Trying to do the same with a[:][1][:,1] is an error.


text:
Q: How to teach keras neural network to solve sqrt I'm learning machine learning with python and keras. I created a neural network to predict square root from even integers from range {1, 4, 9, 16, 25, 36, ..., 100}. I've written code to do that, but the results are far from true (whatever number I will provide to the network, it predicts that it's 1.0).
I've tried changing the number of layers, number of neurons in every layer, activation functions, but nothing helped.
Here is the code I've written so far:
from numpy import loadtxt
from keras.models import Sequential
from keras.layers import Dense
from keras import optimizers

# laod dataset
# dataset = loadtxt('pima-indians-diabetes.csv', delimiter=',')
dataset = loadtxt('sqrt.csv', delimiter=',')

# split into input (X) and output (y) variables
X = dataset[:,0:1] * 1.0
y = dataset[:,1] * 1.0

# define the keras model
model = Sequential()
model.add(Dense(6, input_dim=1, activation='relu'))
model.add(Dense(1, activation='linear'))

# compile the keras model
opt = optimizers.adam(lr=0.01)
model.compile(loss='mean_squared_error', optimizer=opt, metrics=['accuracy'])

# fit the keras model on the dataset (CPU)
model.fit(X, y, epochs=150, batch_size=10, verbose=0)

# evaluate the keras model
_, accuracy = model.evaluate(X, y, verbose=0)
print('Accuracy: %.2f' % (accuracy*100))

# make class predictions with the model
predicitions = model.predict_classes(X)

# summarize the first 10 cases
for i in range(10):
    print('%s => %.2f (expected %.2f)' % (X[i].tolist(), predicitions[i], y[i]))

And here is the dataset:
1,1
4,2
9,3
16,4
25,5
36,6
49,7
64,8
81,9
100,10

When I run this network I get the following results:
[1.0] => 0.00 (expected 1.00)
[4.0] => 0.00 (expected 2.00)
[9.0] => 1.00 (expected 3.00)
[16.0] => 1.00 (expected 4.00)
[25.0] => 1.00 (expected 5.00)
[36.0] => 1.00 (expected 6.00)
[49.0] => 1.00 (expected 7.00)
[64.0] => 1.00 (expected 8.00)
[81.0] => 1.00 (expected 9.00)
[100.0] => 1.00 (expected 10.00)

What am I doing wrong?

A: This is a regression problem. So you should use model.predict() instead of model.predict_classes().
Dataset is not large enough too. However, you can get some sensible predictions with the following code.
from numpy import loadtxt
from keras.models import Sequential
from keras.layers import Dense
from keras import optimizers

# laod dataset
# dataset = loadtxt('pima-indians-diabetes.csv', delimiter=',')
dataset = loadtxt('sqrt.csv', delimiter=',')

# split into input (X) and output (y) variables
X = dataset[:,0:1] * 1.0
y = dataset[:,1] * 1.0

# define the keras model
model = Sequential()
model.add(Dense(6, input_dim=1, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(1))

# compile the keras model
opt = optimizers.adam(lr=0.001)
model.compile(loss='mean_squared_error', optimizer=opt)

# fit the keras model on the dataset (CPU)
model.fit(X, y, epochs=1500, batch_size=10, verbose=0)

# evaluate the keras model
_, accuracy = model.evaluate(X, y, verbose=0)
print('Accuracy: %.2f' % (accuracy*100))

# make class predictions with the model
predicitions = model.predict(X)

# summarize the first 10 cases
for i in range(10):
    print('%s => %.2f (expected %.2f)' % (X[i].tolist(), predicitions[i], y[i]))

Output:
[1.0] => 1.00 (expected 1.00)
[4.0] => 2.00 (expected 2.00)
[9.0] => 3.32 (expected 3.00)
[16.0] => 3.89 (expected 4.00)
[25.0] => 4.61 (expected 5.00)
[36.0] => 5.49 (expected 6.00)
[49.0] => 6.52 (expected 7.00)
[64.0] => 7.72 (expected 8.00)
[81.0] => 9.07 (expected 9.00)
[100.0] => 10.58 (expected 10.00)

EDIT:
As @desertnaut pointed out in the comments, the metric accuracy has no meaning in a regression task. A custom R_squared value (AKA coefficient of determination) is therefore generally used as the metric. R_squared value represents the goodness of a fit in a regression model. Following is the code to calculate R_squared.
def r_squared(y_true, y_pred):
    from keras import backend as K
    SS_res =  K.sum(K.square(y_true - y_pred))
    SS_tot = K.sum(K.square(y_true - K.mean(y_true)))
    return ( 1 - SS_res/(SS_tot + K.epsilon()) )

Now, you could compile the model with;
model.compile(loss='mean_squared_error', optimizer=opt, metrics=[r_squared])


text:
Q: add time greater than 24 hours to datetime in sql I have one datetime field, '2017-05-03 10:00:00' and I want to add the time with field greater than 24 hours, like '30:05' which means 30 hours and 5 minutes in the datetime field. how could I do that? thanks. I'm using sql server 2014.

A: To get the hours:minutes to minutes:
DATEDIFF(MINUTE, 0, timestr)

Where timestr is your 'h:m' string for input.
The result will be minutes.  You should be able to then use this result with the DATEADD function.
DATEADD(minute, DATEDIFF(MINUTE, 0, timestr), dateTimeColumn)

So in an UPDATE I'd expect something like:
SET dateTimeColumn = DATEADD(minute, DATEDIFF(MINUTE, 0, timestr), dateTimeColumn)


text:
Q: Custom Button with images per state I'm trying to create a custom usercontrol that acts like a button, but i want it to use different images for each state (Normal, Hover, Pressed). The user control contains an Image control to show the image. I want to change the Source of the Image control at-runtime, so when the OnMouseEnter event triggers, i would change my image source to the HoverChange (ImageSource) property.
So i tried to add 3 ImageSource properties (NormalState, HoverState and PressedState) to the usercontrol so i can change the images when needed. (Coming from WinForms) But the problem is that the Properties aren't set in code (WinForms behaviour), so i can't assign them to my image. But when i use the usercontrol in my program i can set them via the property panel, but i can't use them in code (they stay NULL).
Here is some (pseudo) code of what i'm trying to reach:
public partial class ThreeStateButton : UserControl
{

    public enum ButtonState
    {
        Normal,
        Hover,
        Pressed
    }

    public ImageSource NormalState { get; set; }
    public ImageSource HoverState { get; set; }
    public ImageSource PressState { get; set; }

    public ThreeStateButton()
    {
        InitializeComponent();
        SetState(ButtonState.Normal);
     }

    public void SetState(ButtonState state)
    {
        switch (state)
        {
            case ButtonState.Normal:
                imgButton.Source = NormalState;
                break;
            case ButtonState.Hover:
                imgButton.Source = HoverState;
                break;
            case ButtonState.Pressed:
                imgButton.Source = PressState;
                break;
        }
    }

    protected override void OnMouseEnter(MouseEventArgs e)
    {
        base.OnMouseEnter(e);

        SetState(ButtonState.Hover);
    }

    protected override void OnMouseLeave(MouseEventArgs e)
    {
        base.OnMouseLeave(e);

        SetState(ButtonState.Normal);
    }

    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        base.OnMouseLeftButtonDown(e);

        SetState(ButtonState.Pressed);
    }

    protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
    {
        base.OnMouseLeftButtonDown(e);

        SetState(ButtonState.Hover);
    }
}

The main problem is that the ImageSource properties aren't set after initialization (and yes there are set through the property panel in the editor), i know the way of working is a bit different in WPF but how could i get this working the way i try?
Thanks

A: I did it on a more WPF-style way.
I create 3 image source properties and for each of them i created a DependencyProperty. I also added 3 Image controls in my xaml code and binded those imagesource properties using their registered name as DependencyProperty to the imagesource property of my image controls. Then it's just a matter of hiding the images or setting them visible on the correct state.


text:
Q: To sum the columns and display results in other column This is bugging me from 2days.
I have data like
   Account.ID asset_name
      6yS        A
      6yS        B
      6yS        B
      6yS        C
      6yU        D
      876        C

From here I want to make more columns of like dummies. But I want only one row each ID.
My output should look like this
   Account.ID asset_name  Flag_A  Flag_B  Flag_C  Flag_D
     6yS          A           1      2      1       0
     6yU          D           0      0      0       1
     876          C           0      0      1       0

I tried aggregating but they make it into another table, which I do not want to merge again, because I will be losing information.
Please help me out.
Thank y'll in advance.

A: This one?
 df %>%
   count(Account.ID, asset_name) %>%
   tidyr::pivot_wider( names_from =  asset_name,
                       values_from = n,
                       values_fill = list(n = 0))
# A tibble: 3 x 5
  Account.ID     A     B     C     D
  <chr>      <int> <int> <int> <int>
1 6yS            1     2     1     0
2 6yU            0     0     0     1
3 876            0     0     1     0

A: You can use dcast from data.table with fun.aggregate argument:
library(data.table)

dcast(data = setDT(df)[, asset_name := paste0('Flag_', asset_name)],
      formula = Account.ID ~ asset_name,
      fun.aggregate = length)

Output:
   Account.ID Flag_A Flag_B Flag_C Flag_D
1:        6yS      1      2      1      0
2:        6yU      0      0      0      1
3:        876      0      0      1      0

A: Here's a tidyverse solution, although not the most elegant.
Account.ID <- c('6yS', '6yS', '6yS', '6yS', '6yU', '876')
asset_name <- c('A','B','B','C','D','C')
df <- data.frame(Account.ID, asset_name)

df <- df %>%
  group_by(Account.ID, asset_name) %>%
  summarise(Count = n()) %>%
  spread(key = asset_name, value = Count, fill = 0)

Returns:
  Account.ID     A     B     C     D
  <fct>      <dbl> <dbl> <dbl> <dbl>
1 6yS            1     2     1     0
2 6yU            0     0     0     1
3 876            0     0     1     0

A: I think I have an answer for you. So this is your dataset:
Account.ID <- c("6yS", "6yS", "6yS", "6yS", "6yU", 876)
asset_name <- c("A", "B", "B", "C", "D", "C")

df <- data.frame(Account.ID, asset_name)
df

  Account.ID asset_name
1        6yS          A
2        6yS          B
3        6yS          B
4        6yS          C
5        6yU          D
6        876          C

For further transformations I am using tidyverse, so install it and load the library:
install.packages("tidyverse")
library(tidyverse)

df <-df %>%
  group_by(Account.ID, asset_name) %>%
  summarize(n=n()) %>%
  spread(asset_name, n)
df

# A tibble: 3 x 5
# Groups:   Account.ID [3]
  Account.ID     A     B     C     D
  <fct>      <int> <int> <int> <int>
1 6yS            1     2     1    NA
2 6yU           NA    NA    NA     1
3 876           NA    NA     1    NA

Now all that needs to be done is turn NAs into 0 and rename columns:
df[is.na(df)] <- 0

names(df)[2:ncol(df)] <- paste0("Flag_", names(df)[2:ncol(df)])
df

# A tibble: 3 x 5
# Groups:   Account.ID [3]
  Account.ID Flag_A Flag_B Flag_C Flag_D
  <fct>       <dbl>  <dbl>  <dbl>  <dbl>
1 6yS             1      2      1      0
2 6yU             0      0      0      1
3 876             0      0      1      0

Is this what you were looking for?


text:
Q: Rust returning a vector of pathbufs from a function after using fs::read_dir Hi i found some code on here that seems to work to return a Vec from a function but im having trouble understanding the code. The code is below, i have added comments to show where im getting confused.
fn read_filename_from_dir<P>(path: P) -> Result<Vec<PathBuf>, io::Error> where P: AsRef<Path>,{
   fs::read_dir(path)? //returns result<readDir> ? unwraps to readDir
   .into_iter() //creates a new iter containing result<DirEntry>
   .map(|x| x.map(|entry| entry.path()))
   .collect()  //the double map confuses me. this is where i lose understanding
}

I would assume since we have an iter containing Result's wouldnt we have to first unwrap each DirEntry then just map once unwrapped or does the double map unwrap somehow?
how would you unwrap an iter of results? using  map(|x| x.unwrap()) ?

A: The first map unpacks the io::Result<DirEntry>.
read_dir is a lazy iterator, so it won't return an error immediately, but only after you try to read the dir by starting iterating. It could also return Ok for the first few entries, and then return an Err.
The internal map transforms DirEntry to PathBuf.
Here's how you could rewrite it with types:
   .map(|entry_result: io::Result<DirEntry>| -> io::Result<PathBuf> {
       entry_result.map(|entry: DirEntry| -> PathBuf {
           entry.path()
       })
   })

collect() is pretty magical too, because not only it builds a Vec, but also short circuits on the first Err, and instead of returning Vec<io::Result<PathBuf>> it actually returns io::Result<Vec<PathBuf>>. This behaviour is specific for iterators with Result's. There's an example of this behaviour in the docs.
You could rewrite the same piece in imperative mode:
    let mut paths = Vec::<PathBuf>::new();
    for entry_result in fs::read_dir(path)? {
        let entry = entry_result?;
        paths.push(entry.path());
    }
    Ok(paths)

It is not longer, but much more straightforward and readable for a wider audience.


text:
Q: Applications of Scoring Play Combinatorial Game Theory I'm currently looking into economic applications of scoring play combinatorial game theory.  Details of the theory can be found in this paper.
http://arxiv.org/abs/1202.4653
A friend of mine suggested options trading.  But I really don't know enough about these things to come up with any substantial ideas.
Does anyone have any thoughts?

A: Taking most fundamental characteristics, this theory could potentially be applied in trading of:
-currencies (to a certain extent you can simplify 2 players, Left - Right movements, but information remains imperfect due to many underlying factors that can't be included in this theory)
-commodities, it may be applicable from money management, rather than trading approach (this theory relates to finite "number of points" hence resources, it can work well providing that winning party most likely takes it all). In trading when "winning" in such style by buying early what is available, one "blocks or immobilizes opponent" by becoming majority controlling prices - buy only very big players can do so, then it usually ends up in the press (hello aluminium?).
For smaller markets and when gradually buying in, it would be better to reverse the final certainty of winning when approaching majority, as with increased price there would be less buyers.


text:
Q: Are families of real analytic functions equicontinuous? 1) Let $f_n:I \to \mathbb{R}$, $n \in \mathbb{N}$, be a family of functions on an Interval $I \subset \mathbb{R}$. If all functions are real analytic, i.e. identical to their Taylor series expansion near every point of $I$, does this imply that the family is equicontinuous? One may assume $I$ to be bounded or even compact here.
2) If not, do you know any useful theorems under which additional assumptions this could be true?

A: Simple example: take $I = [0,1]$ and $f_n(x) = x^n$.  These are real analytic and even uniformly bounded, but not equicontinuous.

A: If you know that the family is bounded and holomorphic on an open region in the complex plane that contains the closure of $I$, then you have equicontinuity by Cauchy estimates on the derivative.


text:
Q: How Can I Help AOMEI Partition Assistant Standard Edition Find My Drive I Want To Migrate My OS To? I'm trying to replace my failing SSD with a Seagate 2TB BarraCuda SATA 6 Gb/s 7200 RPM 64MB Cache 3.5 Inch Desktop Hard Drive (ST2000DM006).
I've made sure that my motherboard is compatible and it is. My motherboard is a MSI           B85M-G43 (MS-7823) which after looking it up is SATA 6 Gb/s (3.0) compatible.
I'm using a StarTech USB 3.0 to SATA adapter (USB3S2SAT3CB).
Right now AOMEI Partition Assistant can't seem to see the new HDD when I connect it with the adapter.

You can see the C drive as well as my external drive but it's not seeing the one I've hooked up with the adapter. It would show as unallocated if it did.
I'm not really sure where the failure is. My system beeps to register that I've connected something and AOMEI Partition Assistant will prompt a reload when I do, so it is connecting.
If it's the software I'm not sure where to check it. I'll be contacting their support after I post this. I'll update this post when I do so hopefully others who might have the same issue can learn from it.
After that I'll try to contact StarTech in case it's the adapter.
If anyone has some ideas I could try I would love to hear them.

A:
I'm not really sure where the failure is.

Your using a 2.5" adapter with a 3.5" Drive. That's never going to work.  You are not supplying enough power to the drive.
This isn't a software issue.  You should be connecting the drive over SATA.


text:
Q: Can't generate javadoc in eclipse This really should be a stupid question, but I'm trying to generate javadoc in my Android eclipse project and I'm getting errors.  I'm on a mac and the javadoc command is set at
 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/javadoc

But for some reason it seems to be using 1.3
 annotations are not supported in -source 1.3
 (use -source 5 or higher to enable annotations)
        @Override

Has anyone else run into this?

A: In Eclipse (Kepler release), go to Project -> Generate Javadoc..., then after the second "Next", you will see an option to select "JRE source compatibility". There, you have selected 1.3 (you have to select 1.5 or higher).


text:
Q: Windows Phone 7: Grab current url and use to Reload my browserpage how can i refresh/reload my browserpage in my app?
i have a webbrowser created to dinamically retrieve a random page from my site, now i want to capture the actual url and use it for the refresh button and for the "open in browser button".
Basically i need to retrieve the current url and use it to refresh it: this is my question.
Thanks!

A: Assuming the webBrowser control is caleld EmbeddedBrowser.
Refresh:
EmbeddedBrowser.Navigate(EmbeddedBrowser.Source.AbsoluteUri);

Launch in IE:
var wbt = new WebBrowserTask
{
    URL = EmbeddedBrowser.Source.AbsoluteUri
};

wbt.Show();


text:
Q: Serial is produced by ... and me At the end of every episode of Serial, Sarah Koenig says:

Serial is produced by Julie Snyder, Dana Chivvis and me.

The word "me" sounds wrong to me there. Is it?  If it's wrong, what is correct there - myself, I,  or me but in a different location?  And if it's not wrong - why not?

A: I'm quite certain that "me" is correct here, and in fact I have absolutely no problem reading or hearing it. Personally, I'm not sure why the confusion.
To use "myself" in this case would come across to me as someone trying to sound more formal or more "proper" and making a misstep in doing so.
Really, "myself" should only be used reflexively when the same person is both the subject and the object: "I washed myself" rather than "I washed me" but "I washed her" rather than "I washed herself".
In the case of your example, it is just a straightforward objective pronoun, and so "me" is correct. The inclusion of other people pushes "me" to the end of the list out of politeness, but has no other bearing at all.
(Note, "myself" can also be used as an intensifier, but it doesn't seem necessary to expand on that here.)


text:
Q: Docker is not freeing memory from fail dockerfile builds Why when I build an image from a docker-file and the build process fails, the memory used in the process is not being freed. I'm using Ubuntu 16.04
And is not appearing as an image, because it fails to be created. Where, then the data is being accumulated?
Thank you, please If you need more information ask me.
UPDATE: Some zombie images starting appearing after some time.
UPDATE 2: Those zombie images and containers (?) somehow are the failed builds... if anyone has more information of what is going on, please share it with me.

A: Docker by default doesn't clean up useless images know as "dangling images". It provides however the following command to safely clean them.
docker image prune

Alternatively, you can pass the following argument to docker build to force cleanup.
  --force-rm                Always remove intermediate containers

A: Run it:
docker builder prune --all -f
By default it make following: Remove all unused build cache from previous build process


text:
Q: Sharepoint Calculated Column Outputting string;# before result I'm outputting a calculated column in a blog archive webpart in sharepoint 2013 in the format of 'MMMM, YYYY' so Im getting a list of dates...however each one has 'string;#' before it...is there anyway to remove this? Ive been looking for a answer for ages.
Example:
string;#November, 2013
string;#October, 2013
string;#November, 2013

A: Try this:-

=SUBSTITUTE([Date Column],"string;#","")


text:
Q: Coerce list of lists to data_frame, but maintain *some* elements in list columns I am looking for a way to reliably coerce a list structure to a data.frame or tibble while maintaining one or more columns as list columns. Consider the following list structure:
d = data.frame(x = 1:10, y = 1.5*(1:10) + rnorm(10))
ex = list(label = "A", number = 1L, model = lm(y ~ x, data = d))

This does not work as intended:
lapply(ex, as_data_frame) %>% bind_rows()

Because the lm object in the "model" column gets vectorized in the conversion. However, wrapping the model in list gets the expected result:
ex2 = list(label = "A", number = 1L, model = list(lm(y ~ x, data = d)))
as_data_frame(ex2)

Unfortunately, I have a use case where I don't know beforehand whether a given column is a list or not. I am working with a function that outputs something like this:
ex3 = list(
  list(label = "A", number = 1L, model = lm(y ~ x, data = d)),
  list(label = "B", number = 1L, model = lm(y ~ x + 0, data = d))
)
# won't work properly
lapply(ex3, as_data_frame) %>% bind_rows()

Is there a way to prevent data_frame from vectorizing an object in the transformation to a tibble? If not, what alternative approach could I use?

A: Here is one option with tidyverse
library(tidyverse)
ex3 %>%
 transpose %>%
 map_if(~all(lengths(.) == 1), unlist) %>%
 as_tibble
# A tibble: 2 x 3
#  label number model
#   <chr>  <int> <list>
#1 A          1 <S3: lm>
#2 B          1 <S3: lm>

For the first case, make the 'model' as a list and then use as_tibble
ex$model <- list(ex$model)
as_tibble(ex)

A: One option that I'm not super happy with, but might help guide the discussion:
Check the types of each element the list structure and wrap them in a list if they are non-atomic or have more than 1 element:
listify = function(x) {
  if(length(x) > 1L || !is.atomic(x))
    list(x)
  else
    x
}
lapply(ex3, function(x) as_data_frame(lapply(x, listify))) %>% bind_rows()

Not sure how robust this is, and probably slow too.

EDIT
Another option, which I found in an old dplyr issue linked from a related tibble issue:
library (purr)
ex3 = map(ex3, ~ as_list(extract(., "model"))

However, this only works on one "column" at a time, and also requires you to know the name of the column you want to wrap in a list.
If as_tibble_row gets implemented, that will probably be the preferred solution.


text:
Q: python - ldap3 lib: How to add multiple values to attribute I want to add more than one email adress to a user in ldap. Therefore is an attribut called mailLocalAdress that looks like this when I search/find a specific user with ldapsearch:
mailLocalAddress: abc@testing.com
mailLocalAddress: abcd@testing.com
mailLocalAddress: abcdefg@testing.com

I'm using python 3, the ldap3 lib and this is how I define the value for the mailLocalAdress attribute
ldap_values['mailLocalAddress'] = [user.email_first, user.email_second, user.email_third]

and this is the add command
ldap_con.add(dn, object_class, ldap_values)

and I got this as result when doing ldapsearch
mailLocalAddress: ['abc@testing.com', 'abcd@testing.com', 'abcdefg@testing.com']

Any ideas how to get the listing above?

A: I'm not able to reproduce the behavior you've reported.  If I start with this in my ldap directory:
dn: dc=example,dc=com
objectclass: dcObject
objectclass: organization
o: example
dc: example

dn: ou=people,dc=example,dc=com
objectclass: organizationalunit
ou: people

And then run the following Python code:
>>> from ldap3 import Server, Connection, ALL
>>> server=Server('localhost')
>>> conn = Connection(server, user='cn=manager,dc=example,dc=com', password='secret')
>>> conn.bind()
True
>>> dn='uid=alice,ou=people,dc=example,dc=com'
>>> object_class=['person', 'organizationalperson', 'inetorgperson', 'inetlocalmailrecipient']
>>> ldap_values={'sn': 'example', 'cn': 'alice example', 'mailLocalAddress': ['alice@example.com', 'alice.example@example.com']}
>>> conn.add(dn, object_class, ldap_values)
True
>>>

An ldapsearch returns:
/etc/openldap # ldapsearch ... -b dc=example,dc=com uid=alice
# alice, people, example.com
dn: uid=alice,ou=people,dc=example,dc=com
sn: example
cn: alice example
mailLocalAddress: alice@example.com
mailLocalAddress: alice.example@example.com
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
objectClass: inetLocalMailRecipient
uid: alice

Which seems to be exactly what you want.

A: It was a completely different problem:
ldap_values = {k: str(v).encode("utf-8") for k,v in ldap_values.items()}

Before I add the values, I had to convert them to UTF8.
Therefore I convert every value in my dict to string, also the lists!
And of course after this 'brilliant move of mine' the list is treated as string when adding the values to ldap.
I've overlooked this one-liner all along.


text:
Q: Cannot access 'ref' before initialization in react I've tried integrate Firebase to my App
I import:
import { getDatabase, ref, onValue, set, push, child, remove } from 'firebase/database';
import {initializeFirebase} from './Firebase';

and call getDatabase in render. getDatabase is:
getDatabase =  () => {
    const db = getDatabase();
    const ref = ref(db, "data/")
  }

I got this problem "
ReferenceError: Cannot access 'ref' before initialization". Why am I wrong, and how should I fix that, thanks

A: Try this:
import { initializeApp } from 'firebase/app';
const app = initializeApp({});
getDatabaseFunc =  () => {
    const db = getDatabase();
    const ref = ref(db, "data/")
  }

change the name of the main function to getDatabaseFunc or any other name different from getDatabase() to prevent overriding


text:
Q: how can i fetch a file that i have already upload and i want to delete it and replace it using bootstrap file input i want to fetch the file based on my applications_id and i want to see it in the bootstrap file input and i want to delete it and replace with a new file. how can i do it. below is what i have tried .can anyone help me .i am stuck.
this is my contoller function SoleProprietorController.php
    public function uploadImages(Request $request, $applications_id)
    {
       $applications = new Applications;

     //  $KRAPIN = Input::get('KRA_unique_field');
      $applications_id = Input::get('applications_id_unique_field');

    if ($request->hasFile('breg_cert')) {
       if ($request->file('breg_cert')->isValid()) {
                  // request()->breg_cert->move(public_path('breg_cert'), $imgName);
            // $imgName = basename($request->breg_cert->store(public_path('breg_cert')));
           $imgName = basename($request->breg_cert->move(public_path('breg_cert')));
           $applications->breg_cert = $imgName;
       }
      return response()->json(['uploaded' => '/breg_cert/'.$imgName]);
      }

    }

this my web.php
Route::post('/uploadImages/{applications_id}', 'SoleProprietorController@uploadImages')->name('home');

this is my bootstrap file in my blade

 Upload Business Registration Document

    <input id="file-0a" name="breg_cert" value="" class="file" accept="text" type="file">

A: 1.Use code like this to store uploaded file and associate it with your Applications
if ($request->hasFile('breg_cert')) {
   if ($request->file('breg_cert')->isValid()) {
       $imgName = basename($request->breg_cert->store(public_path('breg_cert')));
       $applications->breg_cert = $imgName;
   }
}

https://laravel.com/docs/5.8/requests#storing-uploaded-files

To store an uploaded file, you will typically use one of your configured filesystems. The  UploadedFile class has a store method which will move an uploaded file to one of your disks, which may be a location on your local filesystem or even a cloud storage location like Amazon S3.
The store method accepts the path where the file should be stored relative to the filesystem's configured root directory. This path should not contain a file name, since a unique ID will automatically be generated to serve as the file name.

*To handle delete/replace create a corresponding controller method and POST route and then provide the route to deleteUrl option.

In the above method check the filename associated and unlink it. (actual code depends on what dd($request); output)

*To show stored image as preview add option to $("#file-0a").fileinput({

initialPreview: [
    "",
],


text:
Q: countdown timer using php, can't make it work i am making a php countdown timer that display only minutes and seconds.
here is my code:
$time = "10:00";
$time_min = substr($time, 0,2);
echo $time_sec = substr($time, 3) . "
";
$current = date("i:s");
$target = date("i:s" , mktime(0,$time_min,0,0,0,0));
echo $current-$target . "
";
echo $target;

the output should be the remaining time from the time the user opens the page.

A: Not knowing the details of your jQuery I am taking a shot at this.
I prefer working in seconds, so to get the $timeRemaining (you must know the initial time to do this) at any given instant in the 10 minute window, I would do this:
$targetTime = time() + 600; //you have to save this either in database or as variable somewhere

Then on subsequent opening of relevant php file the following code could be used if targetTime is saved in database
$sqlTime = mysqli_fetch_assoc(mysqli_query($cxn, "SELECT targetTime FROM timeTable WHERE id = '$myID'"));
$currentTime = time();
$timeRemaining = (($sqlTime['targetTime'] - $currentTime) / 60) . ":" . (($sqlTime['targetTime'] - $currentTime) % 60);


text:
Q: An unhandled exception was thrown by the application. System.ArgumentNullException: Value cannot be null. (Parameter 'uriString') I am working a asp .net core 6.0 web api project.
Problem overview:
I faced an issue. When running the project the get request's response is 200 ok.  BUT while building the project, a get request show 500Internal Server Error  and in terminal also I got error.
Detail:
When I run the project with dotnet run (Hosting environment: Development, port is 7045 or 5032),
And https://localhost:7045/api/public/opayo-payment/retrieve-transaction/9A5CAE22-7109-D006-A017-41BF9F138076 this get request's response is 200
BUT when I build the project with dotnet publish -c Release , dotnet /home/PaymentApi.dll (Hosting environment: Production, port is 5000 or 5001)
and,  https://localhost:5001/api/public/opayo-payment/retrieve-transaction/9A5CAE22-7109-D006-A017-41BF9F138076 this get request' response is 500Internal Server Error
And in the terminal I got below error
fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HMDJ000A9MDB", Request id "0HMDJ000A9MDB:00000002": An unhandled exception was thrown by the application.
      System.ArgumentNullException: Value cannot be null. (Parameter 'uriString')
         at System.Uri..ctor(String uriString)
         at Program.<>c__DisplayClass0_0.<<Main>$>b__1(HttpClient c) in /home/PaymentApi/Program.cs:line 16
         at Microsoft.Extensions.Http.DefaultHttpClientFactory.CreateClient(String name)
         at Microsoft.Extensions.DependencyInjection.HttpClientBuilderExtensions.AddTransientHelper[TClient,TImplementation](IServiceProvider s, IHttpClientBuilder builder)
         at Microsoft.Extensions.DependencyInjection.HttpClientBuilderExtensions.<>c__DisplayClass13_0`2.<AddTypedClientCore>b__0(IServiceProvider s)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitDisposeCache(ServiceCallSite transientCallSite, RuntimeResolverContext context)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass2_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
         at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
         at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
         at lambda_method9(Closure , IServiceProvider , Object[] )
         at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.<CreateActivator>b__0(ControllerContext controllerContext)
         at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
         at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
         at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)

in program.cs
builder.Services.Configure<MerchantSessionConfig>(builder.Configuration.GetSection("Payments:TestOpayo"));
builder.Services.AddHttpClient<IOpayoPaymentService, OpayoPaymentService>("PublicOpayoApi", c =>
                c.BaseAddress = new Uri(builder.Configuration.GetValue<string>("Payments:TestOpayo:Url"))
                );

service
private readonly HttpClient _client;
        private readonly IHttpClientFactory _clientFactory;
        private readonly MerchantSessionConfig _merchantSessionConfigoptions;

        private readonly DataDbContex _dataDbContex;

        public OpayoPaymentService(HttpClient client, IHttpClientFactory clientFactory,
        IOptions<MerchantSessionConfig> options, DataDbContex dataDbContex)
        {
            client = clientFactory.CreateClient("PublicOpayoApi");
            _clientFactory = clientFactory;
            _client = client;
            _merchantSessionConfigoptions = options.Value;
            _dataDbContex = dataDbContex;

            // Basic Authentication
            _client.DefaultRequestHeaders.Add("Accept", "application/json");
            var authenticationString = $"{_merchantSessionConfigoptions.Username}:{_merchantSessionConfigoptions.Password}";
            var base64EncodedString = Convert.ToBase64String(System.Text.ASCIIEncoding.UTF8.GetBytes(authenticationString));
            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64EncodedString);

        }

appsettings.Development.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=<server>; port=5432; user id=postgres; password=<password>; database=<db>; Integrated Security=true; Pooling=true; CommandTimeout=300;Include Error Detail=true;Log Parameters=true"
  },
  "Payments": {
    "TestOpayo": {
      "Url": "https://pi-test.sagepay.com",
      "VendorName": "vendor",
      "Username": "username",
      "Password": "password"
    }
  }
}

appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Please anyone help me to find the mistake.

A: ok try it :
appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=<server>; port=5432; user id=postgres; password=<password>; database=<db>; Integrated Security=true; Pooling=true; CommandTimeout=300;Include Error Detail=true;Log Parameters=true"
  },
  "Payments": {
    "TestOpayo": {
      "Url": "https://pi-test.sagepay.com",
      "VendorName": "vendor",
      "Username": "username",
      "Password": "password"
    }
  }
}

A: You are loading - Payments:TestOpayo:Url with builder.Configuration.GetValue<string>("Payments:TestOpayo:Url") from your appsettings.
So you should have configured the parameter in your appsettings for production environment.
There is a convention .net 6 documentation for mapping appsettings to Environment (development, production).
It looks like your missing Payments:TestOpayo:Url in your production appsettings.
You should also use __ as seperator to be platform agnostic, which leeds to the key: Payments__TestOpayo__Url


text:
Q: calculating total weight of cart in laravel I need to get my cart total weight in order to use it in my shipping calculator.
here is my code:
@foreach($item->attributes as $sss)
  {{number_format($item->quantity * $sss['value'], 0)}} KG
@endforeach

here is how it looks like:

I need to get 92 as sample.

PS: I really prefer if I can do it in backend and have something like
{{$total_weight}} in front-end only.

how can I do that?
UPDATE

A: Try:
$totalWeight = $items->sum(function ($item) {
    return $item->attributes->sum(function ($attribute) use($item) {
         $val = 0;
         $val += $item->quantity * $attribute['value'];
         return $val;
    });
});

A: Use the sum() method like this:
$items->sum(function($item) {
    return $item->quantity * $item->attributes->attr['value'];
});


text:
Q: Why the defines inside a c++ namespace works outside the namespace? If I use some macro defines in a namespace, then why should they work outside the namespace? Check this code for example:
#include <bits/stdc++.h>

namespace foo {
    #define a x*2

    int f(int x) {
        return a;
    }
}

int main() {
    int a = 50;
    std::cout << a << endl;

    std::cout << foo::f(4) << endl;

    return 0;
}

Here I have never wrote using namespace foo. But still this code doesn't get compiled because, when try to declare int a, it gets disturbed by previously defined a. But why this should happen?

A:
"... when try to declare int a, it gets disturbed by previously defined a. But why this should happen?"

The #define statement is interpreted by the c/c++ preprocessor that has no notion of namespaces (or any other c++ language constructs).
If you want to limit the extent of a definition, use an #undef directive:
namespace foo {
    #define a x*2

    int f(int x) {
        return a;
    }
    #undef a
 // ^^^^^^^^
}

A: The pre-processor does not know anything of high-level language features such as namespaces or scoping. It just looks for lines starting with # and then does simple text replacement. This is one reason why using the pre-processor for anything but #include or file-guards is dangerous in C++.

A: #define does not respect any C++ scope. There is no such thing as a "local" #define. It'll be in effect until it is #undef-ed.
namespace foo {
    #define a x*2

    int f(int x) {
        return a;
    }
    #undef a              <<<<<<<<<<<<<<<<<<<<<
}

A: C preprocessor is pretty much a language of it's own. It's executed first. Macros create code that is passed into actual C/C++ compiler. Whenever you use macros, always remember that macros trump everything, even curly braces. Only another preprocessor directive, like #undef, can stop a macro.
BTW, you can even use C preprocessor alone, on any text file.


text:
Q: animate single layer-list item in android I have a "layer-list" (rotated_image.xml) which is a "imageview" background:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
    <bitmap
        android:gravity="center"
        android:src="@drawable/shadow" />
</item>
<item>
    <bitmap
        android:gravity="center"
        android:src="@drawable/bg" />
</item>
<item>
    <rotate
        android:duration="5000"
        android:fromDegrees="0"
        android:interpolator="@drawable/linear_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:repeatCount="infinite"
        android:toDegrees="360" >
        <bitmap
            android:gravity="center"
            android:src="@drawable/button" />
    </rotate>
</item>

1) I need to start and stop third image rotation on "imageview" click. I do not know how to get reference to my third item in layer-list and how to start animation?
2) I also need to put opacity to my second item in list, is it possible?
3) Can I combine one more animation here (fade in-fade out), I need it for my first item in list?
If my question is to complicated, can someone give me good reference or advice?
Thanks,
Milos


text:
Q: linker not finding shared lapack and blas, but I am pointing right to it I am trying to build a .so that dynamically links against lapack and blas at runtime.  When building, the linker complains that it cannot find lapack and blas, but I am pointing right to them (I think).  What else might I be missing?
I am on a Rocky 9 Linux system (pretty fresh install).  Among other things, I have done yum install gcc-gfortran lapack-3.9.0-8.el9.x86_64 compat-libgfortran-48-4.8.5-36.5.el9.x86_64 openblas-serial lapack scalapack-common and also yum groupinstall "Development tools".  Some of these were done to (successfully) get old binaries working again, but I include them in case they might be interfering now.  With yum list, I don't see anything else promising to install.
In /usr/lib64/ I see (among other things):
lrwxrwxrwx.  1 root root       18 May 25  2022 liblapack.so.3.9 -> liblapack.so.3.9.0*
lrwxrwxrwx.  1 root root       19 May 25  2022 liblapacke.so.3.9 -> liblapacke.so.3.9.0*
lrwxrwxrwx.  1 root root       19 May 25  2022 liblapacke.so.3 -> liblapacke.so.3.9.0*
-rwxr-xr-x.  1 root root  7496688 May 25  2022 liblapack.so.3.9.0*
-rwxr-xr-x.  1 root root  2908088 May 25  2022 liblapacke.so.3.9.0*
lrwxrwxrwx.  1 root root       18 Jan 18 16:18 liblapack.so.3 -> liblapack.so.3.9.0*
lrwxrwxrwx.  1 root root       22 May 16  2022 libopenblas.so.0 -> libopenblas-r0.3.15.so*
lrwxrwxrwx.  1 root root       23 May 16  2022 libopenblaso.so.0 -> libopenblaso-r0.3.15.so*
-rwxr-xr-x.  1 root root 38111888 May 16  2022 libopenblas-r0.3.15.so*
-rwxr-xr-x.  1 root root 39653512 May 16  2022 libopenblaso-r0.3.15.so*
lrwxrwxrwx.  1 root root       17 May 25  2022 libcblas.so.3.9 -> libcblas.so.3.9.0*
lrwxrwxrwx.  1 root root       16 May 25  2022 libblas.so.3.9 -> libblas.so.3.9.0*
-rwxr-xr-x.  1 root root   119640 May 25  2022 libcblas.so.3.9.0*
-rwxr-xr-x.  1 root root   583120 May 25  2022 libblas.so.3.9.0*
lrwxrwxrwx.  1 root root       19 Jun  2  2022 libflexiblas.so.3 -> libflexiblas.so.3.0*
lrwxrwxrwx.  1 root root       24 Jun  2  2022 libflexiblas_mgmt.so.3 -> libflexiblas_mgmt.so.3.0*
lrwxrwxrwx.  1 root root       23 Jun  2  2022 libflexiblas_api.so.3 -> libflexiblas_api.so.3.0*
-rwxr-xr-x.  1 root root  3870704 Jun  2  2022 libflexiblas.so.3.0*
-rwxr-xr-x.  1 root root    53256 Jun  2  2022 libflexiblas_mgmt.so.3.0*
-rwxr-xr-x.  1 root root    15912 Jun  2  2022 libflexiblas_api.so.3.0*
lrwxrwxrwx.  1 root root       17 Jan 18 16:18 libcblas.so.3 -> libcblas.so.3.9.0*
lrwxrwxrwx.  1 root root       16 Jan 18 16:18 libblas.so.3 -> libblas.so.3.9.0*

In addition, whereis liblapack.so and whereis libblas.so both come up empty-handed.
Following what I see here, I have done:
gcc -Wall -fPIC -O -g -fopenmp mylib.c -c -o mylib.pic.o
gcc -shared -fopenmp mylib.pic.o -L/usr/lib64 -lblas -llapack -lm -o mylib.so

but I get
/usr/bin/ld: cannot find -lblas
/usr/bin/ld: cannot find -llapack
collect2: error: ld returned 1 exit status

I know about this, but it seems wrong that I would have to get into system directories and manually make soft links in order to use standard infrastructure.  There must be a "right" solution I am missing.
Thanks for any help.

A:
I am pointing right to them (I think).

No, you are not. You need libblas.so, which is not the same as libblas.so.3.
The libblas.so is needed to link new binaries against libblas. The libblas.so.3 is needed to run already linked binaries.
Usually the .so libraries are installed as part of libblas-devel or a similar package.


text: Q: Переход по кнопке из одного активити во фрагмент другого активити. Как реализовать? Есть два активити. В первом активити есть fragment1 и fragment2. В fragment1 есть кнопка, запускающая второе активити, а в нем есть кнопка, при нажатии на которую должно открываться fragment2 из первого активити. Как надо написать onClick кнопки во втором активити, чтобы открылся fragment2 из первого?


text:
Q: How to check if address lists exist in Active Directory? I need to check if All Global Address Lists, All Address List and All System Address Lists exist in Active Directory before get all item from them.
Could you give me some advices or article that I can solve my problem?
Thanks.

A: Address Lists are part of Exchange functionality not Active Directory which is what I think people are confused about.
Anyway, Address List data is stored in the Active Directory Configuration context under:
CN=Address Lists Container,CN=<EXCHANGE ORGANIZATION NAME>,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=<DEFAULT NAMING CONTEXT>
You can use ADSIEdit to view the information.
In C# you can use an LDAP query to retrieve information for existing Address Lists.
Edit: Something like this:
DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE");
DirectoryEntry configContainer = new DirectoryEntry("LDAP://" + rootDSE.Properties["configurationNamingContext"].Value);
DirectorySearcher configSearcher = new DirectorySearcher(configContainer);
configSearcher.Filter = "(&(objectClass=addressBookContainer))";
configSearcher.PropertiesToLoad.Add("displayName");
configSearcher.PageSize = 10000;
configSearcher.SearchScope = SearchScope.Subtree;
SearchResultCollection results = configSearcher.FindAll();


text:
Q: How to prove $1-\frac{1}{2^x}\lt\eta (x)\lt 1$? Define
$$\eta (x)=\sum_{n=1}^\infty \frac{(-1)^{n-1}}{n^x}.$$
I managed to prove that
$$\left|\eta (x)-\left(1-\frac{1}{2^x}\right)\right|\le\frac{1}{2^x}$$
for $x\gt 1$ by the alternating series error estimate. By trying to get rid of the absolute value, I ended up going in circles. How can I prove the desired inequality
$$1-\frac{1}{2^x}\lt\eta (x)\lt 1,\quad x\gt 1$$
by the error estimate?