text:
Q: External nameserver trouble for kubernetes pods My pods can not resolve external world ( for ex for mail, ... ) how can I add google nameserver to the cluster ? For info the host resolve it without problem and has nameserver.

A: The problem is that the liveness check made skids fail, I changed it like bellow.
apiVersion: v1
kind: ReplicationController
metadata:
  name: kube-dns-v10
  namespace: kube-system
  labels:
    k8s-app: kube-dns
    version: v10
    kubernetes.io/cluster-service: "true"
spec:
  replicas: 1
  selector:
    k8s-app: kube-dns
    version: v10
  template:
    metadata:
      labels:
        k8s-app: kube-dns
        version: v10
        kubernetes.io/cluster-service: "true"
    spec:
      containers:
      - name: etcd
        image: gcr.io/google_containers/etcd:2.0.9
        resources:
          # keep request = limit to keep this container in guaranteed class
          limits:
            cpu: 100m
            memory: 50Mi
          requests:
            cpu: 100m
            memory: 50Mi
        command:
        - /usr/local/bin/etcd
        - -data-dir
        - /var/etcd/data
        - -listen-client-urls
        - http://127.0.0.1:2379,http://127.0.0.1:4001
        - -advertise-client-urls
        - http://127.0.0.1:2379,http://127.0.0.1:4001
        - -initial-cluster-token
        - skydns-etcd
        volumeMounts:
        - name: etcd-storage
          mountPath: /var/etcd/data
      - name: kube2sky
        image: gcr.io/google_containers/kube2sky:1.12
        resources:
          # keep request = limit to keep this container in guaranteed class
          limits:
            cpu: 100m
            memory: 50Mi
          requests:
            cpu: 100m
            memory: 50Mi
        args:
        # command = "/kube2sky"
        - --domain=cluster.local
      - name: skydns
        image: gcr.io/google_containers/skydns:2015-10-13-8c72f8c
        resources:
          # keep request = limit to keep this container in guaranteed class
          limits:
            cpu: 100m
            memory: 50Mi
          requests:
            cpu: 100m
            memory: 50Mi
        args:
        # command = "/skydns"
        - -machines=http://127.0.0.1:4001
        - -addr=0.0.0.0:53
        - -ns-rotate=false
        - -domain=cluster.local.
        ports:
        - containerPort: 53
          name: dns
          protocol: UDP
        - containerPort: 53
          name: dns-tcp
          protocol: TCP
        livenessProbe:
          httpGet:
            path: /healthz
            port: 8080
            scheme: HTTP
          initialDelaySeconds: 30
          timeoutSeconds: 15
        #readinessProbe:
          #httpGet:
            #path: /healthz
            #port: 8080
            #scheme: HTTP
          #initialDelaySeconds: 1
          #timeoutSeconds: 5
      - name: healthz
        image: gcr.io/google_containers/exechealthz:1.0
        resources:
          # keep request = limit to keep this container in guaranteed class
          limits:
            cpu: 10m
            memory: 20Mi
          requests:
            cpu: 10m
            memory: 20Mi
        args:
        - -cmd=nslookup kubernetes.default.svc.cluster.local 127.0.0.1 >/dev/null
        - -port=8080
        ports:
        - containerPort: 8080
          protocol: TCP
      volumes:
      - name: etcd-storage
        emptyDir: {}
      dnsPolicy: Default  # Don't use cluster DNS.


text:
Q: Overriding __getitem__ for a nested list? I'm implementing an exerimental QR code parser and I figured it would be handy to override a list's __getitem__ that takes a given mask into account, like this:
m = [[1, 0], [0, 1]]
def mask(m, i, j):
  if i % 2 == 0 or j == 0:
    return int(not m[i][j])
  return m[i][j]
m2 = list_with_mask(m, mask)
n = m2[0][0]

How can I achieve it in the most Pythonic way?

A: Quick & dirty implementation, maybe it's better to inherit from the built-in list class.
Not directly what OP asked but but at least it's a start, and you can customize it for your needs.
    class CustomNestedObject:
        """Custom weird class to handle __getitem__

        TODO: add error handling for strings and other non list/tuple objects
        """

        ERRORS = {
            'element_doesnt_exist': "You don't have element with such index"
        }

        def __init__(self, obj):
            self._nested = []       # will store nested recursive CustomNestedObject(s)
            self._value = None      # will store value (for example integer or string)
            # recursively parse obj to CustomNestedObject
            self._parse_to_self(obj)

        def __repr__(self):
            """Method which will return string representation for the nested objects or self._value"""
            if not self._nested:
                return str(self._value)
            else:
                return str([x._value for x in self._nested])

        def __getitem__(self, index):
            # handle error
            try:
                self._nested[index]
            except IndexError:
                raise Exception(self.ERRORS['element_doesnt_exist'])
            if not self._nested[index]._nested:
                # it means that returned object will be self.value
                # print(f'trying to access {self._nested[index]._value}')
                return self._nested[index]._value
            else:
                # print('trying to access nested object')
                return self._nested[index]

        def _parse_to_self(self, obj):
            if isinstance(obj, list) or isinstance(obj, tuple):
                for item in obj:
                    self._nested.append(CustomNestedObject(item))
            else:
                # save as number if obj is not a list or tuple
                self._value = obj

    if __name__ == '__main__':
        x = CustomNestedObject([1, 2, 3, [4, 5]])
        print(x[3][1])
        print(x[0])
        print(x[9])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Turn from normal display to bold display with a switch I would like to have an option to turn the document text and math environments to bold.  Is there a way to enable or disable such thing.  So I can turn from normal display to bold display.
Currently I use
\renewcommand{\seriesdefault}{\bfdefault}
\boldmath

in a style file.  But I now want to put this code to work with some sort of switch.


text:
Q: Customlistview Checkbox issue while scrolling? Hi I am Android Developer .Herewith i have mention my code.I have added check box in custom list view i am using Base Adapter .While selected check-box that item only selected very nice but while scrolling after selected check-box went to unchecked automatically .How to make solved this issue.Please give me solution for me .
class LabOrderListAdapter extends BaseAdapter  {
    LayoutInflater mInflater;
    ViewHolder holder;
    Boolean checkboxstate[];
    Context context;

    // DecimalFormat df = new DecimalFormat("#.##");
    public LabOrderListAdapter(Context context) {
        mInflater = LayoutInflater.from(context);
        checkboxstate=new Boolean[observationDetailsList.size()];
        for(int i=0;i<checkboxstate.length;i++)
        checkboxstate[i]=false;
        this.context = context;
    }

    public int getCount() {

        if (observationDetailsList != null) {

            Log.i(this.toString(), "observationDetailsList"+observationDetailsList.size());

            return observationDetailsList.size();
        }
        return 0;
    }
    public Object getItem(int arg0) {
        return arg0;
    }
    public long getItemId(int arg0) {
        return arg0;
    }
    public View getView(final int position, View convertView,
            ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.lab_order_listitem, null);
        }
        if (v != null) {
            holder = new ViewHolder();
            holder.txt_Order_code = (TextView) v
            .findViewById(R.id.orderingcode);
            holder.txt_ProcedureCode = (TextView) v
                    .findViewById(R.id.procedurecode);
            holder.txt_Laboratory = (TextView) v
                    .findViewById(R.id.Laboratory);
            holder.billtypeButton = (AprimaButton) v.findViewById(R.id.billtype);
            holder.txt_Order_Description = (TextView) v
                    .findViewById(R.id.description);
            holder.txt_Date = (TextView) v
                    .findViewById(R.id.collectionDate);
            holder.orderCheckBox = (CheckBox) v
                    .findViewById(R.id.checkboxorder);

            holder.txt_TrackingNumber = (TextView) v
                    .findViewById(R.id.accession);

            if(checkboxstate[position]==null){
                checkboxstate[position]=false;
            }
            if(observationDetailsList.get(position).GenerateLabOrder.equalsIgnoreCase("Flase"))
            {
                holder.orderCheckBox.setChecked(checkboxstate[position]);
            }

            if (observationDetailsList.get(position).GenerateLabOrder
                    .equalsIgnoreCase("False"))
            {
                holder.orderCheckBox.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        if(((CheckBox)v).isChecked()){
                            if (checkboxstate[position] = true)
                            {

                                      patientOrderList.add(orderDetailsList.get(position));
                                      patientObservationList.add(observationDetailsList.get(position));

                            }

                            else{
                                if (checkboxstate[position] = false)
                                {
                                        checkboxstate[position]=false;
                                        patientOrderList.remove(orderDetailsList.get(position));
                                        patientObservationList.remove(observationDetailsList.get(position));
                                }

                            }

                        }
                    }
                });

            }
            v.setTag(holder);
        }
        return v;
    }
    }

A: You need to define a Model for storing the checked information of ListItem.
on getView() method you need to get the value from Model class for each item.
The smiler example are given in this Blog


text:
Q: Why is a negative modulo a negative, a negative? I have understood that $-340$ mod $60$ = $20$ because $-6 \times 60$ = $-360$ is smaller than $-340$.
Can someone explain why $-340$ mod $-60$ = -$40$?

A: All programming languages I'm aware of maintain the following identity
$$ n = d \cdot (n \mathbin{\text{div}} d) + (n \bmod  d) $$
where $\mathbin{\text{div}}$ is some sort of integer-valued division of integers. The two most common choices are "floor division" and "trucation".
Floor division means that you round the quotient $n/d$ down to the next integer, so you'd have
$$3 \mathbin{\text{div}} 2 = 1 \qquad 4 \mathbin{\text{div}} 2 = 2 \qquad 3 \mathbin{\text{div}} (-2) = -2 $$
Truncation means that you always round towards zero, or that you always round the magnitude down to the next integer:
$$3 \mathbin{\text{div}} 2 = 1 \qquad 4 \mathbin{\text{div}} 2 = 2 \qquad 3 \mathbin{\text{div}} (-2) = -1 $$
Either way, the language defines the remainder operator to be compatible with their choice of integer division operator. Both ways, we have $(-3) \mathbin{\text{div}} (-2) = 1$, so we'd have
$$ -3 = (-2) \cdot ((-3) \mathbin{\text{div}} (-2)) + ((-3) \bmod (-2)) $$
$$ -3 = (-2) \cdot 1 + ((-3) \bmod (-2)) $$
$$ -1 = (-3) \bmod (-2) $$

A: We write $a \equiv b \pmod{m}$ or $a \equiv_{\pmod{m}} b$ if and only if you mean $m \mid a-b$. If we want the binary operator we write $a \bmod m$, but different people may define the binary modulo operator differently. One way is $a \bmod m = a-\lfloor \frac{a}{m} \rfloor m$, which gives meaningful results even for real $a,m$ as long as $m > 0$. In Excel "mod" uses exactly this binary operator that I've just defined, even for negative $m$. That produces a non-positive result when $m < 0$.

A: I think I now might be able to answer your question. (Housekeeping details first: in the equation $n = qm + r$, $q$ is a quotient, $m$ is a modulus and $r$ is a remainder, and we write $n \equiv r \pmod m$).
Because out of infinitely many valid answers, the computer has been programmed to give you just one answer. The criterion $|r| < |m|$ which I alluded to earlier narrows down the possible answers to just two, but the computer has to choose just one to present to you. So then, if $m > 1$, it chooses $0 \leq r < m$, and if $m < -1$, it chooses $m < r \leq 0$.
So, in your example, by the $|r| < |m|$ criterion, either 20 or $-40$ is valid. But if $m = -60$, the computer has been programmed to give you $r = -40$ as the answer, because $-60 < -40 < 0$. If $m = 60$, then it chooses $r = 20$ as the answer, because $0 < 20 < 60$.
But if you're still confused about both $-40$ and 20 being valid answers, a geometrical illustration might help. I want you to draw a horizontal line segment 3 inches long (or 3 kilometers long, or whichever unit of length measurement you like). Label the left endpoint "$-360$". Label the right endpoint "$-300$". Then, 1 inch from the left endpoint, mark a dot and label it $-340$. If $m = -60$, the left endpoint corresponds to $qm$ with $q = 6$. Then $r = 20$. The right endpoint corresponds to $qm$ with $q = 5$, and then $r = -40$. Both pairs of $\{q, r\}$ values "address" the same point on the number line. It just happens that $q = 6, r = 20$ gives us the shortest distance.
Changing to $m = 60$ but keeping $n = -340$ hardly changes things. The point $-360$ still corresponds to a $qm$, but now $q = -6$, though $r = 20$ still. And $qm = -300$ with $q = -5$, but $r = -40$ just like before. I personally prefer $r = 20$, but the way the computers have been programmed, it gives you $r = -40$.
Modular arithmetic isn't the only case in which the computer chooses one answer out of several. For example, if you ask your computer to answer $\sqrt[12]{2}$, you're essentially asking it to solve $x^{12} = 2$. There are a dozen valid answers to this equation. But the computer, perhaps arbitrarily, some might say, gives you only the positive real answer. (There is also the issue of numeric vs. symbolic computations, but that's a whole other can of worms).

A: It's because that's the way the computer was programmed. So mod(-340, -60) leads to return -40. But the more "valid" response would be return 20.
Too many of you humans think computers are magical. A computer subroutine is only as good as the human who programmed it. The Tooth Fairy is magical, Siri is not. The Tooth Fairy can tell you the GCDs of any randomly chosen numbers in $\mathbb{Z}[\sqrt{-5}]$, while Siri would either complain she can't apply the Euclidean algorithm in that domain, or, more likely, change the subject.
Of course at this point you don't care about $\mathbb{Z}[\sqrt{-5}]$, you care about good ol' $\mathbb{Z}$ because that's the domain you're doing most of your arithmetic in. But there is a reason I'm bringing up the GCD function. You see, the greatest common divisor of two negative integers in $\mathbb{Z}$ is a positive integer, for even if they're coprime, they nevertheless share $1$ as a trivial divisor. For example, $\gcd(-340, -60) = 20$. A computer, in all its glorious stupidity, could be delayed or prevented from arriving at the right answer for gcd if mod is not defined to always give a positive or $0$ result.
So how does Microsoft Excel define mod? I don't want to tell you, I've got my reasons, but I will tell you that, in very broad strokes, it goes something like this:
function integer mod(integer n, integer modulus) {
    var real intermediate1 := n / modulus;
    var integer intermediate2 := floor(intermediate1);
    return n - (intermediate2 * modulus)
}

You can't check every possible input, but you can check a few positive inputs to see whether or not it gives the correct results. And you can check that this will give $-40$ in your main test case with the negative inputs. But if you want it to give $20$ instead that's accomplished easily enough:
function integer mod(integer n, integer modulus) {
    var integer adjustedModulus := abs(modulus);
    var real intermediate1 := n / adjustedModulus;
    var integer intermediate2 := floor(intermediate1);
    return n - (intermediate2 * adjustedModulus)
}

Then, when you send it mod(-340, -60), it will change the -60 to 60 in its special local variable adjustedModulus. intermediate2 will be -6 rather than 5 and the final result will be the same as if you called the previous function with -340, 60.
But when a human concerns himself too much with programming a silly piece of machinery, he dumbs down his own knowledge. It would be much better for you to think of $-40$ and $20$ as belonging to the same coset of the principal ideal $60\mathbb{Z}$, which you can notate as $-40 + \langle 60 \rangle$ or $20 + (60)$, to name just two of the many possible notations you could use.

A: You could also say that $-340 \equiv -40 \pmod{60}$. It is quite common to see in number theory books things like "$-1 \pmod p$", where $p$ is a positive prime.
So really, $-340 \equiv 20 \pmod{-60}$ is as acceptable as $-340 \equiv -40 \pmod{-60}$.
Here's the way I like to think about it: the expression $\pmod c$ tells us we're thinking about the multiples of $c$, which includes numbers like $-c$ and $-488c$ (so in the case of $-60$, we're also thinking about numbers like 60 and $-300$). And in $a \equiv b \pmod c$, the $b$ tells us that $a$ is $b$ integer notches away from a multiple of $c$. The sign of $b$ tells us in what direction we have to go to hit a multiple of $c$.
Thus, in your example, $b = -40$ means that if we go $-40$ "back" from $-340$, we hit $-300$, and if we go 20 "forward", we hit $-360$. (Don't get too hung up on which is forward and which is back, as long as you don't switch them in the middle of a single operation).

A: $$-340=(-300-40)=(-5)\cdot60-40\equiv-40\equiv-360+20\equiv 20\pmod{60}$$
Or by definition $$a\equiv b\pmod{60}\implies 60\mid a-b\\60\mid -340-(-40)\\60\mid -300$$


text:
Q: If a 'distance function' does not possess triangle inequality property, would the limit of a converging sequence still be unique? Let $X$ be a set and $d$ be a function such that $d:X\times X\to \mathbb{R}$ such that it satisfies positivity, that is, $d(x,y)\geq 0$ and $d(x,y)=0 \iff x=y.$ Moreover suppose it satisfies symmetry property, that is, $d(x,y)=d(y,x).$ However it does not satisfy triangle inequality.
Obviously if triangle inequality was to be satisfied then this will make $(X,d)$ a metric space and subsequently every converging sequence will have a unique limit. Hence I am just curious if this property is taken away, can there still be examples such that every converging sequence has a unique limit with respect to this function $d$?
I hope I explained my question sufficiently clear, many thanks in advance!

A: Let $d(x,y) = (x-y)^2$ on $\Bbb R$, which satisfies the first two axioms but not the triangle inequality, because:
$$d(0,2)=4\not≤2=d(0,1)+d(1,2)$$
however limits are still unique, in fact you have the same limits as the usual metric $d(x,y)=|x-y|$, since $(x_n-y)^2\to0$ iff $|x_n-y|\to0$ (continuity of the root on positive numbers).
There exist "metrics" failing the triangle inequality without unique limits:
Let $$d(x,y)=\begin{cases}0 & x=y \\ \frac1{|xy|}
&x\neq y\end{cases}$$
on $\Bbb N$, then you have that any unbounded sequence $x_n$ converges to any integer.


text:
Q: renaming and saving in NSDocumentsDirectory Its like this, in my app, I have a UIScrollView on it is a thumbnail view, they are images from my NSCachesDirectory.
I saved them from my picker then named them in my array like: images0.png,images.1.png... etc
So for example I have images in my directory this way : images0.png, images1.png, images2.png, images3.png.
Then I delete images1.png, the remaining images will be like this : images0.png,images2.png, images3.png right?
What I wanted to achieve is get the images in NSDocumentsDirectory then renamed them AGAIN or sort them again like images0.png, images1.png, images2.png...etc again?
is this possible? hope you could help me.

A: Use this NSFileManger moveItemAtPath:  toPath:  error:  but you should supply the toPath:same_path_but_different_filename. This moves the file to a new path with new file name that you provide. see this
Since it seems you want the whole logic to rename your images file, here is the code you can try provided the files are in the Document directory
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString * oldPath =[[NSString alloc]init];
NSString * newPath =[[NSString alloc]init];

int count=0;
for (int i=0; i<=[[fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil]count]; i++) {

    oldPath=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"images%d.png",i]];

    if ([fileManager fileExistsAtPath:oldPath]) {

        newPath=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"images%d.png",count]];
        [fileManager moveItemAtPath:oldPath toPath:newPath error:nil];
        count+=1;

    }

}

A: Apple doesnot allow renameing of file saved. So alternative is to get all contents at document directory like this:
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:yourDocDirPath error:NULL];

Now sort like this:
NSSortDescriptor * descriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending: YES comparator:^NSComparisonResult(id obj1, id obj2){
     return [obj1 compare: obj2 options: NSNumericSearch];
 }];

NSArray * sortedDirectoryContent = [directoryContent sortedArrayUsingDescriptors:[NSArray arrayWithObject: descriptor]];

We have sorted array rewrite all files with new name:
for(NSString *fileName in sortedDirectoryContent)
{
  NSString *filePath = [yourDocDirPath stringByAppendingPathComponent:fileName];
  NSData *fileData = [[NSData alloc]initWithContentsOfFile:filePath];
  if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];

    if(fileData)
    {
        NSString *newFilePath = [yourDocDirPath stringByAppendingPathComponent:@"New Name here"];
        [fileData writeToFile:newFilePath atomically:YES];
    }
  }
  else
  {
    if(fileData)
    {
        NSString *newFilePath = [yourDocDirPath stringByAppendingPathComponent:@"New Name here"];
        [fileData writeToFile:newFilePath atomically:YES];
    }
  }

}


text:
Q: Is there a R function for preparing datasets for survival analysis like stset in Stata? Datasets look like this
id  start   end  failure x1
 1    0      1      0    0
 1    1      3      0    0
 1    3      6      1    0
 2    0      1      1    1
 2    1      3      1    1
 2    3      4      0    1
 2    4      6      0    1
 2    6      7      1    1

As you see, when id = 1, it's just the data input to  coxph in survival package. However, when id = 2, at the beginning and end, failure occurs, but in the middle, failure disappears.
Is there a general function to extract data from id = 2 and get the result like id = 1?
I think when id = 2, the result should look like below.
id  start   end  failure x1
1    0      1      0    0
1    1      3      0    0
1    3      6      1    0
2    3      4      0    1
2    4      6      0    1
2    6      7      1    1

A: A bit hacky, but should get the job done.
Data:
# Load data
library(tidyverse)
df <- read_table("
 id   start  end    failure  x1
 1    0      1      0        0
 1    1      3      0        0
 1    3      6      1        0
 2    0      1      1        1
 2    1      3      1        1
 2    3      4      0        1
 2    4      6      0        1
 2    6      7      1        1
")

Data wrangling:
# Check for sub-groups within IDs and remove all but the last one
df <- df %>%
    # Group by ID
    group_by(
        id
    ) %>%
    mutate(
        # Check if a new sub-group is starting (after a failure)
        new_group = case_when(
            # First row is always group 0
            row_number() == 1 ~ 0,
            # If previous row was a failure, then a new sub-group starts here
            lag(failure) == 1 ~ 1,
            # Otherwise not
            TRUE ~ 0
        ),
        # Assign sub-group number by calculating cumulative sums
        group = cumsum(new_group)
    ) %>%
    # Keep only last sub-group for each ID
    filter(
        group == max(group)
    ) %>%
    ungroup() %>%
    # Remove working columns
    select(
        -new_group, -group
    )

Result:
> df
# A tibble: 6 × 5
     id start   end failure    x1
  <dbl> <dbl> <dbl>   <dbl> <dbl>
1     1     0     1       0     0
2     1     1     3       0     0
3     1     3     6       1     0
4     2     3     4       0     1
5     2     4     6       0     1
6     2     6     7       1     1


text:
Q: How to prioritize the events in objective c I have a two delegate events i.e. navigateOut(when the user navigates out of the app) and also textViewDidEndEditing (when user ends editing in the TextView).
The problem is the when I navigate out from one module first the navigateOut delegate function is getting called and then textViewDidEndEditing event is firing at last.
Is there any way that I can control these ? I want to do some computation first in textViewDidEndEditing and then after that  in navigateOut function.
Any help will be appreciated.

A: Obviously you can't change the order of when delegate methods are triggered. If you don't want to call navigateOut every time textViewDidEndEditing is called just set a flag if it is still progressing and reset it if done.
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (!isNavigatingOut) {
        [self navigateOut];
    }
}

- (void)navigateOut
{
    isNavigatingOut = YES;
    //do your stuff here
    //if finished set
    isNavigatingOut = NO;
}


text:
Q: Mixing variables and integer constants in the Boost Preprocessor I am using BOOST_PP for to do precompile computations in the preprocessor. I am focusing on an application where code size is extremely important to me. (So please don't say the compiler should or usually does that, I need to control what is performed at compile time and what code is generated). However, I want to be able to use the same name of the macro/function for both integer constants and variables. As trivial example, I can have
#define TWICE(n) BOOST_PP_MUL(n,2)
//.....
// somewhere else in code
int a = TWICE(5);

This does what I want it to, evaluating to
int a = 10;

during compile time.
However, I also want it to be used at
int b = 5;
int a = TWICE(b);

This should be preprocessed to
int b = 5;
int a = 5 * 2;

Of course, I can do so by using the traditional macros like
#define TWICE(n) n * 2

But then it doesnt do what I want it to do for integer constants (evaluating them during compile time).
So, my question is, is there a trick to check whether the argument is a literal or a variable, and then use different definitions. i.e., something like this:
#define TWICE(n) BOOST_PP_IF( _IS_CONSTANT(n), \
                              BOOST_PP_MUL(n,2), \
                              n * 2 )

edit:
So what I am really after is some way to check if something is a constant available at compile time, and hence a good argument for the BOOST_PP_ functions. I realize that this is different from what most people expect from a preprocessor and general programming recommendations. But there is no wrong way of programming, so please don't hate on the question if you disagree with its philosophy. There is a reason the BOOST_PP library exists, and this question is in the same spirit. It might just not be possible though.

A: You're trying to do something that is better left to the optimizations of the compiler.
int main (void) {
  int b = 5;
  int a = b * 2;

  return a; // return it so we use a and it's not optimized away
}

gcc -O3 -s t.c
 .file "t.c"
 .text
 .p2align 4,,15
.globl main
 .type main, @function
main:
.LFB0:
 .cfi_startproc
 movl $10, %eax
 ret
 .cfi_endproc
.LFE0:
 .size main, .-main
 .ident "GCC: (Debian 4.5.0-6) 4.5.1 20100617 (prerelease)"
 .section .note.GNU-stack,"",@progbits

Optimizing compiler will optimize.
EDIT: I'm aware that you don't want to hear that the compiler "should" or "usually" does that. However, what you are trying to do is not something that is meant to be done in the C preprocessor; the people who designed the C language and the C preprocessor designed it to work with the preprocessing token as it's basic atom. The CPP is, in many ways, "dumb". This is not a bad thing (in fact, this is in many cases what makes it so useful), but at the end of the day, it is a preprocessor. It preprocesses source files before they are parsed. It preprocesses source files before semantic analysis occurs. It preprocesses source files before the validity of a given source file is checked. I understand that you do not want to hear that this is something that the parser and semantic analyzer should handle or usually does. However, this is the reality of the situation. If you want to design code that is incredibly small, then you should rely on your compiler to do it's job instead of trying to create preprocessor constructs to do the work. Think of it this way: thousands of hours of work went into your compiler, so try to reuse as much of that work as possible!

A: not quite direct approach, however:
struct operation {
    template<int N>
    struct compile {
        static const int value = N;
    };
    static int runtime(int N) { return N; }
};

operation::compile<5>::value;
operation::runtime(5);

alternatively
operation<5>();
operation(5);

A: There is no real chance of mixing the two levels (preprocessor and evaluation of variables). From what I understand from you question, b should be a symbolic constant?
I think you should use the traditional one
#define TWICE(n) ((n) * 2)

but then instead of initializing variables with expressions, you should initialize them with compile time constants. The only thing that I see to force evaluation at compile time and to have symbolic constants in C are integral enumeration constants. These are defined to have type int and are evaluated at compile time.
enum { bInit = 5 };
int b = bInit;
enum { aInit = TWICE(bInit) };
int a = aInit;

And generally you should not be too thrifty with const (as for your b) and check the produced assembler with -S.


text:
Q: Facebook access token error on iphone I am trying to get name of facebook user in my app but I am getting
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}
My code is :-
In viewdidload
facebook = [[Facebook alloc] initWithAppId:@"233350100117670" andDelegate:self];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@"FBAccessTokenKey"] && [defaults objectForKey:@"FBExpirationDateKey"])
{
    facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"];
    facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"];
}
NSArray *permissions =  [[NSArray arrayWithObjects:@"read_stream", @"publish_stream", @"offline_access",nil] retain];
[facebook authorize:permissions];

if (![facebook isSessionValid])
{
    [facebook authorize:nil];
}

After that:-
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{
    NSLog(@"%@", [error localizedDescription]);
    NSLog(@"Err details: %@", [error description]);
}

- (void)request:(FBRequest*)request didLoadRawResponse:(NSData*)data
{
    NSString *response = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    NSLog(@"%@", response);
    [response release];
}

- (void) request:(FBRequest*)request didLoad:(id)result
{
    if ([result isKindOfClass:[NSDictionary class]])
    {
        NSString *email = [result objectForKey: @"email"];
        fbUserName = [result objectForKey: @"name"];
        NSString *facebookId = [result objectForKey: @"id"];
        NSString* title=[NSString stringWithFormat:@"%@ has won a gold medal on Olympedia quiz",fbUserName];
        NSMutableDictionary *params =
        [NSMutableDictionary dictionaryWithObjectsAndKeys:title, @"name",@"Feed Dialogs of Olympedia.", @"caption",@"Check out Olmpedia Dialogs.", @"description",@"http://www.facebook.com/olympedia", @"link",@"http://bit.ly/PdpRSD", @"picture",nil];
        [facebook dialog:@"feed" andParams:params andDelegate:self];
   }
}

And on share button click:-
- (IBAction)shareOnFacebook:(id)sender
{
    NSLog(@"Posting message");

    [facebook requestWithGraphPath:@"me" andDelegate:self];
}

Please help as I am trying to solve this for hours.strong text


text:
Q: Summation of N function handles in MATLAB I have N functions in MATLAB and I can define them using strcat, num2str and eval in a for loop. So without defining by hand I am able to define N functions. Let N=4 and let them be given as follows:
f1=@(x) a1*x+1;
f2=@(x) a2*x+1;
f3=@(x) a3*x+1;
f4=@(x) a4*x+1;

Now I add these four functions and I can do this by hand as follows:
f=@(x)(f1(x)+f2(x)+f3(x)+f4(x));

Here I can do it by hand because I know that N=4. However, in general I never know how many functions I will have. For all cases I cannot write a new function.
Is there any way to do this automatically? I mean if I give N=6 I am expecting to see MATLAB giving me this:
f=@(x)(f1(x)+f2(x)+f3(x)+f4(x)+f5(x)+f6(x));

Whenever I give N=2 then I must have the function f, defined as follows:
f=@(x)(f1(x)+f2(x));

How can we do this?

A: First of all, you should read this answer that gives a series of reasons to avoid the use of eval. There are very few occasions where eval is necessary, in all other cases it just complicates things. In this case, you use to dynamically generate variable names, which is considered a very bad practice. As detailed in the linked answer and in further writings linked in that answer, dynamic variable names make the code harder to read, harder to maintain, and slower to execute in MATLAB.
So, instead of defining functions f1, f2, f3, ... fN, what you do is define functions f{1}, f{2}, f{3}, ... f{N}. That is, f is a cell array where each element is an anonymous function (or any other function handle).
For example, instead of
f1=@(x) a1*x+1;
f2=@(x) a2*x+1;
f3=@(x) a3*x+1;
f4=@(x) a4*x+1;

you do
N = 4;
a = [4.5, 3.4, 7.1, 2.1];
f = cell(N,1);
for ii=1:N
   f{ii} = @(x) a(ii) * x + 1;
end

With these changes, we can easily answer the question. We can now write a function that outputs the sum of the functions in f:
function y = sum_of_functions(f,x)
   y = 0;
   for ii=1:numel(f)
      y = y + f{ii}(x);
   end
end

You can put this in a file called sum_of_functions.m, or you can put it at the end of your function file or script file, it doesn't matter. Now, in your code, when you want to evaluate y = f1(x) + f2(x) + f3(x)..., what you write is y = sum_of_functions(f,x).


text:
Q: TreeViewItem.Expanded Im using the latest version of mvvm light toolkit, however i'm not clear how I can use EventToCommand for the event TreeViewItem.Expanded.
THis dosent work... what am I doing wrong?
<TreeView Grid.Column="0" Grid.Row="0" ItemsSource="{Binding Path= MonitoredDatabases}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Queues}">

                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding ServerName}" />
                    <TextBlock Text="\" />
                    <TextBlock Text="{Binding DatabaseName}" />
                </StackPanel>

                <HierarchicalDataTemplate.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding QueueName}" />
                    </DataTemplate>
                </HierarchicalDataTemplate.ItemTemplate>

            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="TreeViewItem.Expanded">
                <cmd:EventToCommand Command="{Binding Path=NodeExpanded}"
                                    CommandParameter="Expanded" />
            </i:EventTrigger>
            <i:EventTrigger EventName="TreeViewItem.Collapsed">
                <cmd:EventToCommand Command="{Binding Path=NodeCollapsed}"
                                    CommandParameter="Collapsed" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TreeView>

help much appreciated.
Regards.
Gary

A: I was able to do this by creating a custom ItemContainerStyle for the TreeView. You should be able to put this together with the following code snippets.
1. A ViewModel for the TreeView
public class TreeViewModelView
{
    public IEnumerable<object> Values
    {
        get { /* return hierarchical data source here ... */ }
    }

    /// <summary>
    /// Command executed when the TreeViewItem expanding event is raised. The data item is passed in as a parameter.
    /// </summary>
    public RelayCommand<object> ExpandedCommand
    {
        get { return new RelayCommand<object>( o => MessageBox.Show( o.GetType().Name ) ); }
    }

    /// <summary>
    /// Command executed when the TreeViewItem collapsing event is raised.
    /// </summary>
    public RelayCommand CollapsedCommand
    {
        get { return new RelayCommand( () => MessageBox.Show( "Collapsed" ) ); }
    }

}

2. Define the TreeView and setup the required data binding:
 <TreeView x:Name="lstItems" HorizontalAlignment="Left" Margin="21,19,0,80" Width="283"
          DataContext="{DynamicResource TreeViewModelView}"
          ItemsSource="{Binding Values, Mode=OneWay}"
          ItemTemplate="{DynamicResource TreeViewDataTemplate}"
          ItemContainerStyle="{DynamicResource TreeViewItemStyle}">
    <TreeView.Resources>
        <mv:TreeViewModelView x:Key="TreeViewModelView" />

        <HierarchicalDataTemplate x:Key="TreeViewDataTemplate" ItemsSource="{Binding Items}">
            <Grid>
                <TextBlock Text="{Binding Name}" />
            </Grid>
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>

3. In Expression Blend you can create edit a copy of the ItemContainerStyle template
<Style x:Key="TreeViewItemStyle" TargetType="{x:Type TreeViewItem}">

    ...

</Style>

4. Then replace the ToggleButton with:
<ToggleButton x:Name="Expander" ClickMode="Press" IsChecked="{Binding IsExpanded, RelativeSource={RelativeSource TemplatedParent}}" Style="{StaticResource ExpandCollapseToggleStyle}">

    <i:Interaction.Triggers>
        <!-- When the Checked event is raised execute the ExpandedCommand with the data item as a parameter. -->
        <i:EventTrigger EventName="Checked">
            <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding Path=DataContext.ExpandedCommand, RelativeSource={RelativeSource AncestorType={x:Type TreeView}}, Mode=OneWay}"
                CommandParameter="{Binding}" />
        </i:EventTrigger>
        <!-- When the Unchecked event is raised execute the CollapsedCommand. -->
        <i:EventTrigger EventName="Unchecked">
            <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding Path=DataContext.CollapsedCommand, RelativeSource={RelativeSource AncestorType={x:Type TreeView}}, Mode=OneWay}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>

</ToggleButton>

A: The event to command behavior is implemented as an attached property, which must be attached to a FrameworkElement. Your sample has the Triggers attached property attached to the TreeView which doesn't have an Expanded or Collapsed event. You attempted to use "TreeViewItem.Expanded" as the event name, but it doesn't work that way.
If you were creating your TreeViewItems statically in XAML, or manually in code-behind, you could attach to each TreeViewItem. Unfortunately, I'm not aware of any way to attach to the TreeViewItem from the HierarchicalDataTemplate. You can bind to the TemplatedParent RelativeSource, but you can't attach to it. Your only solution is to iterate through the TreeViewItems in code-behind, and manually handle the events, but even then you'd have to do so using the VisualTreeHelper only after the TreeView control has been data bound and rendered, which is a huge hack.


text:
Q: differentiate between user entered time and current time, compare both time with if-else or suitable loops need to compare the user entered time in editbox with the current time, I'm using HH:MM format not using seconds or milliseconds.

A: There's two way to do this:
You can convert HH:MM format to minutes, convert current time to minutes and compare.
Or you can split HH:MM at : and compare HH given by user to HH of current time and same for MM.

A: You could do like this:
        int hour = Integer.parseInt(YourHourEdit.getText().toString());
        int minute = Integer.parseInt(YourMinuteEdit.getText().toString());

         Calendar cal = Calendar.getInstance(Locale.getDefault());
        cal.set(Calendar.HOUR_OF_DAY, hour);
        cal.set(Calendar.MINUTE,minute);
        Date inputDate = cal.getTime(); //get user input date

        Date currentDate = Calendar.getInstance(Locale.getDefault()).getTime(); //get current date

        if(inputDate.after(currentDate)){
           //compare two dates and do something
        }


text: Q: "error while loading user profile metadata" with WSO2 API Manager 4.1 I have added an Active Directory to the carbon console to connect to WSO2 API Manager , i have successfully read the users list but when i try to get the informations of each user i got error error while loading user profile metadata .


text:
Q: llamar a funcion php desde javascript buenas tardes amigos tengo un problema que me rompe la cabeza y no logro solucionar tengo este codigo
function llenar_tabla_json(){
    $('.cargando').hide();
    $(".table-carrito tbody").empty();
    $("#carrito_ventas .table tbody").html("");
    $.post("comprobantes/listado_carrito",{accion:''},function(data){
        var tabla = ""; var i=1; var total = 0;
        if(jQuery.isEmptyObject(data) == false){
            $.each(data, function(index, val) {
                tabla += '
'
                        +''+i+'	'
                        +''
                        +'<input type="number" class="cantidad" min="1" value="'+val['cantidad']+'" data-item="'+val['id']+'|'+val['precio']+'|'+val['unidad']+'|'+val['nombre']+'|'+val['codigo_servicio']+'" style="width:50px;height:25px;text-align: center;padding: 0;">'
                        +'	'
                        +''+val['codigo_servicio']+'	'
                        +''+val['unidad']+'	'
                        +''+val['nombre']+'	'
                        +''
                        +'<input type="number" step="any" class="precios" value="'+val['precio']+'" data-item="'+val['id']+'|'+val['cantidad']+'|'+val['unidad']+'|'+val['nombre']+'|'+val['codigo_servicio']+'" style="width:60px;height:25px;text-align: center;padding: 0;">'
                        +'	'
                        +''+(val['precio'] * val['cantidad']).toFixed(2)+'	'
                        +''
                        +''+
                        +'	'
                        +'
';
                i++;
                total += (val['precio'] * val['cantidad']);
            });
            $("#carrito_ventas .table > tbody > tr").remove();
            $(".table-carrito tbody").append(tabla);
        }else{
            tabla = '
'
                        +''
                            +'Agregue items para empezar'
                        +'	'
                    +'
';
            $(".table-carrito tbody").append(tabla);
        }`

Quiero enviar el numero de item para elimnar del carrito de compras a esta funcion
La direccion es comprobantes/unset_producto y debo agregarle la variable i
public function unset_producto($unique_id)
    {
        unset($_SESSION["carrito_v"][$unique_id]);

    }

A: al ver que ya estas usando jquery, pues lo podrias hacer de la siguiente manera:
en esta linea:
+''+

agregale el atributo data-id_item y la clase "btn_delete_item", para que quede asi:
+''+

y esta parte fuera de tu función "llenar_tabla_json"
$(".table-carrito").on("click", ".btn_delete_item", function(e){
    e.preventDefault();
    var btn = $(this);
    $.ajax({
        url: btn.attr('href'),
        type: "GET",  //GET si el backend recibe los datos por URL o POST si los recibe con el método literal "POST"
        dataType: "json",
        data: {unique_id: btn.data('id_item')}
    })
    .done(function(data){
        alert(data.status);
    });
});

y el código PHP quedaría de la siguiente forma:
<?php

public function unset_producto($unique_id){
    //al ver que la recibes como argumento entonces diría que mandas
    //la clave por la url, aquí depende mucho de como este construido tu backend
    //para ver como recibes los datos y ver como las vas a mandar con AJAX

    unset($_SESSION["carrito_v"][$unique_id]);
    echo json_encode(["status" => "El producto con clave " . $unique_id . " ha sido borrado"]);
}

Espero y te sea útil esta pequeña ayuda :)


text:
Q: Finding differential of inverse? Let $f(x)=6x^3-11x^2-2$, $x\geqslant 1.
5$. Find $\frac{\text{d}f^{-1}}{\text{d}x}$ at the point $x=1517=f(7)$.
I thought you should first find the inverse and then differentiate but from looking at the inverse, that's clearly not what I should do. Any ideas? Also, why did they give me x>=1.5?

A: Hint: Indeed, you don't need to know the inverse function of $f$.
Note that by inverse function theorem, you can find $$\frac{df^{-1}}{dx}(b)=(f^{-1})'(b)=\frac{1}{f'(a)}$$
where $b=f(a)$ and only you need  show that $f'(a)\not=0$ and then you need to find $\frac{1}{f'(a)}$.

A: They gave you $x\ge 1.5$ because the function is invertible in the interval $[1.5,+\infty)$
as you can see in the graph below the function is invertible in the intervals $(-\infty,0]$, $\left[0,\frac{11}{9}\right]$ and $\left[\frac{11}{9},+\infty\right)$. The values are the $x$ of the critical points of the function.
$f'(x)=18 x^2-22 x$ and $f'(7)=728$ thus the derivative of the inverse is $\left(f^{-1}\right)'(1517)=\frac{1}{f'(7)}=\frac{1}{728}\approx 0.0014$. The value is so small because $f(x)$ grows very fast around $x=7$, therefore its inverse grows very slowly.

A: Just to show you what you did avoid to face.
If $y>0$ the inverse is given by
$$x=\frac{11}{18} \left(1+2 \cosh \left(\frac{1}{3} \cosh ^{-1}\left(\frac{486y+2303}{1331}\right)\right)\right)$$
$$\frac {dx}{dy}=\frac{11 \sinh \left(\frac{1}{3} \cosh ^{-1}\left(\frac{486
   y+2303}{1331}\right)\right)}{\sqrt{729 y^2+6909 y+10902}}$$ If $x=1517$, $y=20921018297$ making at this point
$$\frac {dx}{dy}=\frac{11 \sinh \left(\frac{1}{3} \cosh
   ^{-1}\left(\frac{10167614894645}{1331}\right)\right)}{20694914
   \sqrt{745016541}}$$ while,as given in the answers,
$$\frac {dy}{dx}=18 x^2-22 x$$ which is for $x=1517$
$$\frac {dy}{dx}=41389828 \implies \frac {dx}{dy}=\frac 1 {41389828}$$
Which one do you prefer ?


text:
Q: How can I create a script to switch between my ARM conda and x86 conda? I am on an apple silicon M1 MacBook Pro. I would like to have a native ARM python environment, and an environment that runs on x86 architecture with rosetta 2. I have installed two mini forge distributions, both in the home directory: miniforge3 for the native ARM installation and miniforge3_x86_64 for the x86 installation.

A: So far, the best solution I've found is to start the terminal with Rosetta 2, then run a function I have saved in .zshrc to initialize the correct conda installation so that I can use the correct architecture for my needs depending on the situation.
My current solution is the following function named x86:
x86 () {

conda deactivate

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/Users/$USERNAME/miniforge3_x86_64/bin/conda' 'shell.zsh' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/Users/$USERNAME/miniforge3_x86_64/etc/profile.d/conda.sh" ]; then
        . "/Users/$USERNAME/miniforge3_x86_64/etc/profile.d/conda.sh"
    else
        export PATH="/Users/$USERNAME/miniforge3_x86_64/bin:$PATH"
    fi
fi
unset __conda_setup
# <<< conda initialize <<<

export PATH="/Users/$USERNAME/miniforge3_x86_64/bin:$PATH"
export PATH="/Users/$USERNAME/miniforge3_x86_64/condabin:$PATH"
}

I am still feeling this out. I may add some aliases within the function as well so things like pip do not conflict, but I hope that by prepending the x86 paths the correct packages will be referenced


text:
Q: I need to change the grid height and size of each of the graphs using ggplot2 I am new to R programming. I am trying to create a grid using multiple graphs but I want to change the height and width of the graphs as the plot is not clear
I am getting the plot but I need some changes to it to make it meaningful
plot_1 <- ggplot(data_airfares ) +
geom_point(aes(x= NEW, y = FARE ), size = 1,colour="blue") + ggtitle("New Flights vs Fare")

plot_2 <- ggplot(data_airfares )+
geom_point(aes(x= COUPON, y = FARE ), size = 1,colour="red") + ggtitle("Coupon vs Fare")

plot_3 <- ggplot(data_airfares )+
geom_point(aes(x= HI, y = FARE ), size = 1,colour="green")+ ggtitle("HI vs Fare")+
theme(axis.text.x = element_text(angle = 90))

plot_4 <- ggplot(data_airfares )+
geom_point(aes(x= S_INCOME, y = FARE ), size = 1,colour="red")+ ggtitle("S_Income vs Fare")+
theme(axis.text.x = element_text(angle = 90))

plot_5 <- ggplot(data_airfares )+
geom_point(aes(x= E_INCOME, y = FARE ), size = 1)+ ggtitle("Income(E)vs Fare")+
theme(axis.text.x = element_text(angle = 90))

plot_6 <- ggplot(data_airfares )+
geom_point(aes(x= S_POP, y = FARE ), size = 1)+ ggtitle("Start_City_Population vs Fare")+
theme(axis.text.x = element_text(angle = 90))

plot_7 <- ggplot(data_airfares )+
geom_point(aes(x= E_POP, y = FARE ), size = 1)+ ggtitle("End_City_Population vs Fare")+
theme(axis.text.x = element_text(angle = 90))

plot_8 <- ggplot(data_airfares )+
geom_point(aes(x= DISTANCE, y = FARE ), size = 1)+ggtitle("Distance vs Fare")+
theme(axis.text.x = element_text(angle = 90))

plot_9 <- ggplot(data_airfares )+
geom_point(aes(x= PAX, y = FARE ), size = 1)+ ggtitle("Pax vs Fare")+
theme(axis.text.x = element_text(angle = 90))

grid.arrange(plot_1, plot_2, plot_3, plot_4, plot_5, plot_6, plot_7, plot_8,
 plot_9, nrow = 3)

Changes in height and width of each plot in the grid using ggplot2

A: My suggestion is to use different tick labels for the x-axis and to reduce the font size for title and axes.
library(ggplot2)
library(gridExtra)
library(scales)
# Generate data for the example
n <- 300
data_airfares <- data.frame(NEW = rbinom(n,4,0.25)+1,
                            FARE=runif(n,0,400),
                            COUPON=runif(n,1,2),
                            HI=runif(n,0,10000),
                            S_INCOME=runif(n,0,40000),
                            E_INCOME=runif(n,0,40000),
                            S_POP=runif(n,0,7500000),
                            E_POP=runif(n,0,7500000),
                            DISTANCE=runif(n,0,3000),
                            PAX=runif(n,0,70000))
# Create plots using a loop
plots <- NULL
var_names <- names(data_airfares)[-2]
for (k in 1:length(var_names)) {
  var_name <- var_names[k]
  df <- data_airfares[, c("FARE", var_name)]
  p <- ggplot(data=df, aes_string(x=var_name, y="FARE")) +
   geom_point(size = 1,colour="blue") +
   ggtitle("New Flights vs Fare") +
   theme(plot.title = element_text(size = 10), axis.title = element_text(size = 10))
  if (var_name %in% c("S_POP","E_POP")) {
    plots[[k]] <- p +
      scale_x_continuous(labels = comma_format(accuracy=1, scale=10^(-6), suffix = "M"))
  } else if (var_name %in% c("NEW","COUPON")) {
    plots[[k]] <- p
  } else {
    plots[[k]] <- p +
      scale_x_continuous(labels = comma_format(accuracy=1, scale=10^(-3), suffix = "K"))
  }
}

grid.arrange(grobs=plots, nrow = 3)


text:
Q: How to Remove `\marginparwidth` for Pages without Margin Notes? In regular LaTeX, how could I remove the space reserved for sidenotes on pages that don't have any margin notes?
Issue: Just trying to use the extra space if possible.
I am trying to do this with either \marginnote or \marginpar.
Although I would prefer to have the sidenotes 'inset', right now I am just trying to do it the traditional way.  The "inset" approach I have tried uses another question's\wrapfig approach, but "weirdness" happens when notes are close to the bottom of the page, which seems to be a known/accepted issue.

A: It would be possible in luatex (and with a lot of lua to re-implement the linebreaking rules) but normally this isn't possible: tex breaks the paragraph in to lines before considering page breaking, so you can not change the line width at a page break.


text:
Q: Docker Image For Deploying DotNet Core Output to Firebase I'm struggling to create a BitBucket Pipeline script which can compile a DotNet Core application, run it and then deploy the output html files to Firebase using the CLI.
image: microsoft/dotnet:sdk

pipelines:
  default:
    - step:
        caches:
          - dotnetcore
        script:
          - dotnet restore
          - dotnet build MySolution.sln
  branches:
    master:
      - step:
           caches:
             - dotnetcore
           script:
            - dotnet restore
            - dotnet build MySolution.sln
            - cd MySolution
            - dotnet run MySolution.
            - npm install -g firebase-tool
            - firebase deploy --token "$FIREBASE_TOKEN"

The image microsoft/dotnet:sdk doesn't contain npm or the Firebase-Tools package I require. I'm struggling to find an alternative Docker Image which contains both dotnet and npm / Firebase-Tools. Is there a simpler way to deploy the output of the application to Firebase directly from BitBucket?

A: I think you should dig into the multi-step approach of Bitbucket pipelines. There you will be able to run each of the steps with different docker images.
More documentation you may find at Bitbucket here
For example:
pipelines:
  default:
    - step:
        name: Build and test
        image: microsoft/dotnet:sdk
        script:
          - dotnet restore
          - dotnet build
          - dotnet publish -o /out -c Release
        artifacts:
          - out/**
    - step:
        name: Run npm
        image: node:8
        script:
          - npm install -g firebase-tool
          - firebase deploy --token "$FIREBASE_TOKEN"
    - step
        name: Run app
        image: microsoft/dotnet:sdk
        script:
          - dotnet run MySolution .


text:
Q: How to create this CSS border Hi guys i'm trying to create this(image) css border around a div, but having trouble.
I have created the border but cannot get the border to be smooth.
here is my code
border-left: 5px solid #036;
border-right: 5px solid #036;
border-top: 10px solid #036;
border-bottom: 5px solid #036;

A: Fiddle Up, You can see it here.
Hope it help.
EDIT:
Html:

    Title here?

        Hello.

Css:
div.a {
    border-top: 10px solid #333;
    border-left: 5px solid #333;
    border-bottom: 5px solid #333;
    border-right: 5px solid #333;
    border-radius: 10px;
    background-color: #333;
    width: 200px;
    height: 400px;
}
div.b {
    border-radius: 5px;
    background-color: #FFF;
    width: 180px;
    height: 350px;
    padding: 10px;
}

.abs {
    color: #FFF;
    display: inline-block;
    font-weight: bold;
    margin-bottom: 10px;
}

A: You can attain such a setup using new CSS3 facilities, namely border-radius and gradient form of background image. You can find information about those all around the internet, for example background gradient and border radius.
Below is example, it will not work in all browsers, and is not exactly what you want, but it should be enough to give you the basic idea:
The html structure could look like this:

    Search for a hotel

    Some other content

And the corresponding css would be:
#big_div {height:450px;width:250px;border-radius: 5px;background-color:red;
background-image: linear-gradient(bottom, rgb(33,51,140) 5%, rgb(125,187,209) 51%,
rgb(33,51,140) 100%);
background-image: -o-linear-gradient(bottom, rgb(33,51,140) 5%, rgb(125,187,209) 51%,
rgb(33,51,140) 100%);
background-image: -moz-linear-gradient(bottom, rgb(33,51,140) 5%, rgb(125,187,209)
51%, rgb(33,51,140) 100%);
background-image: -webkit-linear-gradient(bottom, rgb(33,51,140) 5%, rgb(125,187,209)
51%, rgb(33,51,140) 100%);
background-image: -ms-linear-gradient(bottom, rgb(33,51,140) 5%, rgb(125,187,209) 51%,
rgb(33,51,140) 100%);
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0.05, rgb(33,51,140)),
color-stop(0.51, rgb(125,187,209)),
color-stop(1, rgb(33,51,140))
);}
#small_white_div {height:400px;width:220px;margin:auto;border-radius:5px;
background-color:white;margin-top:20px;}

Good luck.

A: It's done with background image.

A: You are looking for border-radius to get the rounded corners. Try out something like this:
-webkit-border-radius: 8px 8px 8px 8px;
-moz-border-radius: 8px 8px 8px 8px;
border-radius: 8px 8px 8px 8px;

Note this is CSS3 and will not work in older versions of IE


text:
Q: KafkaStreams interactive queries with Spring-Kafka I am writing a Spring Boot app with Spring Kafka.
As my app is focused on Kafka Streams and I need to use interactive queries and query my state stores I am wondering: is there any particular way to access kafka streams state stores with Spring Kafka?
From what I've seen there is some support in Spring Cloud Stream Binder Kafka Streams for interactive queries but I cannot find anything about them in Spring Kafka.
Am I missing something or there is no support for it in Spring-Kafka?
And if so - is there anything in particular I should have in mind while creating my own version of org.springframework.cloud.stream.binder.kafka.streams.InteractiveQueryService ?
It seemed a little too much to include Spring Cloud Streams when all I use is only Kafka and Kafka Streams but if interactive query support provided there would be difficult to implement on my own maybe it is recommended to include it anyway? I would appreciate any advise.

A: Well if you use Spring-Kafka and Kafka-Streams,
i suggest you to define your KafkaStreams as @Bean so spring will take care of the lifecycle of the object, having something like
@Configuration
public class KafkaConfig{
  @Bean
  KafkaStreams ingestAndAggregateStream(KafkaProperties kafkaProps){
  Topology t....
  KafkaStreams stream = new KafkaStreams(t,kafkaProps.buildStreamsProperties())
  stream.start();
  return stream;
  }
}

Once you do that you can autowire the stream in the controller and use it to retrieve and query the LOCAL KVStore
@RestController
public class StreamingController {

  private final KafkaStreams ingestAndAggregateStream;
  public StreamingController(KafkaStreams ingestAndAggregateStream){
    this.ingestAndAggregateStream = ingestAndAggregateStream;
  }

  @RequestMapping(value = "/queryStore", method = RequestMethod.GET)
  @ResponseBody
  public Value getKVStoreValue(@RequestParam String key){
    ReadOnlyKeyValueStore<String, Value> store = ingestAndAggregateStream
        .store("KV_STORE_NAME",
            QueryableStoreTypes.<String, Value>keyValueStore());
    return store.get(key);
  }
}

A: If you have @EnableKafkaStreams on you application, then you can autowire StreamsBuilderFactoryBean.
You can inject StreamsBuilderFactoryBean, and then get the KafkaStreams object from it with .getKafkaStreams():
@RestController
public class StreamingController {

  private final KafkaStreams ingestAndAggregateStream;
  public StreamingController(KafkaStreams ingestAndAggregateStream){
    this.ingestAndAggregateStream = ingestAndAggregateStream;
  }

  @RequestMapping(value = "/queryStore", method = RequestMethod.GET)
  @ResponseBody
  public Value getKVStoreValue(@RequestParam String key){
    ReadOnlyKeyValueStore<String, Value> store = ingestAndAggregateStream
        .store("KV_STORE_NAME",
            QueryableStoreTypes.<String, Value>keyValueStore());
    return store.get(key);
  }
}


text:
Q: How to write a function that takes a list of column names of a DataFrame, reorders selected columns the left and preserves unselected columns I'd like to build a function
def reorderColumns(columnNames: List[String]) = ...
that can be applied to a Spark DataFrame such that the columns specified in columnNames gets reordered to the left, and remaining columns (in any order) remain to the right.
Example:
Given a df with the following 5 columns
| A | B | C | D | E
df.reorderColumns(["D","B","A"]) returns a df with columns ordered like so:
| D | B | A | C | E

A: Try this one:
def reorderColumns(df: DataFrame, columns: Array[String]): DataFrame = {
  val restColumns: Array[String] = df.columns.filterNot(c => columns.contains(c))
  df.select((columns ++ restColumns).map(col): _*)
}

Usage example:
val spark: SparkSession = SparkSession.builder().appName("test").master("local[*]").getOrCreate()

import spark.implicits._
val df = List((1, 3, 1, 6), (2, 4, 2, 5), (3, 6, 3, 4)).toDF("colA", "colB", "colC", "colD")
reorderColumns(df, Array("colC", "colB")).show

// output:
//+----+----+----+----+
//|colC|colB|colA|colD|
//+----+----+----+----+
//|   1|   3|   1|   6|
//|   2|   4|   2|   5|
//|   3|   6|   3|   4|
//+----+----+----+----+


text:
Q: OpenGL quad buffered stereo doesn't show both buffers When using quad buffered stereo with my application, my video card does support quad buffered stereo (Quadro 5000/PCIe/SSE2), only one buffer is displayed on the screen, i am using glut and openGL with vbos arrays, i am initialising glut this way :
    int type = GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_STEREO;
    glutInitDisplayMode(type);
    glutInitWindowSize(width,height);

    win = glutCreateWindow(title.c_str());
    glutSetWindow(win);
    GLenum err = glewInit();
    if (GLEW_OK != err) {
        fprintf(stderr,"  ## ERROR: %d: %s\n",
            (int)err,(char*)gluErrorString(err));
    }
    glutDisplayFunc(loop_function);

and when drawing here is how i fill both buffers :
        glDrawBuffer(GL_BACK_LEFT);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    camera->OnMouseMotion(sf::Vector2i(-100,0));
    camera->look();
    for (auto i = objects->cbegin(); i != objects->cend(); ++i)
        (*i)->draw(camera);
    glDrawBuffer(GL_BACK_RIGHT);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    camera->OnMouseMotion(sf::Vector2i(200,0));
    camera->look();
    for (auto i = objects->cbegin(); i != objects->cend(); ++i)
        (*i)->draw(camera);
    camera->OnMouseMotion(sf::Vector2i(-100,0));
    camera->look();

    glutSwapBuffers();

Only the right buffer (the last one called) is displayed for both eyes. I tried drawing the right buffer first but then the display is blank (none is drawn)
the OnMouseMotion does move the mouse according to the position and i know my movements are not set properly but right now i am focusing on displaying two different images, one for the right eye, one for the other one.
Is there anything i have forgotten here ? or maybe the gl calls aren't right ?


text:
Q: Oracle Apex - Dynamic Actions In Oracle Apex- Dynamic Actions:
My Queries about in Dynamic action to enable/disable two different items as below.
I am working with apex 5 and need to do enable/disable with these item
Having two items in my apex page

*

*p1_text_field

*p2_select_list
I want to disable the p2 when I am entering value in p1 which is enabled to type
vise-versa
I want to disable the p1 when I am entering value in p2 which is enabled to select the values.

A: For item p1_text_field:

*

*Create a dynamic action with properties: Event - Key down or Change, Selection Type - Item, Item(s) - p1_text_field

*Add a Client Side Condition: Type - Item is null, Item - p1_text_field. This condition will allow you to unlock disabled field in a case you clear p1_text_field

*Add True action with type Enable, Selection Type - Item, Item(s) - p2_select_list

*Add False action with type Disable, Selection Type - Item, Item(s) - p2_select_list
After that, when a user input something into p1_text_field, p2_select_list will be disabled. If the user clears value of p1_text_field, p2_select_list will be enabled. If you don't need this, do not create Client Side Condition.
Repeat same steps for p2_select_list.
UPD - Important notice
I forgot about one "feature" of APEX. When you create a new true or false action, check field Fire on initialization. It have to be No, otherwise action will be executed on page load. The main problem is that APEX sometimes creates new actions with this field set to Yes.


text:
Q: How to pass the binding context to custom handler call? I'm using Knockout custom handlers to update my objects like this:
ko.bindingHandlers.Tile = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var $element = $(element);

        var $parent = bindingContext.$parent || viewModel.$parent; // TODO: Clean up this mess

        /*
            Do lot of things using bindingContext.$parent, calculate elements dimension, populate fields etc.
        */
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        $(element).show();
    }
};

ko.bindingHandlers.TileColumn = {
    /*  another custom handler, we got a lot of those things  */
}

Now I implemented a Resize function and I can reuse all that weird logic in the custom handler to redraw/resize my elements.
var baseResize = this.Resize;
this.Resize = function () {
    baseResize.call(this);

    var tiles = this.Element.find('.tile');
    var tilesVM = this.DataSource.Items;

    for (var i = 0x0; i < tiles.length; i++) {

        tilesVM[i].$parent = this.ViewModel; // Clean up this mess too

        ko.applyBindingsToNode(tiles[i], null, tilesVM[i]);
    }
}

This works but feels like it's not the right way to do it. I'm struggling to refactor that handlers and get out of it the resize logic: not sure if this is the right way to do it.
While we wait for that refactoring I want a better way to call the applyBindings passing the correct bindingContext.
Note I did a very ugly thing here:
var $parent = bindingContext.$parent || viewModel.$parent; // TODO: Clean up this mess

And here:
tilesVM[i].$parent = this.ViewModel; // Clean up this mess too

Because the bindingContext parameter does not contain the parent view model when I explicit call the custom handler.
Of course that handler works just fine without that ugly messy line when the component loads and knockout is doing all the magic behind the curtain.

A: Robert, thanks for your time.
That documentation link does not helped since I got 3 levels: TileParent, Tile and TileChilds and I want to only call the Tile level and I cannot see a way to do it without applyBindingsToNode.
But that pointed me out to the binding documentation. After reading this blog and digging in the ko source code I realized one wonderfull thing: I can pass a ViewModel OR a BindingContext as parameter.
At first I was sad I cannot pass both at the same time but I see the VM is inside the BC $data.
Finally I found this usefull ko.contextFor(element)
            for (var i = 0x0; i < tiles.length; i++) {
            var bindingContext = ko.contextFor(tiles[i]);

            ko.applyBindingsToNode(tiles[i], null, bindingContext);
        }

and I also cleaned my handler callback
            var $parent = bindingContext.$parent;

Everything still working, but this time a bit more cleaner!


text:
Q: Make function observe and react to variable changes in separate function Javascript This is probably an easy one but I'm stuck and can't find a good solution.
I am getting data from a WebSocket and am passing this data into a function using localStorage.setItem.
This works pretty well, but unfortunately, it only works once.
Since my code keeps getting new data from my WebSocket, I would like to keep passing this data into my function, but the function never asks for it again.
How can I make one function observe changes in another and update its variables accordingly?
Here's my code:
let ws = new WebSocket("ws://localhost:3000/");
let delayTimeElement = document.getElementById('numberonwebsite')

ws.onmessage = (event) => {
    let delayTimes = parseInt(event.data);
    delayTimeElement.innerText = delayTimes;
    localStorage.setItem('value1', `${delayTimes}`);
};

var pJS = function bla(tag_id, params){
  var canvas_el = document.querySelector('#'+tag_id+' > .particles-js-canvas-el');
  let particlecount = localStorage.getItem('value1');
  console. log(particlecount)

  /* particles.js variables with default values */
  this.pJS = {
    canvas: {
      el: canvas_el,
      w: canvas_el.offsetWidth,
      h: canvas_el.offsetHeight
    },
    particles: {
      number: {
        value: 0,
        density: {
          enable: true,
          value_area: 9000
        }
      },
      color: {
        value: '#000'
      },
      shape: {
        type: 'circle',
        stroke: {
          width: 0,
          color: '#ff0000'
        },
        polygon: {
          nb_sides: 5
        },
        image: {
          src: '',
          width: 100,
          height: 100
        }
      },
      opacity: {
        value: 1,
        random: false,
        anim: {
          enable: false,
          speed: 2,
          opacity_min: 0,
          sync: false
        }
      },
      size: {
        value: 2,
        random: false,
        anim: {
          enable: false,
          speed: 20,
          size_min: 0,
          sync: false
        }
      },
      line_linked: {
        enable: true,
        distance: 100,
        color: '#fff',
        opacity: 1,
        width: 1
      },
      move: {
        enable: true,
        speed: 2,
        direction: 'none',
        random: false,
        straight: false,
        out_mode: 'in',
        bounce: false,
        attract: {
          enable: false,
          rotateX: 3000,
          rotateY: 3000
        }
      },
      array: []
    },
    interactivity: {
      detect_on: 'canvas',
      events: {
        onhover: {
          enable: true,
          mode: 'grab'
        },
        onclick: {
          enable: true,
          mode: 'push'
        },
        resize: true
      },
      modes: {
        grab:{
          distance: 100,
          line_linked:{
            opacity: 1
          }
        },
        bubble:{
          distance: 200,
          size: 80,
          duration: 0.4
        },
        repulse:{
          distance: 200,
          duration: 0.4
        },
        push:{
          particles_nb: particlecount,
        },
        remove:{
          particles_nb: 2
        }
      },
      mouse:{}
    },
    retina_detect: false,
    fn: {
      interact: {},
      modes: {},
      vendors:{}
    },
    tmp: {}
  };

I'm retrieving my data from the WebSocket connection and turn it into a variable called delayTimes then I'm passing delayTimes via local storage to var pJS = function bla(tag_id, params) where I convert it to particlecount which I then call around line 121 at push:{ particles_nb: particlecount.
Now I would like to update particlecount "live" when I receive a new dataset from my WebSocket but have no idea how to.


text:
Q: cfmail is not working properly I am trying to send email using following script but it's not working and throwing error:
<cfmail to="user@mydomain.com"
            from="user@mydomain.com"
           <!---  subject="#sub#"   --->
            type="html"
            server="smtp.sendgrid.net"
            timeout="360"
            username="un"
            password="psw"  >

            <cfmailparam name="X-SMTPAPI" value="{\"category\":\"Cool Emails\"}">
            <cfoutput>
                Hello
            </cfoutput>
     </cfmail>

Error is :Invalid token \ found on the <cfmailparam tag line
I have tried removing tags as well still it didn't work.

A: That is not how you escape quotes in CFML. You should be able to just double them up. Like so:
<cfmailparam name="X-SMTPAPI" value="{""category"":""Cool Emails""}">

Or you could use single-quotes to surround your values instead of double quotes. This will allow you to use double-quotes within your values. Like so:
<cfmailparam name='X-SMTPAPI' value='{"category":"Cool Emails"}'>

Also, in your example you do not need to use <cfoutput> tags within the <cfmail> tags.


text:
Q: Find Script start time and uptime in centos I have a php script (cron job) running on my server which takes up a lot of cpu. I took a look on the code and couldn't find anything wrong. Now I have to check the logs for anomaly and for this I need to get the script start time and/or uptime. I tried top, ps -aux, htop etc but couldn't get that. Is there any other command/method available for this?
ps -aux | grep php shows Oct 11, the date. But How can I get the time?

A: You can run
ps -o lstart PID

Which will give the start time of the process.

A: I suggest wrapping the php script inside a shell script:
date >/your/log ; /usr/bin/time /path/to/your.php

A: If you know PID of script; you can get the start time of script with

stat  -c %z /proc/PID

Additionally you can analyze what's going on in script with strace e.g.

strace -p PID -s 128 -tT

This will give you idea where time is spent in this process which appears to be trashing your CPU


text:
Q: r markdown fancyhdr - \undefinedpagestyle I am struggling with adding a header to my pdf. When it compiles I always get an error of \undefinedpagestyle and compiling stops.
This is my current yaml:
---
output:
  bookdown::pdf_document2:
    toc: true
    toc_depth: 3
    number_section: true
    header-includes:
      - \usepackage{float}
      - \usepackage{fancyhdr}
      - \usepackage[margins=raggedright]{floatrow}
      - \usepackage{placeins}
      - \usepackage{chngcntr}
      - \counterwithin{figure}{section}
      - \counterwithin{table}{section}
      - \usepackage[german]{babel}
    includes:
      before_body: Abstract.tex
fontsize: 11pt
linestretch: 1.5
lang: de-DE
geometry: margin=2.5cm
bibliography: references.bib
link-citations: true
csl: elsevier-harvard.csl
linkcolor: black
---

This is how I use the fancyhdr package:
\pagebreak
\pagenumbering{Roman}
\newpage
\listoffigures
\newpage
\listoftables
\newpage
\section*{Abkürzungsverzeichnis}

\pagebreak

\pagenumbering{arabic}

\pagestyle{fancy}
\fancyfoot[CO,CE]{\thepage}

\renewcommand{\footrulewidth}{\headrulewidth}

# Einführung
```{r child = 'Einfuehrung.Rmd'}
```

This is the occuring error:
! Undefined control sequence.
<argument> \undefinedpagestyle

Fehler: LaTeX failed to compile Masterarbeit_Vorlage_neu.tex.


text:
Q: Li-Po battery leaking current when connected to TP-4056 charger I've been using a Nokia BL-5C 1020mAh, 3.7 Li-Ion battery to power up my SIM800l GSM module. Everytime I used the battery for testing out the various AT commands for maybe 30 mins or an hour, I'd check the voltage, and it'd still be at around 4.2 volts. Not much drain.... But the next day (overnight), the battery would be dead. At around 3 volts (Thanks to the overdischarge protection of the TP-4056). This happened a couple of times.
So I decided to check if the battery was leaking current when connected to the TP-4056 without any load connected to it.
And... I was right. Around 25mA!
Why could this be happening?
Is my TP-4056 module bad?

A: The TP-4056 is rated to draw a maximum of 6 micro-amps in standby, so either the circuit is poorly implemented or something is defective.
(Ibat in standby mode on the datasheet)

A:
Why could this be happening? Is my TP-4056 module bad?

My TP4056 was also doing same.
I used a new battery and tried changing switches.
Lastly I found the problem was with the TP4056 itself.
I exchanged it for a new one and voila. No more power drain.
As I had the same problem as you and as the replacement 4056 and almost all others do not have this problem it seems very likely that your 4056 is faulty.


text:
Q: iOS SwiftUI widget issue, the widget load old/default data when is added to lockscreen / home on a physical device forgive me if I say nonsense, I have been fiddling with swift for just over 2 months ...be patient :-)
So, I have a problem with the widget and I don't understand what it depends on, maybe it happened to someone and it could help me.
Everything works perfectly, app and widget update, except one (damned) thing: when I add the widget from the gallery for the first time, it loads me the default data.
Let me explain: when selecting from the widget gallery the snapshots are updated correctly; when I select it it flashes on an old view (something I would say imperceptible even if it bothers me personally) and then, no one knows why, it loads the default data when it is added to the home / lockscreen, as if the userdefaults were empty .
On the simulator it loads it well, on my device it doesn't (iPhone 7).
I would like to understand, from you who know more than me, how the views are divided at the juncture of the gallery:
from what I understand, when I see the preview from the gallery it is the getSnapshot: in that context, I load the data from the Userdefaults store to get an updated preview; the same goes for the placeholder since I don't have to fetch anything and therefore I should have the result immediately (but I didn't really understand where the placeholder would appear .. maybe it's that flash I hate so much?).
in getTimeline I do the same, I load the data from the store and then in the for of the timeline I recall them.
has it ever happened to anyone?
I would like to post code but I do not have the possibility for various reasons .. i'm really sorry.
thank you very much to those who will try to help me!


text:
Q: Historical Exchange Rates I want to know if there is an API ( it doesn't matter if it is paid or free) in java / javascript which gives Historical Exchange Rates. I have searched and found some:

*

*https://www.mashape.com/joss/open-exchange-rates#!documentation

*http://currencies.apps.grandtrunk.net/
Please help me in finding a reliable API which gives Historical Exchange Rates.

A: Here are a few useful links:
http://openexchangerates.org/documentation#historical-data
Free Forex Historical Data
Yahoo Finance (Currency Rates)
See their data,you can retrieve (csv, xls, xml) historical data an then use it as per your requirements.


text:
Q: ElasticSearch C# Nest Getting top words with 5.1 I have an ElasticSearch object with these fields:
[Keyword]
public List<string> Tags { get; set; }
[Text]
public string Title { get; set; }

And, before I used to get the top Tags, in all the documents, using this code:
var Match = Driver.Search<Metadata>(_ => _
                  .Query(Q => Q
                  .Term(P => P.Category, (int)Category)
                     && Q.Term(P => P.Type, (int)Type))
                  .FielddataFields(F => F.Fields(F1 => F1.Tags, F2 => F2.Title))
                  .Aggregations(A => A.Terms("Tags", T => T.Field(F => F.Tags)
                  .Size(Limit))));

But with Elastic 5.1, I get an error 400 with this hint:

Fielddata is disabled on text fields by default. Set fielddata=true on
  [Tags] in order to load fielddata in memory by uninverting the
  inverted index.

Then the ES documentation about parameter mapping tells you "It usually doesn't make sense to do so" and to "have a text field for full text searches, and an unanalyzed keyword field with doc_values enabled for aggregations".
But the only doc with this is for 5.0, and the same page for 5.1 seem to not exist.
Now, 5.1 has a page about Term Aggregation that seems to cover what I need, but there is absolutely nothing to be found in C# / Nest that I can use.
So, I'm trying to figure out how I can just get the top words, across all documents, from the Tags (where each tag is its own word; for example "New York" is not "New" and "York") and the title (where each word is its own thing) in C#.

I need to edit this post because there seems to be a deeper problem. I wrote some test code that illustrates the issue:
Let's create a simple object:
public class MyObject
{
    [Keyword]
    public string Id { get; set; }
    [Text]
    public string Category { get; set; }
    [Text(Fielddata = true)]
    public string Keywords { get; set; }
}

create the index:
var Uri = new Uri(Constants.ELASTIC_CONNECTIONSTRING);
var Settings = new ConnectionSettings(Uri)
.DefaultIndex("test")
.DefaultFieldNameInferrer(_ => _)
.InferMappingFor<MyObject>(_ => _.IdProperty(P => P.Id));
var D = new ElasticClient(Settings);

fill the index with random stuff:
for (var i = 0; i < 10; i++)
{
    var O = new MyObject
    {
        Id = i.ToString(),
        Category = (i % 2) == 0 ? "a" : "b",
        Keywords = (i % 3).ToString()
    };

    D.Index(O);
}

and do the query:
var m = D.Search<MyObject>(s => s
    .Query(q => q.Term(P => P.Category, "a"))
    .Source(f => f.Includes(si => si.Fields(ff => ff.Keywords)))
    .Aggregations(a => a
        .Terms("Keywords", t => t
            .Field(f => f.Keywords)
            .Size(Limit)
        )
    )
);

It fails the same way as before, with a 400 and:

Fielddata is disabled on text fields by default. Set fielddata=true on
  [Keywords] in order to load fielddata in memory by uninverting the inverted
  index.

but Fielddata is set to true on [Keywords], yet it keeps complaining about it.
so, let's get crazy and modify the class this way:
public class MyObject
{
    [Text(Fielddata = true)]
    public string Id { get; set; }
    [Text(Fielddata = true)]
    public string Category { get; set; }
    [Text(Fielddata = true)]
    public string Keywords { get; set; }
}

that way everything is a Text and everything has Fielddata = true.. well, same result.
so, either I am really not understanding something simple, or it's broken or not documented :)

A: It's less common that you want Fielddata; for your particular search here where you want to return just the tags and the title fields from the search query, take a look at using Source Filtering for this
var Match = client.Search<Metadata>(s => s
    .Query(q => q
        .Term(P => P.Category, (int)Category) && q
        .Term(P => P.Type, (int)Type)
    )
    .Source(f => f
        .Includes(si => si
            .Fields(
                ff => ff.Tags,
                ff => ff.Title
            )
        )
    )
    .Aggregations(a => a
        .Terms("Tags", t => t
            .Field(f => f.Tags)
            .Size(Limit)
        )
    )
);

Fielddata needs to uninvert the inverted index into an in memory structure for aggregations and sorting. Whilst accessing this data can be very fast, it can also consume a lot of memory for a large data set.
EDIT:
Within your edit, I don't see anywhere where you create the index and explicitly map your MyObject POCO; without explicitly creating the index and mapping the POCO, Elasticsearch will automatically create the index and infer the mapping for MyObject based on the first json document that it receives, meaning Keywords will be mapped as a text field with a keyword multi_field and Fielddata will not be enabled on the text field mapping.
Here's an example to demonstrate it all working
void Main()
{
    var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
    var defaultIndex = "test";
    var connectionSettings = new ConnectionSettings(pool)
            .DefaultIndex(defaultIndex)
            .DefaultFieldNameInferrer(s => s)
            .InferMappingFor<MyObject>(m => m
                .IdProperty(p => p.Id)
            );

    var client = new ElasticClient(connectionSettings);

    if (client.IndexExists(defaultIndex).Exists)
        client.DeleteIndex(defaultIndex);

    client.CreateIndex(defaultIndex, c => c
        .Mappings(m => m
            .Map<MyObject>(mm => mm
                .AutoMap()
            )
        )
    );

    var objs = Enumerable.Range(0, 10).Select(i =>
        new MyObject
        {
            Id = i.ToString(),
            Category = (i % 2) == 0 ? "a" : "b",
            Keywords = (i % 3).ToString()
        });

    client.IndexMany(objs);

    client.Refresh(defaultIndex);

    var searchResponse = client.Search<MyObject>(s => s
        .Query(q => q.Term(P => P.Category, "a"))
        .Source(f => f.Includes(si => si.Fields(ff => ff.Keywords)))
        .Aggregations(a => a
            .Terms("Keywords", t => t
                .Field(f => f.Keywords)
                .Size(10)
            )
        )
    );

}

public class MyObject
{
    [Keyword]
    public string Id { get; set; }
    [Text]
    public string Category { get; set; }
    [Text(Fielddata = true)]
    public string Keywords { get; set; }
}

This returns
{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 5,
    "max_score" : 0.9808292,
    "hits" : [
      {
        "_index" : "test",
        "_type" : "myobject",
        "_id" : "8",
        "_score" : 0.9808292,
        "_source" : {
          "Keywords" : "2"
        }
      },
      {
        "_index" : "test",
        "_type" : "myobject",
        "_id" : "0",
        "_score" : 0.2876821,
        "_source" : {
          "Keywords" : "0"
        }
      },
      {
        "_index" : "test",
        "_type" : "myobject",
        "_id" : "2",
        "_score" : 0.13353139,
        "_source" : {
          "Keywords" : "2"
        }
      },
      {
        "_index" : "test",
        "_type" : "myobject",
        "_id" : "4",
        "_score" : 0.13353139,
        "_source" : {
          "Keywords" : "1"
        }
      },
      {
        "_index" : "test",
        "_type" : "myobject",
        "_id" : "6",
        "_score" : 0.13353139,
        "_source" : {
          "Keywords" : "0"
        }
      }
    ]
  },
  "aggregations" : {
    "Keywords" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "0",
          "doc_count" : 2
        },
        {
          "key" : "2",
          "doc_count" : 2
        },
        {
          "key" : "1",
          "doc_count" : 1
        }
      ]
    }
  }
}

You might also consider mapping Keywords as a text field with a keyword multi_field, using the text field for unstructured search and the keyword for sorting, aggregations and structured search. This way, you get the best of both worlds and don't need to enable Fielddata
client.CreateIndex(defaultIndex, c => c
    .Mappings(m => m
        .Map<MyObject>(mm => mm
            .AutoMap()
            .Properties(p => p
                .Text(t => t
                    .Name(n => n.Keywords)
                    .Fields(f => f
                        .Keyword(k => k
                            .Name("keyword")
                        )
                    )
                )
            )
        )
    )
);

then in search use
var searchResponse = client.Search<MyObject>(s => s
    .Query(q => q.Term(P => P.Category, "a"))
    .Source(f => f.Includes(si => si.Fields(ff => ff.Keywords)))
    .Aggregations(a => a
        .Terms("Keywords", t => t
            .Field(f => f.Keywords.Suffix("keyword"))
            .Size(10)
        )
    )
);


text:
Q: Universal Windows Platform - UI not updating when returning from different page I'm learning Universal Windows Platform and I'm currently analysing music player using SoundCloud API from this site. Link to the github project is at the very bottom of the page. To get this project to work variable SoundCloudClientId from App.xaml.cs should be filled in (I used client id from previous example on the same page, not sure if I can paste that).
When application starts the NowPlaying page is loaded and changing tracks causes UI to update accordingly. The problem is when I navigate to any other page and return back to NowPlaying. I can still change music using buttons, but UI doesn't change (song title, album title etc.).
Important parts of the code:
NowPlaying.xaml
<ImageBrush x:Name="albumrtImage" ImageSource="Assets\Albumart.png" Stretch="UniformToFill" />
<TextBlock x:Name="txtSongTitle" Grid.Row="0" HorizontalAlignment="Center"   Text="Song Title " FontSize="25" Foreground="White" Style="{StaticResource HeaderTextBlockStyle}" TextTrimming="WordEllipsis"  />
<TextBlock x:Name="txtAlbumTitle"  Grid.Row="0" Text="Label " HorizontalAlignment="Center" FontWeight="Light" FontSize="20"  Foreground="#9799a5" Style="{StaticResource BodyTextBlockStyle}" TextTrimming="WordEllipsis"/>

NowPlaying.xaml.cs
    async void BackgroundMediaPlayer_MessageReceivedFromBackground(object sender, MediaPlayerDataReceivedEventArgs e)
    {
        TrackChangedMessage trackChangedMessage;
        if (MessageService.TryParseMessage(e.Data, out trackChangedMessage))
        {
            // When foreground app is active change track based on background message
            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                var songIndex = GetSongIndexById(trackChangedMessage.TrackId);
                if (songIndex >= 0)
                {
                    var song = App.likes[songIndex];
                    LoadTrack(song); //Update UI
                }
            });
            return;
        }

        BackgroundAudioTaskStartedMessage backgroundAudioTaskStartedMessage;
        if (MessageService.TryParseMessage(e.Data, out backgroundAudioTaskStartedMessage))
        {
            backgroundAudioTaskStarted.Set();
            return;
        }
    }
    private async void LoadTrack(SoundCloudTrack currentTrack)
    {
        try
        {
            //Change album art
            string albumartImage = Convert.ToString(currentTrack.artwork_url);
            if (string.IsNullOrWhiteSpace(albumartImage))
            {
                albumartImage = @"ms-appx:///Assets/Albumart.png";

            }
            else
            {
                albumartImage = albumartImage.Replace("-large", "-t500x500");
            }
            //Next 3 lines when pages were switched don't cause UI to update
            albumrtImage.ImageSource = new BitmapImage(new Uri(albumartImage));
            txtSongTitle.Text = currentTrack.title;
            txtAlbumTitle.Text = Convert.ToString(currentTrack.user.username);

        }
        catch (Exception ex)
        {
            MessageDialog showMessgae = new MessageDialog("Something went wrong. Please try again. Error Details : " + ex.Message);
            await showMessgae.ShowAsync();
        }
    }

After navigating from NowPlaying->Me->NowPlaying and clicking next the track changes, but UI doesn't update as seen on the screen below:
UI problem
I'm trying to reproduce the problem on a simple example, but without any luck. What could cause this issue? Any help is appreciated.

A: I've found the solution. The problem was with cache. The NowPlaying page required putting following property:
NavigationCacheMode="Required"

A: I just want to add that you can also check navigation mode in OnNavigatedTo method. It can be helpful when for instance you would like to refresh the data when returning to the selected page.
 protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        if(e.NavigationMode == NavigationMode.Back)
        {
            //refresh the data here...
        }
    }


text:
Q: Ignore missing imports in webpack is it possible in webpack to ignore imports that cannot be resolved? To change imports to for example undefined. I would need to control this behavior by regex or function. So if the missing import conforms to some rules, then it would be replaced undefined otherwise it would throw an error as normal.
So i would like to achieve this logic:
if module is resolved then
    import it normally
else
    if module import matching regex then
        replace it with undefined
    else
        throw error

I tried IgnorePlugin, but it ignores import always, even if it exists. I tried searching for a viable way in documentation, e.g. in resolve options, but there is nothing that could help.
Thanks.

A: You could also try something like this
let m = undefined;
try {
    m = require('somemodule');
} catch (ex) {
    console.warn('somemodule not found')
}
if (m) {
    m.doStuff();
}


text:
Q: react-globe.gl shows a distorted version of a geojson file I did edit a geojson file and want to display it using react-globe.gl which is a 3D (threeJS) globe library.
When I see the file on geojson.io it looks perfect:

However, when it's displayed it looks like "Morocco" takes up the whole world oceans:

This is the geojson file.


text:
Q: Snap code error Im trying to instal Vcode++ on linux, but it needs snap.
was installing "sudo snap install --classic code"
But im getting this error.
"error: cannot communicate with server: Post "http://localhost/v2/snaps/code": dial unix /run/snapd.socket: connect: no such file or directory".
how can I fix this? Thanks!

A: Try:
1.service snapd start
2.sudo systemctl start snapd.service
3.sudo snap install --classic code
If the output of the first command is as follows,
snapd.service
   Loaded: masked (/dev/null; bad)
   Active: inactive (dead)

then run the following command and after doing so, run the 3 commands mentioned above.
sudo systemctl unmask snapd.service


text:
Q: How to make all borders the same color? I have a simple form, with text fields that I'm trying to have borders in the same color. For some reason the left and top borders appear in a slightly different color, which appear to be some kind of shadow. How do I get rid of it?
I'm using this (relevant) CSS to style the text fields:
input[type="text"] {
    border-color: red;
    border-width: 2px;
}

The result is this:

I've also tried adding this piece of code, but with no luck:
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;

Any help will be much appreciated. Thanks!

A: Add border-style:solid;

input[type="text"] {
    border-color: red;
    border-width: 2px;
    border-style:solid;
}
<input type="text"/>

I believe "inset" is the default for many browsers for text inputs.

A: This is due to the default input styling applied by your browser, which sets the border-style to inset. You can get your desired styling, and simplify your CSS rule by changing your CSS to:

input[type="text"] {
  border:2px solid red;
}
<input type="text" />

<input type="text" />


text:
Q: firebase middleware function for a static page (hosting) I would like to hook up to static page requests on the firebase and to make a server side log of page loads to the firestore database. Is there any way to do it in a static hosting configuration? To make a generic handler (middleware) before serving a static page back to client?
I was trying different approaches, the only that works for me is placing the whole static folder in the functions directory from where it can be sent in response by the sendFile function (now this is not a hosting but functions service).
Works, but this is just a workaround not a good solution.
Thanks,

A: Firebase Hosting currently doesn't support any sort of logging of static asset requests.


text:
Q: Weakened presuppositions of the strong law of large numbers Is there some version of the strong law of large numbers which only requires pairwise independent random variables, does not suppose identical distributions for them, but guarantees the convergence a. s. as customary?
EDIT: Posted on MathOverflow.

A: $X_n=n$ is an example of a sequence of independent random variables for which $\frac  1n \sum\limits_{k=1}^{n} X_k \to \infty$ alomost surely.


text:
Q: Separate indented hierarchy list into columns based on parent member I have the below mentioned INPUT and I want to get the output as shared below under output header.
In my INPUT data in my column A contains the data which has different indenting level.
Basically the code should run on this range and check for the highest level of indenting and for each highest level of indenting it should put it under "Mapping 1" header and its subsequent lower levels in Mapping 2, 3 and 4.

OUTPUT:

I have developed a code which is giving me error on the below mentioned line:
Run Time error 1004:
    If currVal > arr(i, 3) Then
        ActiveCell.Offset(k, arr(i, 3) - 1).Value = arr(i, 1)
        End If

Overall Code:-
Sub transposerowcolmulti()

 Dim arr(1 To 8, 0 To 3) As Variant
 Dim i As Long, j As Long

 ActiveWorkbook.Sheets("Input").Activate

 For i = LBound(arr, 1) To UBound(arr, 1)

        arr(i, 1) = range("A6").Offset(i, 0).Value
        arr(i, 2) = IsBold(range("A6").Offset(i, 0))
        arr(i, 3) = Level(range("A6").Offset(i, 0))

        Next i
 Dim k As Long, l As Long
       Dim prevVal As Long, currVal As Long

    k = 0
    l = 0

        ActiveWorkbook.Worksheets.Add
        For i = LBound(arr, 1) To UBound(arr, 1)

            If l = 0 Then
                currVal = arr(i, 3)
                l = l + 1
            End If

            If currVal = arr(i, 3) Then
                ActiveCell.Offset(k, currVal - 1).Value = arr(i, 1)
                End If

            If currVal > arr(i, 3) Then
                ActiveCell.Offset(k, arr(i, 3) - 1).Value = arr(i, 1)
                End If

            If currVal < arr(i, 3) Then
                ActiveCell.Offset(k, arr(i, 3) - 1).Value = arr(i, 1)
                End If

             currVal = arr(i, 3)
             k = i
                Next i

End Sub

Function Level(Optional cCell As range)
' LEVEL returns the outline level of the current row. It will not automatically update and therefore
'   a recalculation Ctrl-Alt-F9 is required.

    If cCell Is Nothing Then
        Set cCell = Application.Caller
    End If
    Level = cCell.Rows.IndentLevel

End Function

Function IsBold(ByVal Cell As range) As Boolean

IsBold = Cell.Font.Bold

End Function

A: Although I don't get how exactly the code should work, I'm pretty sure that your runtime error comes from the fact that you access ActiveCell. You add a new Worksheet (which gets the activesheet) and ActiveCell is set to A1of this sheet. In the first iteration of the 2nd loop. currVal is 0, the term ActiveCell.Offset(k, currVal - 1) is ActiveCell.Offset(0, -1) and this causes the runtime error as you are in column 1 - no offset -1 possible.
Strong advice: Don't use ActiveSheet, ActiveCell or Selectas they can cause significant performance issues and are more difficult to debug.