text:
Q: Converting a uint8_t to its binary representation I have a variable of type uint8_t which I'd like to serialize and write to a file (which should be quite portable, at least for Windows, which is what I'm aiming at).
Trying to write it to a file in its binary form, I came accross this working snippet:
uint8_t m_num = 3;
unsigned int s = (unsigned int)(m_num & 0xFF);
file.write((wchar_t*)&s, 1); // file = std::wofstream

First, let me make sure I understand what this snippet does - it takes my var (which is basically an unsigned char, 1 byte long), converts it into an unsigned int (which is 4 bytes long, and not so portable), and using & 0xFF "extracts" only the least significant byte.
Now, there are two things I don't understand:

*

*Why convert it into unsigned int in the first place, why can't I simply do something like
file.write((wchar_t*)&m_num, 1); or reinterpret_cast<wchar_t *>(&m_num)? (Ref)

*How would I serialize a longer type, say a uint64_t (which is 8 bytes long)? unsigned int may or may not be enough here.

A: uint8_t is 1 byte, same as char
wchar_t is 2 bytes in Windows, 4 bytes in Linux. It is also depends on endianness. You should avoid wchar_t if portability is a concern.
You can just use std::ofstream. Windows has an additional version for std::ofstream which accepts UTF16 file name. This way your code is compatible with Windows UTF16 filenames and you can still use std::fstream. For example
int i = 123;
std::ofstream file(L"filename_in_unicode.bin", std::ios::binary);
file.write((char*)&i, sizeof(i)); //sizeof(int) is 4
file.close();
...
std::ifstream fin(L"filename_in_unicode.bin", std::ios::binary);
fin.read((char*)&i, 4); // output: i = 123

This is relatively simple because it's only storing integers. This will work on different Windows systems, because Windows is always little-endian, and int size is always 4.
But some systems are big-endian, you would have to deal with that separately.
If you use standard I/O, for example fout << 123456 then integer will be stored as text "123456". Standard I/O is compatible, but it takes a little more disk space and can be a little slower.
It's compatibility versus performance. If you have large amounts of data (several mega bytes or more) and you can deal with compatibility issues in future, then go ahead with writing bytes. Otherwise it's easier to use standard I/O. The performance difference is usually not measurable.

A: It is impossible to write unit8_t values to a wofstream because a wofstream only writes wide characters and doesn't handle binary values at all.
If what you want to do is to write a wide character representing a code point between 0 and 255, then your code is correct.
If you want to write binary data to a file then your nearest equivalent is ofstream, which will allow you to write bytes.
To answer your questions:

*

*wofstream::write writes wide characters, not bytes. If you reinterpret the address of m_num as the address of a wide character, you will be writing a 16-bit or 32-bit (depending on platform) wide character of which the first byte (that is, the least significant or most significant, depending on platform) is the value of m_num and the remaining bytes are whatever happens to occur in memory after m_num. Depending on the character encoding of the wide characters, this may not even be a valid character. Even if valid, it is largely nonsense. (There are other possible problems if wofstream::write expects a wide-character-aligned rather than a byte-aligned input, or if m_num is immediately followed by unreadable memory).

*If you use wofstream then this is a mess, and I shan't address it. If you switch to a byte-oriented ofstream then you have two choices. 1. If you will only ever be reading the file on the same system, file.write(&myint64value,sizeof(myint64value)) will work. The sequence in which the bytes of the 64-bit value are written will be undefined, but the same sequence will be used when you read back, so this doesn't matter. Don't try do something analogous with wofstream because it's dangerous! 2. Extract each of the 8 bytes of myint64value separately (shift right by a multiple of 8 bits and then take the bottom 8 bits) and then write it. This is fully portable because you control the order in which the bytes are written.


text:
Q: How to perform complex rules system using OAuth2/OpenId? I am looking into building a REST service as back-end and I was looking into OAuth2/OpenId to handle the security, but I'm not sure how to fit my complex structure into the rules or scopes structure.
Nothing is build yet, so maybe my reasoning is wrong and the domain model can be modified to match my needs, or OAuth2/OpenId is not suited for me.
I have a domain model as follows:

*

*A Country.

*A Region, which is linked to a Country. A single Country holds multiple Regions, but a Region belongs only to one Country.

*A Product which is linked to one Country, and optionally one Region.

*An Action which can be performed on a Product. (Not linked to a Product directly, rather CRUD related stuff.)

*A Profile which is linked to a Country, optionally a Region, and which holds the list of Actions.

*A User which is linked to one or more Profiles.

A User can request a list of Products. On those Products, he can perform Actions based on what his Profile allows, thus if the Country/Region of the Product matches the Profile Country/Region.
Imagine:
Product | Country | Region
--------------------------
      A |       X |      Z
      B |       X |      Y

Profile | Country | Region | Action
-----------------------------------
      I |       X |      Z | UPDATE
      I |       X |      Z | DELETE
      J |       X |      Y | DELETE

The user is linked to Profile I and J.

*

*If the user selects Product A, then he is allowed to UPDATE the Product, because the Country X and Region Z match.

*If the user selects Product B, then he is not allowed to UPDATE the Product, because even though Country X matches, Region Y does not match Profile I.

And this is my problem. I don't quite understand how I can achieve this complex rule system using the basic rules and scopes OAuth2/OpenId provides. Most samples use a very simple concept, basic CRUD allow or not, but I require another hierarchical level.
And simply using the system to authenticate a user and then still having to perform an in-depth action validation call each time seems overhead. Then I might simply skip OAuth2/OpenId and perform my own validation.
Or is there another way I can model my requirements to fit OAuth2/OpenId's concept?

A: OpenID Connect is an authentication protocol on top of the more general token request protocol OAuth 2.0.
They have nothing to do with how you implement authorization / business rules.
Furthermore the outcome of OIDC/OAuth is identity data, scopes and maybe coarse grained identity data. The ClaimsPrincipal is not a dumping ground for arbitrary authorization data.
Authorization is done based on the incoming identity, there is no special "technology" or "protocol" used for it. One popular approach is "resource-based authorization". This has been built into the new asp.net core - but otherwise is not hard to implement yourself.
https://docs.asp.net/en/latest/security/authorization/resourcebased.html

A: I would put all those info (country, region,profile,actions) as clams in ClaimsPrincipal and then use information from claims of current user to detect has user privileges or not to perform action

redpajama_set_name: RedPajamaStackExchange


text:
Q: How add Interval on button tag? I'm trying to build an Application that camera takes image automatically in every one minute, I m trying to add interval on button tag means when an application run, after every one minute automatically capture the image
import React, { Component } from 'react';

export class CameraFeed extends Component {

    processDevices(devices) {
        devices.forEach(device => {
            console.log(device.label);
            this.setDevice(device);
        });
    }

    async setDevice(device) {
        const { deviceId } = device;
        const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: { deviceId } });
        this.videoPlayer.srcObject = stream;
        this.videoPlayer.play();
    }

    async componentDidMount() {
        const cameras = await navigator.mediaDevices.enumerateDevices();
        this.processDevices(cameras);
    }

    takePhoto = () => {
        const { sendFile } = this.props;
        const context = this.canvas.getContext('2d');
        context.drawImage(this.videoPlayer, 0, 0, 680, 360);
        this.canvas.toBlob(sendFile);
    };

    render() {
        return (

                    <video ref={ref => (this.videoPlayer = ref)} width="680" heigh="360" />

                <button onClick={this.takePhoto}>Take photo!</button>

                    <canvas width="680" height="360" ref={ref => (this.canvas = ref)} />

        );
    }
}

A: first you need to keep track of the interval ID
this.intervalId = null;

Then, you make your event handler that will be fired on the button's click, and that subscribes the takePhoto to an interval
takePhotoEachDelay = (delay = 60 * 1000) => {
  setInterval(this.takePhoto, delay);
}

When your unmounts, you need to unsubscribe from the interval to avoid any unwanted behavior.
componentWillUnmount() {
  if (this.intervalId) { clearInterval(this.intervalId); }
}

finally,
<button onClick={this.takePhotoEachDelay }>Take photo!</button>


text:
Q: Most likely counts of outcomes of a multinomial after N trials (mode of multinomial) Given a categorical random variable $X = \{x_1,x_2,...,x_k\}$ with corresponding probabilities of each outcome $P = \{p_1, p_2,...,p_k\}$ (i.e. a multinomial):

*

*What are the most likely counts of outcomes aftern $N$ trials?
Let's call the vector of counts after $N$ trials a state: $C_N = \{c_1^N, c_2^N,...,c_k^N\}$. What is the most likely observable state after $N$ trials? In an observable state counts must be integers.
If you just multiply $x_i \times p_i$ you get fractional counts, that doesn't work. Is there a better strategy than computing $x_i \times p_i$ values and then trying all roundings where $\sum_i c_i^N = N$?

*What is the next most likely state (the one that's a little less likely than the best one)?
An example:
Outcome probabilities: $[p_1=0.60, p_2=0.30, p_3=0.10]$.
Number of trials: $N=7$.
Most likely state for $N=7$ trials: $[c_1^7=4.20, c_2^7=2.10, c_3^7=0.70]$.
If you just round it to: $C_{round}=[4, 2, 1]$, you get $P(C_{round})=P([4, 2, 1])=0.1225$, where $P(x)$ is a probability function.
However, $P([5, 2, 0])=0.1470$. So just rounding doesn't work. I guess because of the multinomial coefficient getting in the way of computing probabilities.

A: You can create an algorithm to compute the mode relatively easily in this problem.  To facilitate this analysis, define the function:
$$H_{i,\ell} \equiv \log(\ell) - \log(p_i).$$
The log-mass for the multinomial distribution can be written as:
$$\begin{align}
\log \text{Mu}(\mathbf{x}|N,\mathbf{p})
&= \log(N!) + \sum_{i=1}^k [x_i \log(p_i) - \log(x_i!)] \\[6pt]
&= \log(N!) + \sum_{i=1}^k [x_i \log(p_i) - \log(x_i) - \log(x_i-1) - \cdots - \log(2)] \\[6pt]
&= \log(N!) - \sum_{i=1}^k \sum_{\ell = 1}^{x_i} H_{i,\ell}. \\[6pt]
\end{align}$$
From this form we can see that the mass function is maximised when we allocate values into categories in a way that minimises the quantity $H_{i,\ell}$ corresponding to each allocation.  In the case where the values in $N \mathbf{p}$ are all integers (i.e., the probabilities are all multiples of $\tfrac{1}{N}$) the mode occurs at the point $\hat{\mathbf{x}} = N \mathbf{p}$ --- at this point we have $H_{i,x_i} = \log(N)$ for each $i=1,....k$.  In the more general case we have $\hat{\mathbf{x}} \approx N \mathbf{p}$, but the exact value of the mode requires some search around this approximating point.  Points that are next most likely, etc., can be determined by looking at the values of the $H$ function here.
Here is a simple algorithm in R to compute the mode, where we allocate each of the $N$ values to categories one at a time by minimising the $H$ values (with tie-breakers being given by the lowest category number).  The function takes in parameters size and prob and outputs a vector that is a mode of the distribution.
mode.multinom <- function(size, prob) {

  #Set initial values
  k <- length(prob)
  H <- -log(prob)
  X <- integer(k)
  prob <- prob/sum(prob)

  #Compute mode allocation
  for (i in 1:size) {
    Z    <- which.min(H)
    X[Z] <- X[Z]+1
    H[Z] <- log(X[Z]+1) - log(prob[Z]) }

  #Give output
  X }

Here is an example where we use this algorithm to compute the mode
#Set parameters
N    <- 76
PROB <- c(0.01, 0.13, 0.03, 0.10, 0.22, 0.05, 0.07, 0.32, 0.02, 0.05)

#Check the approximate mode
N*PROB
[1]  0.76  9.88  2.28  7.60 16.72  3.80  5.32 24.32  1.52  3.80

#Compute the mode
MODE <- mode.multinom(size = N, prob = PROB)
MODE
[1]  0 10  2  8 17  4  5 25  1  4

#Compute the log-mass at the mode
dmultinom(MODE, size = N, prob = PROB, log = TRUE)
[1] -14.06952

A: You could start with a solution rounded down. For instance in the example you start with [4,2,0]. Then you iteratively keep adding the remainder (from rounding down) in the places that are making the best improvement.
This is my intuition. I still have to prove that this works.


text:
Q: SFDC using my IP instead of SFDC IP range I am working on an integration between SFDC and an on premise system. This on premise system needs to be accessed from inside of SFDC.  When SFDC API call hits the on premise application it shows my IP address instead of the request coming from SFDC IP List.
Due to this the reverse proxy is blocking the request, how can i make sure that the request to the on premise application comes from SFDC IP's instead of my IP ?
Thanks
A. S.

A: When you use java script or any sort of client side scripting the request is made from your browser to on premise system. Due to this on premises system will get the request from client that your browser. If you want to avoid that then
1) You will need to call those on premise system APIs from apex
2) Wrap apex code created above in rest of soap api
3) And from your web tab/page your will need to call sfdc API created in step 2
Note that now your SFDC api created in step 2 will receive client IP but on premise system will always receive SFDC IP


text:
Q: substitute the elements of an array coditionally I need to create an array of prices. So I've an array of base prices and an array of promotional prices, if the promotional price is lower than the base price, I put it in the new array of prices. For this purpose I wrote this code:
<?php
    $array_base_prices = array(
        array('id'=>1, 'price'=>10),
        array('id'=>2, 'price'=>2),
        array('id'=>3, 'price'=>30),
        array('id'=>4, 'price'=>40)
     );

     $array_promo = array(
        array('id'=>1, 'price'=>20),
        array('id'=>2, 'price'=>5),
        array('id'=>3, 'price'=>2)
     );

     $base_prices_with_promo = array();

     foreach ( $array_base_prices as $j => $u ) {

        foreach ( $array_promo as $k => $v ) {

           if ( ($v['id'] == $u['id']) && $u['price'] < $v['price']) {

                $base_prices_with_promo[$j]['id'] = $array_base_prices[$j]['id'];
                $base_prices_with_promo[$j]['price'] = $array_base_prices[$j]['price'];

           }

           if ( ($v['id'] == $u['id']) && $u['price'] > $v['price']) {

                $base_prices_with_promo[$j]['id'] = $array_promo[$k]['id'];
                $base_prices_with_promo[$j]['price'] = $array_promo[$k]['price'];

           }

        }

    }

    $base_prices_with_promo = array_replace( $array_base_prices, $base_prices_with_promo );

    echo "<pre>";
    print_r($base_prices_with_promo);
    echo "</pre>";

?>

and it works fine, but I think that the if conditions into the nested foreach are a little messy. I'm working with multidimensional, associative arrays, very big with a lot of keys. So I'm wondering if there is any better alternative to achieve the same result.

A: There's really not enough context for me to be sure that this is an option for you, but from your little example I would change the array declaration to this:
$array_base_prices = array(
    1 => 10,
    2 => 2,
    3 => 30,
    4 => 40
);

$array_promo = array(
    1 => 20,
    2 => 5,
    3 => 2
);

Or use an array if you need to store more data than just price:
$array_base_prices = array(
    1 => array("price" => 10, "something_else" => null)
);

The point is to have the id as index of the parent array. Then your nested loops turn to this:
foreach ($array_base_prices as $id => $base_price) {
    $base_prices_with_promo[$id] = $base_price;
    if (isset($array_promo[$id]) && $base_price > $array_promo[$id]) {
        $base_prices_with_promo[$id] = $array_promo[$id];
    }
}


text:
Q: Rails i18n ActiveRecord backed I want to store web site translations in ActiveRecord, because it easy to edit in admin area.
I found only one solution:
https://github.com/svenfuchs/i18n-active_record
But it is completable with 3rd version of rails and last commit was one year ago. I have rails4 application.
Is it any alternative activerecord backends for i18n?


text:
Q: Getting the time at which the latest record was submitted SQL I would like to fetch the time at which the latest record was made by a particular user.
Say there are 4 rows made by a user containing their distinct ID, called steamid. They were all made at different times. I would like to get the time at which the latest one was made.

So to select the bottom record I tried.
$time = "SELECT max(time) FROM bets WHERE steamid='$number'";
$result = mysqli_query($conn,$time);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
    $previous = $row["time"];
}
} else {
$previous = '0';
}

However a dump of $previous returns null.

A: In the result there will be no column named time as you haven't given any alias to the result of max(time)
Change the query to this: SELECT max(time) as time ...


text:
Q: Xcart error caused by sql syntax I am running my store under Xcart and I get following error on top of web browser:
INVALID SQL: 1064 : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'OPTION SQL_MAX_JOIN_SIZE=1073741824' at line 1
SQL QUERY FAILURE:SET OPTION SQL_MAX_JOIN_SIZE=1073741824
INVALID SQL: 1064 : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'OPTION SQL_BIG_SELECTS=1' at line 1
SQL QUERY FAILURE:SET OPTION SQL_BIG_SELECTS=1
INVALID SQL: 1064 : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'OPTION SQL_BIG_SELECTS=1' at line 1
SQL QUERY FAILURE:SET OPTION SQL_BIG_SELECTS=1

what cause this so I can clear the error?
thanks!

A: It seems your MySQL server has been updated.
Replace all strings like
'SET OPTION SQL_MAX_JOIN_SIZE'
to these
'SET SESSION MAX_JOIN_SIZE'
A command for the unix-based hostings
sed -i  's/SET OPTION /SET SESSION /' $(grep --include='*.php' -rl 'SET OPTION ' ~/www/xcart_4_6_x)

A: It needs to check the xcart php scripts where this query is executed and OPTION to be replaced with SESSION for the errors like

SQL QUERY FAILURE:SET OPTION SQL_BIG_SELECTS=1

Also, as for

SQL QUERY FAILURE:SET OPTION SQL_MAX_JOIN_SIZE=1073741824

it might worth to change it just to db_query("SET max_join_size=1073741824");
It works for some xcart installations so please report if it helps to your project as well, thanks


text:
Q: kubelet can't create mountpoint' I create nfs pvc. And I used it in my Deployment YAML. but when I apply the YAML file. I get the following error
Mounting arguments: --description=Kubernetes transient mount for /var/lib/kubelet/pods/341e752b-acbb-4c26-a664-a25b5f1dd28b/volumes/kubernetes.io~nfs/data-certification-files-pv --scope -- mount -t nfs 192.168.123.95:/mnt/nfs/certification /var/lib/kubelet/pods/341e752b-acbb-4c26-a664-a25b5f1dd28b/volumes/kubernetes.io~nfs/data-certification-files-pv
Output: Running scope as unit run-25571.scope.
mount.nfs: Stale file handle
  Warning  FailedMount  13m  kubelet, server08  MountVolume.SetUp failed for volume "data-certification-files-pv" : mount failed: exit status 32

then i check the kubelet log, i get this

6月 11 17:06:56 server08 kubelet[16597]: E0611 17:06:56.977097   16597 kubelet.go:1681] Unable to attach or mount volumes for pod "weedfs-master-7b95f44996-xt427_runsdata(341e752b-acbb-4c26-a664-a25b5f1dd28b)": unmounted volumes=[data], unattached volumes=[default-token-7xtzl log data]: timed out waiting for the condition; skipping pod6月 11 17:06:56 server08 kubelet[16597]: E0611 17:06:56.977150   16597 pod_workers.go:191] Error syncing pod 341e752b-acbb-4c26-a664-a25b5f1dd28b ("weedfs-master-7b95f44996-xt427_runsdata(341e752b-acbb-4c26-a664-a25b5f1dd28b)"), skipping: unmounted volumes=[data], unattached volumes=[default-token-7xtzl log data]: timed out waiting for the condition
6月 11 17:07:23 server08 kubelet[16597]: E0611 17:07:23.636510   16597 mount_linux.go:150] Mount failed: exit status 326月 11 17:07:23 server08 kubelet[16597]: Mounting command: systemd-run
6月 11 17:07:23 server08 kubelet[16597]: Mounting arguments: --description=Kubernetes transient mount for /var/lib/kubelet/pods/341e752b-acbb-4c26-a664-a25b5f1dd28b/volumes/kubernetes.io~nfs/data-certification-files-pv --scope -- mount -t nfs 192.168.123.95:/mnt/nfs/certification /var/lib/kubelet/pods/341e752b-acbb-4c26-a664-a25b5f1dd28b/volumes/kubernetes.io~nfs/data-certification-files-pv
6月 11 17:07:23 server08 kubelet[16597]: Output: Running scope as unit run-30998.scope.6月 11 17:07:23 server08 kubelet[16597]: mount.nfs: Stale file handle6月 11 17:07:23 server08 kubelet[16597]: E0611 17:07:23.637271   16597 nestedpendingoperations.go:301] Operation for "{volumeName:kubernetes.io/nfs/341e752b-acbb-4c26-a664-a25b5f1dd28b-data-certification-files-pv podName:341e752b-acbb-4c26-a664-a25b5f1dd28b nodeName:}" failed. No retries permitted until 2020-06-11 17:09:25.637186297 +0800 CST m=+7477.442805373 (durationBeforeRetry 2m2s). Error: "MountVolume.SetUp failed for volume \"data-certification-files-pv\" (UniqueName: \"kubernetes.io/nfs/341e752b-acbb-4c26-a664-a25b5f1dd28b-data-certification-files-pv\") pod \"weedfs-master-7b95f44996-xt427\" (UID: \"341e752b-acbb-4c26-a664-a25b5f1dd28b\") : mount failed: exit status 32\nMounting command: systemd-run\nMounting arguments: --description=Kubernetes transient mount for /var/lib/kubelet/pods/341e752b-acbb-4c26-a664-a25b5f1dd28b/volumes/kubernetes.io~nfs/data-certification-files-pv --scope -- mount -t nfs 192.168.123.95:/mnt/nfs/certification /var/lib/kubelet/pods/341e752b-acbb-4c26-a664-a25b5f1dd28b/volumes/kubernetes.io~nfs/data-certification-files-pv\nOutput:Running scope as unit run-30998.scope.\nmount.nfs: Stale file handle\n"

i check the mountpoint:
[root@server08 pods]# ll  /var/lib/kubelet/pods/341e752b-acbb-4c26-a664-a25b5f1dd28b/volumes/kubernetes.io~nfs/data-certification-files-pv
ls: cannot access /var/lib/kubelet/pods/341e752b-acbb-4c26-a664-a25b5f1dd28b/volumes/kubernetes.io~nfs/data-certification-files-pv: No such file or directory
[root@server08 pods]# ll  /var/lib/kubelet/pods/341e752b-acbb-4c26-a664-a25b5f1dd28b/volumes/kubernetes.io~nfs
total 0

other info: kubeadm version 1.18  kubelet 1.18
Why doesn't Kubelet create a mount point directory?

A: I don't know why, I replaced the specific IP with the wildcard *, and restart NFS and it works


text:
Q: costume fit with variable parameter I am looking for a way to find a value from diagram fit. I just want to know that is it possible in MATLAB? Is there a code line for this purpose?
For example:
I have two matrix data as follows:
X=[1 2 3 4 5 6 7 8 9]

Y=[9 8 7 6 5 4 3 2 1]

I want to fit these data with nonlinear equation (costume fit) like this:
a*(w+1)*x^w*exp(a*x^(w+1))  ;   a=gamma ((w+2)/(w+1))

But this equation has a variable parameter w. I want to MATLAB give me the w that for this parameter I can get a best fit for my data.

A: use fit for curve fitting:
% define function as a string
f = 'gamma((w + 2)/(w + 1))*(w + 1)*(x.^w).*exp( gamma((w + 2)/(w + 1))*x.^(w + 1) )';
X = [1 2 3 4 5 6 7 8 9];
Y = [9 8 7 6 5 4 3 2 1];
% define fit parameters
fitType = fittype( f, 'Independent', 'x' ,'coefficients',{'w'});
% fit data
fitobject = fit(X(:),Y(:),fitType,'StartPoint', 0);
% coefficient value
w = coeffvalues(fitobject)
% plot
plot(X,Y,'.');
hold on
plot(fitobject);
title(['w = ' num2str(w)])


text:
Q: Dynamo DB Batch Call with LSI I have a table which has customerId and orderId as Primary Partition Key and Sort Key respectively.
I have LSI on CustomerID and ProductID.
Is it possible to make a batch call for multiple ProductIds for a particular customerId?
Is Batch call supported only for key columns ? or it possible to make batch call based on LSI also?

A: BatchGet can only be made on the table, not on any indexes. I think this is because uniqueness of the key is only enforced for the table's key, not any index key.
If you want to return just the specific items for each ProductId and CustomerId, you will have to make multiple query calls, specifying a productId in each.
Alternatively you can query for all the ProductIds between the first and last ProductIds when ordered. i.e. if you need the ProductIds 1, 5, 10, 13, 14, you can query for all ProductIds between 1 and 14 for the Customer.


text:
Q: Return List of type implemented class I am having some problems refactoring some code that returns JSON data from a web service.  I've developed a base class as shown below, but this means I have to pass in the type to the GetList method.  What I really need is it to automatically pick up the type of the derived class but I can't get it to work.
public abstract class LocalSystemTable
{
    public abstract string TableName { get; }
    public abstract string SingularName { get; }

    public List<T> GetList<T>(string baseUri, UserCredentials userCredentials)
    {
        var response = RestClient.At(baseUri).WithContentType(ContentType.Json).For(userCredentials).Get<dynamic>();

        var result = (response.ResponseObject[TableName])[SingularName];
        bool isArray = result.GetType() == typeof(JArray);

        if (isArray)
            return result.ToObject<List<T>>();
        else
        {
            T single = result.ToObject<T>();
            return new List<T> { single };
        }
    }
}

Basically I want to turn this:
GiftAidSettings settings = new GiftAidSettings();
List<GiftAidSettings> results = settings.GetList<GiftAidSettings>("some_uri", userCredentials);

Into this:
GiftAidSettings settings = new GiftAidSettings();
List<GiftAidSettings> results = settings.GetList("some_uri", userCredentials);

Is that possible?
Thanks

A: I dont know if this is what you want, but you can do something like this:
    public abstract class BaseClass<T>
        where T : BaseClass<T>, new()
    {
        public List<T> GetList(string someParameter)
        {
            return new List<T>() { new T() };
        }
    }

    public class BaseClassImplementation : BaseClass<BaseClassImplementation>
    {
        // ..............
    }

then:
    BaseClassImplementation n = new BaseClassImplementation();
    List<BaseClassImplementation> l = n.GetList("some parameter");


text:
Q: Does the mongocli support a formula URL for Apple M1 chips? As per the installation instructions, when running:
brew tap mongodb/brew

I get the following error:
Error: Invalid formula: /opt/homebrew/Library/Taps/mongodb/homebrew-brew/Formula/mongocli.rb

formulae require at least a URL

Error: Cannot tap mongodb/brew: invalid syntax in tap!

I do comply with prerequisites (updated xcode and brew). I made sure to run brew update and brew doctor.
At this point, I looked for answers on the mongodb/homebrew-brew repo and saw a very recent commit for the mongocli.
Apparently, it defines URLs for Mac and Linux machines that have Intel chips but no mention of Apple M1 chips. This is blocking me from tapping mongodb at the moment. Would you know of any workaround or am I making a mistake somewhere?

A: Just had the same problem ...
Go to Finder > Utilities and right click on Terminal and select "Get Info"
Find the option "Open using Rosetta" and check it.
Open new Terminal and run "brew tap mongodb/brew"
After it completes close the terminal and uncheck "Open using Rosetta", open Terminal again and then run "brew install mongodb-community@4.4".
That worked for me and MongoDB is installed.

A: Try the following command
arch -arm64 brew install mongodb-community@4.4

A: You can simply run any command under Rosetta on M1 macs by prefixing the command
arch -x86_64

For your use case try
arch -x86_64 brew tap mongodb/brew
brew install mongodb-community@4.4


text:
Q: Kivy TextInput horizontal and vertical align (centering text) How to center a text horizontally in a TextInput in Kivy?
I have the following screen:

But I want to centralize my text like this:

And this is part of my kv language:
        BoxLayout:
            orientation: 'vertical'
            Label:
                markup: True
                text: '[b] Type something... [/b]'
                size_hint: 1, 0.6
                size: self.parent.size[0], 200
                font_size: self.size[0] * 0.1
                text_size: self.size
                halign: 'center'
                valign: 'middle'

                canvas.before:
                    Color:
                        rgb: 0, 0, 204
                    Rectangle:
                        pos: self.pos
                        size: self.size

            TextInput:
                focus: True

How can I center my TextInput's text?

A: @pete halign: 'center' plus the padding on y axis only does the job as well
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
Builder.load_string('''
<Test>:
    TextInput:
        text: 't'
        halign: 'center'
        padding_y: [self.height / 2.0 - (self.line_height / 2.0) * len(self._lines), 0]
''')
class Test(BoxLayout):
    pass
class TestApp(App):
    def build(self):
        return Test()
TestApp().run()

A: Simply use halign: "center" , in your TextInput

A: Afaik, there's no such thing as aligning in the same way as it's in Label, however, you can use padding to push the position wherever you want. Keep in mind that changing the size of text will affect the centering, therefore you'll need to recalculate on change of size (e.g. when working with multiple devices, sizes, etc).
Or there could be even a workaround, where you could make TextInput invisible, use Label to fetch touch event to trigger TextInput (which would open keyboard) and change Label's text on change of TextInput's text property. You'll lose the possibility to work with cursor this way and you'll need to handle wrapping text.
Example:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
Builder.load_string('''
<Test>:
    TextInput:
        text: 't'
        font_size: 60
        # left, right
        padding_x:
            [self.center[0] - self._get_text_width(max(self._lines, key=len), self.tab_width, self._label_cached) / 2.0,
            0] if self.text else [self.center[0], 0]
        # top, bottom
        padding_y: [self.height / 2.0 - (self.line_height / 2.0) * len(self._lines), 0]
''')
class Test(BoxLayout):
    pass
class TestApp(App):
    def build(self):
        return Test()
TestApp().run()

self._get_text_width(...) is obviously a method of a TextInput. It's working with the core of the widget so it might be unstable (first example I posted was buggy because of my mistake) ^^
Now if padding_x's values padd from left and right, you'll need only the left side (the difference is only in using addition and substraction in the right place), so let's do that:

*

*get the longest substring in the TextInput

*get its width (because it's not consistent!) via the fancy method

*substract from center[0] coordinate

When we've already centered the X axis, let's go to the Y. padding_y's values are top and bottom:

*

*padd down the half of the widget's height

*get a half of a height of a single line

*multiply the number by the count of lines that are in TextInput

*substract the number from self.height / 2.0

*bottom is 0, we don't care about it

Note: max() expects some arguments and if there's no text, max() will raise its voice. We'll shut it with an alternative left padding for padding_x using only the center:
<padding_x with max> if self.text else [self.center[0], 0]


text:
Q: When a new consumer comes online, can it read the last x messages? I'm confused how rabbitmq works when a new consumer comes online.
I understand when there are currently x number of consumers connected, and then a producer sends a message the consumers will receive these messages.
But say consumerX was down, and now comes online or it is a brand new consumer.  Is it possible for it to replay messages in the past 24 hours?

A: This is a normal behavior for RabbitMQ.
Please read:
https://www.rabbitmq.com/tutorials/tutorial-two-python.html

A:
Is it possible for it to replay messages in the past 24 hours?

It depends on how you set things up.
If you have queues that don't auto-delete, they'll just keep collecting messages and waiting around for a consumer to connect.
I've had instances w/ thousands of messages stuck in a queue because my consumer was crashing. As soon as I fixed my code, the messages started consuming again.
But, if you're letting your queues get deleted when your consumers die, then you're in a bit of trouble.
There is a plugin to read the last ## of messages from an exchange, but it doesn't work in a time-based manner... just the last ## of messages: https://github.com/rabbitmq/rabbitmq-recent-history-exchange


text:
Q: Working way on creating a root ftp user There are many work arounds for this. One of those I've done:
adduser username
chown -R username /directory/
chmod -R 755 /directory/

I'm using FlashFXP on Windows which ends to
[R] USER xxx
[R] 331 Password required for xxx
[R] PASS (hidden)
[R] 530 Login incorrect.
[R] Connection failed

But I wanna make a ftp user on root ~ directory.
Also tried:
Adding /bin/false to /etc/shells
nano /etc/shells
useradd userftp -p mypass -d /home -s /bin/false
passwd userftp
/etc/init.d/proftpd start

Can't login either!
proftpd.conf
ServerName              "Myserver"
ServerType              standalone

Port                    21
PassivePorts            35000 35999
UseReverseDNS           off
TimesGMT                off
TimeoutLogin            120
TimeoutIdle             600
TimeoutNoTransfer       900
TimeoutStalled          3600

ScoreboardFile                  /var/run/proftpd/proftpd.pid

TransferLog             /var/log/proftpd/xferlog.legacy
LogFormat               default "%h %l %u %t \"%r\" %s %b"
LogFormat               auth    "%v [%P] %h %t \"%r\" %s"
LogFormat               write   "%h %l %u %t \"%r\" %s %b"

#DON'T modify this log format.  It's used by DirectAdmin to determine user usage
LogFormat               userlog "%u %b %m %a"
ExtendedLog             /var/log/proftpd/xxx.xxx.xxx.xxx.bytes WRITE,READ userlog

AuthUserFile                    /etc/proftpd.passwd
DefaultServer           on
AuthOrder mod_auth_file.c

#AuthPAM off

<IfModule mod_tls.c>
        TLSEngine on
        TLSLog /var/log/proftpd/proftpd.tls.log
        TLSProtocol SSLv23
        #TLSProtocol TLSv1
        TLSVerifyClient off
        TLSRequired off

        #Certificates
        TLSRSACertificateFile /etc/exim.cert
        TLSRSACertificateKeyFile /etc/exim.key
        #TLSCACertificateFile /etc/ftpd/root.cert.pem

        TLSCipherSuite HIGH:MEDIUM:+TLSv1:!SSLv2:+SSLv3
</IfModule>

<Global>
        PassivePorts            35000 35999
        DeferWelcome            on

        RequireValidShell       no

        DefaultRoot             ~
        DirFakeUser on ftp
        DirFakeGroup on ftp

        User                    ftp
        Group                   ftp
        #UserAlias              anonymous ftp

        AllowStoreRestart       on
        AllowRetrieveRestart    on

        ListOptions             -a
        ShowSymlinks            on
        <IfModule mod_facts.c>
                ##Enable this with proftpd 1.3.4b+ to fix FileZilla MLSD
                ##http://www.proftpd.org/docs/modules/mod_facts.html#FactsOptions
                # FactsOptions UseSlink
        </IfModule>

        Umask                   022
        DisplayLogin            welcome.msg
        DisplayChdir            readme
        AllowOverwrite          yes
        IdentLookups            off
        ExtendedLog             /var/log/proftpd/access.log WRITE,READ write
        ExtendedLog             /var/log/proftpd/auth.log AUTH auth

        #
        # Paranoia logging level....
        #
        #ExtendedLog    /var/log/proftpd/paranoid.log ALL default

        <IfModule mod_tls.c>
                TLSEngine on
                TLSLog /var/log/proftpd/proftpd.tls.log
                TLSRSACertificateFile /etc/exim.cert
                TLSRSACertificateKeyFile /etc/exim.key
        </IfModule>
</Global>

Include /etc/proftpd.vhosts.conf

A: According to your configuration, you should change
AuthOrder mod_auth_file.c

by
 AuthOrder mod_auth_pam.c* mod_auth_unix.c

Because mod_auth_file.c is made only for use the proftpd special auth file.
You can consult AuthOrder options here ==> Proftpd AuthOrder directive


text:
Q: Jquery Json response works on everything but Ipad I am posting back to get a list of stores after the user enters an address and clicks a button. This works great in all browsers except for the Ipad. In its case it returns a success status but an empty data object. Below is my script and server response code. I have googled everything I can think of but have not found a similar issue. Any help would be appreciated.
---Javascript---------------------
$.post("/storefinder/GetStores",
{
lng: lng,
lat: lat
},
function (data, status) {
var storeLoc = data.split(' -- ')
setupStores(storeLoc);
});

---MVC Controller code----------------
[HttpPost]
public ActionResult GetStores(string lng, string lat)
{
double dLng = double.MaxValue;
double dLat = double.MaxValue;
double.TryParse(lng, out dLng);
double.TryParse(lat, out dLat);
StringBuilder rtrnString = new StringBuilder();

List<Hls.Mapping.Retailer> AllRetailers = Infrastructure.Cache.HeelysCacheItems.RetailerList(false);
List<Hls.Mapping.Retailer> ClosestRetailers = Hls.Mapping.MapRequest.ClosestRetailers(dLat, dLng, 20, AllRetailers);

foreach (Hls.Mapping.Retailer r in ClosestRetailers)
{
    rtrnString.Append(r.DisplayName);
    rtrnString.Append(" -- ");
    rtrnString.Append(r.Address1);
    rtrnString.Append(" -- ");
    rtrnString.Append(r.City + ", " + r.State + " " + r.ZipCode);
    rtrnString.Append(" -- ");
    rtrnString.Append(r.Phone);
    rtrnString.Append(" -- ");
    rtrnString.Append("Distance: " + Math.Round(r.distance, 2).ToString() + " miles");
    rtrnString.Append(" -- ");
    rtrnString.Append(r.Latitude.ToString());
    rtrnString.Append(" -- ");
    rtrnString.Append(r.Longitude.ToString());
    rtrnString.Append(" -- ");
}

return Json(rtrnString.ToString());
}


text:
Q: Book about a group of magicians hunting a creature The book I'm trying to remember was about a group of children that were being trained magic in a society of other magicians.  One of the biggest things I remember was a chapter where a team of children, including the protagonist, were forced to sift through a pile of dirt and sand, lifting the grains one by one until they were all sorted. I also remember them later running into the woods to hunt down some creature who took one of them away. I'm sorry I can't remember more. I believe it was released after 2000.

A: This is not a perfect match.  However, the sorting scene sounds very much like something that happens near the end of The Phantom Tollbooth, a classic fantasy adventure novel by Norton Juster and illustrated by The Village Voice's editorial cartoonist, Jules Feiffer.  Other things do not match so well:  the book is quite a bit older than you suggest, having been published back in 1961; and while there is a lot of magic and plenty of lessons for the child protagonist, those lessons do not involve what we would normally think of as learning "magic" (although see below).
The Phantom Tollbooth tells of a boy, Milo, who goes on a remarkable adventure.  As Wikipedia describes it:

Milo is a boy bored by the world around him; every activity seems a waste of time. He arrives home from another boring day at school to find a mysterious package. Among its contents are a small tollbooth and a map of "the Lands Beyond," illustrating the Kingdom of Wisdom (which will also guide the reader from its place on the endpapers of the book). Attached to the package is a note "For Milo, who has plenty of time." Warned by an included sign to have his destination in mind, he decides without much thought to go to Dictionopolis, assuming this is a pretend game to be played on the floor of his room. He maneuvers through the tollbooth in his electric toy car, and instantly finds himself driving on a road that is clearly not in his city apartment.

Milo gets involved in a quest to rescue the princesses Rhyme and Reason, who have been exiled to the Mountains of Ignorance.  He acts as an agent of by the feuding kings of the Kingdom of Wisdom, Azaz the Unabridged, who teaches Milo about the magic of words, and the Mathemagician, who (unsurprisingly), teaches Milo about the magic than can be done with mathematics.  With Milo are a young watchdog (with clocks on his flanks), Tock, and another rather immature character, the Humbug, whose job is basically to be wrong about everything.
Along the way, they pass through a number of dangerous stretches of forest, including instances where members the trio are temporarily separated.
Among the Mountains of Ignorance, the trio find the Terrible Trivium, one of the demons who infest the mountains.

The polite gentleman asks Milo to move a large pile of sand using tiny tweezers. Then he asks Tock to empty the water from one well into another well using an eye dropper. Finally, he asks the Humbug to use a needle to dig a hole through the cliff.
After the three friends have been working for many hours without seeing any progress, they begin to feel frustrated and start to question the man about why they are doing these jobs. Milo uses the magic staff he got from the Magician to find out how long the jobs will take. The answer is that it will take 837 years to finish the jobs!

(The magic staff mentioned in that summary is actually a pencil, which Milo uses to perform the necessary calculation.)


text:
Q: How do i perform q-learning in Excel? I would like to get the row number and column latter in excel this is what I have:

In H1 I have 4,4 so the excel should check from A22:A6 column and return A5 in I1 but I am getting $A$2 using this formula =CELL("address",INDEX(A2:A6,H1),0). Anyone know what I am doing wrong plus I want to remove that $ signs.

A:
See the image. This is structured identical, and you can see that is the formula I used.

A: An alternative:
="A"&MATCH(H1,A:A,0)


text:
Q: Is it possible to position overlay div on a horizontal scrollable content with css - no JS I have div with horizontal scrollable content. Trying to apply overlay for the entire content just using css. This scrollable content may keep growing. Is there a way to achieve this without javascript code.

.bg {
  height: 50px;
  width: 50px;
  display: flex;
}
.container {
  display: flex;
  overflow-x: auto;
  width: 300px;
  align-items: flex-start;
  position: relative;
  flex-direction: row;
}
.overlay {
  position: absolute;
  background-color: #888888;
  top: 0;
  opacity: 0.8;
  bottom: 0;
  right: 0;
  left: 0;
}

A: try this

Using the overlay effect by flex property  instead of absolute positioning.

.overlay{
  white-space:nowrap;  display: flex;
  align-items: flex-start;
  flex-direction: row;
  background-color: #888888;
  opacity: 0.8;
}

And add the images inside the overlay div

    <-- images here --->

.bg {
  height: 50px;
  width: 50px;
  display: flex;
}
.container {
  display: flex;
  overflow-x: auto;
  width: 300px;
  align-items: flex-start;
  position: relative;
  flex-direction: row;
}

.overlay{
  white-space:nowrap;  display: flex;
  align-items: flex-start;
  flex-direction: row;
  background-color: #888888;
  opacity: 0.8;
}

.images img{ white-space: normal;}

A: position:sticky can do it:

.bg {
  height: 50px;
  width: 50px;
  display: flex;
}

.container {
  display: flex;
  overflow-x: auto;
  width: 300px;
  position: relative;
  flex-direction: row;
}

.overlay {
  position: sticky;
  width:inherit;
  margin-right:-300px;
  flex-shrink:0;
  left:0;
  background-color: #888888;
  opacity: 0.8;
}


text:
Q: CSS color vs. background-color vs. background? In HTML when do I use color, and what is the difference between background-color and also the background tag?
What are the differences?

A: I will give you a example using this html element:
 This is my text
.value { color: red, background-color: black}
The CSS color is used to change the text color of a html element. In this example "This is my text" would be red. The CSS background-color is used to change the background color so in this case you would get a black box with red text inside it. Finally the background is used to set all the background properties in one declaration. For example:
background: #00ff00 url("smiley.gif") no-repeat fixed center;
This changes the background color, adds the image "smiley.gif" to the background and it centers the image, it doesnt repeat the image if it has the space.

A: Quick answer

*

*Color = Text Color

*Background-color = the color of the background

*Background = gives you the posibillity to set color, image , etc...

great tutorials on this are found here

A: It is true that background gives more options versus background-color.  But if you only need to set background color, they are exactly the same, and each will override the other as seen in the snippet.
background: yellow;

background-color: yellow;

.bc {
  background: yellow;
  background-color: green;
}

.bc2 {
  background-color: green;
  background: yellow;
}

  bc { background:yellow; background-color:green; }

  bc { background-color:green; background:yellow; }

A: One big thing about this both css properties is, that a background-color does not overwrite an image or a gradient that has been set with this:
background:url('https://example.com/image.jpg');

or
background: linear-gradient(to bottom, #1e5799 0%,#2989d8 20%,#207cca 51%,#7db9e8 100%);

If you are trying to change the background from an image to a color you have to use the background property.

A: color: is used to add color to the Text within the Tag.
color: blue;

background-color: is used to add color in background of the content inside the tag.
background-color : red;

background: is used for adding different type of background property name to the content within the Tag.
background : red url('image.png') fixed repeat cover;

A: color is referring to the text color in that element.
background-color refers to the background color
background is shorthand to combine many background tags into one line.
background: #ffffff url("img_tree.png") no-repeat right top;

Combines color, image and background image properties in the one line instead of typing our each style individually.
w3schools


text:
Q: Horizontal CSS Layout I'm trying to learn to do things the "CSS" way as opposed to using tables. I have a basic form that needs to be layed out like the following:
Label 1: [Drop Down List]     Label 2: [Drop Down List]   Label 3: Drop Down List

Collectively, the three will be left aligned and NOT take up the entire width of the screen. However, the sizes of the drop down list elements will be dynamic based on the data that fills them. If I were using a table, I would just do the following:

    Label 1:
    <select>...</select>

    Label 2:
    <select>...</select>

    Label 3:
    <select>...</select>

Unfortunately, I'm not sure how to do this via CSS. Any insights are appreciated.
Thank you!

A: You can just put all the elements after each other in the HTML and give the label elements display:inline-block and margin-left: 50px.
HTML
Label 1 <select>...</select>
Label 2 <select>...</select>
Label 3 <select>...</select>

CSS
label {
 display: inline-block; /* perhaps not needed, as commented by cimmanon */
 margin-left: 50px;
}

Live demo
http://jsfiddle.net/Ezgtq/1/

A: Label: <select>....</select>
Label: <select>....</select>
Label: <select>....</select>

CSS:
select {
display:inline-block;
margin-left:12px;
width:40px; /* What You Want */
}

JS Fiddle


text:
Q: Gracefully shutdown JBoss application I am looking for an approach to gracefully handle shutdown of JBoss (Wildfly AS 8.2). This would mean that all current requests are served and the webapp stops receiving further requests. I found that this is possible via command line in version 9 of the application server -
./jboss-cli.sh --controller=remoting://<host>:<port>
--connect --command=:shutdown(timeout=t)

Using this JBoss gracefully handles all requests for t seconds and gracefully shuts down (this would require an upgrade from version 8 to 9).
One possible approach would be to handle this in the Java application by maintaining a count of active requests and waiting for this number to go to 0 till a timeout and then exitting, basically replicating the above mentioned functionality.
I need to shutdown the webapp/JBoss remotely, so we are looking for a JMX (Java Management Extension) based solution. Does JBoss expose any such operation to gracefully shut down possibly via JMX or any other technology?
PS- Ctrl-C or kill commands donot shutdown JBoss gracefully.

A: JBoss EAP 6/7 and above allows graceful shutdown via CLI and even:

The signals SIGHUP, SIGINT and SIGTERM all trigger a graceful shutdown of the JBoss 7/6 application server. Those are signals are respectively the commands kill -1 $PID, kill -2 $PID(or control+c), and kill $PID.

https://access.redhat.com/solutions/18601

A: You can use the Jboss cli remotely as the URL you pass in the controller param shows. You could even use the "REST" API to execute it.
The shutdown should be available from JMX.


text:
Q: Read Minecraft Forge configuration file from Bukkit plugin? I am trying to read the contents of a forge cfg file from my bukkit plugin. I can successfully get the file, however I cannot read the values from bukkits' FileConfiguration (as far as I'm aware of). Here is an example forge cfg file from a mod:
# Configuration file

####################
# player1
####################

player1 {
    I:player2=1
    I:player3=1
}

####################
# player2
####################

player2 {
    I:player1=1
    I:player3=1
    I:player4=1
 }

Is it possible to read these values?

A: Forge uses a different format than bukkit, so the methods would not be compatible. You need to write a manual parser, copy in whatever forge uses, or use it from MCPC+ (As whatever you want is most likely targeted for an MCPC+ server (A spigot server (a kind of bukkit) mixed with forge).


text:
Q: Workarounds for emulating UDFs for window aggregates in BigQuery? I'm trying to write custom aggregate functions in BigQuery. In PGSQL, I can write user-defined aggregate functions which can be used with over clause, but I'm not able to write any such aggregate functions for BigQuery - would it be possible to write a function that takes in an entire array of a column of a partition and return a value based on some custom calculation?
Example of what I tried:
CREATE OR REPLACE FUNCTION temp_db.temp_func(arr ARRAY<int64>)
RETURNS int64 LANGUAGE js AS """
  return arr.length*10 //example calculation
  //actual result involves looping over the array and doing few calculations
""";

select s_id, temp_db.temp_func(s_price) over (partition by s_id order by s_date rows 40 preceding) as temp_col
from temp_db.s_table;

This gives an error: Query error: Function temp_db.temp_func does not support an OVER clause at [6:19]
The existing aggregate functions are not sufficient for my purpose so I need to be able to execute custom calculation over custom window sizes. Are there any workarounds for this in BigQuery?

A: CREATE OR REPLACE FUNCTION temp_db.temp_func(arr ARRAY<int64>)
RETURNS int64 LANGUAGE js AS """
  return arr.length*10 //example calculation
  //actual result involves looping over the array and doing few calculations
""";

select s_id, temp_db.temp_func(ARRAY_AGG(s_price) over (partition by s_id order by s_date rows 40 preceding)) as temp_col
from temp_db.s_table;


text:
Q: Drag and drop from finder to WebView I'm using a WebView in edit mode. I have implemented this method from WebUIDelegate Procotol:
- (void)webView:(WebView *)sender willPerformDragDestinationAction:(WebDragDestinationAction)action forDraggingInfo:(id < NSDraggingInfo >)draggingInfo

and use it to catch the drops of elements on my WebView. When I detect a file being dragged from outside my app, and containing a picture, I build in this method the img DOM element and add it to my document.
This works fine, but as the method's name implies, I am only informed that the drag will happen, and I have no control over it.
As the Finder always does file drag operation, what normally happens when dropping a file on a WebView in editing mode is the webview displays the path of the file.
I end up having the file path string added to my webview, and the image too, but I would like to prevent the text from being added.
Is there any way to configure this without subclassing webview?
I tried it and while it works, it breaks plenty of other things like caret moving for the drop and such.

A: I ran into the same issue.
What I found is that subclassing the view is the best place for this to insert the image data into the pasteboard. Here is how I am doing it for multiple files:
- (BOOL) performDragOperation:(id<NSDraggingInfo>)sender {

    if ( [sender draggingSource] == nil ) {

        NSPasteboard *pboard = [sender draggingPasteboard];

        NSArray *classes = @[ [NSURL class] ];
        NSDictionary *options = @{ NSPasteboardURLReadingFileURLsOnlyKey: [NSNumber numberWithBool:YES],
                                   NSPasteboardURLReadingContentsConformToTypesKey: [NSImage imageTypes] };

        NSArray *fileURLs = [pboard readObjectsForClasses:classes options:options];

        if ( fileURLs ) {

            NSMutableArray *images = [NSMutableArray arrayWithCapacity:[fileURLs count]];

            for ( NSURL *fileURL in fileURLs )
                [images addObject:[[NSImage alloc] initWithContentsOfURL:fileURL]];

            [pboard declareTypes:[NSImage imageTypes] owner:nil];
            [pboard clearContents]; [pboard writeObjects:images];
        }

    } return [super performDragOperation:sender];
}

What I noticed is the following sequence:
1. WebView captures drag operation.
2. Internal WebCore created document fragment
3. Node is inserted into a DOMRange
4. Editing Delegate is called
5. Lastly UI Delegate is called where it is too late to do anything
Also, I suggest setting the following via the UI Delegate:
- (NSUInteger) webView:(WebView *)webView dragDestinationActionMaskForDraggingInfo:(id <NSDraggingInfo>)draggingInfo {

    return WebDragDestinationActionEdit;
}

Ok, now the ISSUE I am running into and I really hope you might have an answer for me. When I select one file no problem. When I select multiple files, I get them and add all of them into the pasteboard properly. Even when I get to (5) for the UIDelegate and inspect the draggingPasteboard for its count I get what is expected. But unfortunately the document fragment is only being created once and likewise only one node gets inserted.
Any ideas how to get multiple fragments to be created so that they can all be inserted?
Thank you in advance.

A: Answering this myself for a change!
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{

    if ([sender draggingSource] == nil)
    {

        NSPasteboard *pboard = [sender draggingPasteboard];

        if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
            NSURL* fileURL;
            fileURL=[NSURL URLFromPasteboard: [sender draggingPasteboard]];

            NSArray *dragTypes = [NSArray arrayWithObject:NSFileContentsPboardType];
            [[sender draggingPasteboard] declareTypes:dragTypes owner:nil];

            NSImage *content = [[NSImage alloc] initWithContentsOfURL:fileURL];
            [[sender draggingPasteboard] setData:[content TIFFRepresentation] forType:NSPasteboardTypeTIFF];
        }
    }

    return [super performDragOperation:sender];

}

Actually, what I did was indeed to subclass the WebView and intercept the performDragOperation to change the content of the dragging pasteboard, if the dragging source is outside of my app and doesn't contain already an image but only a filename.

A: Fixed version for the previous replies, this code works for multiple images dragged in the web view.
- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender
{
    if ( [sender draggingSource] == nil )
    {
        NSPasteboard *pboard = [sender draggingPasteboard];
        NSArray *classes = @[ [NSURL class] ];
        NSDictionary *options = @{ NSPasteboardURLReadingFileURLsOnlyKey: [NSNumber numberWithBool:YES],
                                   NSPasteboardURLReadingContentsConformToTypesKey: [NSImage imageTypes] };
        NSArray *fileURLs = [pboard readObjectsForClasses:classes options:options];

        if(fileURLs)
        {
            NSArray* filenames = [pboard propertyListForType: NSFilenamesPboardType];
            NSMutableString* html = [NSMutableString string];

            for(NSString* filename in filenames) {
                [html appendFormat: @"<img src=\"%@\"/>", [[[NSURL alloc] initFileURLWithPath: filename] absoluteString]];
            }

            [pboard declareTypes: [NSArray arrayWithObject: NSHTMLPboardType] owner: self];
            [pboard setString: html forType: NSHTMLPboardType];
        }

    } return [super performDragOperation:sender];
}


text:
Q: how to upgrade laravel from 4.0 to 4.2 by keeping the old code base working I am using laravel 4.0 for my website, and now i want to add few plugins to the website. But the plugin supports laravel 4.2 , so  i want to upgrade to  laravel 4.2
I followed the official docs from laravel site but it dosen't work
My Composer.json is
{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"require": {
    "laravel/framework": "4.2.*",
    "navruzm/lmongo": "*",
    "imagine/imagine": "~0.5.0",
    "phpoffice/phpexcel": "dev-develop",
    "thujohn/analytics": "dev-master"
},
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
"autoload-dev": {
    "classmap": [
        "tests/TestCase.php"
    ]
},
"scripts": {
    "post-install-cmd": [
        "php artisan clear-compiled",
        "php artisan optimize"
    ],
    "post-update-cmd": [
        "php artisan clear-compiled",
        "php artisan optimize"
    ],
    "post-create-project-cmd": [
        "php -r \"copy('.env.example', '.env');\"",
        "php artisan key:generate"
    ]
},
"config": {
    "preferred-install": "dist"
},
"minimum-stability": "dev"
}

Now when i try to update the composer i get errors like
symfony/security-core suggests installing symfony/validator (For using the user password constraint)
symfony/security-core suggests installing symfony/expression-language (For using the expression voter)
phpseclib/phpseclib suggests installing ext-gmp (Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.)
phpseclib/phpseclib suggests installing pear-pear/PHP_Compat (Install PHP_Compat to get phpseclib working on PHP < 4.3.3.)


text:
Q: Unable to GET url data into model class Currently I have a table that shows a count of all the statuses of a product. Now these counts are clickable and lead to another page that shows the in detail data of whatever item that was clicked. I'm able to get this data by putting it in the URL using

This correctly puts the data for the product that I had clicked in the URL.
Now I'm trying to get this data from the URL and accordingly filter the data according to the values that are present in the URL, but I cannot get the value from to URL to filter it even after I've used $leadsource = $this->input->get('status');
View Class:
<?php
$sess=$this->session->userdata();
$post = array('fstatus'=> $sess['fstatus'],'fsource'=> $sess['fsource']);
$postd = json_encode(array_filter($post));
$leadstatus = $this->input->get('source');
?>

                Ref.No#
                Source


text:
Q: Is this the correct use of NSFetchedResultsController? Is this is correct us of NSFetchedResultsController's getter method with the most modern Object-C and LLVM compiler that doesn't require synthesizing properties?
- (NSFetchedResultsController *)fetchedResultsController {
    if (_fetchedResultsController) {
        return _fetchedResultsController;
    }

    if (!self.managedObjectContext) {
        self.managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    }

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Session" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    [fetchRequest setPredicate: self.predicate];
    [fetchRequest setFetchBatchSize:20];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

    NSFetchedResultsController *aFetchedResultsController= [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
    aFetchedResultsController.delegate = self;

    NSError *error = nil;
    if (![aFetchedResultsController performFetch:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return aFetchedResultsController;
}

In other parts of my code, I have this instead:
- (NSFetchedResultsController *)fetchedResultsController {
    if (_fetchedResultsController) {
        return _fetchedResultsController;
    }

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Set" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat: @"sets == %@", self.exercise]];
    [fetchRequest setFetchBatchSize:20];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;

    NSError *error = nil;
    if (![self.fetchedResultsController performFetch:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return self.fetchedResultsController;
}

A: In your first example, you never assign anything to the property or ivar, so the lazy loading will occur every time the property is accessed. This isn't right.
In your second example you assign to the property, (thereby triggering any side effects of the property setter) and also return the value of the property (which wouldn't take many errors to leave you with an infinite loop). It may work now but it would be easy to break with a careless update.
It would be cleaner to assign to the internal ivar and return that.
So, at the end of your first example:
_fetchedResultsController = aFetchedResultsController;
 return _fetchedResultsController;


text:
Q: Reading files in PhoneGap/Cordova 3.1 So, I'm developing an app that requires a prepopulated database. According to Raymon Camden, there's no direct way in packaging a pre-made database with the app. As a solution, I'll execute a Select count(*)... statement to check and insert if result <= 0,
Now problem is the insertion. I have ~500 rows for a table, and I don't want to paste them in the js file. I found the File API and I believe I can read the .sql file, then execute.
Questions:

*

*How does PhoneGap 3.1 (ugh, naming.) package apps? In my www directory I have

*

*js

*css

*dev

*

*data.sql

So, initially I thought fileSystem.root.getFile('/dev/data.sql', ... would work. (Basing on this, where MattDavis said app data goes to /data/data/packageName.)

*How do I access the file?

*Am I on the right track? Or, is there a better approach?

I am using Cordova 3.1 to build, with the awesome support of Netbeans.
EDIT
I tried creating a .txt file on the root dir of my device. I can successfully access it with fileSystem.root.getFile('test.txt', ...). And so I infer that I simply need to get the actual app directory.

A: Yes, your in right track only. Because your access with in asset/www/dev/ inside data.sql.
/data/data/packageName this is for accessing SD inside your app (app internal storage). so no need do like that.

A: How did I access the file? + Or, is there a better approach?
AJAX. It turns out that I can access the assets folder through:
    $.get('file:///android_asset/www/dev/data.sql', function(response){
        console.log('Data found!');
        console.log(response);
    });

I am not sure if this'll work with other platforms.


text:
Q: How to scroll to a position in Flutter Stepper? I'm using the vertical type stepper, where I have multiple steps (over 20), I want the step with the isActive property to appear at the beginning, but I can still scroll up to see the previous ones.

Stepper(
                  key: key_1,
                  physics: ClampingScrollPhysics(),
                  onStepTapped: (step) => goTo(step),
                  currentStep: currentStep,
                  controlsBuilder: (BuildContext context,
                      {VoidCallback onStepContinue,
                        VoidCallback onStepCancel}) {
                    return Row(
                      children: <Widget>[
                        Container(
                          child: null,
                        ),
                        Container(
                          child: null,
                        ),
                      ],
                    );
                  },
                  steps: steps)

Example: if step 2 is active, I want it to appear at the beginning and that step 1 when scrolling above can see it, but visually the one that is at the beginning is step 2
enter image description here

A: In my case what I did was a modification in the Stepper widget.
Declare the scrollController variable, as follows:
const Stepper({
    Key key,
    @required this.steps,
    this.physics,
    this.scrollController, //Declarate ScrollController
    this.type = StepperType.vertical,
    this.currentStep = 0,
    this.onStepTapped,
    this.onStepContinue,
    this.onStepCancel,
    this.controlsBuilder,
  })  : assert(steps != null),
        assert(type != null),
        assert(currentStep != null),
        assert(0 <= currentStep && currentStep < steps.length),
        super(key: key);
  final ScrollController scrollController;

Once the variable is declared, in the ListView you proceed to add the scrollController as follows:
  Widget _buildVertical() {
    return ListView(
      shrinkWrap: true,
      physics: widget.physics,
      controller: widget.scrollController,//Add ScrollController here
      children: <Widget>[
        for (int i = 0; i < widget.steps.length; i += 1)
          Column(
            key: _keys[i],
            children: <Widget>[
              InkWell(
                onTap: widget.steps[i].state != StepState.disabled
                    ? () {
                        // In the vertical case we need to scroll to the newly tapped
                        // step.
                        Scrollable.ensureVisible(
                          _keys[i].currentContext,
                          curve: Curves.fastOutSlowIn,
                          duration: kThemeAnimationDuration,
                        );

                        if (widget.onStepTapped != null) widget.onStepTapped(i);
                      }
                    : null,
                canRequestFocus: widget.steps[i].state != StepState.disabled,
                child: _buildVerticalHeader(i),
              ),
              _buildVerticalBody(i),
            ],
          ),
      ],
    );
  }

Once that is done, you will have control in the Stepper class, just declare a final variable as scrollController in your document, like this:
final _controller = new ScrollController();

Attach the controller to the Stepper.
When you press onStepContinue, move the animation to the position you want in the controller. I leave you my detailed example below:
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class MyStepper extends StatefulWidget {
  @override
  _MyStepperState createState() => _MyStepperState();
}

class _MyStepperState extends State<MyStepper> {
  int _currentStape = 0;
  final _controller = new ScrollController();
  @override
  Widget build(BuildContext context) {
    return Material(
      child: Container(
        width: double.infinity,
        height: double.infinity,
        child: Stepper(
          currentStep: _currentStape,
          scrollController: _controller,
          physics: ClampingScrollPhysics(),
          onStepContinue: () {
            _currentStape++;
            _controller.animateTo(
              0,
              duration: Duration(milliseconds: 100),
              curve: Curves.bounceIn,
            );
            setState(() {});
          },
          onStepTapped: (value) {
            _currentStape = value;
          },
          steps: [
            Step(
              title: FaIcon(
                FontAwesomeIcons.dog,
              ),
              subtitle: Text('Ingresa la información de tu mascota'),
              content: Container(
                height: 500,
              ),
            ),
            Step(
              title: FaIcon(
                FontAwesomeIcons.userAlt,
              ),
              subtitle: Text('Ingresa tú información personal'),
              content: Container(
                height: 500,
              ),
            ),
            Step(
              title: FaIcon(
                FontAwesomeIcons.image,
              ),
              subtitle: Text('Agrega algunas imágenes'),
              content: Text('Contenido'),
            ),
          ],
        ),
      ),
    );
  }
}

I'm use Flutter 1.17.3


text:
Q: Java for loop to determine legal triangles Three numbers form a legal triangle if the sum of two of the sides are greater than the third. So [7,3,6] and [8,8,8] are valid, whereas [2,6,4] and [8,6,1] are not. I am given an array with only 3 values.
public boolean isLegalTriangle(double[] lens){
  a = lens[0]
  b = lens[1]
  c = lens[2]

  return ( a+b > c && b+c > a && a+c > b )
}

This is the code I have written. Is it possible to rewrite this with a for-loop? (hard-coding the indexes seems primitive)

A: You can use modulo to achieve this:
public boolean isLegalTriangle(double[] lens){
    int l = lens.length;
    for (int i = 0 ; i < l; i++) {
        if ( lens[i%l] + lens[(i+1)%l] <= lens[(i+2)%l] ) {
            return false;
        }
    }
    return true;
}

You will have 3 iterations:

*

*i = 0
lens[0] + lens[1] <= lens[2]

*i = 1
lens[1] + lens[2] <= lens[0]

*i = 2
lens[2] + lens[0] <= lens[1]

A: You could sort the incoming array (using Array.sort() - this will sort the array in-place), and then compare the largest (first) entry vs. the sum of the 2nd/3rd entries, avoiding the multiple clauses in your 'if' statement.
However the above seems concise and readable, and I would favour that generally.

A: Sum the values up. If any value is greater than or equal to half the sum then it's not a valid triangle.
public boolean isLegalTriangle(double[] lens){
  double max = (lens[0] + len[1] + lens[2]) * 0.5;

  return (lens[0] < max) && (lens[1] < max) && (lens[2] < max);
}

using for loops:
public boolean isLegalTriangle(double[] lens){
  double max = 0.0;
  for(int i = 0; i < 3; i++)
      max += lens[i];
  max *= 0.5;

  for(int i = 0; i < 3; i++)
      if(lens[i] >= max)
          return false;
  return true;
]


text:
Q: How to prevent creating intermediate objects in cascading operators? I use a custom Matrix class in my application, and I frequently add multiple matrices:
Matrix result = a + b + c + d; // a, b, c and d are also Matrices

However, this creates an intermediate matrix for each addition operation. Since this is simple addition, it is possible to avoid the intermediate objects and create the result by adding the elements of all 4 matrices at once. How can I accomplish this?
NOTE: I know I can define multiple functions like Add3Matrices(a, b, c), Add4Matrices(a, b, c, d), etc. but I want to keep the elegancy of result = a + b + c + d.

A: You could limit yourself to a single small intermediate by using lazy evaluation. Something like
public class LazyMatrix
{
    public static implicit operator Matrix(LazyMatrix l)
    {
        Matrix m = new Matrix();
        foreach (Matrix x in l.Pending)
        {
            for (int i = 0; i < 2; ++i)
                for (int j = 0; j < 2; ++j)
                    m.Contents[i, j] += x.Contents[i, j];
        }

        return m;
    }

    public List<Matrix> Pending = new List<Matrix>();
}

public class Matrix
{
    public int[,] Contents = { { 0, 0 }, { 0, 0 } };

    public static LazyMatrix operator+(Matrix a, Matrix b)
    {
        LazyMatrix l = new LazyMatrix();
        l.Pending.Add(a);
        l.Pending.Add(b);
        return l;
    }

    public static LazyMatrix operator+(Matrix a, LazyMatrix b)
    {
        b.Pending.Add(a);
        return b;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Matrix a = new Matrix();
        Matrix b = new Matrix();
        Matrix c = new Matrix();
        Matrix d = new Matrix();

        a.Contents[0, 0] = 1;
        b.Contents[1, 0] = 4;
        c.Contents[0, 1] = 9;
        d.Contents[1, 1] = 16;

        Matrix m = a + b + c + d;

        for (int i = 0; i < 2; ++i)
        {
            for (int j = 0; j < 2; ++j)
            {
                System.Console.Write(m.Contents[i, j]);
                System.Console.Write("  ");
            }
            System.Console.WriteLine();
        }

        System.Console.ReadLine();
    }
}

A: In C++ it is possible to use Template Metaprograms and also here, using templates to do exactly this. However, the template programing is non-trivial. I don't know if a similar technique is available in C#, quite possibly not.
This technique, in c++ does exactly what you want. The disadvantage is that if something is not quite right then the compiler error messages tend to run to several pages and are almost impossible to decipher.
Without such techniques I suspect you are limited to functions such as Add3Matrices.
But for C# this link might be exactly what you need: Efficient Matrix Programming in C# although it seems to work slightly differently to C++ template expressions.

A: Something that would at least avoid the pain of
Matrix Add3Matrices(a,b,c) //and so on

would be
Matrix AddMatrices(Matrix[] matrices)

A: You can't avoid creating intermediate objects.
However, you can use expression templates as described here to minimise them and do fancy lazy evaluation of the templates.
At the simplest level, the expression template could be an object that stores references to several matrices and calls an appropriate function like Add3Matrices() upon assignment. At the most advanced level, the expression templates will do things like calculate the minimum amount of information in a lazy fashion upon request.

A: This is not the cleanest solution, but if you know the evaluation order, you could do something like this:
result = MatrixAdditionCollector() << a + b + c + d

(or the same thing with different names). The MatrixCollector then implements + as +=, that is, starts with a 0-matrix of undefined size, takes a size once the first + is evaluated and adds everything together (or, copies the first matrix). This reduces the amount of intermediate objects to 1 (or even 0, if you implement assignment in a good way, because the MatrixCollector might be/contain the result immediately.)
I am not entirely sure if this is ugly as hell or one of the nicer hacks one might do. A certain advantage is that it is kind of obvious what's happening.

A: I thought that you could just make the desired add-in-place behavior explicit:
Matrix result = a;
result += b;
result += c;
result += d;

But as pointed out by Doug in the Comments on this post, this code is treated by the compiler as if I had written:
Matrix result = a;
result = result + b;
result = result + c;
result = result + d;

so temporaries are still created.
I'd just delete this answer, but it seems others might have the same misconception, so consider this a counter example.

A: Might I suggest a MatrixAdder that behaves much like a StringBuilder. You add matrixes to the MatrixAdder and then call a ToMatrix() method that would do the additions for you in a lazy implementation. This would get you the result you want, could be expandable to any sort of LazyEvaluation, but also wouldn't introduce any clever implementations that could confuse other maintainers of the code.

A: Bjarne Stroustrup has a short paper called Abstraction, libraries, and efficiency in C++ where he mentions techniques used to achieve what you're looking for. Specifically, he mentions the library Blitz++, a library for scientific calculations that also has efficient operations for matrices, along with some other interesting libraries. Also, I recommend reading a conversation with Bjarne Stroustrup on artima.com on that subject.

A: It is not possible, using operators.

A: My first solution would be something along this lines (to add in the Matrix class if possible) :
static Matrix AddMatrices(Matrix[] lMatrices) // or List<Matrix> lMatrices
{
    // Check consistency of matrices

    Matrix m = new Matrix(n, p);

    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            foreach (Maxtrix mat in lMatrices)
                m[i, j] += mat[i, j];

    return m;
}

I'd had it in the Matrix class because you can rely on the private methods and properties that could be usefull for your function in case the implementation of the matrix change (linked list of non empty nodes instead of a big double array, for example).
Of course, you would loose the elegance of result = a + b + c + d. But you would have something along the lines of result = Matrix.AddMatrices(new Matrix[] { a, b, c, d });.

A: There are several ways to implement lazy  evaluation to achieve that.  But its important to remember that not always your compiler will be able to get the best code of all of them.
I already made implementations that worked great in GCC and even superceeded the performance of the traditional several For unreadable code because they lead the compiler to observe that there were no aliases between the data segments (somethign hard to grasp with arrays coming of nowhere). But some of those were a complete fail at MSVC and vice versa on other implementations. Unfortunately those are too long to post here (don't think several thousands lines of code  fit  here).
A very complex library with great embedded knowledge int he area is Blitz++ library for scientific computation.


text:
Q: Specified cast is not valid. Trying to display ObservableCollection to another page using Xamarin I'm trying to transfer string from <Entry/> on current to another page and save all strings when a button is pressed repeatedly.
My xaml on first page look like this:
<ImageButton Source="blackheart.png"
                    Grid.Row="1"
                    Grid.Column="3"
                    WidthRequest="40"
                    HeightRequest="40"
                    Opacity="0.7"
                    Clicked="OnGetFavorites"/>

My .cs file on first page look like this:
void OnGetFavorites(System.Object sender, System.EventArgs e)
    {
        Preferences.Set("cityName", _cityEntry.Text);

        var tabbedPage = this.Parent.Parent as TabbedPage;

        var page = (Favorites)tabbedPage.Children[2];

        page.AddCity(_cityEntry.Text);

        tabbedPage.CurrentPage = page;
    }

On my second page on which I will display the xaml look like this:
<StackLayout Padding="0,30,0,0">

            <ListView x:Name="listView"
                      ItemsSource="{Binding CityData}"/>
</StackLayout>

My .cs file on second page look like this:
 public partial class Favorites : ContentPage
{
    ObservableCollection<string> CityData { get; set; }

    public Favorites()
    {
        InitializeComponent();
        NavigationPage.SetHasNavigationBar(this, false);

        CityData = new ObservableCollection<string>();
        this.BindingContext = this;
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
    }

    public void AddCity(string city)
    {
        CityData.Add(city);
    }
}

When I click the button on the first page to add the strings I get an error from Main.cs file:
Specified cast is not valid.

on this line:
UIApplication.Main(args, null, "AppDelegate");

At this step, the debugger passes: var page = (Favorites)tabbedPage.Children[2]; But at this step the debugger makes an error: page.AddCity(_cityEntry.Text);
Is there a way to fix this error ?


text:
Q: mod_jk between apache and tomcat: making sure 8080 requests still go to tomcat This question follows a mod_jk configuration question asked earlier. I have managed to to have http://mywebsite.com/MyTomcatApp/ go to Tomcat while having http://mywebsite.com/ go to Apache.
However, my requests to http://mywebsite.com:8080/ (to access Tomcat's manager for example) don't work anymore. How can/should I update my 000-default file mentioned in my previous question to keep access to Tomcat's manager under this configuration?
P.S.: Yes, I am a newbie/not a sysadmin.

A: Ok, I think understand the role of JkUnMount better. I changed my 000-default file to:
JkMount /* worker1
JkUnMount /*.html worker1

All goes to tomcat and I have access to the manager again. The default Apache html page is still served.


text:
Q: Characterizing freely adjoining K-filtered colimits as K-continuous presheaves Note: This question has a 1-categorical and an $\infty$-categorical versions. I am interested in the $\infty$-categorical one so this is the version that I write below, but an answer for the 1-categorical version would be interesting too.
Given an $\infty$-category $\mathcal{C}$ and a collection of simplciial sets $\mathcal{I}$, there is a notion of "freely adjoining to $\mathcal{C}$ all colimits of shape $\mathcal{I}$". This is the full subcategory $P_{\mathcal{I}}(\mathcal{C})$ of all presheaves on $\mathcal{C}$ generated from the image of the Yoneda by $\mathcal{I}$-colimts (HTT 5.3.6). Now, assume that $\mathcal{I}$ is not any collection, but the collection of all $I$, such that $I$-colimits commute in spaces with all $K$-limits for all $K$ in some collection $\mathcal{K}$. e.g.
1) $\mathcal{K}$ is finite simplicial sets and $\mathcal{I}$ is filtered simplicial sets.
2) $\mathcal{K}$ is finite discrete simplicial sets and $\mathcal{I}$ is sifted simplicial sets.
Assuming $\mathcal{C}$ admits all $K^{op}$-colimits for all $K\in \mathcal{K}$, in these two examples it is known that $P_{\mathcal{I}}(\mathcal{C})$ can be described as the full subcategory $P^{\mathcal{K}}(\mathcal{C})$ of the $\infty$-category of presheaves spanned by the ones which preserve $\mathcal{K}$-limits (for (1) HTT 5.3.5.4 and for (2) HTT 5.5.8.15). The proofs of these two facts seem to be quite different, so I am wondering
Question: Under the above conditions on $\mathcal{I}$, $\mathcal{K}$ and $\mathcal{C}$, does $P_{\mathcal{I}}(\mathcal{C})$ always coincide with $P^{\mathcal{K}}(\mathcal{C})$?
It is easy to see that we have an inclusion of $P_{\mathcal{I}}(\mathcal{C})$ into $P^{\mathcal{K}}(\mathcal{C})$, but the converse seems more complicated. I also have a creepy feeling that the words "sound doctrine" may come up...

A: For the 1-categorical case, it seems to be indeed a question of soundness. More precisely, the condition that $P_{\cal I}({\cal C}) = P^{{\cal K}}({\cal C})$ is equivalent to the condition that every ${\cal K}$-limit preserving presheaf $F:{\cal C}^{op} \to {\rm Set}$ is an ${\cal I}$-colimit of representables, or, in this case, a ${\cal K}$-filtered colimit of representables. Looking in this paper we see that this indeed holds whenever ${\cal K}$ is sound (theorem 2.4), and that furthermore, this being the case appears to be the main motivation for the definition of soundness. For example, it seems to me that $P_{\cal I}({\cal C})$ doesn't contain the terminal presheaf in the non-sound case described in Example 2.3 (vi) of loc.cit.
I would say that it's quite likely that the $\infty$-categorical case will behave similarly, once one defines soundness appropriately (maybe replace "connected" with "weakly contractible" in Definition 2.2 of loc.cit)?


text:
Q: Google-diff-match avoid showing new lines? I am using diff-match http://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_diff.html
To show differences between 2 pieces of html. The problem is that the script shows new line as ¶
Is there any way to set to don't show it?
Now I am just removing all istances of \n and \r, but this doesnt' sound good

A: As you have seen in the documentation, the pretty html function is just a sample to develop some cool ui. However, of you replace the ¶ (& para;) with null in the function, the symbol will disappear.
  diff_match_patch.prototype.diff_prettyHtml = function(diffs) {
    var html = [];
    var pattern_amp = /&/g;
    var pattern_lt = /</g;
    var pattern_gt = />/g;
    var pattern_para = /\n/g;
    for (var x = 0; x < diffs.length; x++) {
      var op = diffs[x][0];    // Operation (insert, delete, equal)
      var data = diffs[x][1];  // Text of change.
      //var text = data.replace(pattern_amp, '&').replace(pattern_lt, '<')
      //    .replace(pattern_gt, '>').replace(pattern_para, '¶
');
      var text = data.replace(pattern_amp, '&').replace(pattern_lt, '<')
          .replace(pattern_gt, '>').replace(pattern_para, '
');
      switch (op) {
        case DIFF_INSERT:
          html[x] = '' + text + '';
          break;
        case DIFF_DELETE:
          html[x] = '' + text + '';
          break;
        case DIFF_EQUAL:
          html[x] = '' + text + '';
          break;
      }
    }
    return html.join('');
  };

To test this, just go to the link you provided in Chrome and in console copy paste above function before hitting the compute diff button.


text:
Q: Are isometric normed linear spaces isomorphic? I should know the answer to this (and I did some time ago, but have forgotten): If the normed linear spaces $X$ and $Y$ are isometric (there is a bijective map from $X$ to $Y$ that preserves distances), are they linearly isomorphic (there is a continuous linear bijection from $X$ to $Y$ with a continuous inverse)?

A: This is true for real vector spaces by the Mazur-Ulam theorem which states that a surjective distance-preserving linear map of one real normed space onto another is an affine map. Indeed, if $f: X \to Y$ is such a map then $g(x) = f(x) - f(0)$ is a linear and onto isometry. The inverse of $g$ is of course linear and isometry, too, so in particular, $X$ and $Y$ are linearly isomorphic.
For a proof of this, one can't do better than refer to Väisälä's recent note which appeared in the Monthly, see here for the paywalled published version. References to the original works are given there.
Further remarks:

*

*One corollary of the Mazur-Ulam theorem is that the group of isometric and onto self-maps of a real normed space is isomorphic to $O(X) \ltimes X$, where $O(X)$ denotes the group of linear isometries and acts on $X$ in the obvious way. This generalizes the usual description of Euclidean isometry group $O(n) \ltimes \mathbb{R}^n$ nicely.

*If surjectivity of $f$ is dropped, the conclusion that $f$ needs to be affine is wrong. The example given by Väisälä is mentioned also this thread here: if we equip $\mathbb{R}^2$ with the max-norm and take $\phi:\mathbb{R} \to \mathbb{R}$ to be a non-linear $1$-Lipschitz map then the map $f: \mathbb{R} \to \mathbb{R}^2$ given by $f(x) = (x,\phi(x))$ is isometric but not affine.

*Isomorphic Banach spaces need not be isometric, as you showed yourself in this recent thread.

*As far as I know, the case of complex Banach spaces doesn't have such a nice formulation, since we need to ensure complex linearity in order to avoid silly counterexamples that stem from complex conjugation.

*Finally, the Mazur-Ulam theorem was mentioned in this MO thread, where Bill Johnson mentions a nice generalization by Figiel which shows in some sense that the counterexample given in 2. is worst possible.

*Tangentially relevant is also this MO thread on notions of isomorphisms of Banach spaces.


text:
Q: Unable to upload file via Python Django 1.10.3 Currently trying to create a small file upload system similar to what was done here I've been trying to get my code to let the user upload any file from their local PC and then let it be copied to my server. albeit with no luck, the example I was following has examples up to 1.9 Django and I can't see much variation with that and 1.10. I've attached my views.py for the project currently the website i have will not upload any type of file and im not sure why
    from django.shortcuts import render

# Create your views here.
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import render
from django.core.urlresolvers import reverse
from .forms import docform
from .models import Document

def upload(request):
    if request.method == 'POST':
        form = docform(request.FILES)
        if form.is_valid():
            newdoc = Document (newfile=request.FILES['newfile'])
            newdoc.save()

        return HttpResponseRedirect(reverse('upload'))
    else:
        form = docform()

    return render( request,'upload.html',)

Attaching upload.html
<!DOCTYPE html>

        File upload system

           <form action="{% url "upload" %}" method="post" enctype="multipart/form-data">
                {% csrf_token %}
                <input type="file" name=myfile" />

<input type="submit" value="upload"/>

            </form>


text:
Q: DRIVING_SITE Oracle Hint with One Remote Table in the script Is there any advantage of using DRIVING_SITE hint when accessing data from only one remote table. The execution plan remains same with and without the hint.
SELECT /*+ DRIVING_SITE(REMOTE_TABLE) */ distinct a.COL1_NB, a.COL2_TX, a.COL3_TX
FROM REMOTE_TABLE@DASH a
WHERE TRUNC(SYSDATE) BETWEEN A.HSTRY_EFCTV_DT AND HSTRY_XPRTN_DT

The Remote_table have close to 2M data and the resultset expected to have around 300K records.

A: Probably not.  If you are only querying objects in the remote database, it is highly unlikely that the optimizer would generate a plan where the local site was the driving site.  If you aren't seeing the query plan change, that implies that this query likely isn't one of the rare ones that the optimizer would screw up.
I'd strongly suggest removing the hint.

A: I have the following query in an Oracle R12 procedure:
SELECT /*+ DRIVING_SITE(FFUSA_MISSING_DOCS) */ *
FROM FFUSA_MISSING_DOCS@EBS_ONBASE FFUSA_MISSING_DOCS
WHERE "Renewal Date" >= DATE '2018-08-01' OR "Renewal Date" IS NULL;

EBS_ONBASE is a database link to MS SQL. I can't get it to filter on the remote database (where equivalent queries take 2 minutes instead of 12+ and return a lot fewer rows). So I personally would strongly suggest keeping the hint and trying to figure out how to get Oracle to listen to you long enough to have them support sending simple filters to remote non-Oracle databases. Here's the explain plan showing how it returns all the data then tries to filter:
------------------------------------------------------------------------------------------------
| Id  | Operation        | Name         | Rows  | Bytes | Cost (%CPU)| Time     | Inst   |IN-OUT|
------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT |              |   195 |   277K|   200   (0)| 00:00:01 |        |      |
|*  1 |  FILTER          |              |   195 |   277K|   200   (0)| 00:00:01 |        |      |
|   2 |   REMOTE         | MISSING_DOCS |       |       |            |          | EBS_O~ | R->S |
------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter("Renewal Date" IS NULL OR "Renewal Date">=TO_DATE(' 2018-08-01 00:00:00',
              'syyyy-mm-dd hh24:mi:ss'))

Remote SQL Information (identified by operation id):
----------------------------------------------------

   2 - SELECT {column list} FROM
       "MISSING_DOCS" (accessing 'EBS_ONBASE' )


text:
Q: Stueckelberg Feynman propagator computation On page 35 of Itzykson-Zuber's textbook on quantum field theory, I am having trouble deriving equation (1-180):
$\displaystyle G_F(0,r) = \frac{i}{(2\pi)^2 r} \int_m^\infty dp \frac{p}{\sqrt{p^2-m^2}} e^{-pr}$
Here $G_F(0,r)$ is the Stueckelberg Feynman propogator $G_F(x) = \frac{-1}{(2\pi)^4} \int d^4 p e^{-i p\cdot x} \frac{1}{p^2 - m^2 + i\epsilon}$, when $x$ is of the form $(0,\vec{x})$ and $|\vec{x}| = r$. Presumably the $i$ in the exponent drops out because we are dealing with complex valued vector $\vec{x}$, but even with that assumption I cannot derive the formula. Any insight is appreciated!

A: Let $p = (p_0,{\bf p})$ and $x = (0,{\bf x})$.
For convenience, define $\rho = |{\bf p}|$ and $r = |{\bf x}|$.
Then
$p\cdot x = -{\bf p}\cdot {\bf x} = - \rho r \cos\theta$ and
$p^2 = p_0^2 - {\bf p}^2 = p_0^2 - \rho^2$.
We find
$$\begin{eqnarray*}
G_F(0,r) = -\frac{1}{(2\pi)^4} \int d^3 p \, e^{i \rho r \cos\theta}
\int_{-\infty}^\infty dp_0 \frac{1}{p_0^2 - E_\rho^2 + i\epsilon}
\end{eqnarray*}$$
where $E_\rho = \sqrt{\rho^2 + m^2}$.
Close the contour in the $p_0$ integral above to pick up the poll at $p_0 = -E_\rho$.
(Notice the pole at $E_\rho$ ($-E_\rho$) is slightly below (above) the $p_0$-axis.
This is the Feynman prescription for handling the poles.)
We find
$$\int_{-\infty}^\infty dp_0 \frac{1}{p_0^2 - E_\rho^2 + i\epsilon}
= 2\pi i \frac{1}{-2E_\rho}
= -\frac{i \pi}{\sqrt{\rho^2 + m^2}}.$$
If we do the angular integral we arrive at
$$\begin{eqnarray*}
G_F(0,r) &=& -\frac{1}{(2\pi)^4} \int_0^\infty d\rho\, \rho^2 \frac{-i\pi}{\sqrt{\rho^2 + m^2}}
\,2\pi \frac{e^{i\rho r} - e^{-i\rho r}}{i\rho r} \\
&=& \frac{i}{(2\pi)^2} \frac{1}{2r} \int_{-\infty}^\infty d\rho \frac{\rho e^{i\rho r}}{\sqrt{\rho^2+m^2}}.
\end{eqnarray*}$$
Move the contour to wrap around the cut in the upper half-plane.
(The cut extending from $i m$ to $i\infty$.)
Define $p = -i \rho$.
We find
$$\begin{eqnarray*}
G_F(0,r) &=& \frac{i}{(2\pi)^2 r} \int_m^\infty dp\, \frac{p}{\sqrt{p^2 - m^2}} e^{-p r} \\
\end{eqnarray*}$$
as claimed by Itzykson and Zuber.
This integral can be evaluated analytically.
Let $p = m \cosh t$.
We find
$$G_F(0,r) = \frac{i m}{4\pi^2 r} \int_0^\infty dt\, \cosh t\, e^{-m r\cosh t}.$$
Recall the integral representation of the modified Bessel function of the second kind,
$$K_n(z) = \int_0^\infty d t\, \cosh n t\ e^{-z \cosh t}.$$
Thus,
$$G_F(0,r) = \frac{i m}{4\pi^2 r} K_1(m r).$$
For large $z$, $K_n(z) \sim \sqrt{\frac{\pi}{2z}}e^{-z}$.
Therefore, for $r$ large we find
$$G_F(0,r) \sim \frac{i e^{-m r}}{(2\pi)^2 r^2} \left(\frac{\pi m r}{2}\right)^{1/2}$$
agreeing with the second half of Itzykson and Zuber's (1-180).

A: Peskin details this integral. Excuse my laziness, but I'll just paste a photo of the relevant page here:


text:
Q: Is the word "to" necessary when you list actions? Which one is correct for a list with "objectives" or "goals" (e.g. for resume or something formal)?

*

*Improve something

*Learn more about something

*Work with something

OR

*

*To improve something

*To learn more about something

*To work with something

If the last one were the case...Is not too repetitive?

A: In my own experience, it depends on how you approach the list.  For example, there can be this:

My goal is:

*

*To improve something

*To learn more about something

*To work on something

Or it can be this:

My goal is to:

*

*Improve something

*Learn more about something

*Work on something

If you include the to before the list of verbs/goals, then you don't need it in the list.  If it's left out, then it should be included in the list (if the list is made of verb infinitives).