text:
Q: Failed to establish communication with Looker host This will be very basic, I do not know how to connect to looker with my client ID and client secret for the Looker Extension SDK. This is a hello world app but the documentation is very lacking on the basics.
import React, { useContext, useEffect, useState } from 'react'
import { ComponentsProvider, Space, Text } from '@looker/components'
import { ExtensionContext } from '@looker/extension-sdk-react'

export const HelloWorld: React.FC = () => {
  const { core40SDK } = useContext(ExtensionContext)
  const [message, setMessage] = useState('')

  useEffect(() => {
    const getMe = async () => {
      try {
        const me = await core40SDK.ok(core40SDK.me())
        setMessage('Hello, '+ me.display_name)
      } catch (error) {
        console.error(error)
        setMessage('An error occurred while getting information about me!')
      }
    }
    getMe()
  }, [core40SDK])

  return (
    <ComponentsProvider>
      <Space p="xxxxxlarge" width="100%" height="50vh" around>
        <Text p="xxxxxlarge" fontSize="xxxxxlarge">
          {message}
        </Text>
      </Space>
    </ComponentsProvider>
  )
}

This results in Failed to establish communication with Looker host, but I do not know how to establish the host url or credentials

A: When you build using the Extension Framework, Looker hosts your react application internally so you don't need to do authentication. Don't use the Extension Framework if you are not hosting your react application inside Looker itself.
If you're hosting your own application and making API calls to Looker then you should just use the Looker Embed SDK. You will need to do the authentication on your webserver using nodejs / python / ruby etc. You shouldn't do authentication from client-side javascript.


text:
Q: ArgumentCaptor and comparing with hasItems i am already desperate, i cannot find out why this test is not evaluated as successful. I have checked it milion times:
package someptest;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
import java.sql.SQLException;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import somep.Order;
import somepBO.BOException;
import somepdao.OrderDAO;

public class XXX {

@Mock
OrderDAO dao;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void captor_A() throws SQLException, BOException {
    Order order = new Order();
    ArgumentCaptor<Integer> intCaptor = ArgumentCaptor.forClass(Integer.class);
    when(dao.read(any(Integer.class))).thenReturn(order);
    dao.read(123);
    dao.read(456);
    verify(dao, times(2)).read(intCaptor.capture());
    @SuppressWarnings("unused")
    List<Integer> xs = intCaptor.getAllValues();
    assertThat(intCaptor.getAllValues(), hasItems(456));
}
}

Here is a screen from my debugging, captor catches correct values, but assertThat does not accept it, why?

A: Phew, something seems to go quite wrong on your machine. Based on your test, I created the following self-contained test class:
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.List;

import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

public class ArgumentCaptorTest {

    private static class Order {
    }

    public static class OrderDAO {
        public Order read(Integer any) {
            return null;
        }
    }

    @Mock
    OrderDAO dao;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void captor_A() {
        Order order = new Order();
        ArgumentCaptor<Integer> intCaptor = ArgumentCaptor.forClass(Integer.class);
        when(dao.read(any(Integer.class))).thenReturn(order);
        dao.read(123);
        dao.read(456);
        verify(dao, times(2)).read(intCaptor.capture());
        assertThat(intCaptor.getAllValues(), hasItems(456));
    }
}

Used dependencies (pom.xml):
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>testing</groupId>
    <artifactId>testing</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>2.18.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

When I start the test, it runs perfectly and gives me a green bar. For what I see, you're doing it right. Maybe you have version conflicts between JUnit, Hamcrest and Mockito that lead to your error? I used these JAR versions:

*

*junit:junit:4.12

*org.hamcrest:hamcrest-core:1.3

*org.mockito:mockito-core:2.18.3

I also left the imports so you can compare them with yours (just in case that a "wrong" import causes the error). As you statically import Matchers.* from the Hamcrest package, I am quite sure that this and/or your used library versions cause your problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to clear backstack in android? I have a Splash screen and have Main Activity ,Scenario is that in Main Activity there is a condition which check Login is true or not and have  a "Login" activity and have a Fragment called "B".when I pressed device back button in "Login" activity it Main Activity comes.which I don't want I simple want to close app when I press device back button in Login activity.
here is my code for Back Pressed in Login activity:-
@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        return;
    }
    this.doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "Please  again to exit", Toast.LENGTH_SHORT).show();
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            doubleBackToExitPressedOnce = false;
        }
    }, 2000);

A: Use the finish() method in the Intent creator activity.
If you have 2 activities - A and B, and A starts B via Intent, without going back to A, the Intent in A will look like this:
 Intent i = new Intent();
                i.setClass(context, MainActivity.class);
                startActivity(i);

                // close this activity
                finish();

A: write the following lines
@Override
public void onBackPressed() {
    super.onBackPressed();
    finish();
}

Here, on back pressed the above method will be called and it will finish the activity.


text:
Q: referral system analyses with pandas I have excel file which looks like this:
currently i have excel file with this data: column 1 - date, column 2 - user id, column 3 - parent of user, column 4 - grandparent of user(i.e. parent of previous user), column 5 - parent of previous user, column 6 - parent of previous user, column 7 - parent of previous user. data contains monthly information for every user, i.e. each user id repeats maximum of 12 times.
My desired output is to count multiple levels of referrals.
I want to calculate how many users did every user invited in the first column, then I need to calculate number of users which was invited by the users which was invited by our user(i.e. grandchildren of first user) and so on.
finally I want output which would look like pyramid if it was visible, first member of the pyramid will be user, next members will be users which were invited by first user. next members will be users which were invited by the users from previous level(i.e. users which were invited by first user). I am working with python pandas but can't do anything yet. I can work with excel as well.
I've tried too many variants, I don't remember any of them right now, my last code was this:
import pandas as pd

df = pd.read_excel("L0-L5.xlsx", sheet_name="Sheet1")
df["invited_at"] = pd.to_datetime(df["Rem Date"], format="%d.%m.%Y")
levels = ["L0", "L1", "L2", "L3", "L4", "L5"]
df_list = []
for i, level in enumerate(levels):
    temp_df = df[df[level].notnull()]
    temp_df["level"] = level
    temp_df["user_id"] = temp_df[levels[i]]
    df_list.append(temp_df)
df = pd.concat(df_list)
result = df.pivot_table(index="user_id", columns="level", values="invited_at", aggfunc="count",
fill_value=0)
result = result[["L1", "L2", "L3", "L4", "L5"]]
result.to_excel("L5-L0.xlsx")

and guess, it didn't work.


text:
Q: How do I allocate memory, assign values, and return it to the calling function? Answers to this question describe how to allocate memory and return it to the calling function. An example was given:
void someFunction (int **data) {
  *data = malloc (sizeof (int));
}

void useData (int *data) {
  printf ("%p", data);
}

int main () {
  int *data = NULL;

  someFunction (&data);

  useData (data);

  return 0;
}

I would also like to assign values before returning to the calling function. However, when I try (for example):
void someFunction (int **data) {
  *data = malloc (2 * sizeof (int));
  *data[0] = 1;
  *data[1] = 1;
}

void useData (int *data) {
  printf ("%p", data);
}

int main () {
  int *data = NULL;

  someFunction (&data);

  useData (data);

  return 0;
}

I receive a segmentation fault. Any help is appreciated.

A: Your problem lies with the statement:
*data[0] = 1;

Because of the way precedence works (a), this is actually equivalent to:
*(data[0]) = 1;

rather than, as you expected:
(*data)[0] = 1;

The former variant actually tries to dereference a not-yet-assigned (arbitrary) value, which is what's causing your crash. You should use the latter form to be more explicit.
In any case, it's always a good idea to check any calls that can fail so as to not cause problems later on based on incorrect assumptions. You may also want to consider what will happen if you call the function twice (or more) - it will currently result in a memory leak since the old memory is never freed.
With those points in mind, I would be modifying your function slightly as follows:
void someFunction (int **data) {
    // Release old memory if any (freeing NULL is fine).

    free (*data);

    // Allocate new memory and initialise only if it worked.

    *data = malloc (2 * sizeof (int));
    if (*data != NULL) {
        (*data)[0] = 1;
        (*data)[1] = 1;
    }
}

(a) Precedence is dictated by the order of appearance of expression types in the standard. For example, C11 6.5 Expressions states:

The syntax specifies the precedence of operators in the evaluation of an expression, which is the same as the order of the major subclauses of this subclause, highest precedence first.

And, since array subscripting appears in 6.5.2.1 compared to indirection in 6.5.3.2, the former will happen first.

A: Sometimes, it is helpful to simplify pointer logic.
For example, in the code shown below, allocation and initialization of memory is done using a more familiar int * (rather than an int **).  Then, after allocation and initialization, the allocated memory is returned to the caller via the int **.
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

#define SUCCESS 0

int SomeFunction(int **OUT_data)
   {
   int rCode = SUCCESS;
   int *data = NULL;

   errno=SUCCESS;
   data = malloc(2 * sizeof(int));
   if(!data)
      return(errno);

   data[0] = 10;
   data[1] = 20;

   *OUT_data = data;

   return(rCode);
   }

void UseData(int *data)
   {
   printf("Data[%p]: %d, %d\n", data, data[0], data[1]);
   }

int main()
   {
   int rCode = SUCCESS;
   int *data = NULL;

   rCode=SomeFunction(&data);
   if(rCode)
     {
     fprintf(stderr, "SomeFunction() reports: %d %s\n", rCode, strerror(rCode));
     return(rCode);
     }

   UseData(data);

   return(rCode);
   }


text:
Q: find the maximum possible product of two positive integers whose digits form a permutation of $\{1,\cdots, 8\}$
What is the maximum possible value of a product of two numbers that use the digits $1,\cdots, 8$ exactly once and no other digits?

I know how to obtain the minimum possible product. Similar to above, we must have that both numbers have digits in ascending order. Let $10b + c$ and $a$ be the two numbers, where $c$ is a digit. Then if $10b+c < a, $ since $(10b+c)a > (10a+c)b,$ moving the last digit from the smaller number results in a smaller number. Hence the smallest product is obtained when one number has one digit, which implies the other has 7 (otherwise we could decrease the product with the above method).
First note that for the largest possible product, the two numbers must have their digits in descending order. We have 256 * 2519 > 2569 * 251, so it is not generally true that removing the last digit from the larger factor and appending it to the smaller one yields a larger product. Or if we want to satisfy the conditions of the problem we also have the example 253 * 1468 > 2538 * 146.
For simplicity, consider the case where the two numbers have four digits. Then one number must have 8 as the first digit. The other number can't have 5 as the first digit (the largest digit) as then the maximum product would be $8761\cdot 5432 < 8321 \cdot 7654 = 63688934.$ So the second number must have $6$ or $7$ as the first digit. Then note that $\overline{87pq} \cdot \overline{6mcd} < \overline{8mrs}\cdot \overline{67pq} < \overline{8mrs}\cdot \overline{76pq},$ where the variables are digits. For instance, $\overline{87pq} \cdot \overline{6mcd} - \overline{8mrs}\cdot \overline{67pq} =(8700+10p+q)(6000+100m+10c+d)-(8000+100m+10r+s)(6700+10p+q),$ and a tedious calculation yields the desired inequality.

A: One number, we'll call it $A,$ must start with the $8.$ Call the other $B.$
Now, if the $100$s digit of $A$ is greater than the $100$s digit of $B,$ we can swap them and get a bigger product. This is because swapping them does not change the sum of the two numbers, and we increase the product if the two numbers are closer together, if their sums remain the same.
[*]
This means the $7$ digit must be the first digit of $B,$ because if it is in $A,$ then the digit can be swapped, and then we can increase the product by moving $7$ to the front of $B.$
The same is true for the $10$s digit and the $1$s digits.
We thus get the last digit of $A$ must be $1.$
Likewise, $6$ must be the second digit of $B.$
So we have numbers $A=8000+100a+10b+1, B=7600+c+d.$ And we know that $b<c.$ Leading to the options:
$$(a,b)=(5,3),(5,2),(4,3),(4,2).$$
That gives you four values to check. You might be able to narrow it down further - my guess is the answer is $8531\cdot 7642.$

[*] The key is that for any $S,$ the function $x(S-x)$ increases when $0\leq x\leq S/2$ and decreases after that.


text:
Q: Relacionar cuatro tablas en SQL Intento relacionar 4 tablas asi:
tabla usuario
id | nombre
-----------
 1 | pedro
 2 | miguel

tabla bolantecompra
idbolante | idusuario | propiedadid | pago
-------------------------------------------
1         | 1         | 1           | 5000
2         | 2         | 3           | 6150

tabla propiedad
idpropiedad | direccion         | barrioid
------------------------------------------
1           | calle falsa 1234  | 1
2           | otra calle 1234   | 2
3           | mitre 1234        | 3

tabla barrio
idbarrio | medidas | localidad
------------------------------
1        | 325m2   | tigre
2        | 5000m2  | san fernando
3        | 400m2   | olivos

Hasta ahora logre traer dos datos
$sql = "SELECT * FROM usuario
    INNER JOIN bolantecompra ON bcompralote.idusuario = usuario.id
    INNER JOIN propiedad ON propiedad.idpropiedad = bcompralote.propiedadid
    INNER JOIN propiedad ON propiedad.barrioid = barrio.idbarrio
    WHERE id = 2";

Y el resultado que obtengo es solo migel 6150 y deberia ser miguel 6150 mitre 1234 olivos.
Bueno, espero me ayuden. Gracias!

A: Tienes un error en el tercer INNER JOIN, en vez de propiedad debería se barrio: sustituye INNER JOIN propiedad por INNER JOIN barrio en la cuarta línea.
$sql = "SELECT * FROM usuario
    INNER JOIN bolantecompra ON bcompralote.idusuario = usuario.id
    INNER JOIN propiedad ON propiedad.idpropiedad = bcompralote.propiedadid
    INNER JOIN barrio ON propiedad.barrioid = barrio.idbarrio
    WHERE id = 2";


text:
Q: Microsoft Web Deploy backup fails and doesn't recover I've recently started working with Microsoft Web Deploy.
I got backups working in a basic configuration and now I'd like to experiment with adding some folder exclusions to the .pubxml file in my projects based on the comments to this answer.
Here are my deploy settings:
    cd "\Program Files\IIS\Microsoft Web Deploy V3\scripts\"
    . .\BackupScripts.ps1
    Reset-BackupSettings
    TurnOn-Backups -On $true
    Configure-Backups -Enabled $true
    Configure-Backups -ContinueSyncOnBackupFailure $false
    Configure-Backups -NumberOfBackups 5
    Configure-Backups -BackupPath "D:\UAT\AppBackups\{siteName}_snapshots"
    Configure-BackupSettingsProvider -CanAddExcludedProviders $true
    Get-BackupSettings

This works until I paste this snippet into my publish profile:
    <Target Name="AddCustomSkipRules">
      <ItemGroup>
        <MsDeploySkipRules Include="SkipAppDataFolder">
          <SkipAction></SkipAction>
          <ObjectName>dirPath</ObjectName>
          <AbsolutePath>$(_DestinationContentPath)\\App_Data$</AbsolutePath>
          <Apply>Destination</Apply>
          <XPath></XPath>
        </MsDeploySkipRules>
      </ItemGroup>
    </Target>

A publish attempt with that code fails, and then seems to get stuck.  Removing the snippet and republishing still fails.
Here's the error I get from the trace:
>trace eventLevel="Error" message="BACKUP_FAILED - Skipping backup because it failed due to an unknown reason.%C2%A0For more information, contact your server administrator."

AspNetModuleDiagErrorEvent
Uri /msdeploy.axd

User: username
Client IP: 10.148.69.225
Content-Type: application/msdeploy
Version: 9.0.0.0
MSDeploy.VersionMin: 7.1.600.0
MSDeploy.VersionMax: 9.0.3802.0
MSDeploy.Method: Sync
MSDeploy.RequestId: fa27c81c-12aa-47f3-ac37-7ea94caa14a4
MSDeploy.RequestCulture: en-US
MSDeploy.RequestUICulture: en-US
ServerVersion: 9.0.1973.0
Skip: objectName="^configProtectedData$"
Provider: auto, Path: A tracing deployment agent exception occurred that was propagated to the client.
Request ID   'fa27c81c-12aa-47f3-ac37-7ea94caa14a4'.
Request Timestamp: '11/10/2021 5:08:45 PM'.
Error Details:
    System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
    at Microsoft.Web.Deployment.BackupManager.HandleExceptionForBackupFailure(DeploymentBaseContext baseContext, BackupSettings settings, Exception ex, Boolean suppressLogging)
    at Microsoft.Web.Deployment.BackupRuleHandler.PreSync(DeploymentSyncContext syncContext)
    at Microsoft.Web.Deployment.DeploymentSyncContext.ProcessSync(DeploymentObject destinationObject, DeploymentObject sourceObject)
    at Microsoft.Web.Deployment.DeploymentObject.SyncToInternal(DeploymentObject destObject, DeploymentSyncOptions syncOptions, PayloadTable payloadTable, ContentRootTable contentRootTable, Nullable``1 syncPassId, String syncSessionId)
    at Microsoft.Web.Deployment.DeploymentAgent.HandleSync(DeploymentAgentAsyncData asyncData, Nullable`1 passId, String user, String siteName)
    at Microsoft.Web.Deployment.DeploymentAgent.HandleRequestWorker(DeploymentAgentAsyncData asyncData)
    at Microsoft.Web.Deployment.DeploymentAgent.HandleRequest(DeploymentAgentAsyncData asyncData)

Restarting IIS or the Web Deploy service doesn't help and I'd rather not restart the entire server if I can help it.
How can I get the backup service unstuck?


text:
Q: Windows Runtime dependency properties that depend on each other I got a Windows Runtime component authored in C++/CX that contains four dependency properties. Three of those properties set the color channels red, green and blue in the underlying renderer. The C++/C code for one such property looks as follows:
uint8_t DemoControl::Red::get()
{
  return static_cast<uint8_t>(GetValue(RedProperty));
}

void DemoControl::Red::set(uint8_t r)
{
  SetValue(RedProperty, r);
}

DependencyProperty^ DemoControl::_redProperty =
  DependencyProperty::Register("Red",
                               uint_t::typeid,
                               DemoControl::typeid,
                               ref new PropertyMetadata(127, ref new PropertyChangedCallback(&DemoControl::OnRedChanged)));

void DemoControl::OnRedChanged(DependencyObject^ d, DependencyPropertyChangedEventArgs^ e)
{
  DemoControl^ DemoControl = static_cast<DemoControl^>(d);
  DemoControl->renderer->SetRed(static_cast<uint8_t>(e->NewValue));
}

The fourth property returns the entire color, i.e. it is a combination of the values of the three other properties.
The question is, how would I update that color property if either the red, green or blue property changes without triggering the code attached to the color property via data binding?
A similar question has been asked here but for WPF. The answer suggests to use value coercion but this seems to be a feature unavailable to Windows Runtime components. The PropertyMetadata object used when registering the dependency property does not support CoerceValueCallback from what I can see.

A: I'm not a C++ expert, but at least for your scenario, I think I can help.
You can register the same callback for multiple Dependency Properties. So in your specific case, you could just have a single OnColorComponentChanged callback:
void DemoControl::OnColorComponentChanged(DependencyObject^ d, DependencyPropertyChangedEventArgs^ e)
{
  DemoControl^ DemoControl = static_cast<DemoControl^>(d);

  if (e->Property == DemoControl::RedProperty) // Hand Wave Syntax Here
  {
    DemoControl->renderer->SetRed(static_cast<uint8_t>(e->NewValue));
  }
  else if (e->Property == DemoControl::GreenProperty)
  {
    DemoControl->renderer->SetGreen(static_cast<uint8_t>(e->NewValue));
  }
  else if (e->Property == DemoControl::BlueProperty)
  {
    DemoControl->renderer->SetBlue(static_cast<uint8_t>(e->NewValue));
  }

  // Hand Wave Here
  DemoControl->Color = MakeColor(DemoControl->Red, DemoControl->Green, DemoControl->Blue);
}


text:
Q: Getting Error while importing docx module I have a simple program to read .docx files. But when I run it, the following error occurred. Can someone explain to me what the error description is?

A: i have resolved the issue myself. There was a file named docx.py inside the folder where i kept all of my python stuff. Actually, pythons was import that file instead of original module "docx".


text:
Q: D3.js parseFloat and iterate throught .json first of all I don't know how to make the type() function go through all the elements of the list in the .JSON file.
I get this result:
//0:{x: 0.1, y: 0.966}
//1:{x: 0.3, y: 0.757}
//2:{x: 0.6, y: 0.71}
//x: NaN
//y: NaN

and I thought I would have seen this:
//0:{x: NaN, y: NaN}
//1:{x: NaN, y: NaN}
//2:{x: NaN, y: NaN}

here is the code:
<!-- .JSON file:
[
  {
    "x": 0.1,
    "y": 0.966
  },
  {
    "x": 0.3,
    "y": 0.757
  },
  {
    "x": 0.6,
    "y": 0.71
  }
]
-->

<html>
<head>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>

<script>

var svg = d3.select("body").append("svg")
.attr("witdh", 250)
.attr("height", 250);

d3.json("data.json", function (myArrayOfObjects){

render(type(myArrayOfObjects))
console.log(myArrayOfObjects)
});

var scale = d3.scaleLinear();

scale.domain([0,1]);
scale.range([0,250]);

function type(d){
d.x = parseFloat(d.x);
d.y = parseFloat(d.y);
return d;
}

function render(data) {
svg.selectAll("rect").data(data)
.enter().append("rect")
.attr("x", scale(function(d) {return d.x;}))
.attr("y", 0)
.attr("height", scale(function(d) {return d.y;}))
.attr("width",10);
}

</script>

</body>
</html>

Event when I try the following for type function:
function type(d){
d[0].x = parseFloat(d.x);
d[0].y = parseFloat(d.y);
return d;
}

I get this:
//0: {x: NaN, y: NaN}
//1: {x: 0.3, y: 0.757}
//2: {x: 0.6, y: 0.71}

is that because the parseFloat() fucntion is not working? why does it give me NaN and does not translate the strings into floats?

A: First of all, there is a misunderstanding about the type function here. An accessor function, a.k.a. row conversion function, is a function that is invoked for each row in a CSV or TSV (or any kind of DSV). That d in the type function is a parameter referring to the row.
The thing is d3.json does not accept a row conversion function, only d3.csv and d3.tsv accept it. The good news is that you don't need one. And the reason is simple: you already have numbers (when using d3.csv or d3.tsv, on the other hand, even if your file has numbers, they are converted to strings).
Let's prove that, this is a simple d3.json using your data, look at the console:

d3.json("https://api.myjson.com/bins/6u80r", function(data) {
  data.forEach(function(d) {
    for (var key in d) {
      console.log("The typeof " + d[key] + " in '" + key + ":" + d[key] + "' is " + typeof d[key])
    }
  })
})
<script src="https://d3js.org/d3.v4.min.js"></script>

Also, you're using your scales incorrectly. Instead of:
.attr("x", scale(function(d) {return d.x;}))

It should be:
.attr("x", function(d) {return scale(d.x);})

Check the demo:

var svg = d3.select("body").append("svg")
  .attr("witdh", 250)
  .attr("height", 250);

var scale = d3.scaleLinear()
  .range([0, 250]);

d3.json("https://api.myjson.com/bins/6u80r", render)

function render(data) {
  svg.selectAll("rect").data(data)
    .enter().append("rect")
    .attr("x", function(d) {
      return scale(d.x);
    })
    .attr("y", 0)
    .attr("height", function(d) {
      return scale(d.y);
    })
    .attr("width", 10);
}
<script src="https://d3js.org/d3.v4.min.js"></script>


text:
Q: Lightswitch lambda use I'm writing a LightSwitch application and i could do with some advice.
I wanted to calculate the total number of child objects related to the parent object that fulfil the criteria of being true and related to the Client.
partial void OpenPositions_Compute(ref int result)
{
    foreach (Position position in this.DataWorkspace.ApplicationData.Positions)
    {
        if (position.IsPositionOpen && position.Client.Id == this.Id)
        {
            result++;
        }
    }
}

I did experiment with calculating the number of Positions a client had without using a foreach loop and i came up with this:
partial void TotalPositons_Compute(ref int result)
{
    result += this.Position.Count();
}

Question 1: Is it possible to write snippet 1 in a better/more efficient way? Perhaps as a lambda equation? (or similar to the second code snippet)
Question2: What benefits would a lambda equation give other than readability of code?

A: Question 1:
partial void OpenPositions_Compute(ref int result)
{
    result = this.DataWorkspace.ApplicationData.Positions
        .Count(p => p.IsPositionOpen && position.Client.Id == this.Id);
}

Question 2:
It depends on usage. In this case, the biggest advantage is concise code, since you can use LINQ without having to re-implement the counting functionality. Performance can sometimes be increased. Using LINQ as an example again, LINQ uses deferred execution to prevent executing code until it is needed.
Usually, the lambda is not the solution, rather, it is part of the solution. Using LINQ is generally the solution for thing like this.


text:
Q: SAS XML mapping - with multiple XML files I would like to know how to use SAS XML Mapping with multiple XML files
The code below is what I use to extract one xml file (data1.xml) using mapping from SAS XML Mapper (global.map) I was able to get the final extracted dataset "GlobalDecision" ...
filename  data1 'c:\data1.xml';
filename  SXLEMAP 'c:\global.map';
libname   data1 xml xmlmap=SXLEMAP access=READONLY;

proc datasets lib=data1; quit;

DATA GlobalDecision; SET data1.GlobalDecision; run;

However my XML is stored in mySQL for each ID,  each record has the xml text ( uncompressed) named "var_x" , so if I want to extract say 10 records,  I would pull my dataset using this code below
proc sql; create table x as select ID, var_x from table1 limit 10 ;quit;

My question is how can I incorporate my x table to the Mapping code above to get the "GlobalDecision" final table that would give me 10 records with all values extracted.
Thank you!!

A: One row of data ( "var_x" ) would have xml that looks like this
 <?xml version="1.0" encoding="utf-8"?>
    <AResponse>
      <GenerationTime>20120301120031</GenerationTime>
      <CodeVersion>4.34.1</CodeVersion>
      <RequestVersion>3.0</RequestVersion>
      <TransactionId>156368133</TransactionId>
      <TrackHash>2211bc09ee00c45fe6ffa61648f33d3e</TrackHash>
      <Id>1125051053</Id>
      <Response>
        <GlobalDecision>
          <Decision>N</Decision>
          <Mcost>0</Mcost>
          <LC>A1</LC>
          <Check>A1</Check>
          <IDet>D6</IDet>
          <ReferBuckets>
            <Bucket>P1</Bucket>
          </ReferBuckets>
 </GlobalDecision>
  </Response>
</AResponse>


text:
Q: MongoDB/Mongoose update parent objects and nested array from document
Hello everyone,
I am trying to update an object that is on the root of the document and a specific array object that is nested two within another array.

This is how my Mongoose Schema looks like this:
{
  name: String,
  group_total: Number,
  members: [
   user_id: { type: String, index: true },
   purchases:[
    purchase_id: { type: String, index: true },
    cost: Number
   ]
  ]
}

I would like to update the document from:
{
      name: 'example',
      group_total: 100,
      members: [
       user_id: '123',
       purchases:[
        purchase_id: '456',
        cost: 20
       ]
      ]
    }

To:
{
      name: 'example',
      group_total: 120,
      members: [
       user_id: '123',
       purchases:[
        purchase_id: '456',
        cost: 40
       ]
      ]
    }

Where the content of members is the object of index i from an array of length n and the content of purchases is the object of index j from an array of length m

I cannot seem to update the nested object cost within the arrays but I can easily update the root object group_total
My query right now is as follows:
Group.update(
    {
      _id: ObjectId(req.body.group_id),
      members: {
        $elemMatch: {
          user_id: req.body.user_id }
        }
      },
    {
      $set: {
        group_total: req.body.cost,
        'members.$[mem].providers.$[prov].title': req.body.title,
      }
    },
    {
      multi: true,
      arrayFilters: [
        { 'mem.user': user_id: req.body.user_id } },
        { 'prov.purchase_id': req.body.purchase_id }
      ]
    }
  )

I used this MongoDB doc url as a reference


text:
Q: How to set "Run this program as an administrator" programmatically I'm having a problem with good ol' bdeadmin.exe in Vista. First, let's get the predictable responses out of the way:
"You should not require your application to be elevated."
This one does. C'est la vie.
"You need to embed a manifest file."
It is already compiled, it is many years old, the company that created it has no intention of doing it again, and it is installed from a Merge Module (MSM file).
"BDE is obsolete, you should be using dbExpress"
One and a half million lines of code. 'Nuff said.
"Drop a manifest file next to the EXE."
Tried that, did nothing. As a test, that same manifest file was able to make several other EXE files require elevation, just not the one I wanted. Something in there is preventing the external manifest from being read.
"Create a shortcut and set SLDF_RUNAS_USER."
Can't do that, it's a Control Panel applet.
The only thing that worked was setting "Run this program as an administrator" under the Compatibility tab of its Properties window. I shouldn't have to tell users to do this. Bad for business. I need to have the installer do this. The MSM file uses a static path.

A: This is a long shot, but if you have the word "setup" or "install" in the name of the EXE, Windows will prompt for elevation when running it. I don't know if that'll work with a control panel applet, though.

A: You can programmatically set the "Run this program as an administrator" flag (the option you find in the Compatibility tab of an EXE's properties), by setting a simple registry key. You need to create a string value (REG_SZ) under one of these keys (if you want the setting to be per user or per machine, respectively):

HKEY_CURRENT_USER\Software\Microsoft\Windows
  NT\CurrentVersion\AppCompatFlags\Layers

or

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
  NT\CurrentVersion\AppCompatFlags\Layers

The name of the value needs to be the full path to your executable (if the path contains spaces, do not surround the path with quotes) and the data of the value must contain the string RUNASADMIN.
For sample:
reg.exe Add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers" /v "C:\Program Files\MyApp\Test.exe" /d "PUT__VALUE__HERE"

Compatibility Modes
WIN95       Windows 95
WIN98       Windows 98
WIN4SP5     Windows NT 4.0 SP5
WIN2000     Windows 2000
WINXPSP2    Windows XP SP2
WINXPSP3    Windows XP SP3
VISTARTM    Vista
VISTASP1    Vista SP1
VISTASP2    Vista SP2
WIN7RTM     Windows 7
WINSRV03SP1 Windows Server 2003 SP1
WINSRV08SP1 Windows Server 2008 SP1
Privilege Level
RUNASADMIN  Run program as an administrator

REG ADD "HKLM\SOFTWARE\Microsoft\Windows
  NT\CurrentVersion\AppCompatFlags\Layers" /v
  "C:\temp\compatmodel\iconsext.exe" /t REG_SZ /d "WINXPSP3 RUNASADMIN"
  /f

References:
http://www.verboon.info/2011/03/running-an-application-as-administrator-or-in-compatibility-mode/

A: Use a wrap program which uses ShellExcute that uses "runas" as its "verb" to run the program you want.

A: I have found that the .manifest file method doesn't work if the .exe is under C:\Program files\... and the .exe has previously been run without the .manifest file. Windows remembers the .manifest from the first time the .exe is run. This means you can't just send the manifest when users complain that their installations don't run. The manifest file has to be placed before or during the same installation that places the .exe.
Windows rechecks the .manifest if the .exe changes (e.g. new release or different number of bytes)

A: Have you tried Microsoft's Application Compatibility Toolkit? It analyses your app and provides compatibility shims that might be able to help resolve your problem.

A: Pack your app into WinRar SFX with silent mode + admin request mode.
Much simpler than messing with .MSI variables.

A: I'd be surprised if this was possible. It would be an ideal way for malicious code to abuse the system. You're probably going to have tell the user the administrator must install or they must have admin rights (like all the other programs on windows do).


text:
Q: AngularJS interpolates array to string inside directive TL;DR
directive interpolates array as string..
http://plnkr.co/edit/ZwV8jmi0tUTgezWlEq3S?p=preview
Here is code:
index.html
<!DOCTYPE html>

        {{bar}}

app.js
!(function(ng) {
  'use strict';

  FooCtrl.$inject = ['$scope'];
  function FooCtrl($scope) {
    $scope.foo = {
      bar: [
        'foo',
        'bar'
      ]
    };
  }

  function FooDirective() {
    return {
      restrict: 'A',
      scope: {
        model: '@foo'
      },
      link: function($scope) {
        var watcher = function(model) {
          console.log(model, typeof model);
        };

        $scope.$watch('model', watcher, true);
      }
    };
  }

  ng.module('foo', [])
    .controller('FooCtrl', FooCtrl)
    .directive('foo', FooDirective);
})(window.angular);

Why do I have "typeof model" string instead of array?

A: If you want to bind the actual array of the parent scope use:
scope: {
  model: '=foo'
}

When using @foo you are just binding the result of the expression {{foo.bar}}. In your case the string interpretation of the array foo.
Addition
As an alternative you can call an expression on the parent scope from the isolated scope when you use the & symbol:
scope: {
  model: '&foo'
}

and evaluate it in your directive using:
model().bar


text:
Q: jQuery price slider filter I have created my jquery price slider but I am not sure how to filter my results so that as you slide you only see the products with that value in range.
HTML:

    Price range:
    <input type="text" id="amount" style="border:0; color:#f6931f; font-weight:bold;" />

 product - £10

 product - £50

 product - £100

 product - £150

 product - £200

JavaScript:
$(function() {
    var options =
        {
            range: true,
            min: 0,
            max: 500,
            values: [ 50, 300 ],
            slide: function( event, ui ) {
                $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
            }
        };

        $( "#slider-range" ).slider(
            options
        );
        $( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) +
            " - $" + $( "#slider-range" ).slider( "values", 1 ) );
    });

My fiddle is http://jsfiddle.net/ktcle/uvJ8F/

A: I would make a few changes:

*

*Give your list of products an id attribute and give each product a data-price attribute that is equal to the price of the item:

 product - £10

 product - £50

 product - £100

 product - £150

 product - £200

*Add a function that will show or hide those products when a slide event occurs:
function showProducts(minPrice, maxPrice) {
    $("#products li").hide().filter(function() {
        var price = parseInt($(this).data("price"), 10);
        return price >= minPrice && price <= maxPrice;
    }).show();
}

*Call that function from the slide event handler:
slide: function(event, ui) {
    var min = ui.values[0],
        max = ui.values[1];

    $("#amount").val("$" + min + " - $" + max);
    showProducts(min, max);
}

*Also call that function right after the slider is initialized so that the correct products are hidden initially:
var options = {
   /* snip */
}, min, max;

$("#slider-range").slider(options);

min = $("#slider-range").slider("values", 0);
max = $("#slider-range").slider("values", 1);

$("#amount").val("$" + min + " - $" + max);

showProducts(min, max);

The entire snippet:
function showProducts(minPrice, maxPrice) {
    $("#products li").hide().filter(function() {
        var price = parseInt($(this).data("price"), 10);
        return price >= minPrice && price <= maxPrice;
    }).show();
}

$(function() {
    var options = {
        range: true,
        min: 0,
        max: 500,
        values: [50, 300],
        slide: function(event, ui) {
            var min = ui.values[0],
                max = ui.values[1];

            $("#amount").val("$" + min + " - $" + max);
            showProducts(min, max);
        }
    }, min, max;

    $("#slider-range").slider(options);

    min = $("#slider-range").slider("values", 0);
    max = $("#slider-range").slider("values", 1);

    $("#amount").val("$" + min + " - $" + max);

    showProducts(min, max);
});

Example: http://jsfiddle.net/5aPg7/


text:
Q: VBA Copy Row - > Paste Row with Column +1 I am just trying to Copy and Paste one row by
sht.Rows(rowCount).Copy Workbooks("TEST.xlsm").Sheets("TEXT").Rows("8")

when sht is my selected sheet from another file (don´t worry about it, it works),
but I need to paste it with offset 1 column (from A to B). Any elegant and easy idea?


text:
Q: How to SemanticImport Multiple Excel Sheets I have an Excel workbook with multiple sheets that I'd like to import into a dataset each.  With Import I can target individual sheets by their name into a nested list.
firstSheet=Import[NotebookDirectory[]<>"data.xlsx",{"Sheets","SomeData"}];
secondSheet=Import[NotebookDirectory[]<>"data.xlsx",{"Sheets","SomeMoreData"}];

I'd like to use SemanticImport to import the sheets with some control over their data types.  I tried
firstSheet = SemanticImport[NotebookDirectory[]<>"data.xlsx",
 {"String", "Date", "String", "Number"}]

This appears to return a Dataset with the first sheet (something odd with it not understanding the date but I think if I change the Excel format for that column it will be ok).
How do I get the second sheet? I tried:
SemanticImport[{NotebookDirectory[]<>"data.xlsx", {"Sheets", "SomeMoreData"}},
 {"String", "Date", "String", "Number"}]

It does not like this.  Is my only option to:

*

*Do the two Imports

*Make a function with Association to format the lists as a lists of associations

*Pass the association lists to Dataset to create the datasets

Also, is there a way to get all the sheets (with either Import or SemanticImport) by only opening the file once. Something along the lines of:
{firstSheet, secondSheet} = Import[NotebookDirectory[]<>"data.xlsx", "XLSX"]

but where it gives datasets instead of lists.  I tried:
{firstSheet, secondSheet} =
 SemanticImport[NotebookDirectory[]<>"data.xlsx",
  {"String", "Date", "String", "Number"}]

Well, I should be able to do this myself once I find out how to get SemanticImport to give up the other sheets.
Thanks,
Edmund
Update:
With @PatoCriollo usage of Set, Evaluate, and Symbol (and some further research in the mean time) I've gotten closer to what I'd like to do using Dataset.  It still does not use SemanticImport but it does let me get an arbitrary number of sheets with different header rows into datasets.
dataFile = NotebookDirectory[] <> "\\data.xlsx";
sheetList = {"someData", "someMoreData"};
data = Import[dataFile, {"Sheets", sheetList}];
Set[Evaluate[Symbol[#] & /@ sheetList],
 Table[
  Dataset[Association /@
   Table[
    First[data[[sheet]]][[col]] -> Rest[data[[sheet]]][[row, col]],
    {row, Length[Rest[data[[sheet]]]]},
    {col, Length[First[data[[sheet]]]]}
  ]],
 {sheet, Length[sheetList]}]
];

someData (*is now a Dataset of sheet someData with headers from 1st row*)
someMoreDate (*is now a Dataset of sheet someMoreData with headers from 1st row*)

A:
sheets = Import["sample.xlsx", "Sheets"]
(*{"DataSet1", "DataSet2"}*)

data = Import["sample.xlsx", "Data"]
(*{{{"Country", "Value"}, {"AR", 10.}, {"BE", 20.}, {"SG", 30.}, {"TW",
   40.}}, {{"City", "Value", "Color"}, {"Amsterdam", 10.,
   "Blue"}, {"London", 20., "Red"}, {"Paris", 30., "Yellow"}}}*)

Set[Evaluate[Symbol[#] & /@ sheets], data];
DataSet1
(*{{"Country", "Value"}, {"AR", 10.}, {"BE", 20.}, {"SG", 30.}, {"TW",
  40.}}*)
DataSet2
(*{{"City", "Value", "Color"}, {"Amsterdam", 10., "Blue"}, {"London",
  20., "Red"}, {"Paris", 30., "Yellow"}}*)

A: I think this is a problem that may arise often. I have read your update. If someone is interested in Importing an arbitrary number of Excel worksheets, each one having a relational table of data with a header-body, and transforming them into Datasets, then the following solution is just 5 lines of code, it can read any worksheet name, and it is easy to follow ;-)
sheets    = Import["sample.xlsx", "Sheets"] ;

headerSet = (#[[1]] &) /@ sheets;
bodySet   = (#[[2 ;;]] &) /@ sheets;

rel2ds[header_, body_]:=Dataset[AssociationThread[header, #] & /@ body];

MapThread[rel2ds[#1,#2]&,{headerSet, bodySet}

A: I don't think SemanticImport has been designed to deal with multiple Excel sheets. I work around this problem using Import to get the number of sheets and their names, and to import them and ExportString to export them as "TSV" which, on its turn, can be imported by SemanticImportString. An intermediate conversion of DateObject/TimeObject to DateString is necessary, because this data type is not handled well.
My test file:

fileName =  FileNameJoin[{"C:", "Users", "Sjoerd", "Desktop", "test.xlsx"}];

sheets = Import[fileName, "Sheets"];

# -> SemanticImportString[
       ExportString[
         Import[fileName, {"Sheets", #}]
            /. x : DateObject[__] :>  DateString[x, {"Year", "-", "Month", "-", "Day"}],
         "TSV"],
         HeaderLines -> 0
       ] & /@ sheets // Association // Dataset


text:
Q: Manually calculate image gradient in tensorflow I know there is image_gradients in tensorflow to get dx, dy of the image like this
dx, dy = tf.image.image_gradients(image)
print(image[0, :,:,0])
tf.Tensor(
      [[ 0.  1.  2.  3.  4.]
      [ 5.  6.  7.  8.  9.]
      [10. 11. 12. 13. 14.]
      [15. 16. 17. 18. 19.]
      [20. 21. 22. 23. 24.]], shape=(5, 5), dtype=float32)
print(dx[0, :,:,0])
tf.Tensor(
      [[5. 5. 5. 5. 5.]
      [5. 5. 5. 5. 5.]
      [5. 5. 5. 5. 5.]
      [5. 5. 5. 5. 5.]
      [0. 0. 0. 0. 0.]], shape=(5, 5), dtype=float32)
print(dy[0, :,:,0])
tf.Tensor(
      [[1. 1. 1. 1. 0.]
      [1. 1. 1. 1. 0.]
      [1. 1. 1. 1. 0.]
      [1. 1. 1. 1. 0.]
      [1. 1. 1. 1. 0.]], shape=(5, 5), dtype=float32)

It looks like the gradient values are organized so that [I(x+1, y) - I(x, y)] is in location (x, y).
If I would like to do it manually, I'm not sure what I should do.
I tried to input the formula [I(x+1, y) - I(x, y)], but I have no idea how to implement it in the loop
x = image[0,:,:,0]
x_unpacked = tf.unstack(x)

processed = []
for t in x_unpacked:
    ???
    processed.append(result_tensor)

output = tf.concat(processed, 0)

Or if I can shift the whole tensor to the x,y direction, I could do the tensor subtraction, but still not sure about how to handle the edge information. (Above example, they are all zero for the last row/column)
Any help would be appreciated.

A: for the above example,dx
dx = tf.pad(img[1:,] - img[:-1,], [[0,1],[0,0]])

for dy
dy = tf.pad(img[:,1:] - img[:,:-1], [[0,0],[0,1]])


text:
Q: Android Studio emulator not launching on macOS (Big Sur) macOS Big Sur 11.1, Android Studio 4.1.2
Based on some similar issues I found online, I attempted to uninstall and reinstall Intel x86 Emulator Accelerator (HAXM installer)from Android Studio itself. But also got an error:

Installation did not complete successfully. See the IDE log for details

Where can I find the IDE log and what is the possible solution that will fix the emulator issue?

A: You can find the logs from the option in the Help menu, which opens
~/Library/Logs/AndroidStudio/idea.log


text:
Q: passing a global variable in one C file to another Let's say I have a global variable
 char  Dir[80];  /* declared and defined in file1.c  but not exported using extern etc */

The Dir variable is the name of a directory created at run time in the program's main().
In this file we manipulate this variable and pass it to  a function func defined in file2.c
This Dir variable is a directory in which all functions create thier individual logs.
Instead of passing this variable n number of times to each one of the functions which finally called func().I made it global.
func(x,Dir); /* x is a  local variable in a function  */

/* now in file2.c */
void func(int x,char *Dir)
{
   /*use this variable Dir */
}

The value of Dir we receive here is not the same as in file1.c. Why ?
 Compiler: gcc on Windows

A: Your code is fine as it stands. I can give you an example of how multiple source files should be used in C and you can compare with what you have written.
Given a main.c and a some_lib.c containing func, you need to define a some_lib.h which defines the function prototype of func defined in some_lib.c.
main.c:
#include <stdlib.h>
#include <stdio.h>
#include "some_lib.h"
/*
 * This means main.c can expect the functions exported in some_lib.h
 * to be exposed by some source it will later be linked against.
 */

int main(void)
{
    char dir[] = "some_string";

    func(100, dir);
    return EXIT_SUCCESS;
}

some_lib.c (contains definition of func):
#include "some_lib.h"

void func(int x, char * dir)
{
    printf("Received %d and %s\n", x, dir);
}

some_lib.h (contains function prototype/declaration of exported functions of some_lib.c):
#ifndef SOME_LIB_H
#define SOME_LIB_H
#include <stdio.h>

void func(int x, char * dir);

#endif

The above should then be compiled with:
gcc main.c some_lib.c -o main

This will produce:
Received 100 and some_string

However, if you are indeed using a global variable, it is not even necessary to pass dir at all. Consider this modified main.c:
#include <stdlib.h>
#include <stdio.h>
#include "some_lib.h"

char dir[] = "some_string";

int main(void)
{
    func(100);
    return EXIT_SUCCESS;
}

dir is defined in here and is globally accessible/defined. All we need to do is make sure that some_lib.c knows that it exists. The linker can then resolve this symbol during the linking stage. some_lib.h needs to be defined as so:
#ifndef SOME_LIB_H
#define SOME_LIB_H
#include <stdio.h>

/*
 * The extern informs the compiler that there is a variable of type char array which
 * is defined somewhere elsewhere but it doesn't know where. The linker will
 * match this with the actual definition in main.c in the linking stage.
 */
extern char dir[];
void func(int x);

#endif

some_lib.c can then use the globally defined variable as if it were scoped:
#include "some_lib.h"

void func(int x)
{
    printf("Received %d and %s\n", x, dir);
}

Compiling and running this will produce the same output as the first example.


text:
Q: Rascal createM3FromEclipseProject with huge Java project I'm completely new to rascal. I'm currently just trying some basic things on our project and a test project.
On a test project the following works without a problem on the Rascal terminal:
rascal>import lang::java::m3::Core;
ok
rascal>import lang::java::jdt::m3::Core;
ok
rascal>myModel = createM3FromEclipseProject(|project://TestProject|);
... (output)

However, when I try it on our huge project, it still hasn't produced any output after more than 45 minutes of waiting. I was wondering how long this might take for huge projects.
I've checked with the Eclipse search options and we have 404,389 lines of code in our .java files alone, and 1,780 classes. Yes, it's a huge and complex project that's little over 10 years old.
Perhaps I should narrow it down with sub-queries instead of doing createM3FromEclipseProject, but I'm not 100% which yet. Is there a Rascal tutorial perhaps that only focuses on searching through Java projects (apart from the two MeasuringJava recipes?

A: Check your profiler (VisualVM), most likely you are primarily waiting for the Garbage Collector to free up memory, then consume it, and ask for more memory again.. increasing the max memory for the JVM can greatly help (-Xmx8G in the eclipse.ini).


text:
Q: Determining a matrix M that represents $\phi$ relative to a basis B This is for a specific example.
Let V be a vector space of functions q : $R^2$ $\to$ $R$ where f(x,y) = $a_1$$x^2$ + $a_2$$xy$ + $a_3$$y^2$ + $a_4$$x$ + $a_5$$y$ + $a_6$
$a_i$ $\in$ $R$ and $\phi$ : V $\to$ V be linear map given by
$\phi$(f) = $\partial$/$\partial$x $\int$ f(x,y) dy
Question: Determine the matrix M that represents $\phi$ relative to the basis $B$ = { $x^2$, $xy$, $y^2$, $x$, $y$, 1 }
Do you get $\phi$($x^2$) = 2$xy$, $\phi$($xy$) = $y^2$/2, $\phi$($y^2$) = 0, $\phi$($x$) = $y$, $\phi$($y$) = 0, $\phi$(1) = 0 then represent it as a matrix so the 1st column would be "0 2 0 0 0 0 ", 2nd "0 0 1/2 0 0 0", 3rd "0 0 0 0 0 0", 4th "0 0 0 0 1 0" and last two columns are all Os?
Or do you get $\phi$(f(x,y)) = 2$a_1$$xy$ + $a_2$$y^2$/2 + $a_4$y then use that?
I'm not really sure what I'm looking for. The next parts ask for the minimal polynomial and Jordan normal form so i assume the main diagonal in M has non-zero entries.
Any help would be appreciated, thanks.

A: The general process for representing a linear map $\phi: V \to V$ as a matrix with respect to a basis $B$ is very simple:

*

*Compute the images of the elements of $B$ under $\phi$.

*Write each of those images as a sum of elements of $B$.

*Use the coefficients of those terms as the entries of your matrix.

In this case, you have already done the first two steps, so you need only write down the matrix
$$M = \begin{pmatrix}
0 & 0 & 0 & 0 & 0 & 0 \\
2 & 0 & 0 & 0 & 0 & 0 \\
0 & \frac{1}{2} & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 \end{pmatrix}$$

Or do you get $\phi(f(x,y)) = 2a_1xy + a_2y^2/2 + a_4y$ then use that?

You could also do it this way: you'd get the exact same answer.

The next parts ask for the minimal polynomial and Jordan normal form so i assume the main diagonal in M has non-zero entries.

Neither of those requries the main diagonal to have non-zero entries.


text:
Q: How to simulate session closing / expiring in Spring Boot tests? I would like to add a couple of tests to the example shown here:
https://spring.io/guides/gs/securing-web/
to be able to verify that a user can no longer access resources requiring authentication when session closes or expires. I would like to simulate both the following conditions in my tests:
a) the user voluntarily ends their session (e.g. close their browser);
b) the session times out;
I don't know how to reproduce those conditions using MockMvc.
I managed to do the following:
@Test
public void sessionIsInvalid() throws Exception {
    FormLoginRequestBuilder login = formLogin()
            .user("user")
            .password("password");

    mockMvc.perform(login)
            .andExpect(authenticated())
            .andDo(mvcResult -> {
                MockHttpSession session = (MockHttpSession)mvcResult.getRequest().getSession();
                session.invalidate();
                mockMvc.perform(get("/hello")
                        .session(session))
                        .andExpect(status().isFound());
            });
}

...which seems to work but I am not totally sure what invalidate does in this context and whether it matches condition a) above.
To emulate the session timeout, I've done instead:
@Test
public void sessionExpires() throws Exception {
    FormLoginRequestBuilder login = formLogin()
            .user("user")
            .password("password");

    mockMvc.perform(login)
            .andExpect(authenticated())
            .andDo(mvcResult -> {
                MockHttpSession session = (MockHttpSession)mvcResult.getRequest().getSession();
                session.setMaxInactiveInterval(1);
                Thread.sleep(3);
                mockMvc.perform(get("/hello")
                        .session(session))
                        .andExpect(status().isFound());
            });
}

...but this doesn't work. Can someone help me understand what I am doing wrong?

A: When using Spring Boot with Spring Security (which is all about in you link), my approach is this:

*

*create a custom spring security filter that is able to "convince" spring security that the session is expired (whatever it believes a session is)

*add the custom filter just before ConcurrentSessionFilter

*create an inner static @TestConfiguration class which could, in theory, just configure the HttpSecurity to add the custom filter (that's all we want). In practice I found that usually I have to have the class annotated with @TestConfiguration to extend my project's security configuration class (or at least the main one, if having many, e.g. SecurityConfiguration for my project); because in SecurityConfiguration I usually declare other @Bean too (e.g. CorsConfigurationSource) I usually have to also use @WebMvcTest(properties = "spring.main.allow-bean-definition-overriding=true", ...) to avoid the bean overriding error; have the class annotated with @TestConfiguration to be annotated with @Order(HIGHEST_PRECEDENCE) too.

*create a simple web mvc test trying to GET some project-existing endpoint, e.g.:

@Test
@SneakyThrows
@WithMockUser
void sessionExpired() {
    this.mvc.perform(get("/some-endpoint-here")).andExpect(...);
}

*

*run the test and expect for your configured session expiration strategy to kick in; see HttpSecurity.sessionManagement(session -> session...expiredUrl(...)) or HttpSecurity.sessionManagement(session -> session...expiredSessionStrategy(...))
The below spring security configuration provided as a @TestConfiguration works with Spring Boot 2.3.12.RELEASE (and probably many more).
@TestConfiguration
@Order(HIGHEST_PRECEDENCE)
static class Config extends SecurityConfiguration {
    public Config(SessionInformationExpiredStrategy expiredSessionStrategy, InvalidSessionStrategy invalidSessionStrategy) {
        super(expiredSessionStrategy, invalidSessionStrategy);
    }

    @SneakyThrows
    @Override
    protected void configure(HttpSecurity http) {
        super.configure(http);
        // the custom filter as a lambda expression
        http.addFilterBefore((request, response, chain) -> {
            // preparing some objects we gonna need
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpSession session = httpRequest.getSession(false);
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            // getting our hands on the object that Spring Security believes
            // is the "session" and which is in ConcurrentSessionFilter
            List<Filter> filters = (List) ReflectionTestUtils.getField(chain, "additionalFilters");
            int currentPosition = (int) ReflectionTestUtils.getField(chain, "currentPosition");
            ConcurrentSessionFilter concurrentSessionFilter = (ConcurrentSessionFilter) filters.get(currentPosition);
            SessionRegistry sessionRegistry = (SessionRegistry) ReflectionTestUtils.getField(concurrentSessionFilter, "sessionRegistry");
            // the "session" does not exist (from Spring Security's PoV),
            // we actually have to create (aka "register") it
            sessionRegistry.registerNewSession(session.getId(), authentication.getPrincipal());
            // the actual session expiration (from Spring Security's PoV)
            sessionRegistry.getSessionInformation(session.getId()).expireNow();
            // let the filters continue their job; ConcurrentSessionFilter
            // follows and it'll determine that the "session" is expired
            chain.doFilter(request, response);
        }, ConcurrentSessionFilter.class);
        log.debug("begin");
    }
}

A: session.setMaxInactiveInterval(1);  // in seconds

Thread.sleep(3);  // in milliseconds


text:
Q: using paypal API issue I'm trying to use Paypal in my app, but all my attempts failed. I've connected all jars to my App.
For now, i've created an account at https://developer.paypal.com/ , and I'm trying to follow the steps which are described here, but when I press "profile", it sends me to the "overview" page. So the question is, how can i get account userId, account signature, paypal applicationId and other info?
ps. i'm using java.
UPD.
here is my code:
public boolean verifyAddress(String email) throws PayPalException {
        boolean isValid;
        CallerServices caller = new CallerServices();
        APIProfile profile = ProfileFactory.createSignatureAPIProfile();

        profile.setAPIUsername("myUsername");
        profile.setAPIPassword("myPass");
        profile.setSignature("sign");
        profile.setEnvironment("sandbox");

        caller.setAPIProfile(profile);
        AddressVerifyRequestType req = new AddressVerifyRequestType();

        req.setEmail(email);
        req.setStreet("test");
        req.setZip("12345");

        AddressVerifyResponseType resp = (AddressVerifyResponseType) caller
                .call("AddressVerify", req);//throws exception here
        System.out.println(resp.getBuild());
        isValid = resp.getErrors() == null;
        return isValid;
    }

and here is one more question: i should set the e-mail,given by payPal(only numbers) or the pass, which i used for sign up?
UPD here is an image i get in sandbox:

A: Log in to https://developer.paypal.com/. The info you are looking for is in the "API and Payment Card Credentials" tab, in the section "API Credentials". If you haven't yet created a seller test account you must create one first.
In the future you may find useful PayPal's Integration Wizards, which generates all the code you need for you.
Edit:
You don't have to use neither your email or your password, only the information provided by PayPal. For example, in the image below the username would be gemccu_1229982509_biz_api1.cs.com and the password QR9WVHAD2PYGC2P9. Your credentials should be similar to this ones.

Edit:
As said before, you can find all the info in the "API and Payment Card Credentials" tab at https://developer.paypal.com/. Here you have a screenshot of what I see in mine:


text:
Q: Random Max Key in dictionary in case of tie I have a dictionary: keys are strings, values are float.
Example:
A = {'a':1, 'b':2, 'c':2, 'd':0}

I'd like to get 'b' or 'c' as answer with equal probability. I found a way to get said behaviour. However I'm not convinced this is best practice.
import random

A = {'a':1, 'b':2, 'c':2, 'd':0}
all = (A.items())
values = [(x[1],random.random(),x[0]) for x in all]
maxIndex = values.index(max(values))
print(values[maxIndex][2])

Is there a better (or even more elegant) approach?

A: Try this:
import random
A = {'a':1, 'b':2, 'c':2, 'd':0}

mv = max(A.values())
random.choice([k for (k, v) in A.items() if v == mv])
=> 'b' # or 'c'

First, we find the maximum value and then we randomly pick one of the keys that match that value. We're using random.choice, which guarantees a random selection with uniform distribution.


text:
Q: Does the 74LVC1GU04 actually have "Schmitt-trigger action" on its input? The 74LVC1GU04 is an unbuffered inverter, which (according to the datasheet) is intended to be used in linear mode in applications, such as crystal oscillators and linear amplifiers with negative feedback.
But the same datasheet claims that there is a "Schmitt-trigger action" on the input. That is the standard formula meaning there is a small (100 mV) hysteresis on the inputs. All CMOS families use such inputs nowadays.
But even a small hysteresis on the input will definitely make it impossible to use the element in linear mode with negative feedback - it will simply oscillate.
Does the 74LVC1GU04 really have a "Schmitt-trigger action" input? Or is there a mistake in the datasheet and does especially this element have input without hysteresis?

A: This is a copy-paste error. All other (buffered) parts in the 74LVC series have schmitt-trigger inputs, but the 74LVC1GU04 in particular does not. They simply forgot to delete that line from the document template.
Figure 3 in the datasheet shows quite clearly that there is no hysteresis. The part is just a simple two-transistor CMOS inverter with some ESD protection. Another clear indicator of that is Figure 9: the part has a well-defined transconductance (and therefore operates as a linear amplifier), which wouldn't be the case with schmitt-trigger inputs.
I've sent Nexperia an e-mail about it, they'll probably correct it soon.
Keep in mind that the part might dissipate excessive amounts of power when used as a linear amplifier at higher supply voltages due to cross-conduction. Operating it in linear mode with 5V supplies might be pushing things a little too far. You'll have to check for yourself if the chip overheats at your desired supply voltage.


text:
Q: Rails: Page specific javascript running on every page if visited in same window I wanted to run javascript for some particular page. To accomplish this I have created meta tag in layout file like this:
<%= tag :meta, name: :psj, action: action_name, controller: controller_name %>

I have also created a init.js file that will be loaded by application manifest file.
# init.js
var Page, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
Page = (function() {
  function Page() {
    this.action = bind(this.action, this);
    this.controller = bind(this.controller, this);
  }
  Page.prototype.controller = function() {
    return $('meta[name=psj]').attr('controller');
  };
  Page.prototype.action = function() {
    return $('meta[name=psj]').attr('action');
  };
  return Page;
})();
this.page = new Page;

Here is my javascript file for specific controller that need to run on specific action:
# scans.js
$(document).on('turbolinks:load', function() {
  if (!(page.controller() === 'scans' && page.action() === 'index')) { return; }

  var ajax_call = function() {
    $.get("/scans.js", { }, function(table) {
      $("#scans").replaceWith(table);
    });
  }

  var interval = 1000 * 60 * 1 ;
  setInterval(ajax_call, interval);
});

This works perfect for the scans#index page. Now after visiting this page if I click on any link that loads some other page in same window, ajax_call code runs which should not be the case.
On the contrary if I open that other page in different window it works fine (ajax_call don't run). Is it somehow related to browser's cache or turbolinks cache, not sure what is the cause of the problem.

A: The issue you're having is that you've instrumented Turbolinks but you're not actually listening to the page change events to manipulate the state. I.e., when the page changes, you need to clear your interval. Turbolinks doesn't handle the browser opening a new window and navigating to a URL (e.g. super+click), hence why it works in those instances.

A: Try like this:
document.addEventListener("turbolinks:load", function() {
  let interval = null;
  if ((page.controller() === 'scans' && page.action() === 'index')) {
    let ajax_call = function() {
      $.get("/scans.js", { }, function(table) {
        $("#scans").replaceWith(table);
      });
    }
    let interval = 1000 * 60 * 1 ;
    interval = setInterval(ajax_call, interval);
  }else{
    if(interval){ clearInterval(interval) }
  }
}


text:
Q: Firefox 7 starts with an empty "Alert"-Window and browsing does not work Today, after I started Ubuntu (11.04) I noticed this window immediately after running firefox:

As you can see it is empty. No information about what is probably wrong. I closed the file and tryed to open a page (e.g. www.google.de). But firefox does not show any content. Browsing seems not possible.
I restarted firefox several times but the behavior did not change. Sometimes the this "Alert"-Window does show this text:

Could not initialize the application's security component. The most
  likely cause is problems with files in your application's profile
  directory. Please check that this directory has no read/write
  restrictions and your hard disk is not full or close to full. It is
  recommended that you exit the application and fix the problem. If you
  continue to use this session, you might see incorrect application
  behaviour when accessing security features.

I have enough hard disk space (30 Gigabyte remaining free). I reinstalled firefox by the  Ubuntu Software Center, but the problem remained. I don't know how to proceed to track down the error. Any suggestions?

A: I just googled the whole text from the "Alert-Window" as quoted above and google pointed me to a support page from Mozilla. There you will find 4 solutions to get rid of this problem.
In my case the file cert8.db in the Mozilla Profile folder was corrupted. I deleted it while firefox was closed and started firefox. Èt voilá firefox started without complaining.


text:
Q: GHUnit error file _OBJC_CLASS_$_SenTestCase", referenced I'm using GHUnit in my project but when i try to run the app it gives errors

Ld /Users/goldfire/Library/Developer/Xcode/DerivedData/WhatsMySpeed-amkgqintxyhelabqvrpouivmdglf/Build/Products/Debug-iphonesimulator/GHUnitTests.app/GHUnitTests normal i386
      cd /Users/goldfire/Desktop/Example/WhatsMySpeed
      setenv MACOSX_DEPLOYMENT_TARGET 10.6
      setenv PATH "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
      /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch i386 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.1.sdk -L/Users/goldfire/Library/Developer/Xcode/DerivedData/WhatsMySpeed-amkgqintxyhelabqvrpouivmdglf/Build/Products/Debug-iphonesimulator -F/Users/goldfire/Library/Developer/Xcode/DerivedData/WhatsMySpeed-amkgqintxyhelabqvrpouivmdglf/Build/Products/Debug-iphonesimulator -F/Users/goldfire/Desktop/Example/WhatsMySpeed -F/Applications/Xcode.app/Contents/Developer/Library/Frameworks -filelist /Users/goldfire/Library/Developer/Xcode/DerivedData/WhatsMySpeed-amkgqintxyhelabqvrpouivmdglf/Build/Intermediates/WhatsMySpeed.build/Debug-iphonesimulator/GHUnitTests.build/Objects-normal/i386/GHUnitTests.LinkFileList -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -ObjC -all_load -fobjc-arc -Xlinker -no_implicit_dylibs -D__IPHONE_OS_VERSION_MIN_REQUIRED=50100 -framework UIKit -framework Foundation -framework CoreGraphics -framework GHUnitIOS -framework SenTestingKit -o /Users/goldfire/Library/Developer/Xcode/DerivedData/WhatsMySpeed-amkgqintxyhelabqvrpouivmdglf/Build/Products/Debug-iphonesimulator/GHUnitTests.app/GHUnitTests
Undefined symbols for architecture i386:
    "_OBJC_CLASS_$_SenTestCase", referenced from:
        _OBJC_CLASS_$_LogicTests in LogicTests.o
    "_OBJC_METACLASS_$_SenTestCase", referenced from:
        _OBJC_METACLASS_$_LogicTests in LogicTests.o
  ld: symbol(s) not found for architecture i386
  clang: error: linker command failed with exit code 1 (use -v to see invocation)

A: Check out this link:
http://fstanley.github.com/blog/2012/06/10/fixing-ghunit-sentestcase-link-errors/
Basically you need to add:
$(SDKROOT)/Developer/Library/Frameworks
and
$(DEVELOPER_LIBRARY_DIR)/Frameworks
to the framework search paths in the settings for your test target.
I had the same error and this fixed it.
Note: that the items must be added in that exact order, per http://forum.sparrow-framework.org/topic/cant-run-unit-tests.


text:
Q: NSAutoreleasePool problem I am using this line of code in iphone 2.0 its work fine
pool=[[NSAutoreleasePool alloc]init];

[pool release];

When i run this line of code in iphone 3.0 its give some leak message in the log screen..
That message is
2009-10-13 03:26:31.841 Spectrum[3946:4c2b] *** _NSAutoreleaseNoPool(): Object 0xd819d0 of class NSCFString autoreleased with no pool in place - just leaking
Stack: (0x305a2e6f 0x30504682 0x52c14d 0x536f67 0x3058deff 0xb049 0xa554 0x3050a79d 0x3050a338 0x97181155 0x97181012)

can anyone help me?
Thanks in advance....

A: Your pool allocation and release code looks fine.  The error message, nevertheless, indicates something was allocated with autorelease outside the scope of an autorelease pool.  This often happens in when you use a secondary thread, when using some specialty load methods, and when initializing globals.
Once you isolate the leaking bit of code, you could try wrapping it by another set of NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; and [pool release];.

A: That message occurs when an object is sent the autorelease message outside of an autorelease scope. Place a breakpoint on _NSAutoreleaseNoPool and check the stack to see where the pool needs to be added.

A: Look for any place in your code where you make autoreleased objects, while inside another thread than your main run loop.


text:
Q: Building a Neural Network using Keras on R I am attempting to build and train a neural network using R. I am using the Keras package to do this.
This is what I have written so far:
# Select library

library(readr)
library(tensorflow)
library(keras)

# Select data and transform into matrix
setwd("~/R")
data.set <- read.csv('SEBinary.csv')
data.set <- as.matrix(data.set)

# Remove column names

dimnames(data.set) = NULL

# Split data into training and test subsets

set.seed(123)
indx <- sample(2,
               nrow(data.set),
               replace = TRUE,
               prob = c(0.9,0.1))

# Split input variable from output/target variable

x_train <- data.set[indx == 1,1:15]
x_test <- data.set[indx == 2,1:15]

y_test_actual <- data.set[indx == 2, 16]

y_train <- to_categorical(data.set[ indx == 1, 16])
y_test <- to_categorical(data.set[indx == 2, 16])

# Creating the model

model <- keras_model_sequential() %>%
  # Network architecture
  layer_dense(units = 4, activation = "relu", input_shape = c(15)) %>%
  layer_dense(units = 2, activation = "softmax") %>%
  # Backpropagation
  compile(
    loss = 'categorical_crossentropy',
    optimizer = 'adam',
    metrics = c('accuracy')
  )

Everything works fine until I get to:
y_train <- to_categorical(data.set[ indx == 1, 16])
y_test <- to_categorical(data.set[indx == 2, 16])

At that point, I receive the following error and information:
Error: Python module tensorflow.keras was not found.

Detected Python configuration:

python:         C:/Users/chris/AppData/Local/r-miniconda/envs/r-reticulate/python.exe
libpython:      C:/Users/chris/AppData/Local/r-miniconda/envs/r-reticulate/python36.dll
pythonhome:     C:/Users/chris/AppData/Local/r-miniconda/envs/r-reticulate
version:        3.6.10 |Anaconda, Inc.| (default, May  7 2020, 19:46:08) [MSC v.1916 64 bit (AMD64)]
Architecture:   64bit
numpy:          C:/Users/chris/AppData/Local/r-miniconda/envs/r-reticulate/Lib/site-packages/numpy
numpy_version:  1.19.1

I do not understand this error because I have repeatedly installed Keras, Tensor Flow and Miniconda but it persists nonetheless. I have also tried downloading the packages from Github as an alternative.


text:
Q: java.lang.NumberFormatException: For input string: "16000$" in kotlin I want to make display show "16000$" before click increase btn or decrease btn.
when I make code like this error caused by :java.lang.NumberFormatException: For input string: "16000$ . but I should display $. Lets check my code and help me plz.

  var productprice = findViewById<TextView>(R.id.productPrice)
        productprice.text= intent.getStringExtra("price")+"$"
        var price = productPrice.text.toString().toInt()
        var inc_val= price
        var getPrice = price

        decrease.isEnabled=false

        increase.setOnClickListener {
            increaseInteger()
            getPrice+= inc_val
            productprice.text=getPrice.toString()+"$"
        }

        decrease.setOnClickListener {
            decreaseInteger()
            getPrice -= inc_val
            productprice.text=getPrice.toString()+"$"
        }

A: You are trying to parse the string with "$" to int, Hence you are getting NumberFormatException.
Try this instead:
var productprice = findViewById<TextView>(R.id.productPrice)
        productprice.text= intent.getStringExtra("price")+"$"
        var price = parseInt(intent.getStringExtra("price"))
        var inc_val= price
        var getPrice = price

        decrease.isEnabled=false

        increase.setOnClickListener {
            increaseInteger()
            getPrice+= inc_val
            productprice.text=getPrice.toString()+"$"
        }

        decrease.setOnClickListener {
            decreaseInteger()
            getPrice -= inc_val
            productprice.text=getPrice.toString()+"$"
        }

A: var price = productPrice.text.toString().toInt() - you try to convert "16000$" to Int here. Please get substring here first.
Formally, right code is:
val priceText = productPrice.text.toString()
val price = priceText.substring(0, priceText.length - 1).toInt()

However really I advice you to store value internally. You price is part of model. E.g. you can avoid text parsing and just read value from model. E.g. code will be like this:
var price = intent.getIntExtra("price") // we store int value here, not String
var inc_val= price
decrease.isEnabled=false
displayPrice()

increase.setOnClickListener {
    intent.setIntExtra(intent.getIntExtra("price") + inc_val) // read, update, save
    displayPrice()
}
decrease.setOnClickListener {
    intent.setIntExtra(intent.getIntExtra("price") - inc_val) // read, update, save
    displayPrice()
}

/*this function just shows price*/
fun displayPrice() {
   val price = intent.getIntExtra("price")

   productprice.text= "$price\$"
}


text:
Q: Trim or hide Highchart legends based on number of legends Is there an option or formatter to hide or trim Highcharts v6 legends based on number of legends or text count?
eg: if there are 100 legends then display only 20 and a more button which can show all or show all in tooltip. Like in below image show only 6 legends and hide others.

A: You can restrict the area that the legend is displayed in and have navigation to scroll through the entire list.
http://jsfiddle.net/t3uah5k0/1/
legend: {
    maxHeight: 40
},

https://api.highcharts.com/highcharts/legend
There isn't a built in function to show all or show all in a tooltip. But you could change the maxHeight based on some event.


text:
Q: Canon IP4200 driver not working Any Ideas how to setup a IP4200with Ubuntu 12.04 64bit?
As far as I know, there is no official driver by canon.
http://ppa.launchpad.net/michael-gruz/canon/ubuntu oneiric is not working
Hope somebody can help me, thanks.

A: To install this Canon printer driver for Ubuntu you need to add the PPA below in your Ubuntu system. Open a "terminal" window and copy and paste these commands:
sudo add-apt-repository ppa:michael-gruz/canon
sudo apt-get update

Make sure to disconnect the Canon printer from your computer first.
Now copy and paste your appropriate install command based on your printer:
sudo apt-get install cnijfilter-ip4200series

After the Canon printer driver is installed, connect the Canon printer to your computer and turn it on. Your printer will automatically be detected by the system.
source


text:
Q: Does it make sense to fit an ARIMA model to the remainder component of a timeseries? Suppose I have a timeseries, something like this:
# A tsibble: 96 x 2 [1M]
   timestamp targetValue
       <mth>       <dbl>
 1  2011 Jan    8807887.
 2  2011 Feb    8047481.
 3  2011 Mar    4206680.
 4  2011 Apr   12805026.
 5  2011 May    8487980.
 6  2011 Jun    8288872.
 7  2011 Jul    8950038.
 8  2011 Aug    8246225.
 9  2011 Sep    9045951.
10  2011 Oct    8133714.
11  2011 Nov    8615649.
12  2011 Dec    8949665.
13  2012 Jan    7400942.
14  2012 Feb    7774995.
15  2012 Mar    3521120.
16  2012 Apr   12196836.
17  2012 May    7475631.
18  2012 Jun    6378579.
19  2012 Jul    6327822.
20  2012 Aug    7679169.
21  2012 Sep    6852647.
22  2012 Oct    6104852.
23  2012 Nov    6603811.
24  2012 Dec    7103982.
25  2013 Jan    7318718.
26  2013 Feb    6327166.
27  2013 Mar   10583778.
28  2013 Apr    1486028.
29  2013 May    6609755.
30  2013 Jun    6123774.
31  2013 Jul    6525356.
32  2013 Aug    6634035.
33  2013 Sep    6775410.
34  2013 Oct    6139110.
35  2013 Nov    6617715.
36  2013 Dec    5758138.
37  2014 Jan    6173796.
38  2014 Feb    6193086.
39  2014 Mar    1369283.
40  2014 Apr   10862225.
41  2014 May    6719338.
42  2014 Jun    6523341.
43  2014 Jul    7009035.
44  2014 Aug    6429927.
45  2014 Sep    6191727.
46  2014 Oct    6929547.
47  2014 Nov    6436277.
48  2014 Dec    7344969.
49  2015 Jan    6583656.
50  2015 Feb    7025900.
51  2015 Mar   11131747.
52  2015 Apr    2234209.
53  2015 May    7451495.
54  2015 Jun    7112371.
55  2015 Jul    6926740.
56  2015 Aug    7024481.
57  2015 Sep    7209520.
58  2015 Oct    6978664.
59  2015 Nov    5739805.
60  2015 Dec    7053777.
61  2016 Jan    6778982.
62  2016 Feb    6986373.
63  2016 Mar   11368732.
64  2016 Apr    3234200.
65  2016 May    6623093.
66  2016 Jun    7470512.
67  2016 Jul    7106562.
68  2016 Aug    7442240.
69  2016 Sep    7446251.
70  2016 Oct    7408437.
71  2016 Nov    6738305.
72  2016 Dec    7138813.
73  2017 Jan    7442611.
74  2017 Feb    6775783.
75  2017 Mar    2674532.
76  2017 Apr   11571766.
77  2017 May    7376416.
78  2017 Jun    7229772.
79  2017 Jul    6660626.
80  2017 Aug    6572461.
81  2017 Sep    7626926.
82  2017 Oct    7130972.
83  2017 Nov    7073761.
84  2017 Dec    6985022.
85  2018 Jan    6546966.
86  2018 Feb    7252383.
87  2018 Mar   11130375.
88  2018 Apr    2635667.
89  2018 May    7292191.
90  2018 Jun    7218206.
91  2018 Jul    7419891.
92  2018 Aug    6652166.
93  2018 Sep    7095116.
94  2018 Oct    7386819.
95  2018 Nov    6367653.
96  2018 Dec    6474530.

I use STL additive decomposition to decompose the timeseries in seasonality, trend and remainder (the seasonality is not interesting for my analysis, so I use only the seasonally adjusted timeseries)
stl_dcmp = target_ts %>% STL(targetValue ~ season(window = 'periodic') + trend(window = 13), robust = TRUE)

The goal is to "catch" (explain with an exogenous variable) the non seasonal signal, that is the anomaly in the remainder.
I have a dummy variable predictor, like this:
    # A tsibble: 96 x 2 [1M]
   timestamp predValue
       <mth>     <dbl>
 1  2011 Jan         0
 2  2011 Feb         0
 3  2011 Mar        -1
 4  2011 Apr         1
 5  2011 May         0
 6  2011 Jun         0
 7  2011 Jul         0
 8  2011 Aug         0
 9  2011 Sep         0
10  2011 Oct         0
11  2011 Nov         0
12  2011 Dec         0
13  2012 Jan         0
14  2012 Feb         0
15  2012 Mar        -1
16  2012 Apr         1
17  2012 May         0
18  2012 Jun         0
19  2012 Jul         0
20  2012 Aug         0
21  2012 Sep         0
22  2012 Oct         0
23  2012 Nov         0
24  2012 Dec         0
25  2013 Jan         0
26  2013 Feb         0
27  2013 Mar         1
28  2013 Apr        -1
29  2013 May         0
30  2013 Jun         0
31  2013 Jul         0
32  2013 Aug         0
33  2013 Sep         0
34  2013 Oct         0
35  2013 Nov         0
36  2013 Dec         0
37  2014 Jan         0
38  2014 Feb         0
39  2014 Mar        -1
40  2014 Apr         1
41  2014 May         0
42  2014 Jun         0
43  2014 Jul         0
44  2014 Aug         0
45  2014 Sep         0
46  2014 Oct         0
47  2014 Nov         0
48  2014 Dec         0
49  2015 Jan         0
50  2015 Feb         0
51  2015 Mar         1
52  2015 Apr        -1
53  2015 May         0
54  2015 Jun         0
55  2015 Jul         0
56  2015 Aug         0
57  2015 Sep         0
58  2015 Oct         0
59  2015 Nov         0
60  2015 Dec         0
61  2016 Jan         0
62  2016 Feb         0
63  2016 Mar         1
64  2016 Apr        -1
65  2016 May         0
66  2016 Jun         0
67  2016 Jul         0
68  2016 Aug         0
69  2016 Sep         0
70  2016 Oct         0
71  2016 Nov         0
72  2016 Dec         0
73  2017 Jan         0
74  2017 Feb         0
75  2017 Mar        -1
76  2017 Apr         1
77  2017 May         0
78  2017 Jun         0
79  2017 Jul         0
80  2017 Aug         0
81  2017 Sep         0
82  2017 Oct         0
83  2017 Nov         0
84  2017 Dec         0
85  2018 Jan         0
86  2018 Feb         0
87  2018 Mar         1
88  2018 Apr        -1
89  2018 May         0
90  2018 Jun         0
91  2018 Jul         0
92  2018 Aug         0
93  2018 Sep         0
94  2018 Oct         0
95  2018 Nov         0
96  2018 Dec         0

I want to test if this predictor is good for catching that signal, so I thought of isolating the remainder (anomaly signal + white noise) and perform the analysis only on that component, for example comparing results (i.e. predictive accuracy, forecast error reduction, prediction intervals, residuals autocorrelation, etc...) of two ARIMA models fitted to the remainder, one with the dummy variable predictor as exogenous regressor (ARIMA errors) and the other one without it.
Does this kind of analysis make sense?

A: As a general rule you don't want to do piece-fitting using previous results to feed the next stage without a simultaneous optimization.
In this case after identifying the regime shift (visually obvious) , we treat the most recent set of values reflecting homogeneous structure.
I took your very interesting ( to me ! ) time series  which visually appeared to to represent two different regimes.
Using the Chow test for constancy of parameters , AUTOBOX  .. a commercial poece of software that I have helped to develop ... concluded that  a regime shift in parameters occurred on or about period 55
 with this  based upon this model  and
After refining the model with some needed pulse indicators we obtained and
The Actual/Fit and Forecast graph is here  with forecasts here
Finally the statistics for the final model are here
with residual plot here
We have identified the anomalies in the remainder


text:
Q: programmatically login to facebook and post to page (wall) I have a website, and I need it to post status updates to a Facebook Page from time to time.
Using my personal Facebook account, I created an App, and a Page. So far, I've been able to programmatically post to my Page's Wall, by adding this code to my website:
include_once "lib/facebook/src/facebook.php";

$facebook = new Facebook(array('appId' => 'APP_ID_HERE', 'secret' => 'APP_SECRET_HERE'));

if($facebook->getUser()) {

    try {
        $ret_obj = $facebook->api('/FACEBOOK_PAGE_ID_HERE/feed', 'POST', array(
            'link' => 'www.example.com',
            'message' => 'Posting with the PHP SDK!',
            'access_token' => 'FACEBOOK_PAGE_ACCESS_TOKEN_HERE'
        ));
        echo '
Post ID: ' . $ret_obj['id'] . '
';

    } catch(FacebookApiException $e) {
      // user logged out (has user_id, but invalid access token)
      $login_url = $facebook->getLoginUrl(array('scope' => 'publish_stream'));
      echo 'Please login.';
    }
    echo '
getLogoutUrl() . '">logout';

} else {

    $login_url = $facebook->getLoginUrl(array('scope' => 'publish_stream'));
    echo 'Please login.';

}

So I just open my website, click "Please login", login as myself. Once I'm logged it, it will now be able to post the status update to the Facebook Page.
Obviously, the problem here is that I need to be logged in for it to be able to post. If other users will try to login with their user accounts, my website cannot post status updates to the Facebook Page because I am the only Admin for the app/Page.
My question is, is there a way for me to programmatically log myself into Facebook so I can do these status updates to my Page automatically?
Sorry, total noob here to Facebook development.

A: Seems like you need to update status while you are offline from facebook. To do this you need to get the offline access permission of the app user and you need to have a "infinite" token for facebook app to access the APIs, so that your program can update anytime you want with out logging into facebook.
You may get something you want here
http://developers.facebook.com/docs/authentication/

A: I'm a little late to the party here, but I thought I'd post my gist example for how to do something very similar. I added some functionality to fbconsole to make it easy to programmatically login with fbconsole.automatically_authenticate to make it much easier to access this information in a systematic way. This addition has not yet been incorporated into the master branch of fbconsole (it was just posted this morning), but it is available here in the meantime for those that are interested.

A: This is what I use to do,
 // = SET WALL DATA HERE ===============
$attachment = array(
'access_token' => 'My Access token here',
'message'      => '',
'name'         => 'My Wall Post Header/Title Here',
'caption'      => 'Small caption here',
'link'         => 'http://www.mywebsite.org',
'description'  => 'Wall Post Details Here',
'picture'      => "http://www.mywebsite.org/images/logo.gif",
);

// =POST ON FACEBOOK WALL ==========================
$this->facebook->api('/me/feed', 'POST', $attachment);
, $attachment);

So include your Facebook API, Get your Facebook Access token, SET data for your wall post and call for facebook api with me/feed method.
This will make a wall post on your wall without asking for login.
make sure you are using correct Access Token.


text:
Q: Delphi RAD Studio Serial Number We currently use Rad Studio 2007 and are expecting to upgrade to Delphi XE soon!
Does anybody know how we can see what the serial number was used when installing Rad Studio 2007?
Regards, Pieter

A: 'LicenseManager.exe' in the 'bin' folder of the 'Rad Studio' installation should show it.

A: Also, you can see all your registered products with serial numbers on EDN My registered products page (after logging in).