text:
Q: Errors in windows task scheduler while trying to schedule auto download and backup of database from remote server to local server with php script I am trying to auto sync my remote database with my local machine by using php file_get_contents and connecting to remote server with ftp_connect frequent intervals. I am using windows Task Scheduler from my local machine for that.
My php script works perfectly from the browser. But when Task Scheduler Triggers it, the command prompt window comes up showing error messages.
My script is
    <?php
    set_time_limit(0);
    include('functions.php');
    $root=$_SERVER['DOCUMENT_ROOT'];
    $sitearr=array("indianchristians","mc","evaa","laveena","aita","kaazar","landshop");
    $date=Date('Y-m-d H:i:s');
    $vals="";
    $msg="";

    foreach($sitearr as $sa)
        {
            include('connnew.php');
            if($sa=="landshop")
                {
                    $remurl="dwggxtwa_landshoppe.sql";
                    $localurl="$root/$folder/Myadmin/download/sqlbackup/";

   $backupserv=file_get_contents($url."/Myadmin/download/sqlbackup/backupserver.php");
                }
                else{
                    $remurl="$db.sql";
                    $localurl="$root/$folder/admin/download/sqlbackup/";

   $backupserv=file_get_contents($url."/admin/download/sqlbackup/backupserver.php");
                }
                $savedb=$db.".sql";
                $localdb=$localurl.$savedb;
    //          echo $localdb."
";

                $conn = ftp_connect($ftp_server);
                $login_result = ftp_login($conn, $ftp_user_name, $ftp_user_pass);
                ftp_pasv($conn, true);
                if($sa=="landshop"){
                    ftp_chdir($conn, '/public_html/Myadmin/download/sqlbackup/');
                }else{
                    ftp_chdir($conn, '/admin/download/sqlbackup/');
                }
                if (ftp_get($conn, $localdb, $remurl, FTP_BINARY))
                {
    //                  echo "$sa saved locally
";
                $query=$maindb->query("SHOW TABLES") or die("SHOW TABLES ERROR ".$maindb->error);

                    while($st=$query->fetch_array()){
                        $drop=$maindb->query("DROP TABLE $db.$st[0]");
    //if($drop){echo "
$db.$st[0] DROPPED !
";}else{echo "
$db.$st[0] NOT DROPPED !

";}
                    }
                    $templine = '';
                    // Read in entire file
                        $lines = file($localdb);
                    // Loop through each line
                    foreach ($lines as $line)
                    {
                        // Skip it if it's a comment
                        if (substr($line, 0, 2) == '--' || $line == '')
                            continue;

                        // Add this line to the current segment
                        $templine .= $line;
                        // If it has a semicolon at the end, it's the end of the query
                        if (substr(trim($line), -1, 1) == ';')
                        {
                            // Perform the query
                            if(!empty($templine)){
                                $maindb->query($templine) or die('Error performing query
    \'' . $templine . '\': ' . $maindb->error . '

');
                            }
                            // Reset temp variable to empty
                            $templine = '';
                        }
                    }
                    ftp_close($conn);

                $vals.="('$date','$sa'),";
                $msg .="Updated $sa
";

                }
        }

            if(!empty($vals)){
                $vals=rtrim($vals,",");
                $date=Date('Y-m-d H:i:s');
                $link = mysqli_connect('127.0.0.1','admin','admin') or die ("Error connecting to
    mysql : " . mysqli_connect_errno($link).'\r\n');
                $connect=new mysqli('127.0.0.1','admin','admin','admin') or die("Database error
    :".$connect->error);

                $checktab=$connect->query("SELECT * FROM backuptimeline");
                    if(!$checktab)
                    {
                        $createsql = "CREATE TABLE backuptimeline
                         (
                             id int NOT NULL AUTO_INCREMENT,
                             PRIMARY KEY(id),
                             Date datetime,
                             site varchar(500)
                         )";
                        $createtab=$connect->query($createsql) or die($connect->error);
                    }
                        $butlsql="INSERT INTO backuptimeline (Date,site) VALUES $vals";
    //              echo $butlsql."
";
                    $insbu=$connect->query($butlsql)or die($connect->error);
                    if($insbu){
                        //sendEmailAlerts("anitgopinath@gmail.com","anitgopinath@gmail.com","DB
    $sa Backed Up","All DB $sa backed up at $date");
                        $msg.="
Timeline Updated
";
                    }
                    else{
                        $msg.= "
Timeline Not Updated
";
                    }
                    echo $msg."
";
                    sendEmailAlerts("anitgopinath@gmail.com","anitgopinath@gmail.com","DBs Back Up
    Results",$msg);
            }else{
                    echo $msg."
";
                    sendEmailAlerts("anitgopinath@gmail.com","anitgopinath@gmail.com","DBs Back Up
    Failed",'DBs Back Up Failed');
            }

?>

Task Scheduler entries;
Program / Script in Action field:

"C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\binaries\php\php_runningversion\php.exe"

Arguments field

"C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php"

Some error Messages

Warning: ftp_get(/matrimony/admin/download/sqlbackup/rotiraa1_mc.sql): failed to open stream: No such file or directory in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php on line 35 PHP Warning:  ftp_get(): Error opening /matrimony/admin/download/sqlbackup/rotiraa1_mc.sql in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php on line 35
Warning: ftp_get(): Error opening
/matrimony/admin/download/sqlbackup/rotiraa1_mc.sql in C:\Program
Files
(x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php
on line 35 PHP Warning:  file_get_contents(): SSL operation failed
with code 1. OpenSSL Error messages: error:1407742E:SSL
routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version in
C:\Program Files
(x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php
on line 21
Warning: file_get_contents(): SSL operation failed with code 1.
OpenSSL Error messages: error:1407742E:SSL
routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version in
C:\Program Files
(x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php
on line 21 PHP Warning:  file_get_contents(): Failed to enable crypto
in C:\Program Files
(x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php
on line 21
Warning: file_get_contents(): Failed to enable crypto in C:\Program
Files
(x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php
on line 21 PHP Warning:
file_get_contents(https://www.evaa-ethnix.com/admin/download/sqlbackup/backupserver.php):
failed to open stream: operation failed in C:\Program Files
(x86)\EasyPHP-DevServer-14.1VC9\data\localweb\Admin\download\autobackup_task_scheduler.php
on line 21
Warning:
file_get_contents(https://www.evaa-ethnix.com/admin/download/sqlbackup/backupserver.php):
f

I have tried using a batch file (.bat) too. I put it in system32 folder and tried. Still same errors appear.
I am not able identify whether it is a path issue or something else. I have been breaking my for a long time on this.
Any help will be greatly appreciated.

A: Finally after much googling and brainstorming I found I have two issues:

*

*PHP file_get_contents was creating the SSL error. So I replaced it with Curl as follows;
       function file_get_contents_curl( $url ) {

                   $ch = curl_init();

                   curl_setopt( $ch, CURLOPT_AUTOREFERER, TRUE );
                   curl_setopt( $ch, CURLOPT_HEADER, 0 );
                   curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
                   curl_setopt( $ch, CURLOPT_URL, $url );
                   curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, TRUE );

                   $data = curl_exec( $ch );
                   curl_close( $ch );

                   return $data;
         }

*The path local url path ftp_get() began with a variable $root which had

$root=$_SERVER['DOCUMENT_ROOT'];

This was not seen by the Windows Task Scheduler. So I simply replaced $root with the complete path

C:/Program Files (x86)/EasyPHP-DevServer-14.1VC9/data/localweb/$folder

All my problems disappeared ! My system is auto syncing my remote database to my local database on set schedules. I am a happy man now ! :)


text:
Q: Object to follow mouse pointer unity and C# I'm busy working on something that uses a RTS style camera and I want an object to follow the mouse cursor but stay at the same Y-axes at all times. The camera location is set to 0, 15, -15
I've been playing with it for a while now and this is the best that I can come up with:
Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
Vector3 point = ray.GetPoint(5);
transform.position = point;
print (point);

Any help would would be appreciated.

A: You are on the right track but you need to use that ray to raycast onto something to get the world position.
Since its an rts i assume the terrain is somewhat level in which case it would be easy to place a plane at the desired height. If thats not the case i recommend following @The Ryan advice and store the previous y value.
In either case you need to put the thing you raycast against in a separate layer from your other stuff so you dont move things on top of other units
Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);

RaycastHit hit;
if(Physics.Raycast(ray, out hit, maxDistance, layerMask))
{
    float oldY = transform.position.y;
    transform.position.Set(hit.point.x, oldY, hit.point.z);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using super() Multiple Times in a Python Class Why does user.params() not return all the params up the inheritance
chain? -- It's not including the params defined in Person() -- notice
Vertex() does not have a params() method.

class Element(object):
   def __init__(self,element_type):
        self.oid = None
        self.uuid = uuid.uuid4()
        self.key = None
        self.element_type = element_type

   def params(self):
       return dict(uuid=self.uuid, key=self.key)

class Vertex(Element):
   def __init__(self):
       super(Vertex,self).__init__("vertex")

class Person(Vertex):

   def __init__(self,name=None,uri=None,email=None):
       self.s = super(Person,self)
       self.s.__init__()
       self.name=name
       self.uri=uri
       self.email = email

   def params(self):
       params = dict(name=self.name,uri=self.uri,email=self.email)
       params.update(self.s.params())
       return params

class User(Person):

   def __init__(self,
                name=None,
                uri=None,
                email=None,
                first_name=None,
                last_name=None,
                facebook_id=None,
                facebook_link=None,
                facebook_username=None,
                gender=None,
                locale=None):
       self.s = super(User,self)
       self.s.__init__(name,uri,email)

       self.first_name = first_name
       self.last_name = last_name
       self.facebook_id = facebook_id
       self.facebook_link = facebook_link
       self.facebook_username = facebook_username
       self.gender = gender
       self.locale = locale

   def params(self):
       params = dict(first_name=self.first_name,
                     last_name=self.last_name,
                     facebook_id=self.facebook_id,
                     facebook_link=self.facebook_link,
                     facebook_username=self.facebook_username,
                     gender=self.gender,
                     locale=self.locale)
       print self.s.params()
       params.update(self.s.params())
       return params

A: In User you do:
self.s = super(User,self)
self.s.__init__(name,uri,email)

so self.s is what? As you do the same in Person, self.s is super(Person) and that anywhere, in Person and User as you reassign self.s, so the self.s.params that gets picked is the one of Element.

A: edit : also the following code works, Sebastians has the correct interpretation: self.s is reassigned each time in the __init__ of the classes. So self.s is reassigned as super(Person,self).
import uuid

class Element(object):
   def __init__(self,element_type):
        self.oid = None
        self.uuid = uuid.uuid4()
        self.key = None
        self.element_type = element_type

   def params(self):
       print 'here Element'
       return dict(uuid=self.uuid, key=self.key)

class Vertex(Element):
   def __init__(self):
       super(Vertex,self).__init__("vertex")

class Person(Vertex):

   def __init__(self,name=None,uri=None,email=None):
       super(Person,self).__init__()
       self.name=name
       self.uri=uri
       self.email = email

   def params(self):
       print 'here Person'
       params = dict(name=self.name,uri=self.uri,email=self.email)
       params.update(super(Person,self).params())
       return params

class User(Person):

   def __init__(self,
                name=None,
                uri=None,
                email=None,
                first_name=None,
                last_name=None,
                facebook_id=None,
                facebook_link=None,
                facebook_username=None,
                gender=None,
                locale=None):
       super(User,self).__init__(name,uri,email)
       self.first_name = first_name
       self.last_name = last_name
       self.facebook_id = facebook_id
       self.facebook_link = facebook_link
       self.facebook_username = facebook_username
       self.gender = gender
       self.locale = locale

   def params(self):
       params = dict(first_name=self.first_name,
                     last_name=self.last_name,
                     facebook_id=self.facebook_id,
                     facebook_link=self.facebook_link,
                     facebook_username=self.facebook_username,
                     gender=self.gender,
                     locale=self.locale)
       print 'here User'
       params.update(super(User, self).params())
       return params

if __name__ == '__main__':
   u = User()
   print '\n'.join(sorted(u.params().keys()))


text:
Q: What software can I graph with $D(x) \cdot \sin(x)$? Is there a software where I can graph $D(x) \cdot \sin(x)\ \vert \ D(x) \text{ Dirichlet's function}$?
The problem is that it's a known function, and I haven't seen in Wolfram|Alpha, Desmos and Geogebra that it's recognized, and I've also not seen there the option to define graph a function that's defined in cases.

A: In the same sense that the graph of Dirichlet's function looks like the lines $y = 0$ and $y = 1$, with holes at every rational location in the lower line and holes at every irrational location in the upper, the graph
$$
y = f(x) \chi_{\mathbf{Q}}(x)
$$
looks like the graphs $y = 0$ and $y = f(x)$, with holes at every rational location in the line $y = 0$ and holes at every irrational location in the graph $y = f(x)$.


text:
Q: if I know screen size on the mobile device how can separate a line of the text If I know screen size on the mobile device how can separate a line of the text in the html page. Text without blanks and punctuation. For example:
"TestthisstringWithTheMobileDeviceNotMoreThan480pixelsAndThisStringCanBeEvenLongerItDependsOnlyOnMyFantasy".
I do it, because I need a method to create a filter and inside the filter can be everything. I hope it is possible, but if it isn't let me know, please. Write me if you have another better decision for this problem.

A: It is not neccessary to break the string by yourself.
You can use the CSS property word-wrap (reference at w3schools) to control string breaking.
You seem to be looking for the break-word setting that breaks strings
even if there are no blanks.

<div style="width: 100px; word-wrap: break-word;">
  ALongStringThatShouldExceedTheFixedWidthOfThisBox
</div>

In fact StackOverflow uses that property to break the long string example of your question.


text:
Q: In Python how can I overwrite the class attribute of an inherited class, where that attribute is itself an instance of a model? As in the title, I have a base class ListView, with a Serializer attribute that needs overwriting. For each of my django models I create a child ListView class and a Serializer. So for example for the django model Event we have a corresponding view class EventListView(ListView), and we have a corresponding Serializer class EventSerializer(Serializer).
The Serializer child class is specified within the ListViewClass, as in my code below.
Is it possible to have the serializer overwritten automatically based on the value supplied to model, and how may I mark model and Serializer as attributes that are to be overwritten and therefore do not need values specified in the base class?
class EventSerializer(serializers.ModelSerializer):
    class Meta:
        model = Event
        fields = '__all__'

class ListView(APIView):
    model = <Model to be overwritten>        # Event is set as the default.
    Serializer = <Model Serializer to be overwritten>

    queryset = model.objects.all()

    def get(self,request):
        # !!! Get filter conditions from request
        queryset = ListView.queryset.filter()    # !!! Filter conditions
        serializer = ListView.Serializer(queryset,many=True)
        return Response(serializer.data)

    def post(self,request):
        data = JSONParser.parse(request)
        serializer = ListView.Serializer(data = data)
        if serializer.is_valid():
            return Response(serializer.data, status = 201)
        else:
            return Response(serializer.errors, status = 400)

class EventListView(ListView):
    model = Event

A: I think you need to use self.queryset, self.model and self.Serializer instead of ListView.queryset and ListView.Serializer. Then, in each subclass it will use the queryset, model, and serializer of the subclass, rather than of the base ListView.
In each subclass you will need to redefine model, queryset and Serializer.
class ListView(APIView):
    model = <Model to be overwritten>        # Event is set as the default.
    Serializer = <Model Serializer to be overwritten>

    queryset = model.objects.all()

    def get(self,request):
        # !!! Get filter conditions from request
        queryset = self.queryset.filter()    # !!! Filter conditions
        serializer = self.Serializer(queryset,many=True)
        return Response(serializer.data)

    def post(self,request):
        data = JSONParser.parse(request)
        serializer = self.Serializer(data = data)
        if serializer.is_valid():
            return Response(serializer.data, status = 201)
        else:
            return Response(serializer.errors, status = 400)

class EventListView(ListView):
    model = Event
    Serializer = EventSerializer
    queryset = Event.objects.all()

If you don't want to define queryset on all subclasses, you probably want to add a method to get the queryset using the model, like this
class ListView(APIView):
    model = <Model to be overwritten>        # Event is set as the default.
    Serializer = <Model Serializer to be overwritten>

    def get_queryset():
        return self.model.objects.all()

    def get(self,request):
        # !!! Get filter conditions from request
        queryset = self.get_queryset().filter()    # !!! Filter conditions
        serializer = self.Serializer(queryset,many=True)
        return Response(serializer.data)

    def post(self,request):
        data = JSONParser.parse(request)
        serializer = self.Serializer(data = data)
        if serializer.is_valid():
            return Response(serializer.data, status = 201)
        else:
            return Response(serializer.errors, status = 400)

In fact, a lot of this is implemented directly in DRF, which will save you a lot of custom coding. Check out the GenericAPIView (https://www.django-rest-framework.org/api-guide/generic-views/#genericapiview) and ListAPIView (https://www.django-rest-framework.org/api-guide/generic-views/#listapiview)


text:
Q: Adding items selected from dropdown into a list using Javascript DOM I am trying to add selected items from the dropdown into a shopping list using
.
But my code gives the error Uncaught ReferenceError display is not defined at HTMLSelectElement.onchange. Can someone help fixing it?
Code:
<!DOCTYPE html>

Shopping List

    <select id="select_item" onchange="display(this)">
        <option value="NoteBook">Notebook</option>
        <option value="Jello">Jello</option>
        <option value="Spinach">Spinach</option>
        <option value="Rice">Rice</option>
        <option value="Birthday Cake">Birthday Cake</option>
        <option value="Candles">Candles</option>
    </select>

Shopping Cart:

A: There is no display function defined which you use on you html select element.You can get the selected value onchange following way

function display (v) {
   console.log(v)
}
<select id="select_item" onchange="display(this.value)">
        <option value="NoteBook">Notebook</option>
        <option value="Jello">Jello</option>
        <option value="Spinach">Spinach</option>
        <option value="Rice">Rice</option>
        <option value="Birthday Cake">Birthday Cake</option>
        <option value="Candles">Candles</option>
    </select>


text:
Q: create Order Programmatically "message":"Invalid state change requested", I have a function to create order Programmatically, but run after twice, there is an error message:
string(3407) "{"message":"Invalid state change requested","trace":"#0 \/home\/m22\/public_html\/vendor\/magento\/framework\/Interception\/Interceptor.php(121): Magento\\Quote\\Model\\QuoteRepository\\Plugin\\AccessChangeQuoteControl->beforeSave(Object(Magento\\Quote\\Model\\QuoteRepository\\Interceptor), Object(Magento\\Quote\\Model\\Quote))\n#1 \/home\/m22\/public_html\/vendor\/magento\/framework\/Interception\/Interceptor.php(153): Magento\\Quote\\Model\\QuoteRepository\\Interceptor->Magento\\Framework\\Interception\\{closure}(Object(Magento\\Quote\\Model\\Quote))\n#2 \/home\/m22\/public_html\/generated\/code\/Magento\/Quote\/Model\/QuoteRepository\/Interceptor.php(78): Magento\\Quote\\Model\\QuoteRepository\\Interceptor->___callPlugins('save', Array, Array)\n#3 \/home\/m22\/public_html\/vendor\/magento\/module-quote\/Model\/QuoteManagement.php(520): Magento\\Quote\\Model\\QuoteRepository\\Interceptor->save(Object(Magento\\Quote\\Model\\Quote))\n#4 \/home\/m22\/public_html\/vendor\/magento\/module-quote\/Model\/QuoteManagement.php(406): Magento\\Quote\\Model\\QuoteManagement->submitQuote(Object(Magento\\Quote\\Model\\Quote), Array)\n#5 \/home\/m22\/public_html\/vendor\/magento\/module-quote\/Model\/QuoteManagement.php(364): Magento\\Quote\\Model\\QuoteManagement->submit(Object(Magento\\Quote\\Model\\Quote))\n#6 \/home\/m22\/public_html\/app\/code\/namespace\/plugin\/Helper\/Data.php(104): Magento\\Quote\\Model\\QuoteManagement->placeOrder('16')\n#7 \/home\/m22\/public_html\/app\/code\/namespace\/plugin\/Model\/Calculator.php(217): namespace\\plugin\\Helper\\Data->createMageOrder(Array)\n#8 [internal function]: namespace\\plugin\\Model\\Calculator->createOrder('dllm')\n#9 \/home\/m22\/public_html\/vendor\/magento\/module-webapi\/Controller\/Rest.php(330): call_user_func_array(Array, Array)\n#10 \/home\/m22\/public_html\/vendor\/magento\/module-webapi\/Controller\/Rest.php(239): Magento\\Webapi\\Controller\\Rest->processApiRequest()\n#11 \/home\/m22\/public_html\/vendor\/magento\/framework\/Interception\/Interceptor.php(58): Magento\\Webapi\\Controller\\Rest->dispatch(Object(Magento\\Framework\\App\\Request\\Http))\n#12 \/home\/m22\/public_html\/vendor\/magento\/framework\/Interception\/Interceptor.php(138): Magento\\Webapi\\Controller\\Rest\\Interceptor->___callParent('dispatch', Array)\n#13 \/home\/m22\/public_html\/vendor\/magento\/framework\/Interception\/Interceptor.php(153): Magento\\Webapi\\Controller\\Rest\\Interceptor->Magento\\Framework\\Interception\\{closure}(Object(Magento\\Framework\\App\\Request\\Http))\n#14 \/home\/m22\/public_html\/generated\/code\/Magento\/Webapi\/Controller\/Rest\/Interceptor.php(39): Magento\\Webapi\\Controller\\Rest\\Interceptor->___callPlugins('dispatch', Array, Array)\n#15 \/home\/m22\/public_html\/vendor\/magento\/framework\/App\/Http.php(135): Magento\\Webapi\\Controller\\Rest\\Interceptor->dispatch(Object(Magento\\Framework\\App\\Request\\Http))\n#16 \/home\/m22\/public_html\/generated\/code\/Magento\/Framework\/App\/Http\/Interceptor.php(24): Magento\\Framework\\App\\Http->launch()\n#17 \/home\/m22\/public_html\/vendor\/magento\/framework\/App\/Bootstrap.php(256): Magento\\Framework\\App\\Http\\Interceptor->launch()\n#18 \/home\/m22\/public_html\/index.php(39): Magento\\Framework\\App\\Bootstrap->run(Object(Magento\\Framework\\App\\Http\\Interceptor))\n#19 {main}"}"

here is the function:
public function createMageOrder($orderData) {
    $store=$this->_storeManager->getStore();
    $websiteId = $this->_storeManager->getStore()->getWebsiteId();
    $customer=$this->customerFactory->create();
    $customer->setWebsiteId($websiteId);
    $customer->loadByEmail($orderData['email']);// load customet by email address
    if(!$customer->getEntityId()){
        //If not avilable then create this customer
        $customer->setWebsiteId($websiteId)
                ->setStore($store)
                ->setFirstname($orderData['shipping_address']['firstname'])
                ->setLastname($orderData['shipping_address']['lastname'])
                ->setEmail($orderData['email'])
                ->setPassword($orderData['email']);
        $customer->save();
    }

    $cartId = $this->cartManagementInterface->createEmptyCart(); //Create empty cart
    $quote = $this->cartRepositoryInterface->get($cartId); // load empty cart quote
    $quote->setStore($store);
    // if you have allready buyer id then you can load customer directly
    $customer= $this->customerRepository->getById($customer->getEntityId());
    $quote->setCurrency();
    $quote->assignCustomer($customer); //Assign quote to customer

    //add items in quote

    foreach($orderData['items'] as $item){
        $product=$this->_product->load($item['product_id']);

        //$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/templog.log');
        //$logger = new \Zend\Log\Logger();
        //$logger->addWriter($writer);
        //$logger->info($product);

        $product->setPrice($item['price']);
        $quote->addProduct($product, intval($item['qty']));
    }

    //Set Address to quote
    $quote->getBillingAddress()->addData($orderData['shipping_address']);
    $quote->getShippingAddress()->addData($orderData['shipping_address']);

    // Collect Rates and Set Shipping & Payment Method

    $shippingAddress=$quote->getShippingAddress();
    $shippingAddress->setCollectShippingRates(true)
                    ->collectShippingRates()
                    ->setShippingMethod('flatrate_flatrate'); //shipping method
    $quote->setPaymentMethod('checkmo'); //payment method
    $quote->setInventoryProcessed(false); //not effetc inventory

    // Set Sales Order Payment
    $quote->getPayment()->importData(['method' => 'checkmo']);
    $quote->save(); //Now Save quote and your quote is ready

    // Collect Totals
    $quote->collectTotals();

    // Create Order From Quote
    $quote = $this->cartRepositoryInterface->get($quote->getId());
    $orderId = $this->cartManagementInterface->placeOrder($quote->getId());
    $order = $this->order->load($orderId);

    $order->setEmailSent(0);
    $increment_id = $order->getRealOrderId();
    if($order->getEntityId()){
        $result['order_id']= $order->getRealOrderId();
    }else{
        $result=['error'=>1,'msg'=>'Your custom message'];
    }
    return $result;
}

anyone know how to fix that?
-----------------update-----------------
vendor\magento\module-quote\Model\QuoteRepository\Plugin\AccessChangeQuoteControl.php
        case UserContextInterface::USER_TYPE_GUEST:

            $isAllowed = true;

            break;

I need to add $isAllowed = true part of code, but what is

$quote->getCustomerId() == $this->userContext->getUserId()?

A: Not sure what the problem is. but I can give you a place to start debugging.
The only place in the core where this error message is triggered is Magento\Quote\Model\QuoteRepository\Plugin\AccessChangeQuoteControl::beforeSave.
The message is triggered if the result of the method isAllowed from the same class is false.
Check why this method is returning false.


text:
Q: Why HTML datalist's option tag not functioning As title mentioned, I am thinking is there any error for this part of code:

var td5 = document.createElement("td");
td5.innerHTML = "Locale";
tr3.appendChild(td5);

var td6 = document.createElement("td");
tr3.appendChild(td6);

var tdc3 = document.createElement("input");
tdc3.type = "text";
tdc3.style.width = "100%";
tdc3.setAttribute('list', 'lcl');
tdc3.id = "loc";
var tdc3a = document.createElement("datalist");
tdc3a.id = "lcl";
var lop1 = document.createElement("option");
lop1.value = "MY";
lop1.innerHTML = "MY";
var lop2 = document.createElement("option");
lop2.value = "SG";
lop2.innerHTML = "SG";
var lop3 = document.createElement("option");
lop3.value = "AU";
lop3.innerHTML = "AU";
var lop4 = document.createElement("option");
lop4.value = "NZ";
lop4.innerHTML = "NZ";
var lop5 = document.createElement("option");
lop5.value = "PK";
lop5.innerHTML = "PK";
var lop6 = document.createElement("option");
lop6.value = "PH";
lop6.innerHTML = "PH";
var lop7 = document.createElement("option");
lop7.value = "ID";
lop7.innerHTML = "ID";
var lop8 = document.createElement("option");
lop8.value = "VN";
lop8.innerHTML = "VN";
var lop9 = document.createElement("option");
lop9.value = "TH";
lop9.innerHTML = "TH";
var lop10 = document.createElement("option");
lop10.value = "IN";
lop10.innerHTML = "IN";
var lop11 = document.createElement("option");
lop11.value = "CN";
lop11.innerHTML = "CN";
var lop12 = document.createElement("option");
lop12.value = "JP";
lop12.innerHTML = "JP";
var lop13 = document.createElement("option");
lop13.value = "KR";
lop13.innerHTML = "KR";
var lop14 = document.createElement("option");
lop14.value = "TW";
lop14.innerHTML = "TW";
var lop15 = document.createElement("option");
lop15.value = "HK";
lop15.innerHTML = "HK";
var lop16 = document.createElement("option");
lop16.value = "HK-EN";
lop16.innerHTML = "HK-EN";
tdc3a.appendChild(lop1);
tdc3a.appendChild(lop2);
tdc3a.appendChild(lop3);
tdc3a.appendChild(lop4);
tdc3a.appendChild(lop5);
tdc3a.appendChild(lop6);
tdc3a.appendChild(lop7);
tdc3a.appendChild(lop8);
tdc3a.appendChild(lop9);
tdc3a.appendChild(lop10);
tdc3a.appendChild(lop11);
tdc3a.appendChild(lop12);
tdc3a.appendChild(lop13);
tdc3a.appendChild(lop14);
tdc3a.appendChild(lop15);
tdc3a.appendChild(lop16);
document.body.appendChild(tdc3);
document.body.appendChild(tdc3a);

The image below is screenshot after I inject my code into aspx page:

The image below is screenshot after I inject my code into a HTML dummy page which created by myself:

Additional infomation:
The reason why I writing my code in Javascript is I am currently developing a bookmarklet injector for my job uses.
I am trying to inject Javascript code into .aspx page to popup a div block with some text field, datalist and drop-down list in it. The browswer I working with is IE 11.
I have tried to inject the original code file into a dummy HTML page which I created by myself and it is fully working without any error, but not in the .aspx page I mentioned just now.
In order to create a drop-down list, We might need to create a select tag and several option tag as child. This works fine in the .aspx page after injection.
But unfortunately, the option tag in datalist tag won't working well as in the screenshot attached above.
Please kindly advise your opinions.
Thanks a lot.

A: *

*It is necessary to append the datalist element to body or any other element present in the document, e.g.

document.body.appendChild(tdc3a);

*At the moment browsers seem to ignore datalists that are inserted into DOM after the list attribute of an input is set. Therefore, it is important to insert a datalist to the DOM before setting the list attribute of an input. Example: http://codepen.io/askl/pen/kXZLbj

*Datalist does not work in all browsers, e.g. Safari and Firefox don't support it as of July 2016. See also http://caniuse.com/#search=datalist.


text:
Q: Why is vcpkg recommended as a git submodule? Currently the README.md for vcpkg says
"First, download and bootstrap vcpkg itself; it can be installed anywhere, but generally we recommend using vcpkg as a submodule for CMake projects, and installing it globally for Visual Studio projects."
Why is the recommendation submodules for CMake? But global for Visual Studio?

A:
Why is the recommendation submodules for CMake?

The README is kind of out of date. The current advice for CMake uses would be to use FetchContent since it is less of a hassle compared to a git submodules.

But global for Visual Studio?

The is also kind of dated. The reason for it is that vcpkg + VS required integration with a vcpkg instance (vcpkg integrate install) but today there is also (vcpkg integrate project) which could be used. Still having per project setup is kind of a manual setup while having it globally is less manual since vcpkg is directly integrated into VS/MSBuild without having extra setup steps in VS.
Furthermore, at the time the advice was written, binary caching wasn't yet implemented so per project integration would probably have meant a rebuild for every project referencing a different vcpkg instance.
In the end it the suggestion comes down to ease of use. You don't have to do it the suggested way.


text:
Q: Unable to take full page screenshot using "screenshot --fullpage" I am using Firefox 64.0 on Windows 10 (1803).
In past I have been able to take full page screen captures by issuing the command screenshot --fullpage on the browser console. Now using this command gives an error:
screenshot --fullpage
SyntaxError: unexpected token: identifier

Should this feature still work in Firefox 64? Searching for ways to take full page screen captures leads guides telling to use this command but they all seem to be couple of years old.
If this feature still exists, why is it not working for me? If it does not exist is there a build-in alternative?

A: You need to prepend a semicolon to the command:
:screenshot --fullpage

There's more info on that command on MDN web docs.
If the --fullpage parameter doesn't work, i.e. you only get a screenshot of the viewport instead of the whole page, you either typed it wrong or it's a bug. To check whether it's a general bug in Firefox or caused by some setting or add-on, you should create a new Firefox profile and try the command there. If it works there, it's related to your profile.
There's also a page giving more tips how to troubleshoot Firefox.


text:
Q: AttributeError: type object 'h5py.h5r.Reference' has no attribute '__reduce_cython__' I am using python 3.6,Tensorflow 1.3, Keras 2.1.2
I was importing Resnet50 and I got this error"ImportError: load_model requires h5py" so I used
conda install h5py
but then I got this error knowing that the installed version of h5py is 2.9.0enter image description here

A: Any solutions for this error?
I am getting the same thing when trying to import tensorflow (v2.0.0) and Python 3.7.3
Traceback:
>>> import tensorflow as tf
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\*\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:\Users\*\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\__init__.py", line 82, in <module>
    from tensorflow.python import keras
  File "C:\Users\*\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\__init__.py", line 25, in <module>
    from tensorflow.python.keras import applications
  File "C:\Users\*\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\applications\__init__.py", line 26, in <module>
    from tensorflow.python.keras import layers
  File "C:\Users\*\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\layers\__init__.py", line 29, in <module>
    from tensorflow.python.keras.layers.advanced_activations import LeakyReLU
  File "C:\Users\*\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\layers\advanced_activations.py", line 27, in <module>
    from tensorflow.python.keras.utils import tf_utils
  File "C:\Users\*\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\utils\__init__.py", line 38, in <module>
    from tensorflow.python.keras.utils.multi_gpu_utils import multi_gpu_model
  File "C:\Users\*\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\utils\multi_gpu_utils.py", line 22, in <module>
    from tensorflow.python.keras.engine.training import Model
  File "C:\Users\*\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py", line 42, in <module>
    from tensorflow.python.keras.engine.network import Network
  File "C:\Users\potvin\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\engine\network.py", line 40, in <module>
    from tensorflow.python.keras.engine import saving
  File "C:\Users\*\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\engine\saving.py", line 38, in <module>
    import h5py
  File "C:\Users\*\AppData\Local\Continuum\anaconda3\lib\site-packages\h5py\__init__.py", line 36, in <module>
    from ._conv import register_converters as _register_converters
  File "h5py\h5r.pxd", line 21, in init h5py._conv
  File "h5py\h5r.pyx", line 145, in init h5py.h5r
AttributeError: type object 'h5py.h5r.Reference' has no attribute '__reduce_cython__'

Edit: I was able to fix this issue by restarting the kernel.


text:
Q: How to check if the field contains hyphen character in java My Object returns me - from
    Log.d("FormattedDate", Object.getDOB());
if (!Object.getDOB().matches("[^-]*")) {
    txtDOB.setText(Object.getDOB());
   } else {
    txtDOB.setText("-");
}

I am checking if my Object.getDOB() matches with -, then show emptry strings, but this regExp is not working.

A: java.lang.String has a String#contains() method that does this for you:

Returns true if and only if this string contains the specified
  sequence of char values.

if (Object.getDOB().contains("-")) {
    //code
}

A: You could also use
if (Object.getDOB().indexOf("-") != -1) {
    //code
}

if it returns -1 then the string does not contain the char (in your case "-"). Otherwise it returns the index of the char.

A: You can use contains() in java to search which is available in String class

Returns true if and only if this string contains the specified
  sequence of char values.

getDOB().contains("-")

SEE HERE


text:
Q: $\pi \cot (\pi z) = \frac{1}{z} + \sum_{n \in \mathbb{Z},\ n \neq 0} \frac{1}{z-n}+ \frac{1}{n}$ I'm reading the proof that $$\pi \cot (\pi z) = \frac{1}{z} + \sum_{n \in \mathbb{Z},\  n \neq 0} \frac{1}{z-n}+ \frac{1}{n}$$
There is a function $$h(z) =\pi \cot (\pi z) -[ \frac{1}{z} + \sum_{n \in \mathbb{Z},\  n \neq 0} \frac{1}{z-n}+ \frac{1}{n} ]$$ and the proof states that $h(1) = 0$.
I don't understand this point, why $h(1) = 0$ ?

A: Consider the function
$$d(z) = \pi \cot \pi z - \frac{1}{z-1}$$
in a neighbourhood of $1$. Writing $z = 1+h$, we have
$$\begin{align}
d(1+h) &= \pi\frac{\cos \pi(1+h)}{\sin \pi(1+h)} - \frac{1}{h}\\
&= \pi \frac{-\cos \pi h}{-\sin \pi h} - \frac{1}{h}\\
&= \frac{1 - \frac{\pi^2h^2}{2} + O(h^4)}{h\left(1 - \frac{\pi^2h^2}{6}+O(h^4)\right)} - \frac{1}{h}\\
&= \frac{1}{h}\left(1- \frac{\pi^2h^2}{2}+O(h^4)\right)\left(1 + \frac{\pi^2h^2}{6}+O(h^4)\right) - \frac{1}{h}\\
&= \frac{1}{h}\left(1-\frac{\pi^2h^2}{3} + O(h^4)\right) - \frac{1}{h}\\
&= -\frac{\pi^2h}{3} + O(h^3),
\end{align}$$
so $d$ has a removable singularity in $1$, and after removing it, we have $d(1) = 0$.
Then it remains to see that
$$e(z) = \left(\frac{1}{z} + \sum_{n\neq 0} \frac{1}{z-n}+\frac{1}{n}\right) - \frac{1}{z-1} = \frac{1}{z} + 1 + \sum_{n\notin \{0,1\}} \frac{1}{z-n} + \frac{1}{n}$$
also has a zero in $1$. Having cancelled the $\frac{1}{z-1}$ term, we can compute $e(1)$ simply by substituting $1$ for $z$ in the last representation. The sums nicely telescope then and yield the expected result. Since $h(z) = d(z) - e(z)$, that concludes the proof.

A: Try to calculate $\lim_{z\to 1}h(z)$ to get $h(1)$.


text:
Q: I'm having a problem with decimalNumberBySubtracting and decimalNumberByDividingBy Simply put, decimalNumberBySubtracting and decimalNumberByDividingBy are not working ... at all.  No errors, just messed up results.  I really need to fix this but Im not getting any errors and I cant think of any other way for how to do the calculation!!  Im getting numbers like:

257849691392950000000000000000000000000000000000000000000000000000000000000000000

Where they should be evalutating to:

-0.581

Here's the long story.  I am trying to do a simple Z-Score calculation on a data set.  A Zscore is defined as (X - Average)/(stdDev).  Pretty simple.  My test data includes 5 plates each with 96 samples.  This code identifies each individual plate, generates average and stdev for each plate, then for each sample in THAT plate, performs the above calculation.
//identify unique plates
NSSet * uniqueValues = [NSSet setWithArray:[items valueForKey:@"plate"]];
id i;
for (i in uniqueValues) {
    //Lots of NSExpression and Predicate stuff I pulled out cause its working fine

    NSExpression *plateMeanExpression = [NSExpression expressionForFunction:@"average:"
                                                                  arguments:plateArgumentArray];
    NSExpression *plateStdDevExpression = [NSExpression expressionForFunction:@"stddev:"
                                                                    arguments:plateArgumentArray];

    // generate Z Score and StDev:
    NSDecimalNumber *zscoreMean = [plateMeanExpression expressionValueWithObject:nil
                                                                         context:nil];
    NSDecimalNumber *zscoreStdDev = [plateStdDevExpression expressionValueWithObject:nil
                                                                             context:nil];

    //iterate through samples in each plate and perform calculation, update CoreData
    for (ScreenVariables *zValue in eachPlateArray) {
        NSDecimalNumber *deltaTemp = [zValue valueForKey:@"delta"];
        NSDecimalNumber *numerator = [deltaTemp decimalNumberBySubtracting:zscoreMean];
        NSDecimalNumber *zScoreValue = [numerator decimalNumberByDividingBy:zscoreStdDev];
        [zValue setZScore:zScoreValue];

The problem is that when I run this calculation I should get a number from ~(-6,6) with 99% of values falling between -3 and 3.  One data point returned is this:

257849691392950000000000000000000000000000000000000000000000000000000000000000000

So OK fine, I did some troubleshooting by inserting the variables deltaTemp, numerator, zscoreMean, zscoreStdDev into my NSTableView.  The idea was to see what XCode was evaluating these variables out to and fix whichever is the trouble maker.  Did it using this code:
ScreenVariables *addData = [NSEntityDescription insertNewObjectForEntityForName:@"ScreenVariables"
                                                         inManagedObjectContext:self.managedObjectContext];
[addData setValue:deltaTemp forKey:@"someAvailableKey-1"];
[addData setValue:numerator forKey:@"someAvailableKey-2"];
[addData setValue:zscorePlateMean forKey:@"someAvailableKey-3"];
[addData setValue:zscoreStdDev forKey:@"someAvailableKey-4"];

I got values for my variables:
deltaTemp = -919
zscoreMean = -141
numerator = -919    // should be -778.58 = -919 -(-141)
zscoreStdDev = 1337.635067946411

This evaluates to Z-Score= -0.581...
Thats a perfectly valid ZScore ... so the problem is in the:
[deltaTemp decimalNumberBySubtracting:zscoreMean];
[numerator decimalNumberByDividingBy:zscoreStdDev];

The variable numerator isn't evaluating correctly and neither is the zscore value.  My CoreData DataModel SPECIFICALLY has each numeric variable's input type defined as NSDecimalNumber so Im assuming my number encoding is fine cause they're getting inserted individually without any problems ...

A: NSDecimalNumber *zscoreMean = [plateMeanExpression  expressionValueWithObject:nil context:nil];
NSDecimalNumber *zscoreStdDev = [plateStdDevExpression expressionValueWithObject:nil context:nil];

These were evaluating to NSNumber objects, not NSDecimalNumber Objects ... not sure why I didnt get any errors.
    NSNumber *expMean = [plateMeanExpression  expressionValueWithObject:nil context:nil];
    NSNumber *expStdDev = [plateStdDevExpression expressionValueWithObject:nil context:nil];

    NSDecimalNumber *zscoreMean = [NSDecimalNumber decimalNumberWithDecimal:[expMean decimalValue]];
    NSDecimalNumber *zscoreStdDev = [NSDecimalNumber decimalNumberWithDecimal:[expStdDev decimalValue]];

This worked beautifully.


text:
Q: Populating 2d array of ints from string in C I want to populate a 2d array of ints with some numbers.
The numbers is in a grid format like the following :
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48

I want my program to take the string above and store the numbers in a 20x20 2d array of ints.
int main(void)
{

    int grid[20][20];
    for(int i = 0;i<20;i++)
    {
        for(int j = 0;j<20;j++)
        {
            grid[i][j] = //some code to populate int here
        }
    }

}

I am unsure how to get the 'code to populate'
So I tried using strtok as below:
int main(void)
{

    char *input = "08 02 22...48";
    char *output = strtok(input," ");
    printf("%s",output);
}

However, the above is giving me a segmentation fault and I am unsure why.
I am very new to programming, especially in C, and I am a bit unsure how to get an input like above stored as a 2d array of ints. Any alternative routes to the above or any guidance as to why I am getting segmentation faults is appreciated, thanks :)

A: You're almost there. Inside your inner loop,
if (scanf("%d", &grid[i][j]) < 1)
    break; // oops, looks like we ran out of numbers to read!

A: The reason that strtok is giving you a segmentation fault is that you are using a const char* as the input, but strtok expects to modify the string (namely, it inserts a '\0' at the first instance of the terminating character).  If you just changed your code to
char input[] = "08 02 22...48";
char *output = strtok(input," ");
printf("%s",output);

You would find that it works (because that initializer creates a string that is not a const).
Obviously you can then use sscanf to convert the string to a numerical value - make sure that you pass it the address of the location where you want to store:
sscanf(output, "%d", &grid[i][j]);

You look like you know how to combine these elements into a loop structure. Do note that strtok should be called with a char* argument the first time, and with NULL after that...
EDIT re-reading your question, it seems you would benefit from a complete code example:
#include <stdio.h>
#include <string.h>

int main(void) {

char input[]=\
"08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 "\
"49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 "\
"81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 "\
"52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 "\
"22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 "\
"24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 "\
"32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 "\
"67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 "\
"24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 "\
"21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 "\
"78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 "\
"16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 "\
"86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 "\
"19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 "\
"04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 "\
"88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 "\
"04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 "\
"20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 "\
"20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 "\
"01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48";

int ii, jj;
int grid[20][20];
char *s = strtok(input, " ");

for(ii=0; ii<20; ii++){
  for(jj=0; jj<20; jj++){
    sscanf(s, "%d", &grid[ii][jj]);
    s = strtok(NULL, " ");
  }
}
for(ii=0; ii<20; ii++){
  for(jj=0; jj<20; jj++){
    printf("%02d ", grid[ii][jj]);
  }
  printf("\n");
}
return 0;
}

Let me know if any of this needs clarification.

A: You may not apply function strtok to string literals. There is a more simple and robust approach by means of function strtol .
Here is a demonstrative program
#include <stdio.h>
#include <stdlib.h>

#define N   20

int main(void)
{
    char *s =
        "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 "
        "49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 "
        "81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 "
        "52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 "
        "22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 "
        "24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 "
        "32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 "
        "67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 "
        "24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 "
        "21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 "
        "78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 "
        "16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 "
        "86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 "
        "19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 "
        "04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 "
        "88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 "
        "04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 "
        "20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 "
        "20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 "
        "01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 ";
        int a[N][N] = { { 0 } };

        int *p = ( int * )a;

        const char *nptr = NULL;
        char *endptr = s;

        for ( size_t i = 0; i < N * N && nptr != endptr; i++ )
        {
            int x;
            nptr = endptr;
            x = ( int ) strtol( nptr, &endptr, 10 );
            if ( nptr != endptr ) p[i] = x;
        }

        for ( size_t i = 0; i < N; i++ )
        {
            for ( size_t j = 0; j < N; j++ ) printf( "%3d", a[i][j] );
            puts( "" );
        }

    return 0;
}

And this is its output
 8  2 22 97 38 15  0 40  0 75  4  5  7 78 52 12 50 77 91  8
 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48  4 56 62  0
 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30  3 49 13 36 65
 52 70 95 23  4 60 11 42 69 24 68 56  1 32 56 71 37  2 36 91
 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
 24 47 32 60 99  3 45  2 44 75 33 53 78 36 84 20 35 17 12 50
 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
 67 26 20 68  2 62 12 20 95 63 94 39 63  8 40 91 66 49 94 21
 24 55 58  5 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
 21 36 23  9 75  0 76 44 20 45 35 14  0 61 33 97 34 31 33 95
 78 17 53 28 22 75 31 67 15 94  3 80  4 62 16 14  9 53 56 92
 16 39  5 42 96 35 31 47 55 58 88 24  0 17 54 24 36 29 85 57
 86 56  0 48 35 71 89  7  5 44 44 37 44 60 21 58 51 54 17 58
 19 80 81 68  5 94 47 69 28 73 92 13 86 52 17 77  4 89 55 40
  4 52  8 83 97 35 99 16  7 97 57 32 16 26 26 79 33 27 98 66
 88 36 68 87 57 62 20 72  3 46 33 67 46 55 12 32 63 93 53 69
  4 42 16 73 38 25 39 11 24 94 72 18  8 46 29 32 40 62 76 36
 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74  4 36 16
 20 73 35 29 78 31 90  1 74 31 49 71 48 86 81 16 23 57  5 54
  1 70 54 71 83 51 54 69 16 92 33 48 61 43 52  1 89 19 67 48

A: #include <stdio.h>
#include <ctype.h>

int populate(const char **p){
    int n = 0;
    while(isspace(**p))
        ++*p;
    for(n=0; isdigit(**p); ++*p)
        n = n * 10 + **p - '0';
    return n;
}

int main() {
    const char *numbers =
    "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 "
    "49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 "
    "81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 "
    "52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 "
    "22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 "
    "24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 "
    "32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 "
    "67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 "
    "24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 "
    "21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 "
    "78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 "
    "16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 "
    "86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 "
    "19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 "
    "04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 "
    "88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 "
    "04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 "
    "20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 "
    "20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 "
    "01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48";

    const char *p = numbers;
    int grid[20][20];
    for(int i = 0;i<20;i++){
        for(int j = 0;j<20;j++){
            grid[i][j] = populate(&p);
            printf("%02d ", grid[i][j]);
        }
        printf("\n");
    }
    return 0;
}


text:
Q: Infinite read from java socket(windows) simple code
InputStream is = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("utf-8")));
while (true) {
    int ch = reader.read();
    if(ch==-1){
        break;
    }
}

sometime it stuck , because reader return ffff. any idea how to find reason?? look like some memory corruption in jvm. but reproduced only in java 8 on windows 2012. https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#read() The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached.
problem: read never return -1. even client socket is closed

A:
sometime it stuck, because reader returns ffff

This code does not get 'stuck' at all, let alone because the reader returned 0xffff. It returns any char in the range 0..0xffff, all of which is data, not a problem, or -1 at end of stream.
The problem here is that when read() returns -1, i.e. 0xffffffff, you are storing it into a char, so its value becomes 0xffff, which doesn't compare equal to -1, because it isn't, so you loop forever at end of stream. Not 'get stuck'.
ch needs to be declared as int.


text:
Q: Is the compiler forced to evaluate if expressions depending on template parameters? Consider this code snippet:
#include <iostream>

struct A {

    void f() { std::cout << "f"; }
    void g() { std::cout << "g"; }

    template <bool b>
    void call() { (b ? f() : g()); }
};

int main()
{
    A().call<true>();
}

Depending on the template paramter passed to call, either f or g will be called. My question is, if the compiler is somehow forced to pre-evaluate the if condition. Consider this other possible implementation of call:
template <bool b>
void call() {
    bool x = b;
    (x ? f() : g());
}

In this case, the compile-time template is first converted into a runtime variable, before the decision on f or g is made. I would assume, that the compiler would not be able to remove the if statement in this case.
Indeed, if I test this behaviour with godbolt that seems to be exactly what happens.
Is there some part of the standard that defines which template expressions have to be evaluated at compile-time?
(Of course, in this simple example, I could easily write specializations for b == true and b == false, but that is not what this question is about.)

A: All template expressions are evaluated at compile time, because templates don't exist at runtime. You can use if constexpr which is garantueed to be evaluated at compile time:
template <bool b>
void call() { if constexpr (b) f(); else g(); }

In you example (for b = true) this will become
void call() { f(); }

regardless of optimization level.
However when you use a normal if or a ternary operator the generated code might be easily optimized. In your example (again for b=true) template instantion creates something like this:
void call() { (true ? f() : g()); }

which the compiler can easily optimize if you allow him to. G++ with -O3 for example just removes the instantion of A and the call to call alltogether and just moves std::cout << "f" into main. See on godbolt.

Concolusion: All template expressions are evaluated at compile time, but the compiler can recognize if an expression or variable is constant and is able to optimize such cases, but the compiler is not obliged to do so (you don't want optimized code when you try to debug something)


text:
Q: How to add '@' symbol if it doesn't exist in the field? I'm outputting a custom user field in Wordpress, which is user's Twitter username. Some users might add it with '@' symbol, some might without. How can I output that field and check if the symbol already exists, if not, add it?
This is code I'm using to output usrename:
<?php echo get_the_author_meta('twitter_name'); ?>

A: <?php
$authorMeta = get_the_author_meta('twitter_name');
if (strpos('@', $authorMeta) !== 0) {
    $authorMeta = '@'.$authorMeta;
}
echo $authorMeta;

you need to check if @ is on 1st place, you can do this in many ways
<?php
$authorMeta = get_the_author_meta('twitter_name');
if ($authoMeta[0] != '@') {
    $authorMeta = '@'.$authorMeta;
}
echo $authorMeta;

A: Try this...it might help
$a = get_the_author_meta('twitter_name');
$b = explode('@',$a);
if($b[1] == 0){
    echo "@".$a;
}
else{
echo $a;
}


text:
Q: Custom JSON validation constraints in Play Framework 2.3 (Scala) I managed to implement form validation with custom constraints, but now I want to do the same thing with JSON data.
How can I apply custom validation rules to a JSON parser?
Example: The client's POST request contains a user name (username) and not only do I want to make sure that this parameter is a non-empty text, but also that this user actually exists in the database.
// In the controller...

def postNew = Action { implicit request =>
    request.body.asJson.map { json =>
        json.validate[ExampleCaseClass] match {
            case success: JsSuccess[ExampleCaseClass] =>
                val obj: ExampleCaseClass = success.get
                // ...do something with obj...
                Ok("ok")
            case error: JsError =>
                BadRequest(JsError.toFlatJson(error))
        }
    } getOrElse(BadRequest(Json.obj("msg" -> "JSON request expected")))
}

// In ExampleCaseClass.scala...

case class ExampleCaseClass(username: String, somethingElse: String)

object ExampleCaseClass {
    // That's what I would use for a form:
    val userCheck: Mapping[String] = nonEmptyText.verifying(userExistsConstraint)

    implicit val exampleReads: Reads[ExampleCaseClass] = (
        (JsPath \ "username").read[String] and
        (JsPath \ "somethingElse").read[String]
    )(ExampleCaseClass.apply _)
}

That's as far as I get, but this only ensures that username is a String. How do I apply my additional custom validation rule, e.g. to check if the given user really exists? Is this even possible?
Sure, I could take my obj in the case success section in the action and perform additional checks there, but this doesn't seem very elegant, because then I'd have to create my own error message and could only user JsError.toFlatJson(error) for some cases. After searching and trying for hours I couldn't find any examples.
For regular forms I'd use something like this:
// In the controller object...

val userValidConstraint: Constraint[String] = Constraint("constraints.uservalid")({ username =>
    if (User.find(username).isDefined) {
        Valid
    } else {
        val errors = Seq(ValidationError("User does not exist"))
        Invalid(errors)
    }
})

val userCheck: Mapping[String] = nonEmptyText.verifying(userValidConstraint)

val exampleForm = Form(
    mapping(
        "username" -> userCheck
        // ...and maybe some more fields...
    )(ExampleCaseClass.apply)(ExampleCaseClass.unapply)
)

// In the controller's action method...

exampleForm.bindFromRequest.fold(
    formWithErrors => {
        BadRequest("Example error message")
    },
    formData => {
        // do something
        Ok("Valid!")
    }
)

But what if the data is submitted as JSON?

A: The simplest way I can think of would use the filter method from Reads.
Let's say we have some User object that will determine if the user name exists:
object User {
    def findByName(name: String): Option[User] = ...
}

You could then construct your Reads like this:
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.data.validation._

case class ExampleCaseClass(username: String, somethingElse: String)

object ExampleCaseClass {
    implicit val exampleReads: Reads[ExampleCaseClass] = (
        (JsPath \ "username").read[String].filter(ValidationError("User does not exist."))(findByName(_).isDefined) and
        (JsPath \ "somethingElse").read[String]
    )(ExampleCaseClass.apply _)
}

Your controller function can be simplified using a json BodyParser and fold:
def postNew = Action(parse.json) { implicit request =>
    request.body.validate[ExampleCaseClass].fold(
        error => BadRequest(JsError.toFlatJson(error)),
        obj => {
            // Do something with the validated object..
        }
    )
}

You could also create a separate Reads[String] that will check if the user exists, and explicitly use that Reads[String] within your Reads[ExampleCaseClass]:
val userValidate = Reads.StringReads.filter(ValidationError("User does not exist."))(findByName(_).isDefined)

implicit val exampleReads: Reads[ExampleCaseClass] = (
    (JsPath \ "username").read[String](userValidate) and
    (JsPath \ "somethingElse").read[String]
)(ExampleCaseClass.apply _)


text:
Q: Does android support PBAP bluetooth profile? I'm starting to develop a kind of car infotainment system based on android. The idea is to create a cover ROM for the stock android using a development board.
At first step I'm just playing with basic elemnts, and developing something like a launcher. But now I must starting with something more difficult, bluetooth.
I've done an app based on the bluetooth chat example, so I've got some basics on bluetooth. But still isn't enough for this.
As I see, the bluetooth profile that uses to manage the phone's phone book to see it on the car, is the Phone Book Access Profile (PBAP) which it seems that android doesn't support it. On the developers page:
Known Indirect Subclasses:
BluetoothA2dp, BluetoothGatt, BluetoothGattServer, BluetoothHeadset, BluetoothHealth

But now a days, there a few car companies including android on cars, so, there must be some way to achieve this.
Does someone have the knowledge about this to let me see some light?

A: Up ! Same question...
Maybe investigate those kind of links below :
https://android.googlesource.com/platform/frameworks/base/+/ee0b3e9/core/java/android/bluetooth/BluetoothPbap.java
But I don't really know how to use it for now... still missing some stuff, like the source of the unknown IBluetoothPbap class, at line 71.
JB

A: *

*connect bt over Pbap using api in frameworks/base/core/java/android/bluetooth

*use frameworks/base/core/java/android/bluetooth/BluetoothPbapClient.java methods, these methods call PbapClientService.java api in packages/apps/Bluetooth/src/com/android/bluetooth/pbapclient/

*access contacts simply through the content provider.


text:
Q: Matrix equivalent to linear maps - sanity check I'm reading some Linear algebra notes I found online, and am a bit confused about the following:
If $U,V$ are finite dimensional $\mathbb{C}$-spaces with bases $(\mathbf{u}_1,\dots,\mathbf{u}_m)$ and $(\mathbf{v}_1,\dots,\mathbf{v}_n)$ then there is a correspondence:
$$\mathrm{M}_{n\times m}(\mathbb{C})\longleftrightarrow \mathcal{L}(U,V);\;\;A\longleftrightarrow \alpha\;\text{where}\;\alpha(\mathbf{u}_i)=\sum_j A_{ji}\mathbf{v}_j$$

*

*I'm confused about is the definition of $\alpha$. Why is $\mathbf{u}_i$ being sent to $\left(\mathbf{v}^{\text{T}}\cdot A^{\text{T}}\right)_i?$ (If I am reading that right that is). Why is $\alpha$ acting on $\mathbf{u}$ not the same as $A$ acting on $\mathbf{u}$ i.e. so $\left(A\cdot\mathbf{u}\right)_i$ instead?
Similarly it says that if $\alpha$ is represented by $A$ w.r.t. bases $\{\mathbf{u}_i\},\{\mathbf{v}_j\}$ and $\tilde A$ w.r.t. bases $\{ \mathbf{\tilde u}_i\},\{\mathbf{\tilde v}_j\}$ where $\mathbf{\tilde u}_i=\sum_k P_{ki}\mathbf{u}_k$ and $\mathbf{\tilde v}_j=\sum_k Q_{kj}\mathbf{v}_k$ then:
$$\tilde A=Q^{-1}AP$$

*Again it feels like things are the wrong way around. To me it looks like $P$ takes $\{\mathbf{u}_i\}\to\{\mathbf{\tilde u}_i\}$ and $Q$ takes $\{\mathbf{v}_i\}\to\{\mathbf{\tilde v}_i\}$ (both in a weird transpose/row vector way) but then the expression above suggests the opposite.
I realise this is really basic but I'm having a brain-freeze moment here.

A: Choose bases vectors $(\mathbf{u}_1,\dots,\mathbf{u}_m)$ and $(\mathbf{v}_1,\dots,\mathbf{v}_n)$, then the linear map will be completely determined by where it maps each $\mathbf{u}_i$ to. This can be written in matrix form:
$$\alpha(\mathbf{u}_1 \mathbf{u}_2 \cdots \mathbf{u}_m)=(\mathbf{v}_1 \mathbf{v}_2 \cdots \mathbf{v}_n) \left(\begin{array}{cccc} A_{11} & A_{12} & A_{13} & \cdots & A_{1m} \\ A_{21} & A_{22} & A_{23} & \cdots & A_{2m} \\
\vdots & \vdots & \vdots &\cdots &\vdots \\ A_{n1} & A_{n2} & A_{n3} &\cdots & A_{nm}\end{array}\right)$$
Now general vectors can be written as
$$\mathbf{u}=X_1\mathbf{u}_1+X_2\mathbf{u}_2+\cdots+X_m\mathbf{u}_m=(\mathbf{u}_1 \mathbf{u}_2\cdots\mathbf{u}_m)\left(\begin{array}{c} X_1\\X_2\\\vdots\\X_m\end{array}\right)$$
$$\mathbf{v}=Y_1\mathbf{v}_1+Y_2\mathbf{v}_2+\cdots+Y_n\mathbf{v}_n=(\mathbf{v}_1 \mathbf{v}_2\cdots\mathbf{v}_n)\left(\begin{array}{c} Y_1\\Y_2\\\vdots\\Y_n\end{array}\right)$$
After choosing a basis, the vectors can be identified with the column vectors in $\mathbb{F}^m$ and $\mathbb{F}^n$.
Now, by linearity
$$\alpha(\mathbf{u})=\alpha\left[(\mathbf{u}_1 \mathbf{u}_2\cdots\mathbf{u}_m)\left(\begin{array}{c} X_1\\X_2\\\vdots\\X_m\end{array}\right)\right]$$
$$=(\mathbf{v}_1 \mathbf{v}_2 \cdots \mathbf{v}_n) \left(\begin{array}{cccc} A_{11} & A_{12} & A_{13} & \cdots & A_{1m} \\ A_{21} & A_{22} & A_{23} & \cdots & A_{2m} \\
\vdots & \vdots & \vdots &\cdots &\vdots \\ A_{n1} & A_{n_2} & A_{n3} &\cdots & A_{nm}\end{array}\right)\left(\begin{array}{c} X_1\\X_2\\\vdots\\X_m\end{array}\right)$$
$$=(\mathbf{v}_1 \mathbf{v}_2\cdots\mathbf{v}_n)\left(\begin{array}{c} Y_1\\Y_2\\\vdots\\Y_n\end{array}\right)$$
Hence
$$\left(\begin{array}{c} Y_1\\Y_2\\\vdots\\Y_n\end{array}\right)=\left(\begin{array}{cccc} A_{11} & A_{12} & A_{13} & \cdots & A_{1m} \\ A_{21} & A_{22} & A_{23} & \cdots & A_{2m} \\
\vdots & \vdots & \vdots &\cdots &\vdots \\ A_{n1} & A_{n2} & A_{n3} &\cdots & A_{nm}\end{array}\right)\left(\begin{array}{c} X_1\\X_2\\\vdots\\X_m\end{array}\right)$$
This means $\alpha$ can be represented by a linear map from $\mathbb{F}^m$ to $\mathbb{F}^n$ by the above matrix multiplication.
Now, if we change basis to
$$(\tilde{\mathbf{u}}_1 \tilde{\mathbf{u}}_2 \cdots \tilde{\mathbf{u}}_m)=(\mathbf{u}_1 \mathbf{u}_2 \cdots \mathbf{u}_m)\left(\begin{array}{cccc} P_{11} & P_{12} & P_{13} & \cdots & P_{1m} \\ P_{21} & P_{22} & P_{23} & \cdots & P_{2m} \\
\vdots & \vdots & \vdots &\cdots &\vdots \\ P_{m1} & P_{m2} & P_{m3} &\cdots & P_{mm}\end{array}\right)$$
$$(\tilde{\mathbf{v}}_1 \tilde{\mathbf{v}}_2 \cdots \tilde{\mathbf{v}}_n)=(\mathbf{v}_1 \mathbf{v}_2 \cdots \mathbf{v}_n)\left(\begin{array}{cccc} Q_{11} & Q_{12} & Q_{13} & \cdots & Q_{1n} \\ Q_{21} & Q_{22} & Q_{23} & \cdots & Q_{2n} \\
\vdots & \vdots & \vdots &\cdots &\vdots \\ Q_{n1} & Q_{n2} & Q_{n3} &\cdots & Q_{nn}\end{array}\right)$$
Then
$$\mathbf{u}=(\mathbf{u}_1 \mathbf{u}_2\cdots\mathbf{u}_m)\left(\begin{array}{c} X_1\\X_2\\\vdots\\X_m\end{array}\right)=(\tilde{\mathbf{u}}_1 \tilde{\mathbf{u}}_2 \cdots \tilde{\mathbf{u}}_m)P^{-1}\left(\begin{array}{c} X_1\\X_2\\\vdots\\X_m\end{array}\right)=(\tilde{\mathbf{u}}_1 \tilde{\mathbf{u}}_2 \cdots \tilde{\mathbf{u}}_m)\left(\begin{array}{c} \tilde{X}_1\\\tilde{X}_2\\\vdots\\\tilde{X}_m\end{array}\right)$$
Hence
$$\left(\begin{array}{c} \tilde{X}_1\\\tilde{X}_2\\\vdots\\\tilde{X}_m\end{array}\right)=P^{-1}\left(\begin{array}{c} X_1\\X_2\\\vdots\\X_m\end{array}\right)$$
Similarly,
$$\left(\begin{array}{c} \tilde{Y}_1\\\tilde{Y}_2\\\vdots\\\tilde{Y}_n\end{array}\right)=Q^{-1}\left(\begin{array}{c} Y_1\\Y_2\\\vdots\\Y_n\end{array}\right)$$
In the new basis, $\alpha$ is determined by
$$\alpha(\tilde{\mathbf{u}}_1 \tilde{\mathbf{u}}_2 \cdots \tilde{\mathbf{u}}_m)=(\tilde{\mathbf{v}}_1 \tilde{\mathbf{v}}_2 \cdots \tilde{\mathbf{v}}_n) \left(\begin{array}{cccc} \tilde{A}_{11} & \tilde{A}_{12} & \tilde{A}_{13} & \cdots & \tilde{A}_{1m} \\ \tilde{A}_{21} & \tilde{A}_{22} & \tilde{A}_{23} & \cdots & \tilde{A}_{2m} \\
\vdots & \vdots & \vdots &\cdots &\vdots \\ \tilde{A}_{n1} & \tilde{A}_{n2} & \tilde{A}_{n3} &\cdots & \tilde{A}_{nm}\end{array}\right)$$
Therefore we have
$$\alpha\left((\mathbf{u}_1 \mathbf{u}_2 \cdots \mathbf{u}_m)P\right)=(\mathbf{v}_1 \mathbf{v}_2 \cdots \mathbf{v}_n)Q\tilde{A}$$
$$\alpha(\mathbf{u}_1 \mathbf{u}_2 \cdots \mathbf{u}_m)P=(\mathbf{v}_1 \mathbf{v}_2 \cdots \mathbf{v}_n)Q\tilde{A}$$
$$\alpha(\mathbf{u}_1 \mathbf{u}_2 \cdots \mathbf{u}_m)=(\mathbf{v}_1 \mathbf{v}_2 \cdots \mathbf{v}_n)Q\tilde{A}P^{-1}$$
Therefore,
$$A=Q\tilde{A}P^{-1}$$
or
$$\tilde{A}=Q^{-1}AP$$

A: This system uses row vectors $u = (u_1, \dotsc, u_n)$. Then the definitions look a little bit different than with column vectors $u = (u_1, \dotsc, u_n)^T$, e.g.
$$
x A = y
$$
instead of
$$
A x = y
$$


text:
Q: How to check if some css properties are already set? I need to know if an object has the "left", "right", "top" or "bottom" properties set from an external css file, or not.
I'm tracing the properties after the object is created and chrome returns the value "auto" if the properties are not set and that helps me, but firefox does not. Firefox returns some px values (eg. 0 for left).
Do you know a cross-browser solution?


text:
Q: How to include 'animation.gsap' in scrollmagic using bower TL;DR Has anyone been able to use bower to install ScrollMagic + GSAP animations?
I have a website with the full roots stack (that means that I'm using bower for front-end dependency management and gulp to build the website.) and I'm trying to use ScrollMagic animations on it.
Some of those animation have the greensock library as a pre-requisite. So my bower.json has the following:
  "dependencies": {
    "bootstrap-sass": "3.3.6",
    "gsap": "GreenSock-JS#^1.18.2",
    "scrollmagic": "2.0.5"
  },

If I run gulp and browse my website I can see that there are references in main.js to GreenSock
As per the scrollmagic documentation It seems to me that I'm searching for "plugins/animation.gsap.js" but after reading the the oficial documentation from ScrollMagic....
Option 2: Bower
ScrollMagic is also available on bower and will only install the necessary source code, ignoring all example and documentation files.
Please mind that since they are not core dependencies, you will have to add frameworks like GSAP, jQuery or Velocity manually, should you choose to use them.
So it seems obvious that installing the GSAP library via bower should be enough.
Also I'm not sure if the "gsap plugin" is the same that the "gsap library" but there is nothing else in the bower registry that seems more suited.
Thanks!

A: It seems that ScrollMagic default bower include does not have a way to include the plugins so some overriding is needed.
Anyone should be able to change the included files as explained here:
https://roots.io/using-bootstrap-with-bower-how-to-override-bower-packages/
I've created a minimal working bower.json file as a gist here:
https://gist.github.com/MiquelAdell/9ffc8f1a9973b2308340
I've found my answer thanks to the help of some user from discourse.roots.io The conversation can be found here:
https://discourse.roots.io/t/how-to-include-animation-gsap-to-be-used-in-scrollmagic/5834


text:
Q: Integral expressed as a finite sum of $r_n \zeta(2n+1) \pi^{-(2n+1)}$. The integral
\begin{equation}
I_m=\int_0^1 \frac{x^m-x}{\sin \pi x} \:dx
\end{equation}
is expressed as a finite sum of terms of the shape $r_n \zeta(2n+1) \pi^{-(2n+1)}$, where $r_n$ is a rational number that depends on $n$.
In this question Evaluating $\int_0^1 \frac{x^2-x}{\sin \pi x} dx = - \frac{7 \zeta(3)}{\pi^3}.$ The user "user90369" provided a answer for $I_2$. So I followed his steps and generalized the integral.
Define:
\begin{align}
&f(a) = \int_0^1 x e^{ax} dx= \frac{1+e^a(a-1)}{a^2} \\
&g(a) = \int_0^1 x^m e^{ax} dx = \frac{e^a}{a^{m+1}} \left(  (-1)^mm!  + \sum_{n=1}^{m}  (-1)^{m+n} \frac {a^n}{n!} \right) - \frac{(-1)^mm!}{a^{m+1}}
\end{align}
Rewrite $I_m$ as:
\begin{align}
I_m &= \int_0^1 \frac{x^m-x}{\sin \pi x} = 2i \int_0^1 \frac{x^m-x}{ e^{i\pi x } - e^{-i \pi x} }\nonumber\\
&= 2i \sum_{k=0}^{\infty} \int_0^1 (x^m-x)e^{-i\pi x(2k+1) } dx \\
&= 2i \sum_{k=0}^{\infty} g(-i\pi(2k+1)) - f(-i\pi (2k+1)) \nonumber
\end{align}
From that I arrived at the following formulas for $I_m$.
When $m$ is even and $\geq 2$:
\begin{align*}
I_m =  \frac{4m!i^m}{\pi^{m+1}} \left( 1-\frac{1}{2^{m+1}}\right)  \zeta(m+1) + 2 m! \sum_{n\:odd \geq 0}^{m-2} \frac{i\: \zeta (m-n)}{(n+1)!(i\pi)^{m-n}}   \left(  1-\frac{1}{2^{m-n}} \right)
\end{align*}
When $m$ is odd and $\geq 3$:
\begin{align*}
I_m = 2 m! \sum_{n\:even \geq 0}^{m-2} \frac{i\: \zeta (m-n)}{(n+1)!(i\pi)^{m-n}}   \left(  1-\frac{1}{2^{m-n}} \right).
\end{align*}
A few values for $I_m$:
\begin{align*}
& I_2 = - \frac{7\zeta(3)}{\pi^3} \\
& I_3 = -\frac{21 \zeta(3)}{2\pi^3}\\
& I_4 =  \frac{93\zeta(5)}{\pi^5}-\frac{21\zeta(3)}{\pi^3} \\
& I_5 =  \frac{465\zeta(5)}{2\pi^5} - \frac{35\zeta(3)}{\pi^3} \\
& I_6 = -\frac{1}{2} \left(  \frac{5715\zeta(7)}{\pi^7} - \frac{1395\zeta(5)}{\pi^5} + \frac{105\zeta(3)}{\pi^3}  \right) \\
& I_7 = -\frac{1}{2} \left(  \frac{40005\zeta(7)}{2\pi^7} - \frac{3255\zeta(5)}{\pi^5} + \frac{147\zeta(3)}{\pi^3} \right) \\
&I_8 = \frac{160965\zeta(9)}{\pi^9} - \frac{40005\zeta(7)}{\pi^7} + \frac{3255\zeta(5)}{\pi^5}-\frac{98\zeta(3)}{\pi^3}
\end{align*}
It's also possible to integrate by parts $I_m$. Anyway, I found this integral interesting and wanted to share. Perphaps someone can do something cool with it, or not.
Sorry for the weird/sloppy english.

A: Not an answer but too long for a comment.
This is for sure a very interesting integral.
Just by curiosity, I wondered if the approximation
$$\sin(t) \simeq \frac{16 (\pi -t) t}{5 \pi ^2-4 (\pi -t) t}\qquad (0\leq t\leq\pi)$$  proposed by Mahabhaskariya of Bhaskara I, a seventh-century Indian mathematician, could lead to something simple.
Changing variable $x=\frac y \pi$ and considering
$$\int y^m \csc (y)\,dy \approx \frac{y^m \left(5 m y \, _2F_1\left(1,m+1;m+2;\frac{y}{\pi }\right)-4 m y+5 \pi
   (m+1)\right)}{16 m (m+1)}$$ we can arrive to the incredibly simple result
$$I_m \approx \frac{2 m^2+3 m+5}{16\,m\, (m+1)}-\frac 5 {16} H_m $$
The table below reproduces some values (the so-called exact values being obtained by numerical integration)
$$\left(
\begin{array}{ccc}
 m & \text{approximation} & \text{exact} \\
 2 & -0.270833 & -0.271377 \\
 3 & -0.406250 & -0.407066 \\
 4 & -0.497917 & -0.499007 \\
 5 & -0.567708 & -0.569075 \\
 6 & -0.624256 & -0.625896 \\
 7 & -0.671875 & -0.673782 \\
 8 & -0.713046 & -0.715212 \\
 9 & -0.749330 & -0.751749 \\
 10 & -0.781780 & -0.784444 \\
 20 & -0.995573 & -1.000305 \\
 30 & -1.121081 & -1.127370 \\
 40 & -1.210330 & -1.217854 \\
 50 & -1.279654 & -1.288200 \\
 60 & -1.336350 & -1.345767 \\
 70 & -1.384318 & -1.394494 \\
 80 & -1.425892 & -1.436739 \\
 90 & -1.462578 & -1.474027 \\
 100 & -1.495406 & -1.507399
\end{array}
\right)$$
Edit
More amazing (at least to me) would be
$$I_{m+1}-I_m\approx-\frac{5}{16 m}+\frac{1}{4 (m+1)}-\frac{1}{4 (m+2)}$$


text:
Q: How to append from JSON after filter on key value I have a JSON where I use a jQuery $.each function to append the data to a table. I do an if statement to check if a value matches a string.
In my last table column, I need to get data from another text filter. So if the data value matches my filter, then append it as the last td
dataset = [
  "river": {
    "year": "2016",
    "name": "Silver Creek",
    "series": "Caught fish",
    "weight": "100 kg",

  },
  "river": {
    "year": "2016",
    "name": "Silver Creek",
    "series": "Released fish",
    "weight": "60 kg"
  }
];

$(dataset).each(function(i, data){

  if (data.year === "2016" && data.series === "Caught fish") {
    $('tbody').append('
' + this.year + '	' + this.name + 	' + this.weight +
')
  } if (data.year === "2016" && data.series === "Released fish") {
    $('tr.river').append('' + this.weight + '	')
  }

});

The code above does not do but I want, but may be a hint of what I want to achieve.
What I need as a table row:
YEAR | NAME         | CAUGHT | RELEASED
2016 | Silver Creek | 100 kg | 60 kg

Any suggestions? Could I build a new variable based on the dataset outside the $.each function?

A: Use the :contains selector for released fish to see if the year and waterbody already exist in the table:

var dataset = [
  {"year": "2015","name": "Cedar Creek","series": "Caught fish","weight": "90 kg"},
  {"year": "2016","name": "Silver Creek","series": "Caught fish","weight": "60 kg"},
  {"year": "2015","name": "Cedar Creek","series": "Released fish","weight": "40 kg"},
  {"year": "2016","name": "Silver Creek","series": "Released fish","weight": "60 kg"}
];

dataset.forEach(function(data) {
  if(data.series === 'Caught fish') {
    $('tbody').append('
' + data.year + '' + data.name + '' + data.weight);
  } else {
    $('tr:contains(' + (data.year + data.name) + ')').append('' + data.weight);
  }
});
tr > * {border: 1px solid #ddd;}

YEARNAMECAUGHTRELEASED


text:
Q: In Html page  shows the scroller at 5, but the value field should read a file and print the value which is inside file I am setting up an HTML page for a policy which should read the values of the parameters from the policy page and display it in the browser. Right now I have written a shell script to read and display the value for the parameter I provide.
Now my question is, is it possible to put the same script under "input type=range value='./script'" or do you have any other option to read form the config/policy file.

function resetFunc() {
  document.getElementById("myForm").reset();
}

function checkLength1(elem) {
  if (elem.value > 100) {
    alert('Max value is 100')
    elem.value = '';
  }
}

function checkLength2(elem) {
  if (elem.value > 4) {
    alert('Max value is 4')
    elem.value = '';
  }
}

function readValue() {}

Password policy setting page

    <form id="myForm" align="center">
      Expiry
 <input type="range" name="ExpiryRange" min="0" max="100" value="30" oninput="this.form.ExpiryInput.value=this.value" />

              <input type="number" name="ExpiryInput" min="0" max="100" value="30" oninput="this.form.ExpiryRange.value=this.value" onkeyup="checkLength1(this)" />

 Min.Length

<input type="range" name="MinlenRange" min="0" max="100" value="8" oninput="this.form.MinlenInput.value=this.value" />
      <input type="number" name="MinlenInput" min="0" max="100" value="8" oninput="this.form.MinlenRange.value=this.value" onkeyup="checkLength1(this)" />
 Max.Length

<input type="range" name="MaxlenRange" min="0" max="100" value="60" oninput="this.form.MaxlenInput.value=this.value" />
      <input type="number" name="MaxlenInput" min="0" max="100" value="60" oninput="this.form.MaxlenRange.value=this.value" onkeyup="checkLength1(this)" />
 Lowercase Letter
<input type="range" name="LCRange" min="0" max="4" value="1" oninput="this.form.LCInput.value=this.value"
      />
      <input type="number" name="LCInput" min="0" max="4" value="1" oninput="this.form.LCRange.value=this.value" onkeyup="checkLength2(this)" />
 Uppercase Letter
<input type="range" name="UCRange" min="0" max="4" value="1" oninput="this.form.UCInput.value=this.value"
      />
      <input type="number" name="UCInput" min="0" max="4" value="1" oninput="this.form.UCRange.value=this.value" onkeyup="checkLength2(this)" />
 Digit

<input type="range" name="DRange" min="1" max="4" value="1" oninput="this.form.DInput.value=this.value" />
      <input type="number" name="DInput" min="1" max="4" value="1" oninput="this.form.DRange.value=this.value" onkeyup="checkLength2(this)" />
 Symbol

<input type="range" name="SRange" min="1" max="4" value="1" oninput="this.form.SInput.value=this.value" />
      <input type="number" name="SInput" min="1" max="4" value="1" oninput="this.form.SRange.value=this.value" onkeyup="checkLength2(this)" />

    </form>

    <input type="Submit" align="center" onclick="alert('Success!!!')">
    <input id="reset" onclick="resetFunc()" type="button" value="Reset">


text:
Q: implementation of touch ID in our app Anyone explain replyHandler and InvokeOnMainThread works in this code enter code here. I have copied this code form a sample project I need to implement this thing in my project
partial void UIButton7_TouchUpInside (UIButton sender)
    {
        var context = new LAContext ();

        var error = new NSError ();
        if (context.CanEvaluatePolicy (LAPolicy.DeviceOwnerAuthenticationWithBiometrics,out error)) {
            var replyHandler = new LAContextReplyHandler((success, err) => {
                this.InvokeOnMainThread(() => {
                    if(success){
                        Console.WriteLine("You Logged in");
                    } else {
                        var errorAlertView = new UIAlertView("Login Error", err.LocalizedDescription, null, "Close");
                        errorAlertView.Show();
                    }
                });
            });
            context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, "You need to login", replyHandler);
        }
    }

A: The reply handler is basically a callback to manage feedback when get the result from the touch id.
InvokeOnMainThread is to allow show an ui change when gets this result back. It forces to be on the ui thread to be able to reflect an ui change.


text:
Q: Flutter : How to Check Developer Mode Enable? I currently working to make application attendance prototype, in this application i use google maps flutter. I want check if user enable developer option, because inside this have option to enable mock location. I want add more security to prevent user manipulate his location. If user detected actived developer mode , show dialog to turn off that.
Something Like this :

I have reference to make it with this link , but i'm not familiar with native code .
How can i approach this ?
Thank's.

A: https://github.com/jeroentrappers/flutter_jailbreak_detection
import 'package:flutter_jailbreak_detection/flutter_jailbreak_detection.dart';

bool jailbroken = await FlutterJailbreakDetection.jailbroken;
bool developerMode = await FlutterJailbreakDetection.developerMode; // android only.

thanks to appmire.be

A: Use this plugin https://pub.dev/packages/flutter_jailbreak_detection
This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):
dependencies:
  flutter_jailbreak_detection: ^1.8.0

Import it
Now in your Dart code, and use it:
import 'package:flutter_jailbreak_detection/flutter_jailbreak_detection.dart';

bool jailbroken = await FlutterJailbreakDetection.jailbroken;
bool developerMode = await FlutterJailbreakDetection.developerMode; // android only


text:
Q: PDF file or images for a book in android application i am developing an android book selling application
the problem is that i don't know if i should use the books as a PDF file or as images.
reading of the books will be from inside the application.

A: You should use the .PDF Extension for your Ebook.

Because Images tend to become pixelerated when zoomed to a certain level. Where as PDF preserves the vectors and does not reduce the quality of content (Images, text, etc) when zoomed.
Along with that, PDF is a wrapped collection of all the pages in a single file. Instead of many different image files for a single Ebook.
There are many Open Source Libraries for Rendering PDFs in Android
I have used MuPDF Library for rendering PDF Files in my Android App.


text:
Q: Common 6-wire sockets/connectors I'm currently playing around with some load cells in a wheatstone bridge - each cell has 3 wires (sub-1mm thickness). I want to mount these cells onto 2 separate pieces that can be spaced apart to allow them to fit under different sized objects more easily - so I want to connect the 6 wires on one piece over to the other, 30-60cm away.
I'm looking for a 'standard' connector of some kind that can carry 6 wires to connect one piece to the other, so I can mount a socket onto each piece. I'd like to just buy the wires with connectors already attached, and ideally the sockets will come in a form where I can easily attach the wires to them without having to have a custom board made up or require an expensive crimp tool (I'm not sure the load cell wires would be suitable for crimping anyway).
Any suggestions on common connector format that could work here?

A: Try Molex MiniFit connectors, they are fairly common and easy to work with. If you're looking for something smaller their MicroFit and NanoFit are also good options.

A: Ethernet RJ style jacks and cables are pretty common. Some more than others.
They are called Modular Jacks and Cables.
https://www.mouser.com/Connectors/Modular-Connectors-Ethernet-Connectors/_/N-wos3?Keyword=rj45&FS=True

1m Shielded CAT6 cable may have some benefit in high noise areas.


text:
Q: How can I go about implementing parallel computing in my Python code that can't use " if __name__=='__main__' " I am using MATLAB scripts that have been compiled into a Python library for use in evaluating individuals of a population in a genetic algorithm in Python. I'm really having trouble because the setup of the genetic algorithm doesn't really lend itself to using if __name__=="__main__": and the fitness function is a MATLAB runtime object, which cannot be pickled.
The reason I say that the structure of the code can't use if __name__=="__main__": is because the format looks something like this:
fits = []
# initialize population - needs to be parallized
for individual in population:
    fits.append(matlab_sim_function(individual))

new_fits = []
# New evaluation for loop nested in generational for loop
for generation in range(100):
    trace = []
    # evaluation for loop - this is what needs to be parallized
    for individual in population:
        trace.append(matlab_sim_function(individual))
    new_fits.append(trace)

Essentially, I need to parallize that initialization of the population, then I'd need to parallize the for loop nested in the generational for loop. I'm open to any ideas on how to implement Python parallel computing in this niche scenario I'm in, whether it be possible ways to pickle the MATLAB runtime object or how to structure my code for if __name__=="__main__":, or even if there is a package out there that requires neither.


text:
Q: C++ - How to introduce overload set from variadic number of bases. The derived class hides the name of an overload set from the base class if the derived class has the same name defined, but we can always introduce that overload set back with using-declaration:
template <class BASE>
class A : public BASE
{
public:
  using BASE::some_method;
  void some_method();
}

But what if I introduce all overload sets from variadic base classes?
Would I be able to write something like this?
template <class... BASES>
class A : public BASES...
{
public:
  using BASES::some_method...;
  void some_method();
}

I've considered using a helper class like:
template <class... BASES>
struct helper;

template <>
struct helper<> {};

template <class OnlyBase>
struct helper<OnlyBase> : OnlyBase
{
  using OnlyBase::some_method;
};

template <class Base1, class... OtherBases>
struct helper<Base1, OtherBases> : public Base1, public helper<OtherBases...>
{
  using Base1::some_method;
  using helper<OtherBases...>::some_method;
};

And it does work. But it requires a lot of typing (of course I can use macro but I try to use c++'s compile-time feature whenever possible), and when I want to introduce more methods, i have to change much in that piece of code.
A perfect answer would be a simple syntax, but if there's none, I will go with the helper class.

A: Here is a trick how to reduce handwriting:
// U<X,Y> is a binary operation on two classes
template<template<class,class>class U, class... Xs> struct foldr;
template<template<class,class>class U, class X> struct foldr<U,X> : X {};
template<template<class,class>class U, class X, class... Xs> struct foldr<U,X,Xs...> : U<X, foldr<U,Xs...>> {};

// our operation inherits from both classes and declares using the member f of them
template<class X, class Y> struct using_f : X,Y { using X::f; using Y::f; };

struct A { void f(int) {} };
struct B { void f(char) {} };
struct C { void f(long) {} };

struct D : foldr<using_f, A, B, C> {};

int main() {
    D d;
    d.f(1);
    d.f('1');
    d.f(1L);
    return 0;
}

So we should write foldr once, then write simple ad-hoc operations - using_f, using_g, using_f_g
Maybe there is a way to further simplifying. Let me think a bit...


text:
Q: Split Cell by " - " I have this kind of cell
David - England - 08-01-2016
Fred - England - 07-03-2017
Nova - AS - 25-11-2016

And I want to split cell by the dash and space (" - ") only, so the date or may other words with dash without space ("-") not split.
David  England  08-01-2016
Fred   England  07-03-2017
Nova   AS       25-11-2016

A: This can be done with Power Query, a free Microsoft add-in for Excel 2010 and 2013 and built into Excel 2016 / 365 as Get and Transform.
Split column by delimiter, set a custom delimiter " - " (space dash space) as the delimiter.
The date will remain unaffected, because the delimiter is not space dash space.


text:
Q: Sort dict of dict by two values of sub dicts I have the following code:
from collections import OrderedDict

test_dict = {'test1':{'key1': 'dog', 'key2': 'dennis', 'key3': 'bbb'},
             'test2':{'key1': 'apple', 'key2': 'arthur', 'key3': 'fff'},
             'test3':{'key1': 'bear', 'key2': 'bernard', 'key3': 'xxx'},
             'test4':{'key1': 'elephant', 'key2': 'eric', 'key3': 'rrr'},
             'test5':{'key1': 'cat', 'key2': 'charlie', 'key3': 'lll'}
             }

sorted_dict = OrderedDict(sorted(test_dict.items(), key=lambda i: i[1]['key1'][1]['key3']))

for key, value in sorted_dict.items():
    print(key, value)

This generates the error:
TypeError: string indices must be integers

However if I amend as so:
sorted_dict = OrderedDict(sorted(test_dict.items(), key=lambda i: i[1]['key1']))

...it will sort the sub dicts in order successfully by key1 only. However, I want to sort by key1 and key3. What do I need to change?

A: This method you can sort a list by several attributes

Sorting by two keys uses two methods of comparison to sort elements in a collection

sorted_dict = OrderedDict(sorted(test_dict.items(),key=lambda i:(i[1]["key1"],i[1]["key3"])))

for key, value in sorted_dict.items():
    print(key, value)

output :
test2 {'key1': 'apple', 'key2': 'arthur', 'key3': 'fff'}
test3 {'key1': 'bear', 'key2': 'bernard', 'key3': 'xxx'}
test5 {'key1': 'cat', 'key2': 'charlie', 'key3': 'lll'}
test1 {'key1': 'dog', 'key2': 'dennis', 'key3': 'bbb'}
test4 {'key1': 'elephant', 'key2': 'eric', 'key3': 'rrr'}

A: In your snippet, notice this line:
sorted_dict = OrderedDict(sorted(test_dict.items(), key=lambda i: i[1]['key1'][1]['key3']))

Here, test_dict.items() returns a dict_item object containing a list of tuples of key-value pairs. In your case, the keys are strings and the values are dicts. So in the lambda expression, when you select i[1]['key1'] you're already getting the string value attached to that key. So when you're trying to access i[1]['key1'][1]['key3'], you're trying to access key3 value from a single character. Hence the TypeError.
The fix is easy, the lamda expression in sorted can return multiple values and they'll be used to sort your target dict.
sorted_dict = OrderedDict(
    sorted(test_dict.items(), key=lambda i: (i[1]["key1"], i[1]["key3"]))
)

Also, if you're using Python 3.7 and up, you don't actually need the OrderedDict as the native dictionary retains the order of the keys. This is also valid:
sorted_dict = dict(sorted(test_dict.items(), key=lambda i: (i[1]["key1"], i[1]["key3"])))

It'll print the following:
test2 {'key1': 'apple', 'key2': 'arthur', 'key3': 'fff'}
test3 {'key1': 'bear', 'key2': 'bernard', 'key3': 'xxx'}
test5 {'key1': 'cat', 'key2': 'charlie', 'key3': 'lll'}
test1 {'key1': 'dog', 'key2': 'dennis', 'key3': 'bbb'}
test4 {'key1': 'elephant', 'key2': 'eric', 'key3': 'rrr'}


text:
Q: regex to replace all tokens not in quotes? I am trying to process some input data in JavaScript whereby I need to replace the occurrences of all string tokens (in the form "ID1", "ID2", "ID3", ...) with a string that  wraps the original token. For example "ID1" becomes "table['ID1']". However if the original token is wrapped in quotes (single or double) it must be ignored.
For example the input string:
var input = "ID10 \"ID0\" FOO 'ID0' #ID0# ID10 BAR ID1 ID0.";

should become:
"table['ID10'] \"ID0\" FOO 'ID0' #table['ID0']# table['ID10'] BAR table['ID1'] table['ID0']."

I can currently get some of the way using the following code (Try it on jsbin.com here):
var input = "ID10 \"ID0\" FOO 'ID0' #ID0# ID10 BAR ID1 ID0.";

var expected = "table['ID10'] \"ID0\" FOO 'ID0' #table['ID0']# table['ID10'] BAR table['ID1'] table['ID0'].";

// assume 15 is the max number of ids. we search backwards.
for( i=15 ; i>=0 ; i-- )
{
    var id = "ID" + i;

    var regex = new RegExp( "[^\"\']" + id + "", 'g' );

    input = input.replace( regex, "table['" + id + "']" );
}

if( input == expected )
    alert( 'success :)' );

This produces the output:
ID10 "ID0" FOO 'ID0' table['ID0']#table['ID10'] BARtable['ID1']table['ID0'].

It seems close to working, however the first id (ID10) gets ignored and the first character before a match gets lost.
Can anybody please advise how to process this correctly, thanks.

A: I think you're going to need a negative lookahead token.
Take a look here
The whole regex is
(ID\d+(?!\\))

The negative lookahead is the (?!...). It just asserts that the next character after the digits is not a backslash
So the code would be something along the lines of
var re = /(ID\d+(?!\\))/g;
var str = 'ID10 \"ID0\" FOO \'ID0\' #ID0# ID10 BAR ID1 ID0.';
var subst = 'table[\'$1\']';
var result = str.replace(re, subst);
// table['ID10'] \"ID0\" FOO 'table['ID0']' #table['ID0']# table['ID10'] BAR table['ID1'] table['ID0'].

A: You can use this regex based on alternation in String#replace with a callback function:
var input = "ID10 \"ID0\" FOO 'ID0' #ID0# ID10 BAR ID1 ID0.";
var r= input.replace(/"[^"]*"|'[^']*'|(ID\d+)/g, function($0, $1) {
       return ($1)? "table['"+$1+"']" : $0;});
//=> table['ID10'] "ID0" FOO 'ID0' #table['ID0']# table['ID10'] BAR table['ID1'] table['ID0'].

A: Edit it seems that zero-width negative look-behind is no supported in Javascript, so you need a zero-width negative look-ahead to check the next character after the ID plus digits is not either backslash, single or double quotes.
you could try
/(ID\d+(?![\\\'\"]))/g

EDIT Forget all this!
You need a zero-width negative look-behind
you could try
/(?<![\"\'])ID\d+/g

alternatively, you might try to capture your match in a group
/[^\"\'](ID\d+)/g