text:
Q: how to get custom post type by user id/author so, i've custom post type 'pelajaran'. and I made the select option (location and subjects) search for custom post type.
I took the data (location + subjects) and the value from the user. this my code for select option
$query      = get_users('role=GURU&order=ASC&orderby=meta_value&meta_key=address');

<select name="location">
           <option>Location</option>
                <?php foreach ($query as $q) {
                $address = get_the_author_meta('address', $q->ID); ?>
           <option value="<?php echo $q->ID; ?>"><?php echo $address; ?></option>

                <?php } ?>
 </select>

when the results came out, because the value of the id of the user. whether it can retrieve the data of custom post type from user id / author?
this my code for the result, on another page :
<?php
    global $current_user;
    get_currentuserinfo();

    $location = "";
    if (isset($_POST['location'])) {
        $location = $_POST['location'];
    }

    $args = array (
        'post_type' => 'pelajaran',
        'author'        =>  $current_user->ID,
        'posts_per_page'    => -1,
    );

    $pelajaran = get_posts($args);

    for($i=0;$i<sizeof($pelajaran);$i++) { ?>

     <?php if($location == $pelajaran[$i]->ID )
    echo ' '; //some my code html here

      ?>

 <?php } ?>

but, I still can not display the post data type of user id / author.
anyone can help me?
thanks in advance :)


text:
Q: How to refresh the contents of a linked folder in Tomcat 8 I have created a Webapp that requires external images.
I achieved that by creating a shortcut of the extFolder in the eclipse project folder (WebContent/Web/images/extFolder).
Now when a user tries to upload a new picture, after the upload the old picture is shown and new one won't show until I restart the webapp.
a. Is there a better way to add an external folder in Tomcat 8
b. If no then can the Webapp refresh that directory to incorporate the changes?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Update Swing JProgressBar in Java I'm really new to Java, especially working with GUI in Java.
I want to put a progress bar in my program, where it updates its value each time after certain amount of work has been done. Right now I have a button that executes a method when pressed, and I put setValue() function (with the value that I want) each time after certain work has been done in that method. However, when I press the button, the button seems to be stuck pressed while the method continues (the method takes a while to finish executing), and the progress bar doesn't get updated until all the other things has been done in the ButtonListener, so it goes directly to 100% after it's done).
What am I doing wrong?
Thanks in advance.

A: That is, most probably, because you are doing all work in main thread so it hangs your UI until all work is done. You should not do this. You should use separate EDT for such operations. What you should try is do your update progressBar job in separate EDT. Use SwingUtilities.invokeLater(Runnable r) for this.


text:
Q: .htcaccess blocking cron request? I set up my IX Webhosting to conduct the following cronjob every 15 minutes.
usr/bin/wget -O- http://xxx.com/php/xxx.php

I want the php folder to be blocked off from all outside requests for security reasons, so I set the .htaccess file to deny from all. But when the .htaccess file is present the cron job is denied with a 403 error.
I thought that server-side cronjobs are not blocked by .htaccess? Is there any way to get around this?

A: This is still a web request from localhost, since wget is a regular HTTP client requesting the page, and the web server is serving it (even though it may produce no output for humans to read). Instead of denying all, allow localhost:
Order deny,allow
Allow from 127.0.0.1
Deny from all

A: You can add something like:
Order deny,allow
Allow from 192.168.0.1/24
Allow from 127
Deny from all

in your .htacces to allow access from local intranet IP (192.168.0.1/24) and localhost IP i.e. 127.0.0.1

A: Change the cron job to:
/usr/bin/php /path/to/web/root/php/greader_forceupdate.php xxxx

/usr/bin/php may need to be adjusted if PHP is installed elsewhere.
/path/to/web/root is the path on the filesystem.
To access the parameter, use $_SERVER['argv'][1].


text:
Q: MATLAB: Why is double looping so much slower than squaring? I wonder why it is faster to square a matrix with the A2=A^2 command (A being a LxL matrix) than to just do a double for loop and assign the value to a zeroed matrix.
I have run the following code to check the first case
tic
psi2=psi.^2;
T1=toc;

and the following for the second
psi2=zeros(L,L);
tic
for i=1:L
    for j=1:L
        psi2(i,j)=psi(i,j)^2;
    end
end
T2=toc;

In this figure the elapsed time for several matrices sizes (L) are shown and the speedup is clear.
I would not be surprised to see that MATLAB has a very efficient implementation of matrix multiplication as it what is it made for, but I can't understand how there's a faster way to do element-wise operations than just looping over it.
Thanks for time.

A: There are several things that make the vector operation faster than your loop.
First, a loop compiled into C++ code is faster than a script loop which is interpreted / converted and compiled as Java.
Secondly, the C or C++ compiler can use Single Instruction, Multiple Data instructions (SIMD) to do the operation on multiple matrix elements in a single operation.  And then do this in multiple threads.
Finally, it's possible to push the operation to the GPU which can process even more elements simultaneously (hundreds of cores, compared to 4-8 on the CPU).  Your scripted loops cannot do this.

A: .^2 take the advantage of doing parallel operation using CPU. For a nested loop (double loop) solution, the entire solution is done in sequence. In addition it also have over head to increment of the loop control variable and condition checking.


text:
Q: Salesforce chatter Feed Item attachment download - Trigger I need to run a trigger when user download the attachment from Chatter feed item.
Use case: When user clicks on "Download" link on feed item attachment and downloads successfully, need to run a trigger that executes document locking (i.e., Document is locked for editing and no other user can download or upload new version until user unlocks it).
Is there any way to run trigger, when user clicks on "Download" link in feed item attachment, as show in below screen shot? Any inputs on this.
I tried googling it and gone through salesforce guide, but couldn't find a way to do it.

Thanks in Advance.


text:
Q: Concatenate data into one variable An XML file has data like:
<AddtlStsRsnInf>/00000002/Level 2 Reject</AddtlStsRsnInf>
<AddtlStsRsnInf>The Transaction Reference Number is</AddtlStsRsnInf>
<AddtlStsRsnInf>not unique.</AddtlStsRsnInf>

How do you concatenate the data from all the three tags into a variable?
Thanks and regards,
Kiran

A: This may help:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template name="concat" match="/data">
  <xsl:for-each select="AddtlStsRsnInf">
    <xsl:value-of select="." />
    <xsl:if test="position() != last()">
      <xsl:text> </xsl:text>
    </xsl:if>
  </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Given:
<?xml version="1.0"?>
<data>
<AddtlStsRsnInf>/00000002/Level 2 Reject</AddtlStsRsnInf>
<AddtlStsRsnInf>The Transaction Reference Number is</AddtlStsRsnInf>
<AddtlStsRsnInf>not unique.</AddtlStsRsnInf>
</data>

You can wrap it in a variable (v) using:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template name="concat" match="/data">
  <xsl:variable name="v">
    <xsl:for-each select="AddtlStsRsnInf">
      <xsl:value-of select="." />
      <xsl:if test="position() != last()">
        <xsl:text> </xsl:text>
      </xsl:if>
    </xsl:for-each>
  </xsl:variable>

  <xsl:value-of select="$v" />
</xsl:template>

</xsl:stylesheet>

A: I think you would use something like:
<xsl:variable name="myVar" select="fn:string-join(//AddtlStsRsnInf/text(), ' ')" />

You'll need to adjust the XPath query if you're only supposed to select some AddtlStsRsnInf nodes.


text:
Q: Scraping a specific table on webpage but coming up empty every time Apologize for the simple question but this is my first time using StackOverflow.
I am trying to scrape the table within "table class="RankingListGrid" inside the body of the url:
https://www.badmintonplayer.dk/DBF/Ranglister/
The xpath is //*[@id="PanelResults"]/table
The selector is #PanelResults > table
But regardless of what and which method I try - I come up empty. Having watched a number of instruction videos I am getting a bit desperate. Any suggestion or hint would be much appreciated. Thanks in advance

A: As Costaparas mentioned it would be great to get a minimal working example --actually it is not clear what you ar working with,...
Let´s take a look at the following solution / working example:
Cause the website is loading the table and it´s contents dynamically I use Selenium and wait in this simple approach that page is loaded with sleep.
from selenium import webdriver
from time import sleep

url = 'https://www.badmintonplayer.dk/DBF/Ranglister/'

browser = webdriver.Chrome(executable_path=r'C:\Program Files\ChromeDriver\chromedriver.exe')
browser.get(url)

sleep(3)

table=browser.find_element_by_xpath('//*[@id="PanelResults"]/table').get_attribute('innerHTML')
print(table)

browser.close()

Output:

Plac.	BadmintonID	Navn	Række	Point

1	940104‑12	Viktor Axelsen, Skovshoved	SEN E	4803

2	940424‑10	Robin Tabeling (EU), Skagen	SEN E	4714

3	800711‑01	Mathias Boe, Odense OBK	SEN E	4705

4	920306‑08	Kim Astrup Sørensen, Skælskør	SEN E	4694

...


text:
Q: Implementation of FITC approximation for Gaussian Processes I'm attempting to use Gaussian processes for classification. When using a large number of observations, sparse approaches are used to deal with the scalability issue of O(N^3). Sparse approaches typically reduce the computation cost to O(N*M^2).
Currently I'm trying to implement the code provided in the pyGPs python package: https://github.com/marionmari/pyGPs. However I'm finding the computation cost is not being reduced.
In the following example I use an built sklearn function to generate some data to implement classification. X and y correspond to the features and class labels restively. There are 10000 observations and the features have dimension 10. I then split the data into train and test data.
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import pyGPs
import sklearn
from sklearn.datasets import make_classification
%matplotlib inline

n_generate = 10000
n_feature = 10
X, y = make_classification(n_generate, n_feature)
for i in range(n_generate):
    if y[i] == 0:
        y[i] = -1

X_train = X[0:int(n_generate/2.0),]
y_train = y[0:int(n_generate/2.0)]
X_test = X[int(n_generate/2 + 1):n_generate]
y_test =    y[int(n_generate/2 + 1):n_generate]

I try to use the pyGPs package to apply Gaussian processes to this process as follows:
 model = pyGPs.GPC_FITC()
 model.setData(X_train, y_train)
 model.optimize()
 model.predict(X_test)

However the computation time is taking too long. Has anyone experience using this package to speed up computations?

A: The number of inducing points is $5$ along each input dimension by default. So you have $5^{10} \approx 10^7$ inducing points, so you have to do inference with sample size $10^7$ - so no speedup.
You can speed up your inference in two ways:

*

*specify different number of inducing points along each dimension. If you use $2$ instead of $5$ you will get $2^{10} = 1024$ points. In this case use

model.setData(X_train, y_train, value_per_axis=2)

*

*set inducing points manually. For example, select $100$ or $1000$ points from your initial sample at random. In this case instead of model.setData use

model.setPrior(inducing_points=None)

A: Now I introduce my own inducing points as follows:
n_inducing_points = 10
Inducing_points = np.zeros((n_inducing_points, n_feature))
for i in range(n_feature):
Inducing_points[:,i] = np.linspace(min(X_train[:, i]), max(X_train[:,    i]), n_inducing_points)

This is a matrix of 10 x n_feature (10 inducing points) and I use the code:
model = pyGPs.GPC_FITC()
model.setData(X_train, y_train)
model.setPrior(inducing_points = Inducing_points)
model.optimize()

This does not compute in a reasonable time at all. Compare this to :
model = pyGPs.GPC_FITC()
axis_induce_points = 2
model.setData(X_train, y_train, value_per_axis = axis_induce_points )
model.optimize()

The second code implements fast where I now have 2^10 inducing points.
Can you explain where I'm going wrong. The first should have 10 and doens't run, but the second runs with 1000 inducing points. Thanks in advance.


text:
Q: Mass Action not sending all data I've created a mass action for my custom grid. i've encountered a weird problem which is when i check all the checkboxes, it won't send any post id data when i try to retrieve it with:
$this->getRequest->getParams();

but when i don't check all of them, it will send all the data that has been checked, here's my mass action code in xml:
<massaction name="listing_massaction">
  <action name="test">
    <argument name="data" xsi:type="array">
      <item name="config" xsi:type="array">
          <item name="type" xsi:type="string">test</item>
          <item name="label" xsi:type="string" translate="true">Test</item>
          <item name="url" xsi:type="url" path="namespace_module/test/massTest"/>
      </item>
    </argument>
  </action>
</massaction>

MassTest.php:
use Magento\Backend\App\Action\Context;
use Magento\Ui\Component\MassAction\Filter;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;

class MassTest extends \Magento\Backend\App\Action
{

   public function __construct(
       Context $context,
       Filter $filter,
       \Namespace\Module\Model\ResourceModel\Test\CollectionFactory $collectionFactory
   ) {
       $this->filter = $filter;
       $this->_listingProduct = $listingProduct;
       $this->_collectionFactory = $collectionFactory;
       parent::__construct($context, $filter);
   }

   public function execute(){
     //$collection = $this->filter->getCollection($this->_collectionFactory->create()); // get your selected collection
     //$collectionSize = $collection->getSize();
     //echo $collectionSize;
     $data = $this->getRequest()->getParams();
     print_r($data['selected']);
     exit;
   }

   /**
    * @param AbstractCollection $collection
    * @return \Magento\Backend\Model\View\Result\Redirect
    */
   protected function massAction(AbstractCollection $collection)
   {

   }

}

A: I spent a lot of time trying to understand, what is wrong with my code, and why Magento does not send selected parameter with ids in POST request, when mass action is called. Later I found this "feature":
if you have 1 item in list of items, mass action does not send any data. You must have at least 2 items in list, and then selected parameter will exists in POST request and will consists of selected ids.
I have it in Magento 2.1.6.

A: You can try the below code for new way to get the filter or selected collection from the list you selected from your grid.
<?php

namespace Namesapce\Modulename\Controller\Adminhtml\Module;

use Magento\Framework\Controller\ResultFactory;

class MassDelete extends \Magento\Backend\App\Action {

    /**
     * @var \Magento\Ui\Component\MassAction\Filter
     */
    protected $filter;

    /**
     * @var \Namesapce\Modulename\Model\ResourceModel\ModuleModel\CollectionFactory
     */
    protected $_collectionFactory;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\Ui\Component\MassAction\Filter $filter
     * @param \Namespace\Modulename\Model\ResourceModel\ModuleModel\CollectionFactory $collectionFactory
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Ui\Component\MassAction\Filter $filter,
        \Namespace\Modulename\Model\ResourceModel\ModuleModel\CollectionFactory $collectionFactory
    ) {

        $this->filter = $filter;
        $this->_collectionFactory = $collectionFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $collection = $this->filter->getCollection($this->_collectionFactory->create()); // get your selected collection
        $collectionSize = $collection->getSize();

        foreach ($collection as $item) {
            $item->delete(); // Do the stuff you wann to do
        }

        $this->messageManager->addSuccess(__('A total of %1 record(s) have been deleted.', $collectionSize));

        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        return $resultRedirect->setPath('*/*/');
    }
}

A: Please check it
app/code/Company/Module/view/adminhtml/ui_component/company_module_grid.xml
...
<massaction name="listing_massaction">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="selectProvider" xsi:type="string">company_module_grid.company_module_grid.company_module_columns.ids</item>
                    <item name="indexField" xsi:type="string">id</item>
                </item>
            </argument>
            <action name="delete">
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="type" xsi:type="string">delete</item>
                        <item name="label" xsi:type="string" translate="true">Delete</item>
                        <item name="url" xsi:type="url" path="routername/controllername/massDelete"/>
                        <item name="confirm" xsi:type="array">
                            <item name="title" xsi:type="string" translate="true">Delete items</item>
                            <item name="message" xsi:type="string" translate="true">Are you sure you wan't to delete selected items?</item>
                        </item>
                    </item>
                </argument>
            </action>
</massaction>
...

Controller File
app/code/Company/Module/Controller/Adminhtml/Controllername/MassDelete.php
<?php
namespace Company\Module\Controller\Adminhtml\Controllername;

use Magento\Backend\App\Action\Context;
use Magento\Ui\Component\MassAction\Filter;
use Company\Module\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\Controller\ResultFactory;

/**
 * Class MassDisable
 */
class MassDelete  extends \Magento\Backend\App\Action
{
    /**
     * @var Filter
     */
    protected $filter;

    /**
     * @var CollectionFactory
     */
    protected $collectionFactory;

    /**
     * @param Context $context
     * @param Filter $filter
     * @param CollectionFactory $collectionFactory
     */
    public function __construct(Context $context, Filter $filter, CollectionFactory $collectionFactory)
    {
        $this->filter = $filter;
        $this->collectionFactory = $collectionFactory;
        parent::__construct($context);
    }
    /**
     * Execute action
     *
     * @return \Magento\Backend\Model\View\Result\Redirect
     * @throws \Magento\Framework\Exception\LocalizedException|\Exception
     */
    public function execute()
    {
        $collection = $this->filter->getCollection($this->collectionFactory->create());
        $collectionSize = $collection->getSize();

        foreach ($collection as $item) {
            $item->delete();
        }

        $this->messageManager->addSuccess(__('A total of %1 record(s) have been deleted.', $collectionSize));

        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        return $resultRedirect->setPath('*/*/');
    }
}

Company\Module\Model\ResourceModel\Product\CollectionFactory; Please add appropriate extension factory class in about file.


text:
Q: Combine asp-route-id with asp-route-all-data Is there any way to make this work?
Action

This generates the following link:
sitename.com/controller/action?parm1=parm1&parm2=parm2

etc.  I want it to generate this:
sitename.com/controller/action/{id}?parm1=parm1&parm2=parm2

It seems as though you cannot combine the route-id with asp-route-all-data.  It is a link on a table and so my ID changes with each row, the rest of the filters (searchstrings, pages, sorts, etc) do not change.  Would save a lot of copying and pasting if this would work.
While writing this I realized I could probably make a Viewmodel with a Dictionary of items AND an IEnumerable of my Model, rather than just using my model as is.  Is there any other (simpler) way of making this work?

A: Putting the "asp-all-route-data" attribute before "asp-route-id" solves the problem.
Action

And generates the following link:
sitename.com/controller/action/{id}?parm1=parm1&parm2=parm2


text:
Q: $\sum_{n=1}^{\infty}f(z^n)$ converges uniformly with $f$ holomorphic
Let $f$ be an holomorphic function on the unit ball with $f(0)=0$.
  Prove that $\sum_{n=1}^{\infty}f(z^n)$ is uniformly locally
  convergent in the unit ball.

My attemp:
It is suffice to prove that $\sum_{n=1}^{\infty}f(z^n)$ converges uniformly  in any $\overline{B_0(r)}$ with $r<1$.
$f'$ is also an holomorphic function, defined on a compact set and therfore bounded. Let's say $|f'|\leq M$. Then, for every $z\in \overline{B_0(r)}$, $|f(z^n)-f(0)|\leq M|z^n-0|$, $|f(z^n)|\leq M|z^n| = M|z|^n \leq Mr^n$.
The series $\sum_{n=1}^{\infty}r^n$ converges and therefore by the M test our series converges uniformly. Is it correct?
Thanks.

A: Let's do brute force!
If $f(z)=\sum_{n\geq1}a_nz^n$, then as a formal series $$\sum_{k\geq1}f(z^k)=\sum_{n\geq1}\left(\sum_{d\mid n}a_d\right)z^n.$$ If $f$ converges in the unit disc, we know from the Cauchy-Hadamard formula that $\limsup_{n\to\infty}|a_n|^{1/n}\leq1$, and we have to show that then $$\limsup\left|\sum_{d|n}a_d\right|^{1/n}\leq1.$$ One should be able to prove that

If $(x_n)_{n\geq1}$ is a sequence of non-negative real numbers such that $\limsup_{n\to\infty}x_n^{1/n}\leq1$, then $\limsup_{n\to\infty}(x_1+\cdots+x_n)^{1/n}\leq 1$.

and using this our result follows.

A: The answer is no because $M$ depends on $r$ as $M:=\max \{|f'(z)|: z \in \overline{B_0(r)} \}.$


text:
Q: Java JIT a static non-volatile value changed , the access loop becomes a hundred times longer There is a branch judgment on a non volatile static bool value in the loop. When the bool value is modified by other threads, the execution time of the whole loop becomes a hundred times longer, and jstack shows that the thread runs on the line acces
sample:
package test;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

public class StaticTest {

    static boolean tag = true;

    static HashSet<Integer> set = new HashSet<>();

    static boolean getTag(int i) {
        if (!tag) {
            return set.contains(i);
        }
        return true;
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 225 * 225 * 4; i++) {
            set.add(ThreadLocalRandom.current().nextInt(0, 225 * 225 * 4));
        }

        Thread.sleep(5000);
        for (int i = 0; i < 128; i++) {
            Thread t = new Thread(() -> {
                while (true) {
                    long start = System.currentTimeMillis();
                    HashMap<Integer, Boolean> iMap = new HashMap<>();
                    for (int j = 0; j < 225 * 225 * 4; j++) {
                        if (getTag(j)) {
                            iMap.put(j, true);
                        } else {
                            iMap.put(j, false);
                        }
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
        }

        Thread.sleep(TimeUnit.MINUTES.toMillis(3));
        tag = true;
        System.out.println(new Date(System.currentTimeMillis()));
        while (true) {
            Thread.sleep(10000);
        }
    }
}

A: Correct benchmarking comes a bit short here, it seems.
The slow-down could very well be the set.contains(i) call, but it might also be a case  of deoptimization. Besides volatile you might consider one of the following.
I assume optimized usage is not the primary goal of the question, but one should nevertheless consider the data structures.
static BitSet set = new BitSet(225 * 225 * 4);

                BitSet iMap = BitSet(225 * 225 * 4);
                for (int j = 0; j < 225 * 225 * 4; j++) {
                    iMap.set(j, getTag(j);
                }

Or maybe best, if the result is not tri-state (false, true, null), or whether null can be reconstructed:
                Set<Integer> iNot = new HashSet<>();
                for (int j = 0; j < 225 * 225 * 4; j++) {
                    if (!getTag(j)) { // Most unlikely
                        iNot.add(j);
                    }
                }


text:
Q: Excel VBA, over flow error I am using VBA in my excel sheet and it gives me an overlfow error. When I checked I found out that it was related to data error which shows unilmited "#" character in one cell.
All values in each cell is assigned to a string variable and when this cell comes in generates an overflow error. I tried to validate this using an if condition, but whenever we check cell.value this generates an overflow error. Is there any way to fix this?

A: You will not get a runtime error if you just read the cell text:
s = Range("C2").Text
Debug.Print s
' returns: "###########"

If you really want to read the cell value, and not the cell text (why you would need this, I have no idea, since you're stuffing it in a String anyway) then this is a workaround, assuming the #### are caused by dates Jan 1, 10,000 AD or later.
Const MaxDateSerial As Double = 2958466
Dim s As String
Dim dbl As Double
Dim nf As Variant

' Save original number format
nf = Range("C2").NumberFormat

' Use read-safe number format to read cell content
Range("C2").NumberFormat = "General"
dbl = Range("C2").Value

' Restore original number format
Range("C2").NumberFormat = nf

If dbl < MaxDateSerial Then
    s = Range("C2").Value
Else
    s = "Date overflow!"
End If

A: If you are doing something like
Dim s as string
Dim cl as Range
...
s = cl
' or
s = cl.value

s will be set to the value as diplayed on the sheet, which includes an error
(in the form "Error <Error Code>" if that's what the sheet displays
If the underlying cell value is valid, you should be able to access if using cl.value2
If you are doing somthing like
Dim v as Variant
Dim s as string
Dim r as Range
...
Set r = <SomeRange>
v = r
...

And one or more cells in range r are an error, then Runtime Error 6 Overflow will occur
To advise further, please post details of the code, where the error occurs, cell value and cell formatting
The ############### display for dates occurs if the date serial is before 1/1/1900 (negative) or after 1/1/9999 (> 2958101) EDIT actually 31/12/9999 = 2958465

A: Try using the "ISERROR()" function to filter out the invalid values.
IF(ISERROR(A1),0,A1)


text:
Q: How to use negative globs in Perl /usr/bin/sec  --input=/var/log/remote/mail-today/*=FILEEVENT_MAIL
So i'm using an event correlator, in order to select the files for input. /var/log/remote/mail-today/* is the 'glob' string that allows for files to be selected.
But in this directory there are a number of files, i'd only like to select the non-tarred files:
file1.gz
file2.gz
file3.gz
file4
file5
file6
I was wondering whether it was possible to do a negative glob.


text:
Q: Bash 1 liner: How to make a directory for each hour, 00 to 23? A process will be writing to a set of directories, one for each hour using date +%H notation, so 00, 01, 02... 22, 23.  I'm wanting to keep the leading 0 on single digit hours to keep sorted listings tidy.
I=00; until [ $I -gt 23 ]; do mkdir $I; let I=I+1; done
Has predictable effects of not keeping a leading 0 before the single digits.  I could just go and make them by hand, but feel there should be a way to do this.  Any ideas?

A: for i in `seq -w 00 23`;do mkdir $i;done

A: Here's a completely portable answer (to any Bourne-derived shell on pretty much any system that can run one of those), whereas all the other answers are at least a little non-portable, either rely on non-portable shell constructs or seq, which is common but neither in POSIX nor universal:
# start with a blank/clean "dirs" variable
dirs=
# iterate over the first digit
for i in 0 1 2
do
    # ..and the second digit for each first digit
    for j in 0 1 2 3 4 5 6 7 8 9
    do
        # add each digit combination to the dirs list
        dirs=$dirs\ $i$j
        # ..until we reach 23 - then we're done.
        case $i$j in 23) break 2; esac
    done
done
# finally make the directories
mkdir $dirs

Some notes:
Creating dirs initially ensures we don't accidentally use the value of an environment variable named dirs, in case we inherit one.
We could actually skip building the $dirs variable, and just call mkdir $i$j. But this way performs better (one mkdir process launched instead of 24) and is just as portable (if by some chance there's really a system out there were mkdir can only take one directory argument*, this is easy to adapt to call mkdir for each $i$j combination instead of building a $dirs variable).
The lack of quoting everywhere is both intentional and correct. Substitutions do not need to be quoted inside variable assignments and in the first part of the case statement: they don't undergo field splitting in those spots. And in the mkdir line at the end, we're relying on the field splitting to separate the directory list into separate names/arguments for mkdir.
* "Officially" MS-DOS and Windows has a mkdir which only takes one directory name, but at least on Windows 7 it works with multiple directory names, plus any port of a Bourne-like shell to those systems that I know of comes with it's own mkdir, and only weirdos like me would even think about that level of portability.

A: mkdir {0{0..9},{10..23}}

Or in Bash 4:
 mkdir {00..23}

A: mkdir $(seq -w 00 23)


text:
Q: sql Dependency detect changes of records and send message to clients I am trying to use sql Dependency to check that a table data has been changed by other clients I followed the turotial here but when I try to create the queue i get the following error message this is my c# code and sql statement.
Edit 1
Sorry I forgot to include the tutorial in my first post here is the link in the tutorial it states quename but does not say how to ccreate it.
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/detecting-changes-with-sqldependency

CREATE QUEUE ExportedOrdersChangeMessage   CREATE SERVICE
  ExportedOrdersService ON QUEUE ExportedOrdersChangeMessage
  ([http://schemas.microsoft.com/SQL/Notification/PostQueryNotification])

The error I receive after running the above is the following.

Msg 15151, Level 16, State 1, Line 5
  c'http://schemas.microsoft.com/SQL/Notification/PostQueryNotification',
  because it does not exist or you do not have permission.

Basically what I want to be able to do is if a user is atempting to change a record I want to send a notification to the other clients. Is this the best method for this approach its a winforms business app if any other libarys that make this easier would be great.
I am using sql Server 2017 express which I asumes would have this as standard?.
private void DetectChanges()
{
    // Assume connection is an open SqlConnection.

    string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
    using (SqlConnection con = new SqlConnection(connectionString))
    {
        // Create a new SqlCommand object.
        using (SqlCommand command = new SqlCommand("SELECT exportedtoMeteor FROM dbo.exported", con))
        {
            // Create a dependency and associate it with the SqlCommand.
            SqlDependency dependency = new SqlDependency(command);
            // Maintain the reference in a class member.
            SqlDependency.Start(connectionString, "ExportedOrdersChangeMessage");

            // Subscribe to the SqlDependency event.
            dependency.OnChange += new
                OnChangeEventHandler(OnDependencyChange);

            // Execute the command.
            using (SqlDataReader reader = command.ExecuteReader())
            {
                // Process the DataReader.
            }
        }
    }
}

// Handler method
void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
    // Handle the event (for example, invalidate this cache entry).
}

void Termination()
{
    string connectionString = ConfigurationManager.AppSettings["ConnectionString"];

    // Release the dependency.
    SqlDependency.Stop(connectionString, ExportedHacket);
}

A: I don't know the answer to your direct question but Butterfly Server .NET detects changes to databases (MySQL, Postgres, SQLite, MS SQL Server, etc) and allows creating Dynamic Views based on SELECT statements that publish events if the SELECT results change.  There are caveats (like all database operations have to be performed via the IDatabase interface provided by Butterfly Server .NET).  However, it's similar enough to what you are doing that you may be interested.


text:
Q: I want to record a video in android using media recorder I want record a video using Surface view camera and Media Recorder Here is My Code.... I am getting crash at mediarecorder.prepare() and my default path getting null. please help me ...
private boolean startRecording() {
        try {
        camera.unlock();
        mediaRecorder = new MediaRecorder();
            second=0;
            minute=0;
            recordCountTimer = new CountDownTimer(Long.MAX_VALUE,1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    second++;
                    if(second>=60){
                        second=0;
                        minute++;
                    }
                    recordCount.setText(String.format("%02d:%02d",minute,second));
                }

                @Override
                public void onFinish() {
                    finish();
                }
            }.start();
        mediaRecorder.setCamera(camera);
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            Log.d(TAG, "A");
//        mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
//        defaultVideoPath= FileManger.getOutputMediaFile(MEDIA_TYPE_VIDEO).getAbsolutePath();
//        uriVid = Uri.parse(FileManger.getOutputMediaFile(MEDIA_TYPE_VIDEO).getAbsolutePath());
//        defaultVideoPath = getRealPathFromUri(uriVid);
            CamcorderProfile camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
            mediaRecorder.setProfile(camcorderProfile);
        mediaRecorder.setOutputFile(defaultVideoPath);
        mediaRecorder.setVideoSize(recordingCameraSurface.getWidth(), recordingCameraSurface.getHeight());
        mediaRecorder.setVideoFrameRate(20);
            Log.v(TAG, "C");
        mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
        mediaRecorder.prepare();
            Log.w(TAG, "D");
        mediaRecorder.start();
            Log.e(TAG, "E");
        } catch (IOException e) {
            releaseMediaRecorder();
            return false;
        }catch (IllegalStateException t){
            releaseMediaRecorder();
            return  false;
        }

        return true;
    }

When I am sending this default video path in intent the path is getting null

A: hi please try below functions for getting videoPath which you got null
public Uri getOutputMediaFileUri(int p_type)
    {
        return Uri.fromFile(getOutputMediaFile(p_type));
    }

    private File getOutputMediaFile(int p_type)
    {
        File m_mediaFile;
        if (p_type == MEDIA_TYPE_VIDEO)
        {
            // External sdcard location
            File m_videoStorageFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Videos");
            // Create the storage directory if it does not exist
            if (!m_videoStorageFile.exists())
            {
                if (!m_videoStorageFile.mkdirs())
                {
                    return null;
                }
            }
            // Create a media file name
            String m_timeStamp = new SimpleDateFormat(Constant.TIME_STAMP_FORMAT, Locale.getDefault()).format(new java.util.Date());
            m_buffer = new StringBuffer();
            m_buffer.append(m_videoStorageFile.getPath()).append(File.separator).append("VID_").append(m_timeStamp).append(".mp4");
            m_mediaFile = new File(m_buffer.toString());
        }
        else
        {
            return null;
        }

        return m_mediaFile;
    }

Use of function
int MEDIA_TYPE_VIDEO = 0;
private File defaultVideoPath;
String videoPath;

fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
videoPath = fileUri.getPath();

Pass videoPath from one activity to another
Intent intent = new Intent(RecordBuyPage.this,CheckAndSaveActivity.class);
intent.putExtra("VIDEOFILEPATH", videoPath);
startActivity(intent);

write below code in your CheckAndSaveActivity.class
if(getIntent().getExtras() != null)
{
      String imagePath = getIntent().getExtras().getString("VIDEOFILEPATH");
}

Hope you have declared CheckAndSaveActivity in your Manifiest


text:
Q: Rails nested resources Here's the routes.rb:
map.resources :assignments, :shallow => true  do |assignment|
    assignment.resources :problems
end

How do i get the url to edit a problem (/assignments/xyz/problems/abc/edit), in code? I have tried both
    edit_assignment_problem_path(assignment,problem)
    and edit_problem_path(problem).
While the first one works on my local setup, on server it says that method edit_assignment_problem_path is not defined. Any ideas?

A: :shallow => true was introduced in Rails 2.2. Your local setup probably was running an earlier version while your server probably runs 2.2 or earlier version.
With shallow routes, you MUST specify the full route (e.g. /assignments/a/problems/.. ) for :index, :create, and :new actions (because these actions need the complete path) and MUST use the short route (e.g. /problems/..) for :edit, :show, :update, and :destroy actions.
If you want both full and short versions of all routes the only possibility is to use a nested resource route without shallow plus a short route e.g.:
map.resources :assignments, has_many => :problems
map.resources :problems

Note that in your example you did not need to use the block form for map.resources.

A: Run this at your command line:
rake routes

It will tell you all the routes that you have defined, and how they map.  Very handy.

A: Also check out the routing guide that could teach you a lot of new things.


text:
Q: Upgrade from Jboss 6 to wildfly 10 After upgrading from Jboss 6 to wildfly 10, I had this exception for all value attribute that use method call in the managed bean
As example:
<h:inputText value="#{controller.value(cat,subCat)}">

Managed bean contains
public String value(String x ,String y){
 //Code here to return value..
}
public void setValue(String x){
}

Exception:
Caused by: javax.el.PropertyNotWritableException: ... @106,81 value="#{controller.value(cat,subCat)}": Illegal Syntax for Set Operation
at com.sun.faces.facelets.el.TagValueExpression.setValue(TagValueExpression.java:136)
at javax.faces.component.UIInput.updateModel(UIInput.java:832)
... 63 more
Caused by: javax.el.PropertyNotWritableException: Illegal Syntax for Set Operation
at com.sun.el.parser.AstValue.setValue(AstValue.java:228)
at com.sun.el.ValueExpressionImpl.setValue(ValueExpressionImpl.java:294)
at org.jboss.weld.el.WeldValueExpression.setValue(WeldValueExpression.java:64)
at org.jboss.weld.el.WeldValueExpression.setValue(WeldValueExpression.java:64)
at com.sun.faces.facelets.el.TagValueExpression.setValue(TagValueExpression.java:131)
... 64 more


text:
Q: Why does SetBasePath not work in .NET Core 3.1? I've tried adding nuget packages, but it doesn't work
Error CS1061
'ConfigurationBuilder' does not contain a definition for 'SetBasePath' and no accessible extension method 'SetBasePath' accepting a first argument of type 'ConfigurationBuilder' could be found (are you missing a using directive or an assembly reference?)

screenshot
I've installed these packages:
Microsoft.Extensions.Configuration;
Microsoft.Extensions.Configuration.Json;
Microsoft.Extensions.Configuration.FileExtensions

The code is working in .NET Core 2.2 but not in .NET Core 3.1.
Code is here:
using Microsoft.Extensions.Configuration;
using System;
using System.IO;

namespace Core.Logic.Mappers
{
    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            IConfigurationRoot configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                                                                         .AddJsonFile("appsettings.json")
                                                                         .Build();

A: Finally, after couple days I found solution:
I have multiple-projects in my solution, so I was installing
    Microsoft.Extensions.Configuration.Json;

to other project. Noobie :D


text:
Q: How to set alter table add column in sql plus how to set the alter table add column with condition like this as example.
add information about the hobbies possessed by the employees; an employee possesses one or more hobbies, and a hobby is possessed by zero or more employees
How to set alter table to add column with such condition? Sorry, i was still new to the sql query condition.

A: For your explanation, I did this:
You would have to create 3 tables, it is a many to many relationship, ie an employee to have several hobbies and hobby can be of various employees. A table of employees, other hobbies and other foreign keys with the other two.
CREATE TABLE `employees` (
  `id_employees` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  PRIMARY KEY (`id_employees`));

CREATE TABLE `hobbies` (
  `id_hobbies` INT NOT NULL AUTO_INCREMENT,
  `name` INT NULL,
  PRIMARY KEY (`id_hobbies`));

CREATE TABLE `employees_hobbies` (
  `id_employees_hobbies` INT NOT NULL AUTO_INCREMENT,
  `id_employees` INT NOT NULL,
  `id_hobbies` INT NOT NULL,
  PRIMARY KEY (`id_employees_hobbies`),
  INDEX `fk_employees_hobbies_1_idx` (`id_employees` ASC),
  INDEX `fk_employees_hobbies_2_idx` (`id_hobbies` ASC),
  CONSTRAINT `fk_employees_hobbies_1`
    FOREIGN KEY (`id_employees`)
    REFERENCES `employees` (`id_employees`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_employees_hobbies_2`
    FOREIGN KEY (`id_hobbies`)
    REFERENCES `hobbies` (`id_hobbies`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

If you already have tables and want to change them,
ALTER TABLE employees_hobbies ADD id_employees  INT NOT NULL;
ALTER TABLE employees_hobbies ADD id_hobbies  INT NOT NULL;
ALTER TABLE employees_hobbies ADD CONSTRAINT `fk_employees_hobbies_1`
        FOREIGN KEY (`id_employees`)
        REFERENCES `employees` (`id_employees`)
        ON DELETE NO ACTION
        ON UPDATE NO ACTION;
ALTER TABLE employees_hobbies ADD CONSTRAINT `fk_employees_hobbies_2`
        FOREIGN KEY (`id_hobbies`)
        REFERENCES `hobbies` (`id_hobbies`)
        ON DELETE NO ACTION
        ON UPDATE NO ACTION);

Instead of ADD, you can modify an existing column with MODIFY.
Check the source below.
Font:  Alter Table


text:
Q: perturbation of exponentiolly stable system consider the following system on $\Bbb{R}^n$

$\dot{x} = f(x,t)+g(x,t) $$  $$ $$ $ $ (*)  $

assume that f(0,t)=g(0,t) = 0 and
1.  0 is an exponentiolly stable equilibrium of $\dot{x}=f(x,t)$
2.$|g(x,t)| \leq \mu|x| $ $\forall x \in \Bbb{R}^n$
show that 0 is is an exponentiolly stable equilibrium of $(*)$
for small enough $\mu$
all I know for now is that x=0 is critical point of g(x,t), so if I define $F(x,t) = f(x,t) +g(x,t)$ and I prove that $DF_0 (=Df_0 + Dg_0 )$ have only negative eigenvalues, then 0 is exponentiolly stable of the system but how can I show that for small enough $\mu$ .
thanks ahead


text:
Q: Delete all objects in Android Parse local datastore My Android app reads data from a Parse server. All classes have an "isDeleted" boolean column that determines whether or not the object is considered "live" and should be displayed on the client devices.
Unfortunately, a colleague was asked to delete two objects of a class and he didn't know the proper way to mark the objects as deleted. Instead, he did a hard delete of the two objects on the server. Now these two "zombie" objects won't disappear from the local installs.
I thought that I would be able to fix the issue by deleting all local data from the devices and doing a full data refresh from the server. I wrote an app update that, on detecting a new version number, unpins all objects from the local Parse datastore and re-downloads all data from the server.
ParseObject.unpinAll(MyClass.CLASS_NAME);

But this line of code doesn't do what I expected it to do. The two objects that were deleted from the server are not deleted from client devices!
How can I completely, thoroughly delete all pinned objects from the local Parse data store and make these two "zombie" objects go away?
The app is using the latest version of Parse:
compile 'com.parse.bolts:bolts-tasks:1.3.0'
compile 'com.parse:parse-android:1.13.0'
compile 'com.parse:parseui-login-android:0.0.1'
compile 'com.parse:parseui-widget-android:0.0.1'
compile 'com.parse:parseinterceptors:0.0.2'

A: I found the solution to my own question. To delete all objects from the local store, I replaced the call to ParseObject.unpinAll() with ParseObject.unpinAllInBackground().
So instead of
ParseObject.unpinAll(MyClass.CLASS_NAME)

I have
ParseObject.unpinAllInBackground(new DeleteCallback() {
        @Override
        public void done(ParseException e) {
            // ...
        }
    });

Now all the previously saved objects are gone from the local store.


text:
Q: Convergence rate of $\operatorname E|\langle X,f_n\rangle|^p$ Suppose that $X$ is a random element with values in a separable Hilbert space $\mathbb H$ such that $\operatorname EX=0$ and $\operatorname E\|X\|^2<\infty$. Suppose that $f_1,f_2,\ldots$ form an orthonormal basis of $\mathbb H$ (these might be eigenvectors of the covariance operator of $X$). Then, by Parseval's identity, we have that
$$
\sum_{n=1}^\infty\operatorname E|\langle X,f_n\rangle|^2<\infty.
$$
In particular, $\operatorname E|\langle X,f_n\rangle|^2\to0$ as $n\to\infty$.
I am interested in $\operatorname E|\langle X,f_n\rangle|^p$ with $p>2$. If $\operatorname E\|X\|^{2(p-1)}<\infty$, using the fact that $\|f_j\|=1$ for $j\ge1$ and the Cauchy-Schwarz inequality twice, we obtain
\begin{align*}
\operatorname E|\langle X,f_n\rangle|^p
&=\operatorname E[|\langle X,f_n\rangle||\langle X,f_n\rangle|^{p-1}]\\
&\le\operatorname E[|\langle X,f_n\rangle|\|X\|^{p-1}]\\
&\le(\operatorname E|\langle X,f_n\rangle|^2)^{1/2}(\operatorname E\|X\|^{2(p-1)})^{1/2}.
\end{align*}
This shows that $\operatorname E|\langle X,f_n\rangle|^p\to0$ as $n\to\infty$ as well, but at a slower rate than $\operatorname E|\langle X,f_n\rangle|^2$. The rate of convergence does not depend on $p$, which I find counterintuitive. Also, we need to assume that $\operatorname E\|X\|^{2(p-1)}<\infty$.

At the moment, I have that $\operatorname E|\langle X,f_n\rangle|^p=O((\operatorname E|\langle X,f_n\rangle|^2)^{1/2})$ as $n\to\infty$. I suspect that $\operatorname E|\langle X,f_n\rangle|^p$ goes to $0$ faster than that. Is it possible to show that $\operatorname E|\langle X,f_n\rangle|^p\to0$ as $n\to\infty$ faster than $(\operatorname E|\langle X,f_n\rangle|^2)^{1/2}$? Perhaps even $\operatorname E|\langle X,f_n\rangle|^p=O((\operatorname E|\langle X,f_n\rangle|^2)^{p/2})$ as $n\to\infty$?

Any help is much appreciated!

A: I don't think so. Take X to be the random element of $l^2 = \sum a_i Z_i$ where, say, $\sum n^2a_n^2 < \infty$ and the $Z_i$ are independent, mean 0 variance 1,  but not iid. $f_1 = (1, 0, 0, ...) $ etc. so that $\langle f_n ,X \rangle = a_i Z_i$.  In order to get $||X|| \in L^4$ you only need $$\sum a_i^4 E(Z_i^4) < \infty $$ but if your last condition were true it would entail $$E(|Z_i|^4)  \approx  (E(|Z_i|^2))^2$$  I built in a bit of room so I think I can make the lhs much bigger than the right without altering the fact of $||Z||$ being $L^4$.


text:
Q: Get a Contact Picture ios I am trying to figure out how to add persons last name and first name in this code below in order to get their contact image from my phone:
if(ABPersonHasImageData(aABRecordRef))
{
   UIImage *image = [UIImage imageWithData:(NSData *)ABPersonCopyImageData(aABRecordRef)];
   cell.imageView.image = image;
} else {
   UIImage *image1=[UIImage imageNamed:@"User.jpg"];
   cell.imageView.image=image1;
}

I could also be missing code here so please do fill in the areas where it is needed. I just cant figure out how to add the first,last name to the code above so i know when i have reached that contact to extract the image for it.
Any help would be great! Thanks!

A: To get the FirstName and LastName , you can use :
NSString *firstName = (NSString *)ABRecordCopyValue(aABRecordRef, kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(aABRecordRef, kABPersonLastNameProperty);

Here it shows how to Search By Number and Get the image using ABAddressBook.
But you want to search By FirstName and LastName. So According to the Documentation , you should use -recordsMatchingSearchElement: method for Multiple Arguments.
Once you get the matched Data , you can extract the image using below code :
CFDataRef imageData = ABPersonCopyImageData(aABRecordRef);
UIImage *image = [UIImage imageWithData:(NSData *)imageData];
CFRelease(imageData);

Hope you get something useful from this.

A: Try:
CFStringRef firstName, lastName; // can cast this to NSString *

firstName = ABRecordCopyValue(aABRecordRef, kABPersonFirstNameProperty);
lastName = ABRecordCopyValue(aABRecordRef, kABPersonLastNameProperty);


text:
Q: "It does send one straight into thought." meaning What does the sentence in bold font mean? It was used by a Kiwi English speaker in a context of an email

It is very difficult to digest Sam's departure. I mentioned his name
  today and it does send one straight into thought.

The question is about two things:
- What does "one" refer to?
- What does "send one straight into thought" mean?

A: You might be able to understand better what "one" stands for if you replace it with "you". In many languages, when talking about a hypothetical person, "you" is used in colloquial speech.
For example, if Person A says to Person B,

This situation makes you think, doesn't it?

This sentence doesn't mean that the situation made Person B think. It means that it would make anyone think.
Since this "you" can often lead to situations where the addressee of the utterance says, "Are you talking about me? No, this doesn't apply to me", — "one" is used instead.
For example,

One could say these problems would make her rethink her approach to life.

It means simply "It could be said that..."

His response makes one wonder whether he understood the question at all.

This means that X's response probably makes anyone wonder. The speaker is definitely wondering, but s/he doesn't want to restrict the conversation to him/herself and makes the sentence apply to some abstract "anyone". It is a way to remove discussion from the speaker or the addressee so as to make it more impersonal (and not use "me" or "you").
Grammatically speaking, this word is a deictic. It is a placeholder for something else.
Regarding this particular sentence, it seems to be an ad hoc coinage (so not really an idiom that would be repeated by other speakers of English) based on constructions (much more widespread) such as:

something sent someone into a fit of rage/laughter/coughing etc.

This construction is used mostly for situations or actions that qualify as an outburst (similarly to how, if you kick a ball, it will send it into the air). Someone could try to use it metaphorically to imply that a transition from one state to another was very sudden; that a certain action was initiated very suddenly. But these metaphors often don't sound right, including this situation—because thoughts, while they can pop up in your mind, are not usually described in terms of outbursts.


text:
Q: Magento 2: Default mode not merged css I enabled Default Store mode and merge css enabled after that, I have run all the commands from command line but still css not merged. Any one help me?
Magento Version:2.2.4

A: Is there any specific reason why you are trying to merging CSS in default mode ?!!
I think if site development is completed then you should move to the production mode not even developer or default.
https://devdocs.magento.com/guides/v2.3/config-guide/cli/config-cli-subcommands-mode.html
I recently face same issue after digging found that by mistake there's one CSS which going to 404.
After fixing this I can able to do merge css.
Hope it will help you.


text: Q: Android camera API 2 can't open video after saving I am using camera video API 2 from google samples here. All goes right and when I wont check the movie I got an error "Failed to play video, An unknown error has occurred." This bug happens on samsung s7 and nexsus 5x. Where is the problem?  Thanks.


text:
Q: Is double colon access (::) to class member thread safe? There are two types of call to the member of a class, one is directly refer to the member function of a particular object using dot (.), the other method is to use double colon e.g. Obj::function().
My question is, is the double colon call to member is a thread-safe operation?

A:
Is the double colon call to member is a thread-safe operation?

It is thread-safe if the function invoked is thread-safe.  For example:
class C
{
    static std::string mx;

public:
    static std::string fx(const char* x) { mx = x; return mx; } // NOT THREAD SAFE
    static std::string fy(const char* y) { return y; } // THREAD SAFE
};

You can call either function:
cout << C::fx("hello") << endl; // NOT THREAD SAFE
cout << C::fy("world") << endl; // THREAD SAFE

So it has nothing to do with the two colons, and everything to do with the method implementation.

A: the :: is nothing you even have to bother on runtime about. So yeah it is threadsafe as it is allready resolved when threads are comming into action.
The :: is just used to make clear which namespace or class scope is refered to in cases where there could be ambiguous names.


text:
Q: JointJS: Hello World example doesn't work I am always seeing this exception when I try the Hello World example from the JointJS site:
Uncaught TypeError: Cannot call method 'getStrokeBBox' of undefined

Here's the code:
<!DOCTYPE html>
<html>
<head>
<!--
<link rel="stylesheet" href="css/joint.css" />
<script src="js/joint.js"></script>
-->

<link rel="stylesheet" type="text/css" href="http://www.jointjs.com/downloads/joint.css"></link>
<script type="text/javascript" src="http://www.jointjs.com/downloads/joint.js" ></script>

<script>
    var graph = new joint.dia.Graph;

    var paper = new joint.dia.Paper({
        el: $('#myholder'),
        width: 600,
        height: 200,
        model: graph
    });

    var rect = new joint.shapes.basic.Rect({
        position: { x: 100, y: 30 },
        size: { width: 100, height: 30 },
        attrs: { rect: { fill: 'blue' }, text: { text: 'my box', fill: 'white' } }
    });

    var rect2 = rect.clone();
    rect2.translate(300);

    var link = new joint.dia.Link({
        source: { id: rect.id },
        target: { id: rect2.id }
    });

    graph.addCells([rect, rect2, link]);
</script>
</head>
<title>Test</title>

<body>
    <div id="myholder"> </div>
</body>
</html>

I saw that there is another question already asked here for the same problem, but the solution given there isn't relevant as I already have a div element for paper object.

A: el: $('#myholder'),

Browsers read from top to bottom.  The browser is executing this line before it ever finds an element with the id of myholder, so el is an empty jQuery object.
Instead, move your script tag to the bottom of the HTML (so the browser has found myholder before you try to grab it) or wrap it all in a $(document).ready( call.

A: You are trying to get elements which are not created yet. Place your script at the end of <body> or use $(document).ready();

A: you are not using jQuery so this will work:
window.onload = function () {   your entire javascript code here };

but better include jQuery.js too and use:
$(function () {  your entire javascript code here  });

The code is executed line by line so it first loads and runs your javascript and doesn't know what "myholder" is. Doing it like I explained above it will load the javascript but it will only execute it  once the entire page is loaded.


text:
Q: $P = h \rho g$ derivation Here is a snapshot from textbook, University Physics by Sears and Zemansky :
Here only three forces are calculated:

*

*The gravitational force

*The force due to the pressure $p$ on the bottom surface

*The force due to the pressure $p+\mathrm{d}p$ on top surface

Why are only these three forces considered? Why is the force due to the pressure $p+\mathrm{d}p$ on the top surface downward, and why is the force due to the pressure $p$ on the bottom surface upward? Why not vice versa? Why does the downward force only apply on the top surface, it must apply on the bottom surface too, doesn't it?

A: This is a Newton's 3rd law (action/reaction) type situation, similar to what we encounter when we have tension in a rope.  The force per unit area (pressure) that the fluid above exerts on your mass is directed downward, and the reaction force (pressure) that the mass exerts on fluid above is directed upward.  But only the force exerted by the fluid above on the mass figures in the force balance on the mass.  Similar for the bottom surface.


text:
Q: Pycharm not recognizing .robot file extensions I am using Pycharm with Intellibot for Robot framework development.  I have created project and when I started to write code in .robot file it showing me errors for below code. Could you please help on this.. Thank you
*** Settings ***

Library  Selenium2Library

Library  OperatingSystem

Library  DateTime

*** Variables ***

${BROWSER}      chrome

Errors Are :

Can't use starred expression here
Statement expected, found Py:EXP
Unresolved reference 'Settings'
expression expected

I have added below Libraries :
pip                             20.2,
robotframework                  3.2.1,
robotframework-pythonlibcore    2.1.0,
robotframework-selenium2library 3.0.0,
robotframework-seleniumlibrary  4.5.0,
selenium                        3.141.0,
Selenium2LibraryExtension       1.1.0,
setuptools                      40.6.2,
urllib3                         1.25.10.


text:
Q: vb.net printing error: print_printpage continues to loop even though e.hasmorepages = false So here is my situation: First of all, all of my printing code is stored in a module, which is called when I click the print button. My problem is, my pages print fine the first time I print my document, but if I click print again, the pages start printing on top of one another. When I debug, e.hasmorepages will be set to false, but it loops around and runs the print_page event again a couple times... I'm confused why it loops several times even though hasmorepages is definitely set to false?? The fact that usually prints right the first time but not the second time I click print makes the think something needs to be disposed. I know my page number variable is set to 1 before each print so it isn't that. The code I am using used to work until I moved it to it's own module.
Note: When I click print, i choose if I want a delivery recipt. if no, a store copy and customer copy are printed. If yes then Store, customer, and delivery copy are printed. Usually the Store and customer copy are printed on top of one another but the delivery copy is correct, so 2 pages are printed instead of 3.
Here is the basic outline of my module:
Imports System.Drawing
Imports System.Drawing.Printing

Module Receipt2
Public copy As Integer
Dim row As Integer

Dim ItemsRowCount As Integer = Invoice.dgvInvoiceItems.RowCount
Private Doc As New PrintDocument()

Public Sub printInvoice()

    Try
        copy = 1

        AddHandler Doc.PrintPage, AddressOf Print_PrintPage
        Doc.Print()
        row = 0
        Doc.Dispose()

        copy = 1

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

Private Sub Print_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)

    Try

        'RECEIPT ITEMS PRINTED HERE

        'print Store/customer copy and sig line
        If copy = 1 Then
            g.DrawString("Store Copy", New Font("Verdana", 15, FontStyle.Italic), Brushes.DarkRed, 50, 1045)

            e.HasMorePages = True
            copy = copy + 1
            row = 0
            Exit Sub
        ElseIf copy = 2 Then
            g.DrawString("Customer Copy", New Font("Verdana", 15, FontStyle.Italic), Brushes.DarkRed, 50, 1045)

            If Invoice.boolDeliveryReceipt = True Then
                e.HasMorePages = True
                copy = copy + 1
                row = 0
                Exit Sub
            End If

        ElseIf copy = 3 Then
            g.DrawString("Delivery Copy", New Font("Verdana", 15, FontStyle.Italic), Brushes.DarkRed, 50, 1045)

        End If

        'e.HasMorePages = False

    Catch ex As Exception

        MessageBox.Show(ex.Message)

    End Try
End Sub
End Module

Thanks so much for taking the time to look this over! I've spent hours trying to track the problem down and just not having any luck.

A:  Private Doc As New PrintDocument()

This is where the problem started.
    AddHandler Doc.PrintPage, AddressOf Print_PrintPage

This is where you nailed yourself.  The As New syntax is pretty handy, but it will create an object just once.  Problem is, only the first call to printInvoice creates the PrintDocument object.  But every time you call printInvoice(), you add another PrintPage event handler to the same object.  The net effect is that the second time you print, your PrintPage event handler will run twice for each page.  The third time it will run three times.  Etcetera.  The Dispose() method doesn't otherwise do anything, a PrintDocument doesn't use disposable resources.  Setting it to Nothing would fix the problem.
You fix this by just creating a new PrintDocument object every time you print.  So
Private Doc As PrintDocument

Public Sub printInvoice()

    Try
        copy = 1

        Doc = new PrintDocument()
        AddHandler Doc.PrintPage, AddressOf Print_PrintPage
        ItemsRowCount = Invoice.dgvInvoiceItems.RowCount
        Doc.Print()
        '' etc...

Further improve this code by making "Doc" a local variable.  Or moving the code into a class.
Note how your ItemsRowCount variable has the same problem.  It might be initialized too early, storing the wrong row count.  And if you print again, later, with a different invoice then you'll definitely get the wrong number of rows.
Be careful with global variables, they have a knack for causing problems like this.


text:
Q: Generate random colour onclick [Android Studio] Im trying to set a random colour in app with AndroidStudio, this is my code:
 } else if (check.equals("random")) {
                display.setTextColor(Color.rgb(184, 134, 011));

How I can do when the user click set random colour? Now is showing 184, 134, 011
thanks!

A: Try this
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
display.setTextColor(color);


text:
Q: Use getline to split a string and check for int I have a file:
name1 8
name2 27
name3 6

and I'm parsing it into vector. This is my code:
  int i=0;
  vector<Student> stud;

  string line;
  ifstream myfile1(myfile);
  if (!myfile1.is_open()) {return false;}
  else {
    while( getline(myfile1, line) ) {
      istringstream iss(line);
      stud.push_back(Student());
      iss >> stud[i].Name >> stud[i].Grade1;
      i++;
    }
    myfile1.close();
  }

I need to check if the stud[i].Grade1 is int. If it isn't it return false.
File can contain:
name1 haha
name2 27
name3 6

How can I do it?
EDIT:
I have tried another way (without getline) and it seems to work. I don't understand why :/
int i=0;
vector<Student> stud;

ifstream myfile1(myfile);
if (!myfile1.is_open()) {return false;}
else {
  stud.push_back(Student());
  while( myfile1 >> stud[i].Name ) {
    if(!(myfile1 >> stud[i].Points1)) return false;
    i++;
    stud.push_back(Student());
}
myfile1.close();
}

A: If type of Grade1 in numerical such as int, Use std::istringstream::fail() :
// ...
    while( getline(myfile1, line) ) {
      istringstream iss(line);
      stud.push_back(Student());
      iss >> stud[i].Name;
      iss >> stud[i].Grade1;
      if (iss.fail())
        return false;
      i++;
    }
    myfile1.close();
  }
// ...

A: It could look like this:
std::vector<Student> students;
std::ifstream myfile1(myfile);
if (!myfile1.is_open())
    return false;

std::string line;
while (std::getline(myfile1, line))
{
    // skip empty lines:
    if (line.empty()) continue;

    Student s;
    std::istringstream iss(line);
    if (!(iss >> s.Name))
        return false;
    if (!(iss >> s.Grade1))
        return false;

    students.push_back(s);
}

just note that iss >> s.Grade1 will succeed not only for decimal, but also for octal and hexadecimal numbers too. To make sure that only decimal value will be read, you could read it into the temporary std::string object and validate it before you use it to retrieve the number. Have a look at How to determine if a string is a number with C++?


text:
Q: How to link existing sendgrid account to Azure I just migrated my apps to Azure. Now my app has a sending email feature that uses Sendgrid to send email. But now I want to link this account to Azure as I think I need to link this (existing Sendgrid account) to my Azure Sendgrid Account. But how do I do this? In Azure Sendgrid it only allows me to create a Sendgrid account but there are no option to Add an existing Sendgrid account. How do I do this? Btw the reason I want to do this is because I'm getting an error of Unable to read data from the transport connection: net_io_connectionclosed. So I'm guessing this is a permission issue because I did not link my existing sendgrid to my azure sendgrid account. How do I do this?

A: This page explains well. How to Send Email Using SendGrid with Azure
https://learn.microsoft.com/en-us/azure/sendgrid-dotnet-how-to-send-email
We are using existing sendgrid account in azure function and using function binding.  There was no linking required, existing account also provides APIKEY, that is all that is needed. Example here.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-sendgrid?tabs=csharp


text:
Q: Specific, Non convoluated Swap 2 Solana-based tokens with fixed rate I have dived into the space of Solana with very much more confusion than effective exploration as Solana is based on my non core, unfamiliar language, Rust. Toughly speaking, I am dealing with the two token SWAP-based use case rather than simple, essential one like mint/transfer.
Having spent a lot of time looking different repos and a few API docs, I only find only the repo Oyster Swap (rather than Swap-UI or Gfx-swap)  is based on the complete, fine-grained Swap details of Solana. However, not being expert in Blockchain protocol design, I am concerned about how to selectively reduce this kind of complexity to only the requirement of just a fixed rate between two specific tokens. So basically it is for building the swap between 1 customized token pegged as being equal to (for example) 5 SOL. It is the just experimental demo for this specific exchange/swap use-case.
As I couldn't have unlimited time to pick up Anchor and Rust as fast as it is wanted, I have to also accept to build the swap logics based on the simple pool on Typescript.
After studying the models/ directory inside in src/, I have to say that rather than chasing all details of the Swap protocols, what parameters or implementation parts can be omitted to just be enough for the simpler and more specific use case aforementioned:

*

*The pool is still mandatory for building the d-exchange place for the swap, but I still have a bit of doubt about whether having a constant specific rate really needs the implementation of DEX? Or somehow transfer of a pegged token valued with that multiplier can be sufficient for implementation? Without a DEX, I think it still need a program id of where it does such transfer right?

*In the instruction fn for initializeSwap(), it has a curveType parameter, so since this is a fixed exchange rate, how can this parameter be skipped?

*Also, it has concepts of feeDenominator and feeNUmerator, what are these meant for my case to be omitted?

*In deposit/withdraw instructions, does maximumTokenA/B mean the maximum allowances of token A/B or am I wrong in that?
This can be a last question, but the purpose for my tokens swap case, is just perform the swap instruction between two tokens (definitely I don't market token listing) with sufficient yet as simple as possible amount of parameters.
The reference code as followed
    export const createInitSwapInstruction = (
      tokenSwapAccount: Account,
      authority: PublicKey,
      tokenAccountA: PublicKey,
      tokenAccountB: PublicKey,
      tokenPool: PublicKey,
      feeAccount: PublicKey,
      destinationAccount: PublicKey,
      tokenProgramId: PublicKey,
      swapProgramId: PublicKey,
      nonce: number,
      config: PoolConfig,
      isLatest: boolean
    ): TransactionInstruction => {
      const keys = [
        { pubkey: tokenSwapAccount.publicKey, isSigner: false, isWritable: true },
        { pubkey: authority, isSigner: false, isWritable: false },
        { pubkey: tokenAccountA, isSigner: false, isWritable: false },
        { pubkey: tokenAccountB, isSigner: false, isWritable: false },
        { pubkey: tokenPool, isSigner: false, isWritable: true },
        { pubkey: feeAccount, isSigner: false, isWritable: false },
        { pubkey: destinationAccount, isSigner: false, isWritable: true },
        { pubkey: tokenProgramId, isSigner: false, isWritable: false },
      ];

      let data = Buffer.alloc(1024);
      if (isLatest) {
        const fields = [
          BufferLayout.u8("instruction"),
          BufferLayout.u8("nonce"),
          BufferLayout.nu64("tradeFeeNumerator"),
          BufferLayout.nu64("tradeFeeDenominator"),
          BufferLayout.nu64("ownerTradeFeeNumerator"),
          BufferLayout.nu64("ownerTradeFeeDenominator"),
          BufferLayout.nu64("ownerWithdrawFeeNumerator"),
          BufferLayout.nu64("ownerWithdrawFeeDenominator"),
          BufferLayout.nu64("hostFeeNumerator"),
          BufferLayout.nu64("hostFeeDenominator"),
          BufferLayout.u8("curveType"),
        ];

        if (config.curveType === CurveType.ConstantProductWithOffset) {
          fields.push(BufferLayout.nu64("token_b_offset"));
          fields.push(BufferLayout.blob(24, "padding"));
        } else if (config.curveType === CurveType.ConstantPrice) {
          fields.push(BufferLayout.nu64("token_b_price"));
          fields.push(BufferLayout.blob(24, "padding"));
        } else {
          fields.push(BufferLayout.blob(32, "padding"));
        }

        const commandDataLayout = BufferLayout.struct(fields);

        const { fees, ...rest } = config;

        const encodeLength = commandDataLayout.encode(
          {
            instruction: 0, // InitializeSwap instruction
            nonce,
            ...fees,
            ...rest,
          },
          data
        );
        data = data.slice(0, encodeLength);
      } else {
        const commandDataLayout = BufferLayout.struct([
          BufferLayout.u8("instruction"),
          BufferLayout.u8("nonce"),
          BufferLayout.u8("curveType"),
          BufferLayout.nu64("tradeFeeNumerator"),
          BufferLayout.nu64("tradeFeeDenominator"),
          BufferLayout.nu64("ownerTradeFeeNumerator"),
          BufferLayout.nu64("ownerTradeFeeDenominator"),
          BufferLayout.nu64("ownerWithdrawFeeNumerator"),
          BufferLayout.nu64("ownerWithdrawFeeDenominator"),
          BufferLayout.blob(16, "padding"),
        ]);

        const encodeLength = commandDataLayout.encode(
          {
            instruction: 0, // InitializeSwap instruction
            nonce,
            curveType: config.curveType,
            tradeFeeNumerator: config.fees.tradeFeeNumerator,
            tradeFeeDenominator: config.fees.tradeFeeDenominator,
            ownerTradeFeeNumerator: config.fees.ownerTradeFeeNumerator,
            ownerTradeFeeDenominator: config.fees.ownerTradeFeeDenominator,
            ownerWithdrawFeeNumerator: config.fees.ownerWithdrawFeeNumerator,
            ownerWithdrawFeeDenominator: config.fees.ownerWithdrawFeeDenominator,
          },
          data
        );
        data = data.slice(0, encodeLength);
      }

      return new TransactionInstruction({
        keys,
        programId: swapProgramId,
        data,
      });
    };

    export const depositInstruction = (
      tokenSwap: PublicKey,
      authority: PublicKey,
      transferAuthority: PublicKey,
      sourceA: PublicKey,
      sourceB: PublicKey,
      intoA: PublicKey,
      intoB: PublicKey,
      poolToken: PublicKey,
      poolAccount: PublicKey,
      swapProgramId: PublicKey,
      tokenProgramId: PublicKey,
      poolTokenAmount: number | Numberu64,
      maximumTokenA: number | Numberu64,
      maximumTokenB: number | Numberu64,
      isLatest: boolean
    ): TransactionInstruction => {
      const dataLayout = BufferLayout.struct([
        BufferLayout.u8("instruction"),
        uint64("poolTokenAmount"),
        uint64("maximumTokenA"),
        uint64("maximumTokenB"),
      ]);

      const data = Buffer.alloc(dataLayout.span);
      dataLayout.encode(
        {
          instruction: 2, // Deposit instruction
          poolTokenAmount: new Numberu64(poolTokenAmount).toBuffer(),
          maximumTokenA: new Numberu64(maximumTokenA).toBuffer(),
          maximumTokenB: new Numberu64(maximumTokenB).toBuffer(),
        },
        data
      );

      const keys = isLatest
        ? [
            { pubkey: tokenSwap, isSigner: false, isWritable: false },
            { pubkey: authority, isSigner: false, isWritable: false },
            { pubkey: transferAuthority, isSigner: true, isWritable: false },
            { pubkey: sourceA, isSigner: false, isWritable: true },
            { pubkey: sourceB, isSigner: false, isWritable: true },
            { pubkey: intoA, isSigner: false, isWritable: true },
            { pubkey: intoB, isSigner: false, isWritable: true },
            { pubkey: poolToken, isSigner: false, isWritable: true },
            { pubkey: poolAccount, isSigner: false, isWritable: true },
            { pubkey: tokenProgramId, isSigner: false, isWritable: false },
          ]
        : [
            { pubkey: tokenSwap, isSigner: false, isWritable: false },
            { pubkey: authority, isSigner: false, isWritable: false },
            { pubkey: sourceA, isSigner: false, isWritable: true },
            { pubkey: sourceB, isSigner: false, isWritable: true },
            { pubkey: intoA, isSigner: false, isWritable: true },
            { pubkey: intoB, isSigner: false, isWritable: true },
            { pubkey: poolToken, isSigner: false, isWritable: true },
            { pubkey: poolAccount, isSigner: false, isWritable: true },
            { pubkey: tokenProgramId, isSigner: false, isWritable: false },
          ];
      return new TransactionInstruction({
        keys,
        programId: swapProgramId,
        data,
      });
    };

    export const depositExactOneInstruction = (
      tokenSwap: PublicKey,
      authority: PublicKey,
      transferAuthority: PublicKey,
      source: PublicKey,
      intoA: PublicKey,
      intoB: PublicKey,
      poolToken: PublicKey,
      poolAccount: PublicKey,
      swapProgramId: PublicKey,
      tokenProgramId: PublicKey,
      sourceTokenAmount: number | Numberu64,
      minimumPoolTokenAmount: number | Numberu64,
      isLatest: boolean
    ): TransactionInstruction => {
      const dataLayout = BufferLayout.struct([
        BufferLayout.u8("instruction"),
        uint64("sourceTokenAmount"),
        uint64("minimumPoolTokenAmount"),
      ]);

      const data = Buffer.alloc(dataLayout.span);
      dataLayout.encode(
        {
          instruction: 4, // DepositExactOne instruction
          sourceTokenAmount: new Numberu64(sourceTokenAmount).toBuffer(),
          minimumPoolTokenAmount: new Numberu64(minimumPoolTokenAmount).toBuffer(),
        },
        data
      );

      const keys = isLatest
        ? [
            { pubkey: tokenSwap, isSigner: false, isWritable: false },
            { pubkey: authority, isSigner: false, isWritable: false },
            { pubkey: transferAuthority, isSigner: true, isWritable: false },
            { pubkey: source, isSigner: false, isWritable: true },
            { pubkey: intoA, isSigner: false, isWritable: true },
            { pubkey: intoB, isSigner: false, isWritable: true },
            { pubkey: poolToken, isSigner: false, isWritable: true },
            { pubkey: poolAccount, isSigner: false, isWritable: true },
            { pubkey: tokenProgramId, isSigner: false, isWritable: false },
          ]
        : [
            { pubkey: tokenSwap, isSigner: false, isWritable: false },
            { pubkey: authority, isSigner: false, isWritable: false },
            { pubkey: source, isSigner: false, isWritable: true },
            { pubkey: intoA, isSigner: false, isWritable: true },
            { pubkey: intoB, isSigner: false, isWritable: true },
            { pubkey: poolToken, isSigner: false, isWritable: true },
            { pubkey: poolAccount, isSigner: false, isWritable: true },
            { pubkey: tokenProgramId, isSigner: false, isWritable: false },
          ];
      return new TransactionInstruction({
        keys,
        programId: swapProgramId,
        data,
      });
    };

    export const withdrawInstruction = (
      tokenSwap: PublicKey,
      authority: PublicKey,
      transferAuthority: PublicKey,
      poolMint: PublicKey,
      feeAccount: PublicKey | undefined,
      sourcePoolAccount: PublicKey,
      fromA: PublicKey,
      fromB: PublicKey,
      userAccountA: PublicKey,
      userAccountB: PublicKey,
      swapProgramId: PublicKey,
      tokenProgramId: PublicKey,
      poolTokenAmount: number | Numberu64,
      minimumTokenA: number | Numberu64,
      minimumTokenB: number | Numberu64,
      isLatest: boolean
    ): TransactionInstruction => {
      const dataLayout = BufferLayout.struct([
        BufferLayout.u8("instruction"),
        uint64("poolTokenAmount"),
        uint64("minimumTokenA"),
        uint64("minimumTokenB"),
      ]);

      const data = Buffer.alloc(dataLayout.span);
      dataLayout.encode(
        {
          instruction: 3, // Withdraw instruction
          poolTokenAmount: new Numberu64(poolTokenAmount).toBuffer(),
          minimumTokenA: new Numberu64(minimumTokenA).toBuffer(),
          minimumTokenB: new Numberu64(minimumTokenB).toBuffer(),
        },
        data
      );

      const keys = isLatest
        ? [
            { pubkey: tokenSwap, isSigner: false, isWritable: false },
            { pubkey: authority, isSigner: false, isWritable: false },
            { pubkey: transferAuthority, isSigner: true, isWritable: false },
            { pubkey: poolMint, isSigner: false, isWritable: true },
            { pubkey: sourcePoolAccount, isSigner: false, isWritable: true },
            { pubkey: fromA, isSigner: false, isWritable: true },
            { pubkey: fromB, isSigner: false, isWritable: true },
            { pubkey: userAccountA, isSigner: false, isWritable: true },
            { pubkey: userAccountB, isSigner: false, isWritable: true },
          ]
        : [
            { pubkey: tokenSwap, isSigner: false, isWritable: false },
            { pubkey: authority, isSigner: false, isWritable: false },
            { pubkey: poolMint, isSigner: false, isWritable: true },
            { pubkey: sourcePoolAccount, isSigner: false, isWritable: true },
            { pubkey: fromA, isSigner: false, isWritable: true },
            { pubkey: fromB, isSigner: false, isWritable: true },
            { pubkey: userAccountA, isSigner: false, isWritable: true },
            { pubkey: userAccountB, isSigner: false, isWritable: true },
          ];

      if (feeAccount) {
        keys.push({ pubkey: feeAccount, isSigner: false, isWritable: true });
      }
      keys.push({ pubkey: tokenProgramId, isSigner: false, isWritable: false });

      return new TransactionInstruction({
        keys,
        programId: swapProgramId,
        data,
      });
    }

;


text:
Q: gnuplot plotting file with error bars containg strings and number in a colum as xtics In Linux/Ubuntu i have plotted a file with 3 columns ,x, y and error bars. Now i have file with numbers and text in first column. i can i plot it with error bars with numbers and string in the label?.
The contents of file "file1.dat" are
` std 0.05 0.005
  0.1 0.02 0.003
  0.2 0.01 0.001
 `

I have tried this
plot "file.dat" using 2:3:xtic(1) w yerrorbars but i get error on this


text:
Q: Remove leading 0 from specific field I have a file with multiple fields but only want to remove the leading 0s from the 2nd column (col B) rather than all of the columns. I have tried: sed 's/^0//g' filename > new_filename but this does not work.
EXAMPLE DATA:
A B C D E
2 02 56 0.987 0.332
1 09 67 0.567 0.243
9 06 37 0.523 0.263
0 10 47 0.378 0.875

REQUIRED OUTPUT:
A B C D E
2 2 56 0.987 0.332
1 9 67 0.567 0.243
9 6 37 0.523 0.263
0 10 47 0.378 0.875

A: I will chose awk for this task:
awk 'FNR > 1 {$2 = sprintf("%d", $2)};1' <file

or:
awk 'FNR > 1 {$2 += 0};1' <file

or:
awk '{sub(/^0+/, "", $2)};1' <file


text:
Q: A referential integrity constraint violation occurred. When Updating EF I can't seem to be able to update a model with foreignKey constraint getting this error :

Additional information: A referential integrity constraint violation
  occurred: The property value(s) of 'Country.Id' on one end of a
  relationship do not match the property value(s) of 'Setting.CountryId'
  on the other end.

Setting Model
namespace Domain
{
    public class Setting : BaseModel
    {

        public string Address { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string Website { get; set; }
        public string Slogan { get; set; }
        public byte[] Logo { get; set; }

        public string City { get; set; }
        public string RegistrationNo { get; set; }

        [ForeignKey("State")]
        public int StateId { get; set; }
        public  State State { get; set; }

        [ForeignKey("Country")]
        public int CountryId { get; set; }
        public  Country Country { get; set; }

        public string IsDefault { get; set; }

    }
}

State Model
namespace Domain
{
    public class State :BaseModel
    {
        public string Name { get; set; }
    }
}

Country Model
namespace Domain
{
    public class Country : BaseModel
    {
        public string Name { get; set; }
    }
}

Repository to Get and Update Setting
public Setting GetSetting()
{
    try
    {
        return _db.Settings.Include("Country").Include("State").First();
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
}

public Setting UpdateSetting(Setting setting)
{
    try
    {
        _db.Settings.Attach(setting);
        _db.Entry(setting).State = EntityState.Modified;
        _db.SaveChanges();

        return setting;
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }

}

Note I am Using WCF Proxy
Button Click Event
private void btnSave_Click(object sender, EventArgs e)
{
    //MessageBox.Show(Convert.ToInt16(cmbState.EditValue).ToString());
    //return;

    if (dxValidationProvider1.Validate())
    {
        if (picLogo.Image == null)
        {
            XtraMessageBox.Show("Upload Logo");
        }
        else
        {
            var setting = proxy.GetSetting();
            //MessageBox.Show(cmbState.EditValue.ToString()); return;

            setting.HotelName = txtHotelName.Text;
            setting.Address = txtAddress.Text;
            setting.Email = txtEmail.Text;
            setting.Phone = txtPhone.Text;
            setting.Website = txtWebsite.Text;
            setting.Slogan = txtSlogan.Text;
            setting.City = txtCity.Text;

            setting.CountryId = Convert.ToInt16(cmbCounty.EditValue);

            setting.StateId = Convert.ToInt16(cmbState.EditValue));

            setting.Logo = picLogo.Image.ToByteArray();

            var s = proxy.UpdateSetting(setting);

            MessageBox.Show(@"Updated");
        }
    }
    else
    {
        MessageBox.Show("Please fill the required fields");
    }
}

A: I just removed the Include statment from the GetSetting function and everything updated. This solved my problem
public Setting GetSetting()
{
    try
    {
        return _db.Settings.First();
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
}


text:
Q: Why does Merge ignore one specific shapefile? I am working with ArcGIS 10.3.1.4959 (License type: Advanced), and am trying to merge 3 point shapefiles together using the Data Management Tools -> General -> Merge functionality from ArcToolbox.
Between the shapefiles the fields do not match. But what's important is that they share the same coordinate system and geometry, being all points.
When I apply the Merge tool, the final result is never consistent: sometimes it includes the last element of the 1st shapefile, and sometimes the 1st shapefile is not at all present. I always get all the elements in the last two shapefiles, however. All three shapefiles are within the same Geodatabase.
I have tried to use Data Management Tools -> General -> Append but I am forced to use the NO_TEST schema type, losing useful information.
Why does this happen, and what can I do to walk around this obstacle?

A: This does not clarify the reason why this problem occurred, but to advise on a  workaround that seemed to do the trick.
It consisted of:

*

*Using Data Management Tools -> General -> Merge to merge together the 1st with the 2nd shapefile, so to create a "byproduct" shapefile;

*Using Data Management Tools -> General -> Merge to merge the "byproduct" to the 3rd shapefile, so to obtain the intended outcome.

By simply counting the total number of points in the outcome, this seems to have worked.


text:
Q: Angular ng-repeat in table, adding extra rows I'm repeating the contents of a array using ng-repeat with Angular. After that, but in the same table, I want to add some extra rows with info. But because it is in the ng-repeat I get an angular error on {{getCartTotal()}}, which is now called infinite times.
Is there a way to stop the ng-repeat, or a other way to add extra rows after a ng-repeat in the same element?
This is the code I have (in Jade). Only the first tr must been repeating.
table.shop_table.woocommerce-checkout-review-order-table
   tbody
       tr(ng-repeat='product in shoppingCart')
          th
             {{product.name}}
             span.count  x {{product.quantity}}
             td
                span.amount € {{product.price * product.quantity | number:2}}
       tr.cart-subtotal(ng-repeat-end)
         th Subtotaal
           td
             span.amount € {{getCartTotal()}}}
       tr.shipping
         th Verzendkosten
           td
            span
              i
                | Tijdelijk gratis!
        tr.order-total
          th
            strong Totaal
               td
                strong
                   span.amount € {{getCartTotal())}}

A: Duplicate from comment.
ng-repeat-end used with ng-repeat-start and will be repeated too. Try to delete ng-repeat-end
tr(ng-repeat='product in shoppingCart')
    th
        {{product.name}}
        span.count  x {{product.quantity}}
        td
          span.amount € {{product.price * product.quantity | number:2}}
tr.cart-subtotal
    th Subtotaal
        td
            span.amount € {{getCartTotal()}}


text:
Q: Formula to increase lightness of color to meet contrast with background color I'm working on an app where the UI will be dynamically styled to meet AA accessibility (4.5:1). I'm struggling to figure out how to implement this - currently my solution is to reverse the equation for contrast and luminance to get a colour with the target luminance, but the resulting RGB values are all over the place. I've put the code below, but I'm mostly looking for  a pointer into what equations I should be implementing.
import 'dart:math' as math;

import 'package:flutter/material.dart';

extension ToContrast on Color {
  static double _linearizeColorComponent(double component) {
    if (component <= 0.03928) return component / 12.92;
    return math.pow((component + 0.055) / 1.055, 2.4) as double;
  }

  static double _delinearizeColorComponent(double component) {
    if (component <= 0.0031308) return (12.92 * component);
    return math.pow(component * 1.055, 1 / 2.4) - 0.055;
  }

  Color atContrast(double targetContrast, Color background) {
    final selfLuminance = computeLuminance();
    final backgroundLuminance = background.computeLuminance();

    final currentContrast = selfLuminance > backgroundLuminance
        ? (selfLuminance + 0.05) / (backgroundLuminance + 0.05)
        : (backgroundLuminance + 0.05) / (selfLuminance + 0.05);

    if (currentContrast == targetContrast) {
      return Color(value);
    }

    final desiredSelfLuminance = selfLuminance > backgroundLuminance
        ? currentContrast * (backgroundLuminance + 0.05) - 0.05
        : (selfLuminance + 0.05 / currentContrast) - 0.05;

    final selfLinearRed = _linearizeColorComponent(red / 0xFF);
    final selfLinearGreen = _linearizeColorComponent(green / 0xFF);
    final selfLinearBlue = _linearizeColorComponent(blue / 0xFF);

    final newLinearRed = (desiredSelfLuminance -
            0.7152 * selfLinearGreen -
            0.0722 * selfLinearBlue) /
        0.2126;
    final newLinearGreen = (desiredSelfLuminance -
            0.2126 * selfLinearRed -
            0.0722 * selfLinearBlue) /
        0.7152;
    final newLinearBlue = (desiredSelfLuminance -
            0.2126 * selfLinearRed -
            0.7152 * selfLinearGreen) /
        0.0722;

    final newRed = _delinearizeColorComponent(newLinearRed) * 0xFF;
    final newGreen = _delinearizeColorComponent(newLinearGreen) * 0xFF;
    final newBlue = _delinearizeColorComponent(newLinearBlue) * 0xFF;

    final newLuminance =
        Color.fromARGB(alpha, newRed.ceil(), newGreen.ceil(), newBlue.ceil())
            .computeLuminance();
    final newContrast = newLuminance > backgroundLuminance
        ? (newLuminance + 0.05) / (backgroundLuminance + 0.05)
        : (backgroundLuminance + 0.05) / (newLuminance + 0.05);

    return Color.fromARGB(
        alpha, newRed.ceil(), newGreen.ceil(), newBlue.ceil());
  }
}


text:
Q: How to test a custom controller action In my application home page, users can make a choice from a list using a form.
The form collects the choice and sends it to a controller custom action whose only goal is to update the user's attribute choice:
<% form_tag({controller: "weekly_selections", action: "update_choice"}) do %>

<%= hidden_field_tag :user_choice, book.title %>

    <%= submit_tag("choose", class: "btn btn-primary btn-sm") %>
<% end %>

I created a WeeklySelection controller and a custom update_choice action:
class WeeklySelectionsController < ApplicationController

  def update_choice
    if current_user.choice_count < 10
      user_choice = params[:user_choice]
      current_user.update_attribute(:choice, user_choice)
      current_user.increment!(:choice_count)
      flash[:success] = 'Your choice has been recorded'
      redirect_to root_url
    else
      flash[:warning] = "Attention! You already made 10 choices"
      redirect_to root_url
    end
  end

end

How can I test the correct behaviour of this action, or that the action actually works?


text:
Q: Provide different build configurations / flavors (development, production) In my flutter app, I have a configuration like this:
api_url = https://api.poemhub.top

the problem is, in different environment the api url is different, when in develop, the api should look like this :
api_url = https://dev-api.poemhub.top

in test env:
api_url = https://beta-api.poemhub.top

in production environment:
api_url = https://api.poemhub.top

also other config different in different places, so what is the best way to treat this config in different environment? I have read a solution to define different main.dart and run build command like this:
flutter build apk -t lib/main_develop.dart

A: I would suggest to go with flutter flavors. This feature does exactly what you want.

A: as an option
you can put this code somewhere
const APP_ENV = String.fromEnvironment('APP_ENV');

and build project with parameter DEV or PROD for example
flutter build apk -t lib/main_develop.dart --dart-define=APP_ENV=DEV
extended example
enum AppEnvironment { DEV, PROD, MOCK }

class EnvironmentConfig {
  static const APP_ENV = String.fromEnvironment('APP_ENV');
  static const LOG = String.fromEnvironment('LOG');

  AppEnvironment get appEnvironment => APP_ENV.isEmpty ? AppEnvironment.MOCK
      : AppEnvironment.values.firstWhere((e) => e.toString() == 'AppEnvironment.' + APP_ENV);

  String get baseUrl => appEnvironment == AppEnvironment.DEV ? 'https://some dev url'
      : appEnvironment == AppEnvironment.PROD ? 'https://some url'
      : 'https://mock';

}

and then
if (EnvironmentConfig().appEnvironment == AppEnvironment.DEV) {
   // code
}

A: As alternative to flutter flavors suggested by @Pavlo Ostasha you can use flutter flavorizr

*

*In your pubspecs.yaml add
dependencies: flutter_flavorizr: ^1.0.11

*Install packages with
flutter pub get

*In your dart code use:
import 'package:flutter_flavorizr/flutter_flavorizr.dart';

*In your pubspecs.yaml define your flavors, for example test and production like below:

flavorizr:
  app:
    android:
      flavorDimensions: "environment"
    ios:

flavors:
    test:
      app:
        name: "Your app - test"

      android:
        applicationId: "com.yourcompany.appid.dev"

      ios:
        bundleId: "com.yourcompany.appid.dev"

    production:
      app:
        name: "Your app"

      android:
        applicationId: "com.yourcompany.appid"
      ios:
        bundleId: "com.yourcompany.appid"

*In the generated lib/flavors.dart file, define your getter for the api url

enum Flavor {
  TEST,
  PRODUCTION,
}

class F {
  static Flavor appFlavor;

  static String get apiUrl{
    switch (appFlavor) {
      case Flavor.TEST:
        return 'http://www.api-test.com';
      case Flavor.PRODUCTION:
        return 'http://www.api.com';
      default:
        return 'http://www.api.com';
    }
  }
}

*In your code do

import 'package:app/flavors.dart';

class YourApp extends StatelessWidget {
  const YourApp({Key key}) : super(key: key);

  var apiUrl = F.apiUrl; // from flavors.dart
}