text:
Q: TypeError: this.dynamodb.batchGetItem is not a function with jest I'm trying to create a simple class that wraps the Amazon SDK for dynamodb. When testing, I get the error:
TypeError: this.dynamodb.batchGetItem is not a function
Here is my testcase: test.js
import DynamoDBContentAccess from "../../../src/api/dynamodb_content_access";
const AWS = require("aws-sdk");
describe("services", () => {
  it("returns a list of services", async () => {
    let serviceInterface = new DynamoDBContentAccess();
    const params = {
      bearerToken: "fake bearer token",
      filter: {},
      skip: 10,
      limit: 10,
    };
    const mockResponse = {
      Responses: {
        Services: [
          {
            ServiceId: {
              S: "example1",
            },
          },
        ],
      },
    }
    const batchGetItemPromise = jest.fn().mockReturnValue({
      promise: jest.fn().mockResolvedValue(mockResponse),
    });
    serviceInterface.dynamodb = jest.fn().mockImplementation(() => { return {
      batchGetItem: batchGetItemPromise,
    }});
    const result = await serviceInterface.findServices(params);
    expect(result).toEqual(mockResponse);
  });
});

Here is the class under test: dynamodb_content_access.js
import ContentAccess from "./content_access"
const AWS = require("aws-sdk");
class DynamoDBContentAccess {
  constructor() {
   this.dynamodb = new AWS.DynamoDB();
  }
  async findServices (bearerToken, filter, skip, limit) {
    const params = {
      TableName: 'Services',
    };
    const results = await this.dynamodb.batchGetItem(params).promise();
    return results
    }
 }
 export default DynamoDBContentAccess;

Is my mock at the wrong level? What am I missing?

A: You can use jest.spyOn(object, methodName) to mock AWS.DynamoDB class and its instance.
Use mockFn.mockReturnThis() to mock method chain call.
E.g.
dynamodb_content_access.js:
const AWS = require('aws-sdk');

class DynamoDBContentAccess {
  constructor() {
    this.dynamodb = new AWS.DynamoDB();
  }
  async findServices(bearerToken, filter, skip, limit) {
    const params = {
      TableName: 'Services',
    };
    const results = await this.dynamodb.batchGetItem(params).promise();
    return results;
  }
}

export default DynamoDBContentAccess;

dynamodb_content_access.test.js:
import DynamoDBContentAccess from './dynamodb_content_access';

const AWS = require('aws-sdk');

describe('services', () => {
  it('returns a list of services', async () => {
    const params = {
      bearerToken: 'fake bearer token',
      filter: {},
      skip: 10,
      limit: 10,
    };
    const mockResponse = {
      Responses: {
        Services: [
          {
            ServiceId: {
              S: 'example1',
            },
          },
        ],
      },
    };

    const dynamodb = {
      batchGetItem: jest.fn().mockReturnThis(),
      promise: jest.fn().mockResolvedValueOnce(mockResponse),
    };
    const DynamoDBSpy = jest.spyOn(AWS, 'DynamoDB').mockImplementation(() => dynamodb);
    let serviceInterface = new DynamoDBContentAccess();

    const result = await serviceInterface.findServices(params);
    expect(result).toEqual(mockResponse);
    expect(DynamoDBSpy).toBeCalledTimes(1);
    expect(dynamodb.batchGetItem).toBeCalledWith({ TableName: 'Services' });
    expect(dynamodb.promise).toBeCalledTimes(1);
  });
});

unit test result:
 PASS  examples/66858621/dynamodb_content_access.test.js (7.959 s)
  services
    ✓ returns a list of services (3 ms)

----------------------------|---------|----------|---------|---------|-------------------
File                        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------------------------|---------|----------|---------|---------|-------------------
All files                   |     100 |      100 |     100 |     100 |
 dynamodb_content_access.js |     100 |      100 |     100 |     100 |
----------------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.846 s, estimated 10 s


text:
Q: Discrete Math Relations on the set {1, 2, 3} I was just to make sure that I am doing these correctly. Here is what I have:
1. Describe a binary relation on 1,2,3 that is reflexive and symmetric, but not transitive:
And I have: {(1,1), (2,2), (3,3)} it is obviously reflexive and I figured this would be true that it is symmetric as well.
2. Binary relation on 1,2,3 that is reflexive and transitive, but neither symmetric or antisymmetric:
My answer: {(1,1), (2,2), (3,3), (1,2), (2,3), (2,1)}
3. Binary relation on 1,2,3 that is antisymmetric and transitive, but not reflexive:
My answer: {(1,2), (2,3), (1,3)}
Help is very much appreciated. Thank you

A: $1$. The function you gave is symmetric, transitive and reflexive.
For a function that is symmetric, reflexive but not transitive take $\{(1,1),(2,2),(3,3),(1,2),(2,1),(2,3),(3,2)\}$
$2$. the function you gave is not transitive since we have $(1,2)$ and $(2,3)$ but not $(1,3)$.
For an example that works take $(1,1),(2,2),(3,3),(1,2),(2,3),(1,3),(1,3)$. So just add $(1,3)$ to make it transitive and it works.
$3$. your example is good. You can also take  $\emptyset$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can calculate $ a \mod n^2 $ be computed smartly if we know $a \mod n$? By example:

How can $ 2^{65536} \mod 7^2 $ be computed smartly?

I think that there is a faster method than writing next element and find cycles. I found that
$\mod 7 :$
$$ \color{red}{ 2^{0} \equiv 1\\2^{1} \equiv 2\\2^{2} \equiv 4}\\2^{3} \equiv 1 $$
and by these equations each number can be fastly computed for example:
$$2^{65536} = 2^{21845\cdot 3 +1 } \equiv 2^1 \equiv 2 $$
but how can it be applied for $\mod 49$?

A: $$
2^3 = 1 + 7
\implies 2^{21} = (1+7)^7 \equiv 1 \bmod 7^2
\implies 2^{65536} \equiv 2^{65536 \bmod 21} = 2^{16} \equiv 23 \bmod 7^2.
$$
The key point is the binomial expansion of $(1+7)^7$.

A: You can solve this the same way, only the cycle is a bit longer. Euler's theorem guarantees that the length of the cycle is a divisor of $\phi(49)=42$ (where $\phi$ is Euler's totient function). (Modulo $7$, Euler's theorem guarantees that the cycle length is a divisor of $6$, and you found that the cycle has length $3$.)
We get
$$
2^{65536}=(2^{42})^{1560}\cdot2^{16}\\
\equiv 1^{1560}\cdot2^{16}\\
=(2^8)^2\equiv 11^2\equiv 23
$$

A: Repeated squaring:
$$\color{blue}2^2=4$$
$$2^4=16$$
$$2^8=256\equiv11\mod 49$$
$$2^{16}\equiv11^2=121\equiv\color{red}{23}\mod49$$
$$2^{32}\equiv23^2=529\equiv39\mod49$$
$$2^{64}\equiv39^2\equiv(-10)^2=100\equiv\color{blue}2\mod49$$
If you do this another $6$ times, you'll get $$2^{4096}\equiv\color{blue}2\mod49$$
and then after another $4$ times you'll get $$2^{65536}\equiv\color{red}{23}\mod49.$$

A: Hint $\ $ Apply twice the congruence $\ 2^{\large 2^{\Large 6}}\!\!\equiv 2\pmod{\!7^{\large 2}}\,$ by below Lemma
because $\,\ \ \ \begin{align} 2^{\large\color{#c00} 3} &\equiv 1\!\!\!\pmod{\!7}\\ 2^{\large 6} &\equiv 1\!\!\!\pmod{\!\color{#c00}3\cdot 7} \end{align}$
Lemma $\ \ \begin{align} a^{\large\color{#c00} j} &\equiv 1\!\!\!\pmod{\!n}\\ k\,&\equiv 1\!\!\!\pmod{\!\color{#c00}j\:\!n} \end{align} \Rightarrow\  a^{\large k }\! \equiv a \pmod{\!n^2}$
Proof $\ \ a^{\large j} = 1+i\,n\ $ so $\bmod n^2\!:\,\ a^{\large jn} \equiv (1+i\,n)^{\large n}\equiv 1\ $ by Binomial Theorem
therefore $\ jn\mid k-1\,\Rightarrow\,  a^{\large k-1}\equiv 1\,\Rightarrow\, a^{\large k}\!\equiv a$

A: Since, as you noticed, $2^3\equiv 1\pmod 7$, let's look at what multiplying by $2^3$ does to a number mod $7^2$. We'll write our congruence class in the form $7a+b$ where $0\leq a, b\lt 7$; then $2^3(7a+b)$ $=(7+1)(7a+b)$ $=7^2a+7a+7b+b$ $\equiv 7(a+b)+b$.  By iterating this, we see that $2^{3i}(7a+b)$ $\equiv 7(a+ib)+b$, so $2^{21}(7a+b)$ $\equiv 7(a+7b)+b$ $\equiv 7a+7^2b+b$ $\equiv 7a+b$.  In other words, $2^{21}$ here is the identity mod $7^2$ just as $2^3$ was mod $7$ (this is another way of looking at Arthur's answer), so we can remove all the factors of $2^{21}$ from $2^{65536}$ and wind up with $2^{65536}\equiv 2^{16}$ $\equiv 2\cdot2^{15}$ $\equiv 2\cdot (2^3)^5$ $\equiv 2\cdot (5\cdot 7+1)$ $\equiv 3\cdot7+2 \equiv 23$.


text:
Q: Pandas Dataframe, aggregate and put the data in the next column I have a dataset like this:
Country   Name      Match   Result
US        Martin    Win     3
US        Martin    Lose    1
US        Martin    Draw    5
UK        Luther    Win     5
UK        Luther    Draw    3

I'd like to add two more columns with sum result from Win, Lose and Draw, and percentage of each match like this:
Country   Name      Match   Result  All Percentage
US        Martin    Win     3       8   0.375
US        Martin    Lose    1       8   0.125
US        Martin    Draw    5       8   0.625
UK        Luther    Win     6       10  0.6
UK        Luther    Draw    4       10  0.4

I've already tried using groupby and got result for size total match. However I don't know how to put it in the next column.
Thank you

A: IIUC you need GroupBy.transform, sample DataFrame was changed:
df['All'] = df.groupby(['Country','Name'])['Result'].transform('sum')
df['Percentage'] = df.Result.div(df.All)
print (df)
  Country    Name Match  Result  All  Percentage
0      US  Martin   Win       2    8       0.250
1      US  Martin  Lose       1    8       0.125
2      US  Martin  Draw       5    8       0.625
3      UK  Luther   Win       6   10       0.600
4      UK  Luther  Draw       4   10       0.400


text:
Q: How to make automatically delete rows with multiple sheet in google script How to make automatically delete rows with multiple sheet in google script based on trigger, I've used this script and it worked, but I want this script to be able to use two or more tab sheets at once while the current script only uses one tab sheet. how to use more than one tab sheet in getSheetByName?
Can anyone help me? because every time I ask here no one responds, this is my third question, that the previous two no one helped answer. is there something wrong i don't know.

function acraCleanup() {
  var SPREADSHEET_KEY = "AABVGGHJGFGDFG4GFD65GHDF56HGFHG53";

// Replace with your spreadsheet Key,

//you can find this by trying to share the Spread sheet

// and getting the key between the "=" and the "&"

  var SHEET_NAME = "Sheet 1"; //Sheet 1 unless you changed the sheet name
  var rowsToKeep = 1000; //Will keep bottom 1000 Rows
  var sheet  = SpreadsheetApp.openById(SPREADSHEET_KEY).getSheetByName(SHEET_NAME);
  var rows = sheet.getLastRow();
  var numToDelete = rows – rowsToKeep  -1;
  if (numToDelete > 0) sheet.deleteRows(2, numToDelete);
}

A: Try
function acraCleanup() {
  var SPREADSHEET_KEY = "AABVGGHJGFGDFG4GFD65GHDF56HGFHG53";
  var rowsToKeep = 1000; //Will keep bottom 1000 Rows
  const list = ['SheetX','SheetY'];
  var ss  = SpreadsheetApp.openById(SPREADSHEET_KEY)
  ss.getSheets().filter(sh => list.indexOf(sh.getName()) != -1).forEach(function (sheet){
    var rows = sheet.getLastRow();
    var numToDelete = rows - rowsToKeep  - 1;
    if (numToDelete > 0) sheet.deleteRows(2, numToDelete);
  })
}

A: Keep 1000 rows below the header
function acraCleanup() {
  const list = ['Sheet1','Sheet2'];
  var ss  = SpreadsheetApp.openById("ssid")
  ss.getSheets().filter(sh => ~list.indexOf(sh.getName())).forEach(sheet => {
    let rows = sheet.getLastRow();
    if(rows > 1001) {
      sheet.deleteRows(2 ,rows - 1001)
    }
  });
}


text:
Q: Perl network frame/packet parser I am writing a small sniffer as part of a personal project. I am using Net::Pcap (really really great tool).
In the packet-processing loop I am using the excellent Net::Frame for unpacking all the headers and getting at the data. I am getting concerned that this might not be terribly efficient (Net::Frame is great but seems to be more than I need for this project).
Also I dislike that for some Debian systems I had to manually compile libdumbnet (the package provided in the official apt repositories didn't seem to work, Net-Libdnet-0.92 didn't like it).
All I want is to get at the payload inside a TCP segment. Is there any alternative ?
Thank you.
P.S. Would it be really really bad (read "thedailywtf.com worthy") if I just took the packet and searched it for some pattern ?

A: I recently wrote a PCAP dump file unpacker in C and then afterwards wished I'd just used the open source libraries instead (when I realised they existed and were so easy to use). I have to say that as it's a binary file format it's probably easier to do in C than Perl, but I'll no doubt get boo'ed by all the Perl fanatics out there.
What I will say is that using existing code will be quicker all round than coding it yourself, but if you really really want to, the file format is freely available online and is really quite simple.
As for searching for a pattern, it almost certainly won't work. It's a binary file format and the packets can be fragmented and/or duplicated, so the only reliable way to know where a message starts and ends is by unpacking the headers, checking the packet flags, reading the content length field, etc. etc. Doing pattern searches may work 90% of the time, but at some point you'll find a packet capture log that means you need to change your code. And then a while later find another packet that means another change, and so on and so forth.


text:
Q: Comparing SVD of orthogonal matrix $(\sqrt{W}A)$ and matrix $A$ in order to find the singular values of A I have a diagonal matrix W and another matrix A. I also have that $(\sqrt{W}A)$ is an orthogonal matrix.
I have that the SVD of $$\sqrt{W}A=U\Sigma V^T=(\sqrt{W}A)II$$ where I is the identity matrix. So, the singular values of $(\sqrt{W}A)$ are all $1$.
I am trying to figure out what the SVD of just $A$ would be so I can find the singular values of A. I tried to say that it is $$A=\sqrt{W}^{-1}\sqrt{W}AII=AII$$ but this isn't an SVD since A is not orthogonal.
I was also thinking that maybe it would be $$A=(\sqrt{W}A)\sqrt{W}^{-1}II$$ but I don't think that $\sqrt{W}^{-1}$ will commute in that way.
Any help would be much appreciated. Thank you.

A: Since $\sqrt{W}A$ is unitary,
$$ I = (\sqrt{W}A)(\sqrt{W}A)^* = \sqrt{W} AA^* \sqrt{W}^*$$
First note that $\sqrt{W}$ has to be full rank since $\sqrt{W}A$ is full rank. Therefore $\sqrt{W}^{-1}$ exists and, assuming $W$ is real,
$$ AA^* = \sqrt{W}^{-1}\sqrt{W}^{-1} = W^{-1} $$
Now think about how the singular values of $AA^*$ are related to $A$, and how $W^{-1}$ is related to $W$.


text:
Q: Why is so much worse to call a place of an array than a variable I'm starting with Java, and I just came up with this huge difference: why is making references to an array so much worse than assigning the value to a variable and then calling the variable? (If that's not the problem of my code, then what's the problem of my code?)
I tried to implement selection sort in Java and here I show you the times.
In my mind an array was like a list of symbolic variables so I don't see how is that much worse to call array items directly.
Here's the code (times below)
public static int[] selectionSort(int ... numbers) {
  int pos, value;
  int[] result = numbers.clone();
  for (int i = 0; i < result.length - 1; i++) {
    value = result[i];
    pos = i;
    for (int j = i + 1; j < result.length; j++) {
      if (result[j] < value) {
        value = result[j];
        pos = j;
      }
    }
    result[pos] = result[i];
    result[i] = value;
  }
  return result;
}

public static int[] selectionSortWorse(int ... numbers) {
  int pos, value;
  int[] result = numbers.clone();
  for (int i = 0; i < result.length - 1; i++) {
    pos = i;
    for (int j = i + 1; j < result.length; j++) {
      if (result[j] < result[pos]) {
        pos = j;
      }
    }
    value = result[pos];
    result[pos] = result[i];
    result[i] = value;
  }
  return result;
}

Time comparison (average of 10) of selectionSort vs. selectionSortWorse

*

*length of array: 10000; times 33.14 ms vs. 52.33 ms

*length of array: 20000; times 127.13 ms vs. 207.46 ms

*length of array: 50000; times 793.56 ms vs. 1302.48 ms

*length of array: 100000; times 3096.43 ms vs. 5072.56 ms

A: When accessing an array element, for example result[pos], there is an overhead compared to accessing a direct variable, for example value, at least 2 more things have to happen:

*

*Verifying range, for the example, verifying that pos >= 0 && pos < result.length

*The address of the element needs to be calculated, something like "result address + (pos * element_size)" instead of just "value address". This shouldn't be significant, but if repeated enough might have an impact.


text:
Q: S.O.A. with .NET for scalability Anyone know where I can find useful resource for some information for this.
I reckon SOA is the way to go for scalabilty, but are there down sides such as performance and security I should look at.
Overall what architecture should be considered best for enterprise web applications
A good , complete, up to date book would be valuable, any suggestions?

A: Here is an article with some real performance data on systems where every class is a service
WCF Service Performance

A: I would say first take a look at Microsoft's Patterns and Practices.
Specifically I would say:
Architecture Guide
Web Client Software Factory
Here are also some good MSDN Articles:
Understanding SOA


text:
Q: Random Variable: Ordered List of ints. You are given an ordered list of integers : 1, 2, ...100. You then randomly permute (reorder) the integers.
a.) Define a random variable that indicates whether or not a pair of integers in the list is permuted.
    What distribution should the random variable have if this reordering is to be completely random?
b.) How many such random variables should you define for this list?
c.) What is the expected # of permutations of 2 particular integers in the list?
d.) Define the random variable that describes the total number of permutations in this list.
    What is the probability mass function if you assume that each individual permutation is independent of each other?
e.) What is the expected number of permutations in this list. Justify your answer.
f.) What is the standard deviation of the number of permutations in the list?
g.) You observe 1000 pairs. Is that a very likely outcome? Justify your answer.
I'm confused about the phrasing of this question. Specifically for part a, when it says "whether or not a pair of integers in the list is permuted", does it just mean if either a or b is not in the correct spot? Also just general guidance to solving this would be great.


text:
Q: How to cancel Firebase Auth persist on logout? My app has basic authentication form for registered admin user. In the SignIn form Email and pass are required and optionally 'Remember me' could be checked. Initially I set Auth persist to 'session' or 'local' depending on user choice, like showed in the docs.
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)   // or .LOCAL
  .then(function() {
    firebase.auth().signInWithEmailAndPassword(email, password) ...

I have logout button calling firebase.auth().signOut(). It seems to logout the user, and redirects to login screen, but if page is reloaded, user is again logged in, without going through the SignIn form.I thought about adding setPersistence(firebase.auth.Auth.Persistence.NONE) to the logout logic, but (at least in the docs) it needs user credentials to signInWithEmailAndPassword. Problem is at this point if the account is previously persisted, and loged in, user didn't leave email and password. Well, at least the password.Is my approach fundamentally wrong, or do I need to clear local storage in some other way? Or maybe set persistUser to 'none' without calling signInWithEmailAndPassword again?

A: set the persistence depending on the "Remember me checkbox"
// Checked
await firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)

// Unchecked
await firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)

afterwards you can log in user with credentials without worrying about storing anything in the browser Local/Session storage and whenever you call
await firebase.auth().signOut()

user will be logged out


text:
Q: ¿Cuál es la diferencia entre llamar a una función con su parámetro y cuando se la explicita de forma anónima con el mismo parámetro? Realicé un ejercicio donde debí mostrar las coordenadas del mouse en pantalla.
La cuestión es que a la hora de llamar a la función que realiza dicho trabajo, no funciona si la llamo como se haría normalmente
body.onmousemove = mostrarPosMouse(event);

Luego encontré esta solución que hace el trabajo esperado
body.onmousemove = function (event) {
    mostrarPosMouse(event);
};

Mi pregunta es: Que tiene la función anónima que hace posible el correcto funcionamiento?

A: Que tiene la función anónima que hace posible el correcto funcionamiento?
Una cosa muy sencilla: una función anónima es, en si misma, una expresión.
Clarificamos un poco:
variable = expresión

Esa sentencia asigna a la variable variable el resultado de evaluar la expresión.
Eso hace posible, por ejemplo, que esto funcione:
var x = ( 5 * 2 + 10 );

El motor de Javascript primero evalúa lo situado a la derecha del operador =, y es el resultado de esa evaluación lo que se asinga a variable.
Ahora, veamos el resultado de evaluar una función:
function algo( ) { }
var variable = algo( );

Fíjemos en los paréntesis ( y ). Eso es la marca distintiva de una llamada  a función. Al encontrarse con nombre_de_variable ( , el lenguaje entiende que eso es una expresión, cuyo resultado final es el valor retornado por la llamada a la función nombre_de_variable.
Por lo tanto, en tu ejemplo:
body.onmousemove = mostrarPosMouse(event);

*

*Se evalua event (si no es una variable local, se usa window.event en el navegador).

*Se llama a la función mostrarPosMouse( ) con un argumento: el resultado del punto 1.

*A body.onmousemove se le asigna el valor retornado en el punto 2.

Si como expresión usas una funcionan anónima, las cosas transcurren de manera similar ... pero no idéntica:
body.onmousemove = function (event) {
  mostrarPosMouse(event);
};

*

*El motor encuentra la palabra clave function, y entiende que eso es una declaración de función.

*La declaración de función devuelve una referencia a la función recién creada.

*La referencia obtenida en 2 es usada como valor a asignar.

Podríamos decir que
function (event) {
  mostrarPosMouse(event);
};

es, en cierto modo, igual que si hicieramos
{
  return ( function( event ) { mostrarPosMouse( event ); ); }
}

La Mozilla Developer Network, como casi siempre, tiene una excelente documentación sobre las funciones, con un apartado sobre las expresiones de función.

A: La diferencia es que en el primer fragmento de código no se está atando una función sino más bien la ejecución de una función (eventualmente, el valor que dicha función retorne).
En este caso debería ser:
// Definición de la función
function mostrarPosMouse(event) {
    // ...
};

// Atar la función al evento, no la ejecución. Nótese la ausencia de ()
// ya que no queremos ejecutarla, sólo atarla al evento
body.onmousemove = mostrarPosMouse;


text:
Q: Using Windows api TimeZoneInfo ConvertTimeFromUtc In powershell I can use the windows system api
$estzone = [System.TimeZoneInfo]::FindSystemTimeZoneById("Eastern Standard Time")
$esttime = [System.TimeZoneInfo]::ConvertTimeFromUtc($test2, $estzone)
"GMT= " +$test2 + " EST =" + $esttime

I can't seem to reference FindSystemTimeZoneById or ConvertTimeFromUtc in VB
I have tried
Option Explicit

Private Type SYSTEMTIME
    wYear As Integer
    wMonth As Integer
    wDayOfWeek As Integer
    wDay As Integer
    wHour As Integer
    wMinute As Integer
    wSecond As Integer
    wMilliseconds As Integer
End Type

Private Type TIME_ZONE_INFORMATION
    Bias As Long
    StandardName(0 To 31) As Integer
    StandardDate As SYSTEMTIME
    StandardBias As Long
    DaylightName(0 To 31) As Integer
    DaylightDate As SYSTEMTIME
    DaylightBias As Long
End Type

Private Enum TIME_ZONE
    TIME_ZONE_ID_INVALID = 0        ' Cannot determine DST
    TIME_ZONE_STANDARD = 1          ' Standard Time, not Daylight
    TIME_ZONE_DAYLIGHT = 2          ' Daylight Time, not Standard
End Enum
Private Declare PtrSafe Function FindSystemTimeZoneById Lib "kernel32" (lpTimeZone As String) As TIME_ZONE_INFORMATION
Private Declare PtrSafe Function ConvertTimeFromUtc Lib "kernel32" (lpSystemTime As Date, pTimeZoneInformation As TIME_ZONE_INFORMATION) As Long

Function GetLocalTimeFromGMTerc(GMTTime As Date)
    Dim estzone As TIME_ZONE_INFORMATION
    Dim esttime As Date
    estzone = FindSystemTimeZoneById("Eastern Standard Time")
    esttime = ConvertTimeFromUtc(GMTTime, estzone)
    GetLocalTimeFromGMTerc = esttime
End Function

This seems to compile/run but give "A value use in the formula is of the wrong data type"
I assume I am doing it completely wrong. Any help?
Thanks!


text:
Q: Proper implementation of foldl1 The Haskell Wikibook provides one
foldl1           :: (a -> a -> a) -> [a] -> a
foldl1 f (x:xs)  =  foldl f x xs
foldl1 _ []      =  error "Prelude.foldl1: empty list"

that doesnt work. I tried to compile this version of it:
myFoldl1           :: (a -> a -> a) -> [a] -> a
mFoldl1 f (x:xs)  =  myFoldl1 f x xs
myFoldl1 _ []      =  error "Prelude.foldl1: empty list

I first thought it was missing a case to end the fold and that there was a problem with the typing
foldl1 _ [x] = x
foldl1 f (x:xs)  =  foldl (f x) xs

But this wont work either. I think the type issue goes deeper, but I dont have a good enough grasp of Haskell to think further. Can someone help me out?

A: mFoldl1 f (x:xs)  =  myFoldl1 f x xs

You've made two mistakes when renaming the function: First you misspelled the function name in the definition of the above case (mFoldl1 instead of myFoldl1) and secondly you replaced the call to foldl in the original with a recursive call to myFoldl1.
The correct version would be:
myFoldl1 f (x:xs) = foldl f x xs

A: I too stumbled across the error in the wikibook, and found this entry.
The answers above seem to be wrong: they are not even of the right type.
foldl1 f [x]       = x
fold11 f [x,y]     = f x y
foldl1 f x:y:zs    = f (f x y) (foldl1 f zs)
foldl1 _ []        = error "foldl1 undefined on []"

does the job, I think. I hope there is something more elegant.

A: Correction! Above works, but the original using a call to foldl is far better.
The confusion arises with fonts that don't clearly distinguish "l" and "1"! To be clear
fold1 f (x:xs) = foldl f x xs

is the obvious and simple original.


text:
Q: Show that the center of a division ring is a field. I tried the proof, but wasn't able to proceed further:
let a and b be any elements belonging to Z(center),
Now a.b=b.a
hence Z is commutative.
Now proving that Z is a division ring:(then we can show that since every commutative division ring is field, Z is a field)
NO CLUE...

A: Hopefully you can already prove:

The center of a ring is a ring, in fact, a commutative ring.

Furthermore, if $D$ is a division ring, then for all $x\in Z(D)$, if $x\neq 0$, then $x^{-1}$ exists somewhere in $D$.
Now to show the commutative ring $Z(D)$ is a field, you'd have to show that $x^{-1}\in Z(D)$, because inverses are unique, and a field necessarily has inverses for its nonzero elements.
So, the task is clear: if $0\neq x\in Z(D)$, prove $x^{-1}\in Z(D)$.


text:
Q: Digispark: Driving high Zener-connected pin on ATtiny85 In my project I need all available pins on my Digispark.
Pin PB4 is connected to a 68 Ω resistor and a 3.6 Zener diode.

This pin is used for USB protocol. This means that at some point in time the ATtiny is "writing" to this pin (meaning it is pulling it high). As a consequence the current drawn will be (5 - 3.6) / 68 = 20.5 mA. This is very close to the maximum allowed although it seems it is supported by the chip.
I want to drive this pin (with digitalWrite) high for an unspecified period of time(could be 5 minutes or 1 h). Would this damage my board?

A: The IO pin has absolute maximum rating of 40mA. The digital output voltage rating is listed at 10mA current, which basically tells the drive strength. But pins are not guaranteed to source current greater than the listed condition. However, the characterisric curve shows output voltage vs output current up to 20mA.
So basically, the pin should typically be able to source 20mA at about 4.5V,  but they don't guarantee that it can source over 10mA.


text:
Q: Possible lost data from Stack Overflow answer Regarding How to install SQL Server 2008 Express with Inno Setup?, I just had a comment posted saying it was incomplete. And it was.
Thing is, I'm pretty sure it was complete when I posted it, and here's another interesting thing.
There were links in the answer that still worked but, when I went into edit mode, the links were not at the bottom (the square bracket thingies) and the preview showed just the text for the links (double square bracket groups), not the HTML links themselves.
Now, I don't particularly care about the answer itself, I've edited it to get rid of the code since we ended up testing the Microsoft-blessed solution and it was fine, so there was no need for the hacky workaround.
I'm just raising this for the powers that be in case they want to investigate. I live in mortal fear of all the information I've pumped into Stack Overflow over the last year just up and disappearing on me :-)

A: At first I thought it was the same as this issue:
https://meta.stackexchange.com/questions/12988/serverfault-cut-off-truncated-on-long-post
However, this is something different.  In all the other posts, the entire contents are visible if you view the source or edit history and you can fix the post to show all the data with a simple no-op edit (add a space somewhere). It looks like the missing content really did vanish.

A: In the original version of the accepted answer to Accepting answers, what is it all about? the entirety of the text was there.
But on editing to include the image of plain sight, the edit window only contained about one third of the original text.
The revision list of that particular post illlustrates better. The only actual edit made by random to that post was adding in the image and yet it looks as if he added in a massive bulk. No whey there.
The eventual edit luckily happened only after this realisation and no loss of the answer was suffered.
Another find: To those who can edit, what do you see in the edit box when you try to update the accepted answer on the Voting limits FAQ?
The same content, I see in the revision list. Very weird, indeed. Smithers

A: That is odd -- it looks like the data is truncated in both fields (raw markdown and cooked html) in the original post. From our database's perspective, it never arrived.
https://stackoverflow.com/revisions/527117/list
Random's example is a bit .. random .. since there's no repro or artifact, just an anecdote.
If you can reproduce it, let us know.

A:
I live in mortal fear of all the information I've pumped into SO over the last year just up and disappearing on me

Don't live in mortal fear. Download the Creative Commons Data Dump for SOFU and burn it on a DVD. It is relatively simple to import the data into a database or (for one-offs) to write simple scripts to extract the required information.


text:
Q: Count based on multiple conditions using sqldf Hi all I'm writing a sql query on R using sqldf and seem to hit a roadblock. I have a table with an Id column, two dates columns and a grouping by column.
AlertDate  AppointmentDate  ID  Branch
01/01/20   04/01/20         1   W1
01/01/20   09/01/20         1   W1
08/01/20   09/01/20         1   W2
01/01/20   23/01/20         1   W1

The query I'm writing is
sqldf('select Branch,count(ID) from df where AlertDate <= AppointmentDate
and AppointmentDate <AlertDate+7 group by Branch')

From this query the result I'm getting is
Branch Count
W1      1
W2      1

Whichis correct based on the query. What I want to achieve is if my 2nd condition is false ie AppointmentDate is less than AlertDate+7. Instead of dropping the count it should be counted in the next group depending on date. Example if the alertdate is 01/01/20 and appointment date is 23/01/20 then it should be counted in W4. ceil((Appointmentdate-alertdate)/7) SO in the end I want the result as
Branch  Count
W1      1
W2      2
W4      1

The second row should be counted in W2 and 4th should be in W4 rather than being discarded. I was trying to achieve this in sql using sqldf in R. Any possible solution using R or Sql would work for me.
Output of dput(test)
structure(list(AlertDate = structure(c(18262, 18262, 18269, 18262), class = "Date"), AppointmentDate = structure(c(18265, 18270,18270, 18284), class =
"Date"), ID = c(1, 1, 1, 1), Branch = c("W1","W1", "W2", "W1")), class = c("spec_tbl_df", "tbl_df", "tbl","data.frame"), row.names = c(NA, -4L), problems =
structure(list( row = 4L, col = "Branch", expected = "", actual = "embedded null",
file = "'C:/Users/FRssarin/Desktop/test.txt'"), row.names = c(NA,-1L), class = c("tbl_df", "tbl", "data.frame")), spec = structure(list(  cols = list(AlertDate =
structure(list(format = "%d/%m/%y"), class = c("collector_date",
"collector")), AppointmentDate = structure(list(format = "%d/%m/%y"), class = c("collector_date",  "collector")), ID = structure(list(), class = c("collector_double", "collector")), Branch = structure(list(), class =
c("collector_character",  "collector"))), default = structure(list(), class = c("collector_guess",  "collector")), skip = 1), class = "col_spec"))

A: Here is one way to do it using data.table
df <- structure(list(AlertDate = structure(c(18262, 18262, 18269, 18262), class = "Date"), AppointmentDate = structure(c(18265, 18270,18270, 18284), class =
                                                                                "Date"), ID = c(1, 1, 1, 1), Branch = c("W1","W1", "W2", "W1")), class = c("spec_tbl_df", "tbl_df", "tbl","data.frame"), row.names = c(NA, -4L), problems =
              structure(list( row = 4L, col = "Branch", expected = "", actual = "embedded null",
                              file = "'C:/Users/FRssarin/Desktop/test.txt'"), row.names = c(NA,-1L), class = c("tbl_df", "tbl", "data.frame")), spec = structure(list(  cols = list(AlertDate =
                                                                                structure(list(format = "%d/%m/%y"), class = c("collector_date",

I am converting this to data.table and creating a new column for your logic.
library(data.table)
df <- data.table(df)
df <- df[AlertDate <= AppointmentDate]
df[, new_branch:= ifelse(as.numeric(AppointmentDate-AlertDate)>=7
            ,paste0("W", as.character(ceiling(as.numeric(AppointmentDate-AlertDate)/7))),Branch)]

Here is the resulting table
    AlertDate AppointmentDate ID Branch new_branch
1: 2020-01-01      2020-01-04  1     W1         W1
2: 2020-01-01      2020-01-09  1     W1         W2
3: 2020-01-08      2020-01-09  1     W2         W2
4: 2020-01-01      2020-01-23  1     W1         W4

This is the goupby result..
df[, .(.N, alert=head(AlertDate,1),  appoint=head(AppointmentDate,1)), by = list(new_branch)]
   new_branch N      alert    appoint
1:         W1 1 2020-01-01 2020-01-04
2:         W2 2 2020-01-01 2020-01-09
3:         W4 1 2020-01-01 2020-01-23


text:
Q: How often are new SO versions deployed? In Remove Alternative openID it is said that this feature will be included in next SO deployment. So, how often are new SO versions deployed?

A: Unless it's an odd week (when the team is at MIX, or holidays for example) we're usually building every day, and often several times a day.  To be accurate, we're probably even building then, since we're all a bit insane.
As a general rule, we don't build during peak traffic. We try to cause as little interruption as possible.  If there's a high-impact bug or change that needs to be fixed/made, we'll make an exception.


text:
Q: Duplicate child_process in Nodejs I'm working with a child_procress in Nodejs.
import { fork } from 'child_process';
import { POINT_CONVERSION_COMPRESSED } from 'constants';
import { logger } from '../config/logger';

async function startAssignment() {
  const process = fork('./app/course/startAssigmentProcess.js');

  process.on('error', error => {
    logger.error(error);
  });
  process.on('exit', () => {
    logger.info('Exit procress assign assignment');
  });
}

export { startAssignment };

This process is running a heavy task. So it may take a few minutes. I want to check when a new process is forked whether it is duplicated with a previous running process, so I won't start it.
Thank you.
Note: I'm using node-schedule to run this function every 1 minute.

A: You can lookup previously running process and decide to defer new process until last one is finished.
This library can help you in looking up the running process
A Node.js module for looking up running processes.


text:
Q: Iwasawa theory and perfectoid spaces Have there been any applications of perfectoid theory to Iwasawa theory? At a first glance, this seems like a natural choice. For instance, the field $\mathbb Q_p(\mu_p^{1/p^\infty})$ is studied in both theories (the class group in Iwasawa theory and as a natural example of a perfectoid field (possibly after completion)).
Can we use the tilting correspondence to get information about class groups as in Iwasawa theory?

A: A flippant response is that people had the idea of using perfectoid theory in Iwasawa theory long before perfectoid theory even existed. What I'm referring to here is the work of Fontaine--Wintenberger, who studied the "field of norms" of a tower of p-adic fields, or the "tilt" as youngsters like you would call it, way back in the 1970's. Scholze's tilting equivalence generalises this to a much wider class of rings, of course, but for fields it's all there in Fontaine--Wintenberger.
Fontaine--Wintenberger's construction of the field of norms is the starting point for the theory of $(\varphi, \Gamma)$-modules, and these are essential tools for handling Iwasawa theory for p-adic Galois representations; see e.g. Cherbonnier and Colmez's JAMS paper "Theorie d'Iwasawa des representations p-adiques d'un corps local".


text:
Q: MYSQL Trigger - Using SUM with JOIN I have two tables:
A week table with columns week,Team_Number, and Points.
A Teams table with columns Team_Number and Session1Points.
I'd like  to sum all of the Points from the week table where week column is between 1 and 9, then add that to the Teams table in the Session1Points column.
I've tried:
UPDATE Teams P
SET Session1Points =
(SELECT SUM(Points) from week
where week.Team_Number= P.Team_Number)
where P.Team_Number = New.Team_Number

that's not working. I'd like it to trigger after I update the week table. Do I need to Join first?

A: You can use a JOIN this way
UPDATE Teams P
INNER Join (SELECT
          Team_Number
        , SUM(Points)  as team_sum
      from week
      group by Team_Number ) t on t.Team_Number=P.Team_Number
SET Session1Points = t.team_sum


text:
Q: Raml same resource different query parameters i don't understand how i have to configure a raml api, to call the same resource but with different parameters:
www.mysite/user?uid=""
www.mysite/user?name=""&surname=""

Is possible to do something?
Thanks

A: The resource is the same: /user and you can only specify it once in your RAML.
What you can do is setting the query parameters as optional.
For example:
/user:
  get:
    queryParameters:
      uid:
        type: string
        required: false
      name:
        type: string
        required: false
      surname:
        type: string
        required: false

Or something like this:
#%RAML 1.0
types:
  uuid: string
  person:
    properties:
      name: string
      surname: string
/user:
  get:
    queryString:
      type: [uuid | person]


text:
Q: Problem looping through array filled with result of SQL query I currently have a PowerShell script which runs queries across 18 tables, generates text file output for each table, and merges these text files into an Excel file. I want to have this process run for each corp number I have via a loop.
I have this code right now:
$corplist = "select distinct bc01_corp from BC01"

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString =
"Server=$SQLSERVER;Database=$DATABASE;Integrated Security=True;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $corplist
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$cp = @($DataSet.Tables[0])

foreach ($bc01_corp in $cp)
{
write $bc01_corp
write fml
}

$Query1 = "SELECT * FROM BC01 where bc01_corp = $bc01_Corp"

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString =
"Server=$SQLSERVER;Database=$DATABASE;Integrated Security=True;" ##User ID = ; Password = ;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $Query1
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)

Everything runs up until the end of the for loop. The code prints the corp number and the string "fml" 22 times each; I have 22 distinct corp numbers in the bc01 table. However when I try to pass the bc01_corp value to query 1, I get the following error:

Exception calling "Fill" with "1" argument(s): "The multi-part identifier "System.Data.DataRow" could
  not be bound."
  At C:\Users********\Documents\SQL Stuff for Sean - Codes\Parse out for each corp!.ps1:60 char:1
  + $SqlAdapter.Fill($DataSet)
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : SqlException

it looks like the variable being passed is "system.data.datarow) not the bc01_corp values, which is printed successfully to the console when I run the loop.

A: The issue is that you close your loop, and after it is done you try to reference $bc01_corp which only exists within the scope of your ForEach loop. You need to move your closing } for the loop to after the last line in your sample code (and probably after you do something with $dataset once it is filled). I would also create most of your objects outside the loop, and only update things inside it that need to be, most of which you've done in the initial connection and query.
foreach ($bc01_corp in $cp)
{
    write $bc01_corp
    write fml

    $Query1 = "SELECT * FROM BC01 where bc01_corp = $bc01_Corp"

    $SqlCmd.CommandText = $Query1
    $SqlAdapter.SelectCommand = $SqlCmd
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet)

    <#
    Do stuff with $DataSet
    #>
}


text:
Q: Somar campo do tipo decimal entity framework Eu tenho uma tabela Conserto nela tenho ValorMaoObra, valorPeca e ValorTotal todos do tipo decimal. O campo ValorTotal = ValorMaoObra +  valorPeca. Porem esta retornando 0. Estou mostrando isso na View de detalhes quando eu clico vou ver o resumo do conserto com seu preço total.
Minha ConsertoController/detalhes
public ActionResult Detalhes(int id)
{
    decimal total = 0m;

    ConsertoVM model;
    using (Db db = new Db())
    {
        Conserto cons = db.Conserto.Find(id);
        decimal peca = cons.Pecas.ValorUnitatio;
        total += (cons.ValorMaoObra + peca);

        model = new ConsertoVM(cons);
    }

    return View(model);
}


text:
Q: Is there any advantage in specifying types of variables and return type of functions? I always set the types of my variables and functions, a habit I brought from my Java learning, seems the right thing to do.
But I always see "weak typing" in other people's code, but I can't disagree with that as I don't know what are the real advantages of keep everything strong typed.
I think my question is clear, but I gonna give some examples:
var id = "Z226";

function changeId(newId){
    id = newId;
    return newId;
}

My code would be like this:
var id:String = "Z226";

function changeId(newId:String):String{
    id = newId;
    return newId;
}

A: Yes, the big advantanges are:

*

*faster code execution, because the runtime know the type, it does not have to evaluate the call

*better tool support: auto completion and code hints will work with typed arguments and return types

*far better readability

A: You get performance benefits from strongly typing. See http://gskinner.com/talks/quick/#45
I also find strongly typed code to be much more readable, but I guess depending on the person they may not care.

A: As pointed out by florian, two advantages of strongly typing are that development tools can can use the information to provide better code-hinting and code-completion, and that type, as an explicit indicator of how the variable or method is intended to be used, can make the code much easier to understand.
The question of performance seems to be up for debate. However, this answer on stackoverflow suggests that typed is definitely faster than untyped in certain benchmark tests but, as the author states, not so much that you would notice it under normal conditions.
However, I would argue that the biggest advantage of strong typing is that you get a compiler error if you attempt to assign or return a value of the wrong type. This helps prevent the kind of pernicious bug which can only be tracked down by actually running the program.
Consider the following contrived example in which ActionScript automatically converts the result to a string before returning. Strongly typing the method's parameter and return will ensure that the program will not compile and a warning is issued. This could potentially save you hours of debugging.
function increment(value) {
    return value + 1;
}

trace(increment("1"));
// 11

A: While the points in the other answers about code hinting and error checking are accurate, I want to address the claim about performance. It's really not all that true. In theory, strong type allows the compiler to generate code that's closer to native. With the current VM though, such optimization doesn't happen. Here and there the AS3 compiler will employ an integer instruction instead of a floating point one. Otherwise the type indicators don't have much effect at runtime.
For example, consider the following code:
function hello():String {
    return "Hello";
}

var s:String = hello() + ' world';
trace(s);

Here're the AVM2 op codes resulting from it:
getlocal_0
pushscope
getlocal_0
getlocal_0
callproperty 4 0 ; call hello()
pushstring 12    ; push ' world' onto stack
add              ; concatenate the two
initproperty 5   ; save it to var s
findpropstrict 7 ; look up trace
getlocal_0       ; push this onto stack
getproperty 5    ; look up var s
callpropvoid 7 1 ; call trace
returnvoid

Now, if I remove the type indicators, I get the following:
getlocal_0
pushscope
getlocal_0
getlocal_0
callproperty 3 0
pushstring 11
add
initproperty 4
findpropstrict 6
getlocal_0
getproperty 4
callpropvoid 6 1
returnvoid

It's exactly the same, except all the name indices are one less since 'String' no longer appears in the constant table.
I'm not trying to discourage people from employing strong typing. One just shouldn't expect miracle on the performance front.
EDIT: In case anyone is interested, I've put my AS3 bytecode disassembler online:
http://flaczki.net46.net/codedump/
I've improved it so that it now dereferences the operands.


text:
Q: C++ file stream for reading/writing I need to open a file for both reading/writing using fstream and read each character then write that character back to the file. for example i have this code.
fstream in("test.txt",ios::in | ios::out);
if(!in)
    cout<<"error...";
else
{
    char ch;
    in.seekg(0,ios::end);
    int end=in.tellg();//get the length

    in.seekg(0);//get back to the start
    for(int i=0;i<end;i++)
    {
       //in.seekg(in.tellg());//if i uncomment this the code will work
       if(!in.get(ch).fail())//read a character
       {
           in.seekp(static_cast<int>(in.tellg())-1);//move the pointer back to the previously read position,so i could write on it
           if(in.put(ch).fail())//write back,this also move position to the next character to be read/write
               break;//break on error
       }
    }
}

I have a file named "test.txt" which contains "ABCD". As i understand it both put() and get() methods of the stream object move the file pointer forward(i see that by getting the return value of tellg() or tellp() functions after each get() or put() method call). My question is when i comment out the code that will seek the stream pointer to "where it is now"(in.seekg(in.tellg()), the code will result incorrect results. I don't understand why this is since tellg() is showing the correct position of the character to be read next.what is the purpose of explicitly seeking to it? I am using visual studio 2005.
The incorrect result is it writes to the file "ABBB" instead of "ABCD".

A: The output buffer has to be flushed when switching between write and read.
fstream in("test.txt",ios::in | ios::out);
if(!in)
   cout<<"error...";
else
{
   char ch;
   in.seekg(0,ios::end);
   int end=in.tellg();//get the length

   in.seekg(0);//get back to the start
   for(int i=0;i<end;i++)
   {
      if(!in.get(ch).fail())//read a character
      {
          in.seekp(static_cast<int>(in.tellg())-1);//move the pointer back to the previously read position,so i could write on it
          if(in.put(ch).fail())//write back,this also move position to the next character to be read/write
           break;//break on error

          in.flush();
      }
   }
}


text:
Q: TableView with custom cells doesn't begin editing I have a table view with custom cells in it. The cells have some buttons inside of them.
When I press a button to make the table go to editing mode, it doesn't do anything.
If I set the cell's class to UITableViewCell then it works.
The weird thing is that if I set the table view to be in editing mode by default, then when I launch the app the table is in editing mode.
The only problem is when I press the button that is supposed to set it in editing mode.
Edit button:
@objc func didTapEdit(sender: AnyObject){
    if table.isEditing == false{
        table.isEditing = true
        print("okokokok")
    } else {
        table.isEditing = false
    }
}
//This works properly with table views with default cells

Table setup:
view.addSubview(table)
table.translatesAutoresizingMaskIntoConstraints = false
table.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
table.topAnchor.constraint(equalTo: view.topAnchor, constant: navBarHeight).isActive = true
table.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30).isActive = true
table.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -30).isActive = true

Custom cell:
contentView.addSubview(btn)
btn.translatesAutoresizingMaskIntoConstraints = false
btn.topAnchor.constraint(equalTo: topAnchor, constant: topSpace).isActive = true
btn.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -5).isActive = true
btn.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -5).isActive = true
let btnWidth = NSLayoutConstraint(item: btn, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0.0, constant: bounds.height-10)
btn.addConstraint(btnWidth)

I have mutiple buttons which I set up in the same way.
So where's the problem? I created other table views with custom cells and they all worked fine. Plus if I setup the table view to be in editing mode by default, when I run the app it is in editing mode and I can move the cells around! What is going on here? I think the problem might be with how I set the constraints but I have no clue really

A: You add your btn to the cell's contentView, as you should. But then you constrain the button to the cell, which you should not do. Change your constraints to:
contentView.addSubview(btn)
btn.translatesAutoresizingMaskIntoConstraints = false

btn.topAnchor.constraint(equalTo: contentView.topAnchor, constant: topSpace).isActive = true
btn.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -5).isActive = true
btn.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -5).isActive = true
let btnWidth = NSLayoutConstraint(item: btn, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0.0, constant: bounds.height-10)
btn.addConstraint(btnWidth)

As a side note, your btnWidth constraint looks very odd... if you want the button width to be the 10-pts less than the height of the cell, you should be able to get that with:
btn.widthAnchor.constraint(equalTo: contentView.heightAnchor, constant: -10)

Edit -- here is a complete example... adds a "Edit" button to the navigation bar that toggles between editing and not-editing:
class EditTestTableViewController: UITableViewController {

    lazy var editBtn = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(self.editTapped(_:)))
    lazy var doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.editTapped(_:)))

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(EditTestCell.self, forCellReuseIdentifier: "cell")

        self.navigationItem.rightBarButtonItem = editBtn
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 8
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let c = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! EditTestCell
        c.label.text = "\(indexPath)"
        return c
    }
    @objc func editTapped(_ sender: Any) -> Void {
        tableView.isEditing.toggle()
        self.navigationItem.rightBarButtonItem = tableView.isEditing ? doneBtn : editBtn
    }
    override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        // handle moving row...
    }
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        // handle delete row...
    }

}

and a simple custom cell class:
class EditTestCell: UITableViewCell {
    let btn = UIButton()
    let label = UILabel()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() -> Void {
        btn.backgroundColor = .red
        btn.setTitle("Test", for: [])

        label.backgroundColor = .green

        contentView.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(btn)
        btn.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            btn.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12.0),
            btn.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -12.0),
            btn.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -5.0),
            btn.widthAnchor.constraint(equalTo: contentView.heightAnchor, constant: -10.0),

            label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 5.0),
            label.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
        ])
    }
}


text:
Q: What do i have to do if i want to Sum my result using Python? import string
dict = {}
bool = False
user_string = input("Bitte gebe hier die Buchstaben ein, welche du Summieren möchtest:")
String_Num = ""

for i, char in enumerate(string.ascii_lowercase):
    dict[i] = char # This is dictinoary.

for val in user_string.lower():
    if(val.isdigit()):
       print("Entschuldige, der Vorgang konnte nicht abgeschlossen werden!")
       bool = True
       break
    for key, value in dict.items():
        if(val == value):
            String_Num += str(key+1)
            # For spaces
            String_Num += " "

if (not bool):
    print(String_Num)

A: Add just one line after the 'print(String_Num)'
print(sum(map(int, String_Num.split())))

I had to use Google translate, but it looks like you are trying to sum the letters that are inputted.


text:
Q: How can i get bank information from source? I have liked a online bank with plaid API to stripe. i have created a stripe customer with source bank token. But later I couldn't get bank information from source. It is showing
An uncaught Exception was encountered

Type: Stripe\Error\InvalidRequest

Message: No such source: btok_1BOiMhGnklINT0gr7TYCRuvO

A: This error means that the API key you used to make the second API call is not from the Stripe account you linked to your Plaid account and also not the same you used when creating the customer. I'd recommend checking the API keys in both of your scripts.
Also once you fix this part, you should not reuse the token in subsequent calls as it would have been consumed by the customer creation call. You need to use the bank account id that was created instead (ba_xxx).


text:
Q: Web Crawler buscando texto específico na página Bem, estou fazendo um web crawler para buscar o valor de uma moeda.
Escrevi o seguinte código em python:
#coding: utf-8

from urllib2 import urlopen

conteudo = urlopen('http://dolarhoje.com/bitcoin').read()

procurar1 = ''
posicao1 = int(conteudo.index(procurar1) + len(procurar1))
moeda1 = conteudo[posicao1 : posicao1 + 3]

procurar2 = ''
posicao2 = int(conteudo.index(procurar2) + len(procurar2))
moeda2 = conteudo[posicao2 : posicao2 + 3]

procurar3 = '<input type="text" id="nacional" value="'
posicao3 = int(conteudo.index(procurar3) + len(procurar3))
valor = conteudo[posicao3 : posicao3 + 8]

print(moeda1 + ' 1,00 ' + 'vale ' + moeda2 + ' ' + valor)
print ('\n')

Sei que quando coloco: procurar1 = '' e utilizo: conteudo.index(procurar1) ele vai me retornar a primeira incidência, porém eu gostaria de chamar a segunda incidência.
O código executado vai retornar:
฿ 1,00 vale ฿ 25086,77
O esperado:
฿ 1,00 vale R$ 25086,77
Ou seja, retornar tanto o símbolo da primeira moeda quanto o símbolo da segunda moeda, pegando apenas a segunda incidência por similaridade do código da página.
Como fazer?

A: Você pode fazer mais facilmente com a biblioteca MechanicalSoup  (https://github.com/MechanicalSoup/MechanicalSoup)
Para usar basta instalar no seu ambiente: pip install MechanicalSoup
Para pegar o valor que você quer é bem simples:
import mechanicalsoup

browser = mechanicalsoup.StatefulBrowser()
browser.open("http://dolarhoje.com/bitcoin")

page = browser.get_current_page()

symbols = page.select(".symbol")
inputs = page.find_all("input")

moeda1 = { 'symbol': symbols[0].text, 'value': inputs[0].attrs['value'] }
moeda2 = { 'symbol': symbols[1].text, 'value': inputs[1].attrs['value'] }

print(moeda1)
print(moeda2)

A: Apesar do tempo, à fim de fechar esta pergunta com uma solução, é simples se utilizarmos algumas bibliotecas específicas para tal.
Bibliotecas

*

*urllib.request: responsável por capturar o html da página;

*re: biblioteca para se usar expressões regulares.

Explicação de Código
Para capturar o conteúdo usei o seguinte trecho:
html_content = urllib.request.urlopen('http://dolarhoje.com/bitcoin').read().decode('utf-8')

Estou atribuindo dentro da variável html_content o conteúdo do html da página para consumir posteriormente, o read() faz a leitura, decode('utf-8') é para evitar que o site seja capturando em outros padrões de acentuação, as vezes isso acontece.
Ao analisar, podemos ver que há um padrão onde o símbolo das moedas é mostrado dentro presente de uma tag html como por exemplo:
฿
R$

Assim, podemos construir uma expressão regular para capturar as incidências dos símbolos, sendo representado pelo seguinte trecho:
symbols = re.findall(r'\"symbol\">([\S]+)</', html_content)

re estamos usando a biblioteca logo importada no começo do código;
findall() é uma função para capturar em forma de uma lista, as incidências;
r'...' é onde colocamos a respectiva expressão regular;
Assim, a regex construída sobre \"symbol\">([\S]+)</ captura os símbolos e apresenta-as na seguinte lista: ['฿', 'R$']
Enquanto value=\"([.\d,]+)\" captura os valores e apresenta: ['1,00', '13583,42']
html_content é a respectiva variável onde desejamos encontrar a incidência - ou como dizemos quando usamos regex de match.
E, usamos o print print('{0} {1} vale {2} {3}'.format(symbols[0], values[0], symbols[1], values[1])) para mostrar os respectivos valores usando o format(), obtendo assim o resulto desejado:
฿ 1,00 vale R$ 13583,42
Script completo
Abaixo segue o script completo:
# !/usr/bin/python
# -*- coding: utf-8 -*-

# começando com os imports
import urllib.request
import re

# capturando o conteúdo html
html_content = urllib.request.urlopen('http://dolarhoje.com/bitcoin').read().decode('utf-8')

# pegando os símbolos das moedas
symbols = re.findall(r'\"symbol\">([\S]+)</', html_content)

# pegando os valores das moedas
values = re.findall(r'value=\"([.\d,]+)\"', html_content)

# mostrando em console o resultado parecido com: '฿ 1,00 vale R$ 13583,42'
print('{0} {1} vale {2} {3}'.format(symbols[0], values[0], symbols[1], values[1]))

Espero que esta solução ajude outras pessoas que possam estar com uma dúvida parecida.


text:
Q: XPath - select nodes by analyzing following sibllings I have the following XML document,
<doc>

aa

bb

cc

dd

ee

ff

gg

jj

kk

ll

hh

ii

jj

</doc>

I need to write an XPath query to get
 nodes where there are following-siblings
 nodes exist before appear another
node. In this case 2nd and 4th
 nodes should be selected. (
 nodes exist in following-sibligs before another
node).
I tried to do this hours but could not think of any proper solution to get those nodes?
Can anyone suggest a method for how can I do this?

A: Just find h2 and take preceding h1
 //h2/preceding-sibling::h1[1]

result
Element='
dd
'
Element='
hh
'

A: Select such h1 nodes that have h2 as first following sibling among h1 and h2 nodes
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

    <xsl:template match="/doc">
        <xsl:for-each select="h1[following-sibling::*[self::h1 or self::h2][1][self::h2]]">
            <xsl:copy-of select="."/>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>


text:
Q: QGIS: I can barely see the labels in layer panel So, I finally bit the bullet and upgraded to QGIS 3.2.3 Bonn.  However, for layers that are not turned on the font is a super light grey in the layer panel and I can barely read it.  How can I change what this looks like so I won't need to get glasses in 6 months?

A: This question about changing the background color of the layer panel may help. They recommend the Load QSS - US Themes plugin. Try the  themes "dark" and "wombat." The other themes actually make it harder to read deactivated layer names.
You can also create your own UI theme using the examples that come with the Load QSS plugin as templates. The qss files for these examples are available on GitHub: https://github.com/All4Gis/Load-QSS/tree/master/examples

Or you can change some display settings in the Options dialog (Settings menu > Options > General). Unfortunately you can't change the font color, but the night mapping* UI theme may help, or enlarging the font.

*There's a bug in QGIS 3.0 where switching to night mapping mode might cause QGIS to crash. https://issues.qgis.org/issues/18669
*There's a bug in QGIS 3.2 where you can't turn on night mapping mode. https://issues.qgis.org/issues/19944

Here's a rather silly workaround. Put every layer in its own group with the same name as the layer. When a group is disabled, the group name is still displayed in black.


text:
Q: Origin of a custom of deceased attending their own wakes? In the first book of the Amra Thetys series a charming local custom is described in which the deceased attends his own funeral banquet:

I was a little late. They'd already had the ceremonial meal and were cleaning up from that. Which was fine; as much as I cared for Corbin, he wasn't smelling like a flower, and despite the careful makeup he looked like what he was- a corpse propped up in a comfy chair at the head of the funerary table. It reminded me of nothing so much as some sort of gruesome child's tea party, but like I said, I'm not from Lucernis.
 The Thief Who Pulled on Trouble's Braids - Chapter 16

What was the inspiration for this particular custom? Does it come from the author's imagination entirely or maybe it's based on historical or anthropological records of similar traditions?


text:
Q: Replace character between two string in PCRE (Perl) syntax How can I replace a special character between two special strings.
I have something like this:
"start 1
2-
G
23
end"

I want to have the following:
"start 1 2- G 23 end"

Only replace \n with space between "start and end"
Test1;Hello;"Text with more words";123
Test2;want;"start
1-
76 end";123
Test3;Test;"It's a test";123
Test4;Hellp;"start
1234
good-
the end";1234
Test5;Test;"It's a test";123

Is it possible in notepad++?

A: You can use this pattern:
(?:\G(?!\A)|\bstart\b)(?:(?!\bend\b).)*\K\R

demo
details:
(?:
    \G(?!\A)       # contiguous to a previous match
  |
    \bstart\b      # this is the first branch that matches
)
(?:(?!\bend\b).)*  # zero or more chars that are not a newline nor the start of the word "end"
\K                 # remove all on the left from the match result
\R                 # any newline sequence (\n or \r\n or \r)

Note: (?:(?!\bend\b).)* isn't very efficient, feel free to replace it by something better for your particular case.

A: Magic words are lazy quantifier, lookaheads and single line mode.
A solution for PHP (uses PCRE) would be:
<?php
$string = __your_string_here__;

$regex = '~(?s)(?:start)(?<content>.*?)(?=end)(?s-)~';
# ~ delimiter
# (?s) starts single line mode - aka dot matches everything
# (?:start) captures start literally
# .*? matches everything lazily
# (?=end) positive lookahead
# (?s-) turn single line mode off
# ~ delimiter
preg_match_all($regex, $string, $matches);
$content = str_replace("\n", '', $matches["content"][1]);
echo $content; // 1234good-the

?>


text:
Q: Difference between socket libraries I have a script that I can configure to either use a socket library or use libcurl. I am using http access methods. When I use the socket library each request takes much longer as compared to when I switch to libcurl. Both of them work though.
I am curious to understand the difference. Is there a way I can look at the raw request and response for the network communication so I can investigate this? Something like what the browser shows for each page request would be ideal.
I am on a windows system. But if there is a software that can work on both windows and linux that would be great. Any help on how I can dig into this would be helpful.
Thanks.


text:
Q: How to fix "iptables: No chain/target/match by that name"? I built and installed iptables on my linux embedded system. If I list all rules, everything works fine:
#iptables --list
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

But, if I add a new rule to block icmp ping, I'll get the follwing error:
iptables -A INPUT -i eth0 -p icmp --icmp-type any -s 0/0 -d 10.20.3.179 -m state --state NEW,ESTABLISHED,RELATED -j DROP
iptables: No chain/target/match by that name.

How to fix it?

A: The chain and target look correct, so it must be the match. Make sure CONFIG_NETFILTER_XT_MATCH_STATE is enabled in your kernel config.


text:
Q: How to model for word search in cassandra my model design to save word search from checkbox and it must have update word search and status, delete(fake). my old model set pk is uuid(id of word search) and set index is status (enable, disable, deleted)
but I don't want to set index at status column(I think its very bad to set index at update column) and I don't change database
Is it have better way for model this?
sorry for my english grammar

A: You should not create index on very low cardinality column status

Avoid very low cardinality index e.g. index where the number of distinct values is very low. A good example is an index on the gender of an user. On each node, the whole user population will be distributed on only 2 different partitions for the index: MALE & FEMALE. If the number of users per node is very dense (e.g. millions) we'll have very wide partitions for MALE & FEMALE index, which is bad

Source : https://www.datastax.com/dev/blog/cassandra-native-secondary-index-deep-dive
Best way to handle this type of case :

*

*Create separate table for each type of status

*Or Status with a known parameter (year, month etc) as partition key

Example of 2nd Option
CREATE TABLE save_search (
    year int,
    status int,
    uuid uuid,
    category text,
    word_search text,
    PRIMARY KEY((year, status), uuid)
);

Here you can see that i have made a composite partition key with year and status, because of low cardinality issue. If you think huge data will be in a single status then you should also add month as the part of composite partition key
If your dataset is small you can just remove the year field.
CREATE TABLE save_search (
    status int,
    uuid uuid,
    category text,
    word_search text,
    PRIMARY KEY(status, uuid)
);

Or
If you are using cassandra version 3.x or above then you can use materialized view
CREATE MATERIALIZED VIEW search_by_status AS
    SELECT *
    FROM your_main_table
    WHERE uuid IS NOT NULL AND status IS NOT NULL
    PRIMARY KEY (status, uuid);

You can query with status like :
SELECT * FROM search_by_status WHERE status = 0;

All the deleting, updating and inserting you made on your main table cassandra will sync it with the materialized view


text:
Q: Augment module declarations with types from an external module Context
I'm making a React renderer for NativeScript (i.e. a library that allows you to declare NativeScript UIs using React), and I want to provide typings for it.
React's typings already fully support React DOM (i.e. there's references to HTMLElements throughout), but I need to augment the typings to make them aware of NativeScript elements, too. To provide accurate typings, I need to provide references to external modules, e.g. by importing ActionBar. My attempt looks something like this (which does compile, but isn't picked up by the other modules in my project):
// react-nativescript/index.d.ts
import { ActionBar } from "tns-core-modules/ui/action-bar/action-bar";

declare namespace JSX {
    interface IntrinsicElements {
        actionBar: React.ClassAttributes<ActionBar>
          & React.NativeScriptAttributes<ActionBar>
    }
}

declare namespace React {
    interface NativeScriptAttributes<T> {
        className?: string;
        children?: ReactNode;
        onClick?: MouseEventHandler<T>;
    }

// Omitting DetailedNativeScriptFactory<P, T> for brevity.
    interface ReactNativeScript {
        actionBar: DetailedNativeScriptFactory<
            NativeScriptAttributes<ActionBar>,
            ActionBar
        >,
    }
}

Root of the problem
Adding the top-level import ActionBar changes the file from a 'script' to a 'module':

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).

Further clarification of terminology is provided by TypeScript Contributor Mohamed Hegazy.
Upon importing it, the declarations cease to be available to other modules. That is to say, I can only use the type React.ReactNativeScript when my file lacks top-level imports/exports. Otherwise, the following error appears:

Namespace 'React' has no exported member 'ReactNativeScript'.

NOTE: this may be incorrect configuration on my part of my tsconfig.json, but I have tried just about every combination of tsconfig typeRoots and package.json types at this point and nothing makes a difference.
(Failing) alternative approach
In order to keep the declarations available to other modules, we can try moving the ActionBar imports into the namespaces themselves, e.g.:
// react-nativescript/index.d.ts
declare namespace JSX {
    import { ActionBar } from "tns-core-modules/ui/action-bar/action-bar";
    import { ClassAttributes, NativeScriptAttributes } from "react";
    interface IntrinsicElements {
        actionBar: ClassAttributes<ActionBar>
          & NativeScriptAttributes<ActionBar>
    }
}

However, this introduces another compilation error:

Import declarations in a namespace cannot reference a module

... not to mention hundreds of other resulting compiler errors that I'd rather not dig into.
Known issue?
I found this seemingly related issue: https://github.com/Microsoft/TypeScript/issues/4166

Our current answer today is "Move your stuff to another .d.ts file". This is an OK workaround, but not great. The real sticker is when there's a type defined inside an external module -- it's impossible to use those types to augment a global interface, even though this is a thing that actually happens. It gets even trickier because this encourages people to move types into the global namespace when they didn't want to in the first place, exacerbating the problem.

I don't really know what is meant by "Move your stuff to another .d.ts file". I began trying to declare everything I needed in global scope (essentially building a lib.dom.d.ts for NativeScript), but NativeScript is simply too big to take that approach – and it would be a nightmare if they ever updated their typings.
Question
How can I augment React's typings with references to external modules like tns-core-modules?
It seems like my initial approach would work if only TypeScript would expose that file to all other files within my library (and any projects that consume it), but no matter my tsconfig.json settings, the declarations file is only noticed by other modules if it is a script rather than a module.

A: Have you tried declare global similar to the below?
// react-nativescript/index.d.ts
import { ActionBar } from "tns-core-modules/ui/action-bar/action-bar";

declare global {
  declare namespace JSX {
    interface IntrinsicElements {
      actionBar: React.ClassAttributes<ActionBar>
        & React.NativeScriptAttributes<ActionBar>
    }
  }

  declare namespace React {
    interface NativeScriptAttributes<T> {
      className?: string;
      children?: ReactNode;
      onClick?: MouseEventHandler<T>;
    }

  // Omitting DetailedNativeScriptFactory<P, T> for brevity.
    interface ReactNativeScript {
      actionBar: DetailedNativeScriptFactory<
        NativeScriptAttributes<ActionBar>,
        ActionBar
      >,
    }
  }
}

export {} // this is needed for the file to be considered a module
// so that it isn't erased during compilation

Note that declare may or may not be required on some or all type/interface/namespace declarations. It could be required, given the TS docs on merging namespaces. But it might not be required, given the TS docs on global augmentation.


text:
Q: Angular 5 Material Paginator resets to negative values when updating pageIndex I'm using an Angular Material data table to display a list of objects that can be added to. When an object is added to the data source, the page index breaks and shows a negative. The only way I've found to fix this is to reset the page index of the material paginator to 0. However, any further changes to the paginator result in a pageIndex of -1 or a broken paginator. Here is an example:
I first set new data in the Angular Material data source like so:
private refreshTable() {
    // first we update the length of the paginator with the new length of the datasource data to ensure parity
    this.paginator.length = this.dataSource.data.length;

    // next we get the current page number so we can return to it later.
    let currentPage = this.paginator.pageIndex;

    this.tempSubscription2 = this.rrService.getSearchResults(this.searchEnv.outputPayload(true, true)).subscribe(
        (data: any) => {
            this.extractSBRs(data);
            this.dataSource.data = [];
            // Here is where the dataSource is reset...
            this.dataSource.data = this.sbrs;

            this.paginator.length = this.dataSource.data.length;
            this.paginator.pageIndex = 0;
            this.dataSource.paginator = this.paginator;
            console.log('made it this far');

            if (this.dataSource.paginator.pageIndex < currentPage) {
                console.log('need to return to the current page');
                this.paginator.pageIndex = currentPage;
                this.paginator._pageIndex = currentPage;
                this.dataSource.paginator.pageIndex = currentPage;
                this.dataSource.paginator._pageIndex = currentPage;

            }
        },
        (err: any) => {
        },
        () => {
        }
    );
}

When this code is run, updates from the first page are fine because the this.paginator.pageIndex is being set to 0. Once an element is added on a page greater than zero, the table shows the first page, the paginator has a pageIndex of -1 and the paginator in the UI looks like this:

Notice the negative index -9 - 0. There seem to be very few examples of updating an Angular Material Data Table and even fewer that have further notes about how updating them effects the Angular Material paginator. How can I get the paginator to go to a pageIndex other than 0 without getting the negative index issue?
I've tried updating just the this.paginator which is grabbed via ViewChild() per the recommendation here. I've also tried updating the dataSource.paginator which you can see in the code above.
Here are my imports:
import {
AfterContentInit, AfterViewInit, ApplicationRef, ChangeDetectorRef,
Component, OnDestroy, OnInit,
    ViewChild
} from '@angular/core';
import { SearchEnvironment } from "../classes/search-environment";
import { SearchFilterDropdown } from "../classes/search-filter-dropdown";
import { ActivatedRoute, Router } from "@angular/router";
import {MatTableDataSource, MatPaginator, MatDialog, MatTable, MatSnackBar} from "@angular/material";
import { RemoteRetrievalService } from "../core/services/remote-retrieval.service";
import { Observable } from "rxjs/Observable";

How can I get the desired paginator behavior of returning to the currentPage index without causing a negative index in the paginator.pageIndex value or the bad user experience of the negative values in the item(s) range?

A: It is strange how they build some of these components. I am not sure my solution will work, but based upon what I've read in the issue it seems that they can not handle both a length change and pageIndex change in the same digest cycle.
So I would recommend changing the length first, and then later changing the pageIndex.
 this.paginator.length = this.dataSource.data.length;
 this.paginator.pageIndex = 0;
 this.dataSource.paginator = this.paginator;
 console.log('made it this far');

The above sets the values we know will work on the component, and the next part uses window.setTimeout to run the next set of changes after the component has had a chance to update itself.
 if (this.dataSource.paginator.pageIndex < currentPage) {
     window.setTimeout(()=>{
         this.zone.run(()=>{
            console.log('need to return to the current page');
            this.paginator.pageIndex = currentPage;
            this.paginator._pageIndex = currentPage;
            this.dataSource.paginator.pageIndex = currentPage;
            this.dataSource.paginator._pageIndex = currentPage;
            // EDIT: You must then set the datasource paginator back to the newly edited paginator.
            this.dataSource.paginator = this.paginator;
         });
     });
 }

You will need to inject NgZone to run the code inside Angular's zones (which is for error handling). It's just a good practice when using window.setTimeout.
Keep in mind that window doesn't exist in Angular Universal incase you want to later to do server side rendering, but that's a different issue.


text:
Q: Running Commands from C# Worst topic but can't really say much more.
Thing is, i am trying to run a certain command from cmd, if i do this normally in windows, it's flawless, in C# it doesn't work, even though it's the exact same string.
Here is how i do it:
        Process cwebp = new Process();
        cwebp.StartInfo.FileName=("cmd.exe");
       cwebp.StartInfo.Arguments = Settings.EncoderSettings[0];
       cwebp.Start();

And well arguments is pretty much anything, for example:
opusenc --bitrate 100 input.wav output.opus
Is there any fundamental issue here?
Been searching a lot and can't find any information, everything says (use Arguments), and i do, and it doesn't work as expected.

A: Additionally to Steve's answer, you can start your command directly, without using cmd in the first place:
Process.Start("opusenc", "--bitrate 100 input.wav output.opus");

A: To execute a shell command you need to add the parameter /C (/K) on the arguments line
 Process cwebp = new Process();
 cwebp.StartInfo.FileName=("cmd.exe");
 cwebp.StartInfo.Arguments = "/C " + Settings.EncoderSettings[0];
 cwebp.Start();

Without it, the Process.Start method starts the cmd command processor, but, this one, exits immediately without processing the passed arguments.


text:
Q: How to draw an image on canvas as if it has the "background-size: cover" and "background-position: 100% 100%" property applied to it I know I can draw the whole image on canvas using:
ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height);

but this will mess up the image on certain screens. I want to draw the image as it would have appeared on a div with background-size: cover applied. Is it possible at all?
This question answered the background-size: cover part. I want to figure out how to simulate background-position: 100% 100% now. In other words, I want to draw the bottom right of image in the bottom right part of canvas. How can I do that?


text:
Q: java groovy split array for csv output Aim is to create a groovy script that will read from the database and export to a csv file.  I am using the apache commons csv writer. I have been working with this javacode geeks - apache commons tutorial..
This works
I have put here to help explain what I am trying to achieve.
fileWriter = new FileWriter(fileName);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecord(FILE_HEADER);

//Write a new student object list to the CSV file
for (Student student : students) {
   List studentDataRecord = new ArrayList();
   studentDataRecord.add(String.valueOf(student.getId()));
   studentDataRecord.add(student.getFirstName());
   studentDataRecord.add(student.getLastName());

   csvFilePrinter.printRecord(studentDataRecord);
}

What Im trying to do In groovy/java.
I have created a groovy script calls the DB ok.  I can make it iterate and loop over fine and prints the rows.  However I dont want to manually write all the 'student.getFirstName' student.getLastName etc calls. If I modify the query in the future it makes more work -- I just want to export it straight to csv having only modified the query.
Something like this is what I have so far..  I am unsure of the syntax etc.
#!/usr/bin/env groovy
import groovy.sql.Sql
import org.apache.commons.csv.CSVFormat

CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
fileWriter = new FileWriter(fileName);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecord(FILE_HEADER);

sql.eachRow("Select field1, field2, field3, etc FROM Student") {
    for( keyIndex  k ){
        List studentDataRecord = new ArrayList();
        studentDataRecord.add(k.value)
    }
    csvFilePrinter.printRecord(studentDataRecord);
}

A: If you are iterating with eachRow, each row is a groovy.sql.GroovyResultSet (strictly speaking, a groovy.sql.GroovyResultSetProxy). Since it does not implement Map interface, you cannot use collect, etc.
Therefore, there are several options:
Get each field by name (the one you want to avoid)
sql.eachRow("select field1, field2, field3, etc from student") { row ->
   csvFilePrinter.printRecord([row.field1, row.field2, row.field3, ...])
}

Get each field by number (I guess you don't like this either)
sql.eachRow("select field1, field2, field3, etc from student") { row ->
   csvFilePrinter.printRecord([row[0], row[1], row[2], ...])
}

Use the underlying ResultSet: get the number of colums and then build a List
sql.eachRow("select field1, field2, field3, etc from student") { row ->
    def record = []
    row.getMetaData().columnCount.times { record << row[it] }
    csvFilePrinter.printRecord(record)
}

Use the rows() method, that returns a List<GroovyRowResult> where GroovyRowResult implements Map and then you can apply collect:
def rows = sql.rows('select * from student').each { row ->
    csvFilePrinter.printRecord(row.collect { entry -> entry.value })
}


text:
Q: Checking if a matroid is binary(Detecting $U^2_4$ minor in a matroid) I am wondering what is the (computationally) best way to tell if a matroid of size $n$ and rank $r$ is binary(or whether it has a $U^2_4$ minor) given either one of these:
1) An independence oracle
2) Its rank vector
3) A basis oracle
I want to implement $U^2_4$/binary detection(Most likely given a basis oracle which will be in form of the reverse-lexicographic encoding in [3]).
What I know(or what I think I know):
1) can't be solved by asking polynomial number of questions to the oracle which is due to Seymour[1].
2) and 3) One can write a brute force implementation which would compute and check all minors of size 4.
Also, I considered following ideas:
a) For problem (3), given a matroid $M$ one can start with an $r\times r$ Identity matrix and assign its columns to elements of some basis say $B^*$. Now we expand this matrix by adding columns that correspond to $e\in E(M)\setminus B^*$. We now fill r entries in this new column with $0$ or $1$. For filling $i^{th}$ entry in the column, we ask the basis oracle if $(B^*\setminus i)\cup e$ is a basis. If it is, we put a $1$ in that entry, $0$ otherwise. When we are done constructing all $n-r$ columns this way we have the only binary matrix that correctly reflects if an $r$-subset S of $E(M)$ with $|S\cap B^*|=r-1$ is a basis or not.  As for other $r$-subsets, we can test their rank in the matrix and ask basis oracle whether each of them is a basis. If the two results don't match for any $r$-subset, we conclude that the matroid is not binary representable. This way seems better than the brute-force 'compute and check all minors' in terms of complexity.
b) One can compute all $r-1$ flats of $M$ from bases(Using an algorithm again due to Seymour [2]). Then compute all $r-2$ flats. Then use scum theorem(i.e. check if any $r-2$ flat is contained in more than three $r-1$ flats).
EDIT
Some extra info: Here is what I am really trying to do: Much on the lines of [3] and [4] I am trying to enumerate(list) matroids, but only the binary ones using single element extensions(by simply not extending any non-binary matroids produced). This list(scalar binary codes) and more lists created after pairing of bits(vector binary codes)  are then to be used for computer assisted achievability proofs of rate regions of multisource network coding problems.  Matsumoto [3] was very generous to share his c++ code which I am parallelizing using OpenMPI(My C $U^2_4$ check which is currently brute-force seamlessly goes into this scheme). Since the binary matroids are so less in number[5] compared to all matroids, I am expecting to go much farther. I have to care about computational efficiency because there are millions of matroids to be tested just at ground set size 14.
Given all this, although I appreciate and have been following sage-matroid library, I am not much of a Python guy I am not very sure how sage's code will go into my OpenMPI-C++ code(well, I won't exclude the possibility of existence of some hack that will let me do this). Hence, what I am looking for is pointers to best algorithms around which Dr. Royle's answer does tell.
[1] Seymour, P. D.; Walton, P. N. (1981), "Detecting matroid minors", Journal of the London Mathematical Society, Second Series 23 (2): 193–203
[2] P.D. Seymour, A Note on Hyperplane Generation, Journal of Combinatorial Theory, Series B, Volume 61, Issue 1, May 1994, Pages 88-91
[3] Yoshitake Matsumoto, Sonoko Moriyama, Hiroshi Imai, and David Bremner. Matroid enumeration for incidence geometry. Discrete & Computational Geometry, 47(1):17–43, 2012
[4] Dillon Mayhew and Gordon F. Royle. Matroids with nine elements. Journal of Combinatorial Theory, Series B, 98(2):415 – 431, 2008
[5] Marcel Wild: The Asymptotic Number of Binary Codes and Binary Matroids. SIAM J. Discrete Math. 19(3): 691-699 (2005)

A: This is actually implemented (as well as a host of other features) in the latest version of Sage.  This is the culmination of 2 and a half years of hard work by Stefan van Zwam and Rudi Pendavingh, together with help from Michael Welsh and Gordon Royle.  See this page from the Matroid Union Blog to get started.  For your particular question, it is easy to construct $U_{2,4}$ via the Sage command
Sage: N = matroids.Uniform(2,4)
To test if an input matroid M has an N-minor you can run the Sage command
Sage: M.has_minor(N)
As you can see, Stefan and Rudi have worked hard to make the syntax easy to understand.   Of course this is a very generic approach, so I am not sure how optimal it will be.  Feel free to contact Stefan if you have any questions, or (better yet) want to develop for the package (Sage is open-source).


text:
Q: infinispan CLI cache does not liist all cache names I am trying to use infinispan CLI to remove a key from cache.
Once i connect I get the prompt with the default cache manager
As per the documentation , when I type cache and tab out , the list  of cache names will be printed. But It does not happen . I get the below printed in the console.
org.infinispan.cli.interpreter.Interpreter.createSessionId()
None of the commands are working as per the documentation. May  be i am missing some steps . Has any one faced such issue ?
I am using infinispan 5.2
Thanks
lives


text:
Q: Copy (or USE) data from two tables in different databases
Possible Duplicate:
Possible to perform cross-database queries with postgres?

I don-t know how to use one table from one database and second table from another databse at the same time or copy data from table in one database to table from another databse.
I tried following query:
select * into NewTable from existingdb.dbo.existingTable;
But it doesnt't work.

A: In existing table name, specify the full path. that's database name and table table to be copied. In New table also specify the database name and table name or make sure the console is in same database.
Also verify both the tables have same table structure.

A: What is the exact error message? It would not work if NewTable already exists. Then you should type insert into NewTable select * from ExistingDb.dbo.ExistingTable.


text:
Q: ¿Puedo usar una base de datos de SQL Server en mi proyecto de RAILS 4 en ubuntu? Quiero desarrollar un sitio web en RAILS 4 pero necesariamente debo de usar una base de datos existente de SQL Server, ¿sera posible usarla en ubuntu o necesariamente debo de programar en Windows?

A: SQL Server no lo puedes instalar en ubuntu, de todas formas si tienes una base existente de SQL Server ya funcionando en algun servidor, puedes hacer tu desarrollo en RAILS y conectarte a esta base SQL Server, o puede armarte un entorno separado con Windows de S.O. y SQL Server instalado para tu ambiente de desarrollo. Y tu sitio web en RAILS lo seguirias desarrollando en tu maquina con Ubuntu.

A: Actualmente tus opciones son:

*

*Existe una versión de sql server para linux, pero aún está en desarrollo. Si quieres acceder a un preview de esta versión tienes que inscribirte en https://www.microsoft.com/en-us/server-cloud/sql-server-on-linux.aspx pero no te aseguro que sea estable del todo, tampoco que sea compatible con los drivers sql server para Ruby.

*Correr sql server en un equipo dedicado (OJO, aquí me refiero a una instancia de DESARROLLO, no una instancia con datos reales) y que tu aplicación rails se conecte a él. Para mi ésta es la mejor opción, sin embargo necesitas un equipo extra que corra la aplicación.

*virtualizar una máquina windows en tu ubuntu con virtualbox y ahí instalar SQL server. esta opción es la más barata, sin embargo alentará tu equipo de desarrollo considerablemente ya que tendrás 2 sistemas operativos corriendo.

*desarrollar la aplicación rails en windows. Esta es la opción más simple, sin embargo te espera un mar de incompatibilidades a medida que integres nuevas gemas a tu proyecto que no sean compatibles con windows.


text:
Q: Weird behaivour getting value from merged cell I've come across this behaivour in Excel. Given these cells:
        A         B         C         D
   |---------|---------|---------|---------|
 1 | merged cell text  | foo     | bar     |
   |---------|---------|---------|---------|
 2 |         |         |         |         |
   |---------|---------|---------|---------|

When Cell C1 is selected (foo), the following VBA statement returns an empty string:
Debug.Print Selection.Offset(0, -1).Range("A1").Value

This next VBA however returns the expected value (merged cell text):
Selection.Offset(0, -1).Select
Debug.Print Selection.Range("A1").Value

I can't for the life of my figure out why - surely as Offset returns a Range and Selection is also a Range, it's just breaking down the same behaivour over multiple lines, and getting different results. The behaivour does not occur when there are no merged cells.
Can anyone explain what's going on here?

A: This should be the reason:
Debug.Print Selection.Offset(0, -1).Range("A1").Value

Your current selection is C1, offset -1 column gives you B1.  You are trying to print A1's value while selecting B1, thus gives nothing.  Merged cell does not automatically cause both A1 and B1 being selected.
(you can test by printing B1's value instead).  However:
Selection.Offset(0, -1).Select
Debug.Print Selection.Range("A1").Value

selects the range B1 first, which when merged, cause it to select both A1 and B1 on a application level, thus able to print A1's value
Hope that's clear to you

A: if you want to read the value in a1 from anywhere of the mergedcell,
Debug.Print Range("anyCellFormMergedRange").cells(1,1).Value  'wich gets the value from the first cell of a bigger range (here A1:B1)

or
Debug.Print Range("anyCellFormMergedRange").MergeArea(1, 1).value 'wich gets the value from the first cell of a MERGED range (here A1:B1)
'for a small mergedcell like yours, a simple .mergearea(1) works too

you can change the range to anything you need (selection, .offset(x,y), activecell ...) wich are also ranges.
if you want to use the whole mergedCells (A1:B1), without using .select :
(from C1)
    Debug.Print selection.offset(0,-1).MergeArea.address

Also remember that comment, validation data, are also contained in the first cell of the range (A1 here).


text:
Q: Short story same as the "Lucy" movie I am trying to remember the name and the author of a short story that seems to have a similar plot to the Besson's movie "Lucy".
I read that stories more than 30 years ago: A scientist made an evolution experiment on a man and a woman. The man de-evolves to a beast and the woman evolves to have God-like power, having to fight against people trying to control her.
I remember having read classic "pulps" authors at that time.

Edit
I have browsed lot of novella descriptions. There is one that seems to match, "Research Alpha" - Van Vogt (1965).  It features an "evolution serum" and "big IQ levels". Unfortunately, I don't have the book at hand. If someone would check it that would be great.

Edit
This list has been submitted by Deepak

*

*Flowers for Algernon by Daniel Keyes

*The Dark Fields by Alan Glynn

*Understand by Ted Chiang.

A: The short story "Understand" that's in the book "Stories of Your Life and Others" by Ted Chiang follows a very similar premise.
A man in a coma is injected with an experimental drug called Hormone K which regenerates neurons and allows the subject to develop hyper intelligence which they can use to even influence other people's biological processes

A: You've pinpointed the correct story in the comments, so if you want to add your own answer I'll delete this. For now I'll answer in case anyone wants more information.
The story is called "Research Alpha" and was cowritten by Van Vogt and James H. Schmitz. It appeared in the anthology More than Superhuman, and also also appeared as a subplot in the novel Supermind. Van Vogt had a tendency to bolt together his short stories to make novels - not always with happy results.
Spoilers follow:
The underlying idea is that the Great Galactics have injected some of their own genes into the races they encounter, but during human evolution these genes have become unevenly distributed. The scientist Dr Gloge is working on a project called Point Omega Stimulation which aims to enhance human evolution. Gloge secretly injects two people, Barbara Ellington and Vincent Strather with the Omega serum. Barbara possesses an unusually favourable package of Great Galactic genes and the serum enhances these so she basically turns into a Great Galactic. In Vincent the serum enhances other genes and he becomes a goblin like figure - it's implied but not stated explicitly that he's become mentally subnormal.
In Supermind it's made clear that this is a deliberate manipulation by the Great Galactic William Leigh. He had detected the favourable genes in Barbara and wanted her to attain her full potential so he can have her as a companion. Vincent was included in the experiment to demonstrate to mankind that the process would mostly fail so it shouldn't be used routinely. As far as I recall this aspect of the plot is absent from the original short story.
Vincent recovers, so it's a happy ending :-)


text:
Q: Is it possible to send a Whatsapp message from Mathematica? Just as the question reads.
The only way I could think of this working is if one could interface with the Whatsapp web app.
The motivation is to simply alert me when simulations or batch routines have finished.