text:
Q: Sorting a reference to an array of rows where each row is stored as a hash I'm trying to sort the following data structure in Perl, by location_id.
my $employees = $dbh->selectall_arrayref(qq[
    SELECT name, type, code, emp_cat_id,
           percentage, location_id
    FROM table_1
],{ Slice => {} });

for my $row (@$employees) {
   push @{
      $args->{employees}{ $row->{emp_cat_id} }
   }, $row;
}

Example:
123 => [
   {
      percentage  => 0.25,
      code        => "XYZ",
      name        => "John Doe",
      type        => "pt",
      location_id => 001,
      emp_cat_id  => 123

   }
],
555 => [
   {
      percentage  => 0.50,
      code        => "ZZZ"
      name        => "Chris Cringle",
      type        => "ft",
      location_id => 007,
      emp_cat_id  => 555

   },
   {
      percentage  => 0.25,
      code        => "XXX"
      name        => "Tom Thompson",
      type        => "pt",
      location_id => 002,
      emp_cat_id  => 555

   }
]

For every emp_cat_id, I need the structure to have the location_ids in asc order.
I've tried the following, but I get "useless use of sort in void context at line #" or "useless use of sort in scalar context at line #" errors.
$args->{employees} = sort {
   $a->{location_id} <=> $b->{location_id}
} $args->{employees};

Any help understanding the sort is appreciated!

A: The problem is that you are sorting the array(ref) at emp_cat_id of 555, then of 123, and so need to dereference for sorting those  arrayrefs. So
foreach my $id (keys $args->{employees}) {
    @{ $args->{employees}{$id} } = sort {
            $a->{location_id} <=> $b->{location_id}
        }
        @{ $args->{employees}{$id} }
}

(tested with the structure shown in the question, omitted here)†
Doing anything like this loses 007 into 7. This is of course possible to fix, let me know if it matters.
If you really have only the key employees then consider extracting the $args->{employees} hashref and working with that. It'll be way easier
use Storable qw(dclone);

my $employees = dclone $args->{employees};  # need deep copy

† Oh well, here's the whole thing
use warnings;
use strict;
use feature 'say';
use Data::Dump qw(dd);

my $args = {
    employees => {
        123 => [
            {
                percentage  => 0.25,
                code        => "XYZ",
                name        => "John Doe",
                type        => "pt",
                location_id => 001,
                emp_cat_id  => 123
            }
        ],
        555 => [
            {
                percentage  => 0.50,
                code        => "ZZZ",
                name        => "Chris Cringle",
                type        => "ft",
                location_id => 007,
                emp_cat_id  => 555

            },
            {
                percentage  => 0.25,
                code        => "XXX",
                name        => "Tom Thompson",
                type        => "pt",
                location_id => 002,
                emp_cat_id  => 555

            }
        ]
    }
};

foreach my $id (keys $args->{employees}) {
    @{ $args->{employees}{$id} } = sort {
            $a->{location_id} <=> $b->{location_id}
        }
        @{ $args->{employees}{$id} }
}

dd $args;

A: So, you have a hashref where each element is an arrayref of hashrefs that should be sorted based on a key of that inside hashref?
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;

my $hashref = {
    123 => [
        {
            percentage  => 0.25,
            code        => "XYZ",
            name        => "John Doe",
            type        => "pt",
            location_id => 001,
            emp_cat_id  => 123
        }
        ],
    555 => [
        {
            percentage  => 0.50,
            code        => "ZZZ",
            name        => "Chris Cringle",
            type        => "ft",
            location_id => 007,
            emp_cat_id  => 555
        },
        {
            percentage  => 0.25,
            code        => "XXX",
            name        => "Tom Thompson",
            type        => "pt",
            location_id => 002,
            emp_cat_id  => 555
        }
        ]
};

foreach my $arrayref (values %$hashref) {
    @$arrayref = sort { $a->{location_id} <=> $b->{location_id} } @$arrayref;
}

print Dumper($hashref);

The important part you're missing is in dereferencing the arrayrefs. @$arrayref instead of just $arrayref.


text:
Q: Project Euler 11 Pyth0n I am trying to solve this puzzle but I cannot work out the logic that works for the example yet breaks for the solution!
I think it has something to do with negative numbers for the directional list of tuples.
Any advice would be most appreciated.!
Here is the code I am having trouble with :)
How can I find the greatest product of four adjacent numbers in the same direction. as described below?
# Largest product in a grid
# Problem 11
# In the 20×20 grid below, four numbers along a diagonal line have been marked in red.

# The product of these numbers is 26 × 63 × 78 × 14 = 1788696.

# What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?

grid = [
    [8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8],
    [49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0],
    [81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65],
    [52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91],
    [22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],
    [24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],
    [32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],
    [67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21],
    [24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],
    [21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95],
    [78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92],
    [16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57],
    [86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],
    [19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40],
    [4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],
    [88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],
    [4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36],
    [20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16],
    [20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54],
    [1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48]
]

straight = [(1,0), (0,1), (-1,0), (0,-1)]
diagonal = [(1,1), (-1,1), (1,-1), (-1,-1)]

def prod(lst):
    """ returns the product of a list """
    p = 1
    for i in lst:
        if i != 0: # ignore zeros..
            p *= i
    return p

def traverse(start, steps, grid, direction):
    """ Input a starting point and number of steps to Traverse """
    x, y = start[0]-1,  start[1]-1
    print(x, y)
    j, k = direction[0], direction[1]
    print(j, k)
    try:
        for i in range(steps):
            print(grid[x+i+j][y+i+k])
            yield grid[x+i+j][y+i+k]
    except IndexError:
        pass

print()
# Example
d = traverse((6, 8), 4, grid, (1, 1))
p = prod([x for x in d])
print('26 x 63 x 78 x 14 = ', 1788696, p == 1788696, '\nActual:', p) # [26, 63, 78, 14] 1788696
print()
#Answer
d = traverse((15, 3), 4, grid, (1, -1))
p = prod([x for x in d])
print('87 x 97 x 94 x 89 = ', 70600674, p == 70600674, '\nActual:', p) # [87, 97, 94, 89] 70600674

A: I know this is a late entry but I did this using numpy array. Here's the code:
import numpy as np
s = '''08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48'''

ss = np.array([[int(x) for x in s.split()][i:i+20] for i in range(0,400,20)]).reshape(20, 20)

#process 4 elements to right, down, left-down-diagonal, right-down-diagonal

#check right: row: 1 thru 20 (index 0:19); columns: 1 thru 16 (index 0:15)
mr = max(np.prod(ss[i,j:j+4]) for i in range(20) for j in range(16))

#check down: row: 1 thru 16 (index 0:15); columns: 1 thru 20 (index 0:19)
mc = max(np.prod(ss[i:i+4,j]) for i in range(16) for j in range(20))

#check right-down-diagonal: row: 1 thru 16 (index 0:15); columns: 1 thru 16 (index 0:15). row,col increments by 1 to go right-down-diagonal
mx = max(np.prod([ss[i+k,j+k] for k in range(4)]) for i in range(16) for j in range(16))

#check left-down-diagonal: row: 1 thru 20 (index 0:19); columns: 4 thru 20 (index 3:19). row increments by 1 and col decrements by 1 to go right-down-diagonal
my = max(np.prod([ss[i+k,j-k] for k in range(4)]) for i in range(16) for j in range(3,20))

ans = max([mr,mc,mx,my])

print (ans)

A: You were pretty close. Here's the edited code that works:
def traverse(start, steps, grid, direction):
    """ Input a starting point and number of steps to Traverse """
    x, y = start[0],  start[1]  # EDIT: remove "- 1"
    print(x, y)
    j, k = direction[0], direction[1]
    print(j, k)
    try:
        for i in range(steps):
            print(grid[x+i*j][y+i*k])  # EDIT: i*j instead of i+j
            yield grid[x+i*j][y+i*k]   # EDIT: i*j instead of i+j
    except IndexError:
        pass

print()
# Example
d = traverse((6, 8), 4, grid, (1, 1))
p = prod([x for x in d])
print('26 x 63 x 78 x 14 = ', 1788696, p == 1788696, '\nActual:', p) # [26, 63, 78, 14] 1788696
print()
#Answer
d = traverse((15, 3), 4, grid, (-1, 1))  # EDIT: fix direction
p = prod([x for x in d])
print('87 x 97 x 94 x 89 = ', 70600674, p == 70600674, '\nActual:', p) # [87, 97, 94, 89] 70600674

I commented all edits I did to your code to make it work. Please comment below if you have any questions.

A: data = '08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48'

number = (data.split())

Get product of four adjacent numbers in left to right direction
def leftToRight(list, diff):
    first = 0
    last = len(list) - diff
    product = []

    for x in range(first, last):
        multi = int(list[x]) * int(list[x + 1]) * int(list[x + 2]) * int(list[x + 3])
        product.append(multi)
    return product

Get product of four adjacent numbers in top to bottom direction
def topToDown(list, diff):
    first = 0
    last = len(list) - (diff * 20)
    product = []

    for x in range(first, last):
        multi = int(list[x]) * int(list[x + 20]) * int(list[x + 40]) * int(list[x + 60])
        product.append(multi)
    return product

Get product of four adjacent numbers in left Diagonal to right Diagonal direction
def rightDiagonal(list, diff):
    first = 0
    last = len(list) - (diff * 20)
    product = []

    for x in range(first, last):
        if x % 20 < 17:
            # print((list[x]), int(list[x + 21]), int(list[x + 42]), int(list[x + 63]))
            multi = int(list[x]) * int(list[x + 21]) * int(list[x + 42]) * int(list[x + 63])
            product.append(multi)
    return product

Get product of four adjacent numbers in right Diagonal to left Diagonal direction
def leftDiagonal(list, diff):
    first = 0
    last = len(list) - (diff * 20)
    product = []

    for x in range(first, last):
        if x % 20 > 2:
            # print((list[x]), int(list[x + 19]), int(list[x + 38]), int(list[x + 57]))
            multi = int(list[x]) * int(list[x + 19]) * int(list[x + 38]) * int(list[x + 57])
            product.append(multi)
    return product

Get greatest product
new_list = leftToRight(number, 3) + topToDown(number, 3) + rightDiagonal(number, 3) + leftDiagonal(number, 3)
sort = list(reversed(sorted(new_list)))
highest = sort[0]
print(highest)

A: I spend some time and made it myself which is more readable and beginner friendly. See comments for more info
grid_text = """08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48"""

grid = list(map(lambda v: v.split(' '), grid_text.split('\n'))) # make array of array which contain each value

def euler11(grid, k):
  def product(n):
    aggregate = 1
    for i in n:
        aggregate *= int(i)
    return aggregate

  arr = [] # for all values obtained by some of 'k' values in any axis

  for i,row in enumerate(grid):
    # horizontal traverse and calculation
    for i2,_ in enumerate(row):
      if i2 < len(row) - k+1:
        arr.append(product(row[i2: i2 + k]))
    # vertical traverse and calculation
    for i2,_ in enumerate(row):
      if i < len(grid) - k+1:
        values = [grid[i][i2], grid[i+1][i2], grid[i+2][i2], grid[i+3][i2]]
        arr.append(product(values))
    # forward-diagonal traverse and calculation
    for i2,_ in enumerate(row):
      if (i < len(grid) - k+1) and (i2 < len(row) - k+1):
        values = [grid[i][i2], grid[i+1][i2+1], grid[i+2][i2+2], grid[i+3][i2+3]]
        arr.append(product(values))
    # reverse-diagonal traverse and calculation
    for i2,_ in enumerate(row):
      if (i < len(grid) - k+1) and (i2 > k - 2):
        values = [grid[i][i2], grid[i+1][i2-1], grid[i+2][i2-2], grid[i+3][i2-3]]
        arr.append(product(values))

  return max(arr)

print(euler11(grid,4))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding solutions to $h(j)=15+j^2 \mod 17, j \in \mathbb{N}$ I have a function such as this:
$$h(j)=15+j^2 \mod 17, j \in \mathbb{N}$$
When $h(j)=7$ I know that there is a solution to this as: $h(3)=15+(3)^2 \mod{17}=7$
How can I prove that there no solutions to this for $h(j)=4$?

A: If $h(j)=4$, then this means
\begin{align*}
15+j^2 & \equiv 4 \pmod{17}\\
j^2 & \equiv 6 \pmod{17}
\end{align*}
But if you consider the squares mod $17$ you get $\{0^2,1^2,2^2, \ldots , 8^2\}=\{0,1,4,9,16,8,2,15,13\}$. This means $6$ has no square root hence the equation has no solution.

A: We have
$$
h(j)=4\iff j^2\equiv4-15\equiv17-11=6\pmod{17}
$$
Using the Jacobi Symbol and its properties we then have
$$
\begin{align}
\left(\frac{6}{17}\right)&=\left(\frac{2}{17}\right)\left(\frac{3}{17}\right)\\
&=\left(\frac{3}{17}\right)\\
&=\left(\frac{17}{3}\right)\\
&=\left(\frac{2}{3}\right)\\
&=-1
\end{align}
$$
telling that $6$ is a quadratic non-residue modulo $17$. So no solution exists.

Here is a summary of the properties, I have used above:

*

*If $n$ is odd and $a\equiv b\pmod n$, then $$\left(\frac{a}{n}\right)=\left(\frac{b}{n}\right)$$

*If $n$ is odd, then $$\left(\frac{2}{n}\right)=\begin{cases}1&\quad\text{if }n\equiv\pm1\pmod8\\-1&\quad\text{if }n\equiv\pm3\pmod8\end{cases}$$

*If $n$ is odd and $a=2^kb$, then $$\left(\frac{a}{n}\right)=\left(\frac{2}{n}\right)^k\left(\frac{b}{n}\right)$$

*If $a,n$ are odd, then $$\left(\frac{a}{n}\right)=\begin{cases}-\left(\frac{n}{a}\right)&\quad\text{if }a\equiv n\equiv3\pmod4\\\left(\frac{n}{a}\right)&\quad\text{otherwise}\end{cases}$$

A: $h(j) = 4\to 15+j^2 = 4\pmod {17} \to 15+j^2-4 = 17k \to 11+j^2=17k$. Best way is the check case by case $11+1^2, 11+2^2,\cdots , 11+16^2 \pmod {17}$, and find out yourself that none of them is $0\pmod {17}$

A: Hint $\,\ {\rm mod}\ 17\!:\,\ j^{\,\large 2}\equiv 6\,\overset{\Large (\ \ )^{8}\!\!}\Rightarrow 1\equiv j^{\,\large 16}\equiv 6^{\large 8} \equiv 2^{\large 4}\,\Rightarrow\!\Leftarrow$


text:
Q: The ISP keeps changing my modem DNS address The ISP of mine in (Iran) keeps changing my DNS address on a daily basis, my modem goes on/off and then DNS changed to some other address:
5.200.200.200
217.218.127.127

How can I set the Google DNS and prevent the ISP from changing that, the modem is D-link DSL-2750U.

A: The simple answer is: don't use the DNS provided by the modem. Most OS-es are able to force a static DNS server. Of course how it is done depends on the OS.
An alternative is to put your own SOHO-router between your network and the ISP's. You will be able to control your own SOHO router completely.


text:
Q: Using Euclidean Algorithm to find GCD of polynomials in $\mathbb{Q}[x]$ I had to find the $\gcd$ of the following polynomials in $\mathbb{Q}[x]$ using the Euclidean algorithm, and I wanted to check that I had done so correctly, since my notes on the subject from class are a little questionable.

*

*$x^{3}-1$ and $x^{2}+x-2$

My attempt:
Using polynomial long division to divide $y:=x^{3}-1$ by $x:=x^{2}+x-2$, on the first step, I obtained
  $$ x^{3}-1 = (x-1)(x^{2}+x-2)+(3x-3) $$
  where the remainder $r= 3x-3$
Now, on the second step, replace $y$ with $r$ to obtain $y:=3x-3$, $x:=x^{2}+x-2$, and swap $x$ and $y$ so that now $y:=x^{2}+x-2$ and $x:=3x-3$.
Using polynomial long division to divide $y$ by $x$, I obtain that
  $$\displaystyle x^{2}+x-2 = \left( \frac{1}{3}x+\frac{2}{3}\right)(3x-3) + 0 $$
And so now that $r=0$,
  $$\mathbf{\gcd(x^{2}+x-2,\, x^{3}-1) = \gcd(3x-3,\, x^{2}+x-2)} = 3x-3$$

*$x^{4}+1$ and $x+1$

My attempt:
Using polynomial long division to divide $y:=x^{4}+1$ by $x:=x+1$, on the first step, I obtained
  $$ x^{4}+1 = (x+1)(x^{3}-x^{2}+x-1)+2 $$
  where the remainder $r= 2$
Now, on the second step, replace $y$ with $r$ to obtain $y:=2$, $x:=x+1$, and swap $x$ and $y$ so that now $y:=x+1$ and $x:=2$.
Using polynomial long division to divide $y$ by $x$, I obtain that
  $$\displaystyle x+1 = \left( \frac{1}{2}x+\frac{1}{2}\right)(2) + 0 $$
And so now that $r=0$,
  $$\mathbf{\gcd(x^{4}+1,\, x+1) = \gcd(2,\, x+1} )= 2$$
Since $2$ is a unit in $\mathbb{Q}$, this means that $x^{4}+1$ and $x+1$ are relatively prime in $\mathbb{Q}[x]$

Did I do these correctly?
For the second one, especially, I wasn't sure if that actually meant that the two polynomials were relatively prime in $\mathbb{Q}[x]$, because my notes didn't say anything about that, but it seemed to make sense.
Thank you ahead of time.


text:
Q: Angular How to easier maintain build in i18n translations We use the build in i18n module for angular.
I successfully generated source file for my original lang (en). Then I copied the source file and created another file with (es) translation.
It is easy to regenerate source file. But the problem is that it is very painful to update es localization file. I sync changes manually
For example: even if I change a row of the string in html/ts after the source regeneration it specifies that new row number. So I need then manually go to my ES file and update this row here too. But eventually it happens like that: I edit/add new/change location of plenty of the strings, so that regenerated source file has a lot of changes. And it becomes just easier to manually create ES file again and paste translations in it.
Just in case. This is how the difference between files look every time:

Is there any good solution for developers to easily maintain other locale files when original file changes?


text:
Q: How to create a server url for local file to provide download on the frontend? I have a local file on the disk, so my purpose is to make a url for that file on local server(like https://localhost:8080/xxx), whatever make the url on backend and frontend. And then I can provide download with that url.
I was trying to do that on the frontend, but since javascript cannot access to the local file system, I guess I might only can do it on backend?

Or is there anyway I can directly post the local file as byte[] from backend to frontend with REST API? I tried to use Response to contain the file on backend, but I might did it wrong somehow it cannot be received on frontend.

Please give me some advices to achieve that, alternative solutions would be awesome, I would like to learn more. Thank you!

A: There is no magic way to do that. You can use any URL you want. In your service you can decide, what URL you want to resolve to what file.
If you already do that, then check following:

*

*Check if you set correct content type

*Check if you really send ally the bytes of the file

*If you expect that browser doesn't open the file in place but opens a save file dialog, check if you set header "Content-Disposition". See also hints here.


text:
Q: Issue tracking location on Apple Watch I have built an Apple Watch App which uses CLLocation to track the users location. The idea of the app is for it to work using the built in GPS and not need the phone.
When I run the watch app it prompts me to give the various permissions which have to be granted from the phone app.
If I do this and then start tracking on the watch I get an initial call to
- (void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error
which is quite normal, I just start tracking again. I then get a handful of calls to
- (void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray*)locations
But then it just stops receiving updates.
If I run a full track on the iPhone and then run the track on the Watch the tracking works fine.
Tests done:

*

*checked permissions for both workout and location are set correctly on the iPhone

*if on the track that is not receiving updates you deny permission to location services on the phone and then turn it back on again it again calls the two methods above a handful of times and then stops. So everything is staying in memory

*tested on a running app, 'Pear', and seemed to get the same bug, that is it doesn't track location on the watch on the first run.

I think it's most likely an Apple bug, but I'm hoping someone here can somehow point me in a direction that I may have missed.


text:
Q: SSL Termination on Ingress-Nginx Behind HA-Proxy Currently I'm learning Kubernetes.
It's running on my laptop VBox.
I plan to deploy it on 'real' network, but with verry limited public IP.
So all API service and Ingress-Nginx will be on private IP address (i.e: 192.168.x.y)
My question is: Can I do the SSL termination on ingress-nginx if it behind HA-Proxy that only reverse-proxying TCP?

Note : The line in red is the only physical ethernet network with Public IP Address
Sincerely
-bino-

A: ingress is more like an API gateway (reverse proxy) which routes the request to a specific backend service based on, for instance, the URL.
SSL Termination is part of reverse proxy. Encrypting the traffic between clients and servers protects it as it crosses a public network like the Internet. But decryption and encryption can be computationally expensive. By decrypting incoming requests and encrypting server responses, the reverse proxy frees up resources on backend servers which they can then devote to their main purpose, serving content.
Reverse proxy as a website's "public face." Its address is the one advertised for the website, and it sits at the edge of the site's network to accept requests from web browsers and mobile apps for the content hosted at the website.
For more information refer to this document.
HAProxy is a reverse proxy for TCP and HTTP applications. Users can make use of HAProxy to improve the performance of websites and applications by distributing their workloads. Performance improvements include minimized response times and increased throughput.
HAProxy Ingress Controller - It does all the heavy lifting when it comes to managing external traffic into a kubernetes cluster.


text:
Q: Does GCE work with distributions other than debian and RHEL? I see only debian and RHEL images listed... What if I want to run ubuntu 12.04 or something else?  Is there a way to bring up a debian instance and install ubuntu 12.04 on top of it and make my own image?

A: Since the General Availability launch, it is possible to use standard kernels with Compute Engine.
Paul Rashidi has posted detailed steps for creating a FreeBSD image. You should be able to create an Ubuntu image from scratch by following similar steps.
If you'd like to modify an existing image, here are detailed steps for creating a custom image.

A: For Ubuntu specifically, Canonical and Google now provide GCE images for Ubuntu.
You can find more information on how to spin up instances using these images in the GCE documentation.

A: Google offers images for Debian 7, CentOS 6, Red Hat Enterprise Linux 6 and SUSE Linux Enterprise Server 11. Windows Server 2008 R2 is coming soon
You can also build you own images


text:
Q: Gap appears in Longtable once copied into main document I created a longtable in a test file and made it work the way I want it. I then pasted that table in my main document, a two column book.
Although the longtable was looking good in my test document, once pasted in the book, a gap appeared on the first page of the table.
(see screen captures 1, 2, and 3: that's the whole longtable which should neatly fit on two pages, but now spreads over three pages, because of that gap).
After some tests to try and figure out what's going on, I ended up (as a test) pasting the exact same longtable after the first one (in the main book document), just to see what would happen. Lo and behold the second iteration of the table doesn't show the gap at all, and in fact looks as intended: a longtable spreading over two pages.
(see screen capture 4 and 5).
Why can't the first table work? Where is that gap coming from? How do I get rid of it?
Thank you.
Note: I'm pasting all the code (and only a portion of the table) from the test page, which is the same code that's used in the book, of course.
% PREAMBLE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\documentclass[oneside,centered,twocolumn]{book}
%\documentclass[a4paper,oneside,centered,twocolumn]{book}
\special{papersize=215.9mm,279.4mm}
%\usepackage[top=3cm, bottom=3.2cm, left=2.5cm, right=2.5cm]{geometry}
\usepackage[english]{babel}

\usepackage{tocloft} % Customization of TOC LOF LOT
\usepackage[table,xcdraw]{xcolor} % For shading in tables
%\usepackage{pdfcolmk} <==== not needed with xelatex
\usepackage{multirow}

%\usepackage{wallpaper}
\usepackage{blindtext}
\usepackage{showframe}

\usepackage{caption} % To change way captions are labelled
\usepackage{pdfpages}
\usepackage{ltablex}
\usepackage{nicefrac} % to write fractions
\usepackage{attrib} % For source of quotations
\usepackage{lettrine} % For NewThought formatting
\usepackage{array} % To define width of columns in long table
\usepackage{booktabs} % Nicer spacing in columns
\usepackage{siunitx} % To write Celsius, etc.
\usepackage{enumitem} % To create item lists

\usepackage{scrextend}
\usepackage{threeparttable} % For table notes + To allow footnote material to stay with the tabular environment
\usepackage{etoolbox} % To make table footnote font smaller
\usepackage{threeparttablex}
\appto\TPTnoteSettings{\footnotesize}
\usepackage{textcomp} % For Numero symbol
\usepackage{titlesec}
\usepackage{xcolor}
\usepackage[linguistics,edges]{forest}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{titling}
%\usepackage{newpxtext} % Font for document instead of obsolete Palatino
\usepackage{fancyhdr}
\usepackage{etoolbox}
\usepackage{fontspec}
\setmainfont{TeX Gyre Pagella} % Palatino clone

% To make TOC in two columns and List of Tables into one column.
\usepackage{multitoc}
\makeatletter
\renewcommand*{\@starttoc}[1]{%
    \ifthenelse{\equal{#1}{toc}}{%
        \ifnum\multicolumntoc>1
        \begin{multicols}{\multicolumntoc}%
            \@multitoc@starttoc{#1}%
        \end{multicols}%
        \else
        \@multitoc@starttoc{#1}%
        \fi}{}%
    \ifthenelse{\equal{#1}{lot}}{%
        \ifnum\multicolumnlot>1
        \begin{multicols}{\multicolumnlot}%
            \@multitoc@starttoc{#1}%
        \end{multicols}%
        \else
        \@multitoc@starttoc{#1}%
        \fi}{}%
    \ifthenelse{\equal{#1}{lof}}{%
        \ifnum\multicolumnlof>1
        \begin{multicols}{\multicolumnlof}%
            \@multitoc@starttoc{#1}%
        \end{multicols}%
        \else
        \@multitoc@starttoc{#1}%
        \fi}{}%
}
\makeatother
\renewcommand{\multicolumnlot}{1}

% CREATING INDEX AND GLOSSARY %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\onecolumn
\usepackage{imakeidx}
\usepackage[itemlayout=singlepar]{idxlayout}
%\makeindex[options=-s back-matter/index.ist]
%\twocolumn

%\usepackage{imakeidx}
%\indexsetup{othercode=\small}
\makeindex[program=makeindex,intoc=true,options={-s index.ist}]

\usepackage{hyperref} % Hyperlinks

\usepackage[toc,acronyms,automake,xindy]{glossaries}
\makeglossaries

% TO JUMP LINES IN TABLES see navy tables %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newcommand{\mysplit}[1]{%
    \begin{tabular}[t]{@{}l@{}}   %% remove [t] if you need vertical centered things.
        #1
    \end{tabular}
}

% DEFINING CHAPTER AND SECTION COLORS %%%%%%%%%%%%%%%%%%%%%%%

\definecolor{green}{HTML}{3f8854}
\definecolor{runeg}{HTML}{3d857c}
\definecolor{blue}{HTML}{3d587e}
\definecolor{runeo}{HTML}{b6732b}
\definecolor{runer}{HTML}{af1824}

% HEADER AND FOOTER STYLE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\pagestyle{fancy}
\fancyhf{}
\fancyhead[LE,RO]{\headingfont \leftmark}
%\fancyhead[RE,LO]{Guides and tutorials}
\fancyfoot[CE,CO]{\headingfont \thepage}
%\fancyfoot[LE,RO]{\thepage}

%\renewcommand{\headrulewidth}{2pt}
%\renewcommand{\footrulewidth}{1pt}

\makeatletter
\patchcmd{\f@nch@head}{\rlap}{\color{runeg}\rlap}{}{}
\patchcmd{\headrule}{\hrule}{\color{white}\hrule}{}{}
%\makeatother

% CHAPTER, SECTION, SUBSECTION STYLE %%%%%%%%%%%%%%%%%%%%%%%%

\newfontfamily\headingfont[]{Candara}
\titleformat{\chapter}[display]
{\bfseries\color{runeg}\filcenter\fontsize{35}{35}\headingfont} % Size of Chapter1&Chapter
{\huge\MakeUppercase\headingfont{\chaptertitlename} \thechapter}
{12pt}
{\tikz[remember picture,overlay]\node[inner sep=0pt] at ($(current page.north) +
    (0pt,-117pt)$) {\includegraphics[width=14cm]{chapterHead_10cm}};}
\titlespacing{\chapter}{0pt}{50mm}{42.5mm}
\titleformat*{\section}{\LARGE\color{runer}\headingfont}
\titleformat*{\subsection}{\Large\color{runeo}\headingfont}
\titleformat*{\subsubsection}{\large\color{runeo}\headingfont}
\renewcommand{\maketitlehooka}{\headingfont}

\renewcommand{\cfttoctitlefont}{\Huge\color{runeg}\headingfont} % tocloft <=====
\renewcommand{\cftlottitlefont}{\Huge\color{runeg}\headingfont} % tocloft <=====
\renewcommand{\cftchapfont}{\bfseries\color{runer}\headingfont} % tocloft <=====
\renewcommand{\cftsecfont}{\color{runeo}\headingfont} % tocloft <===============
\renewcommand{\cftsubsecfont}{\color{runeo}\headingfont} % tocloft <============
\renewcommand{\cftchappagefont}{\color{runeo}\headingfont} % tocloft <==========
\renewcommand{\cftsecpagefont}{\color{runeo}\headingfont} % tocloft <===========
\renewcommand{\cftsubsecpagefont}{\color{runeo}\headingfont} % tocloft <========
\renewcommand{\cftsubsubsecpagefont}{\color{runeo}\headingfont} % tocloft <=====

\begin{document}

{\small
    \onecolumn
    \begin{ThreePartTable}

        \begin{longtable}
            {
                >{\raggedleft\arraybackslash}p{2cm}
                >{\raggedright\arraybackslash}p{6.6cm}
                >{\raggedright\arraybackslash}p{6.6cm}
            }

            \caption{Prefered and restricted weapons of the non-humans}\label{AliensWeapons} \\
            \toprule
            & \multicolumn{2}{c}{Weapons}\\
            \cmidrule{2-3}
            \multirow{-2.5}*{Species} & Preferred & Restricted \\
            \midrule
            \endfirsthead

            \caption*{\autoref{AliensWeapons} (\textit{Continued})} \\
            \toprule
            & \multicolumn{2}{c}{Weapons}\\
            \cmidrule{2-3}
            \multirow{-2.5}*{Species} & Preferred & Restricted \\
            \midrule
            \endhead
            qwertya & qwerty, erqgy, asdfghjj, assdf adfsf, sss ffff, fffsss cvbnmq. & wer hjkllod Ones never throw daggers or axes and rarely employ any type of missile weapon, slings being the only one used when they do. \\
            dadfg & that swords the are 234567rty' knives and chopper weapons like thin shaped, discs of. the convex rim with all around pizza (like sharpened cutters) & Else is little known of rim  use bronze \\
            vaaet & Light javelins, slender straight one-handed swords, occasionally light crossbows. They may also drop rocks or incendiaries from the air. Their rapier-like tail, which is usually poisoned, also functions as a weapon. & The furred jlehwn do not fight with their fists, nor do they employ bows, polearms, or one-handed weapons. A few have mastered the sling, however. \\
            \bottomrule
        \end{longtable}
    \end{ThreePartTable}
    \twocolumn
}

\end{document}


text:
Q: Android 6.0 permission denied I am using Android 6.0. I have an application that copies executable file (compiled for arm) to the app data folder.
In the app I have set the executable permissions to:
chmod 777 /data/data/pckname/files/executable

when I try to run the file using adb shell I get this message
/system/bin/sh: /data/data/pckname/files/executable: can't
execute: Permission denied

Any suggestions?
UPDATE:
I tried
ls -l

and this is the result
-rwxrwxrwx u0_a54   u0_a54    1620988 2016-12-14 13:59 execFile

is the problem in the user?


text:
Q: GLMs Limitations First I'll explain the data and then the problem.
Data:
Let's say that we need to build a GLM model to predict the income of $N$ individuals. The income variable is positive and skewed to the right, thus we assume it follows Gamma distribution.
We have three continuous predictors, $X_1$, $X_2$, and $X_3$, with $X_i \in [0, 100]$, for $i=1,2,3$. Also, we assume that they are not correlated with each other.
Also, let's assume that $X_1$ and $X_2$ are negatively correlated with income, while $X_3$ is positively correlated. So after building the GLM model (gamma with log-link), $X_1$ and $X_2$ will have negative coefficients while $X_3$ has a positive coefficient.
Also, for illustration, let's assume that $\hat{\beta}_0 = 0.5$, $\hat{\beta}_1 = -0.1$, $\hat{\beta}_2 = -0.2$, and $\hat{\beta}_3 = 0.3$,
Problem:
Let's say that both $X_1$ and $X_2$ are large values (say, 90 and 90) and also $X_3$ is large (equals 100), then the fitted income value will be lowered because $X_1$ and $X_2$ have large values. What I want is if $X_3$ is large I need to give it more weight and kind of ignore $X_1$ and $X_2$ contributions. I feel that GLM is not appropriate here. Do you have suggestions of using other models, perhaps non-linear, and if so, what the structure would be?

A: What you are describing here is a non-linearity. From a modeling perspective, most non-linearities can be accommodated by creating a clever set of derived variables. The model which only adjusts for $X_1$, $X_2$, $X_3$ as covariates is not correct. Therefore this is not so much a limitation of the GLM as it is one of specifying the right mean model.
For this answer, a caveat: large is not well-defined. Is it 40? 80? I am assuming we know what large is, it is a clear break-point, and once we exceed it, linear effects in $X_1, X_2, X_3$ are otherwise acceptable.
You can create the indicator variable: x3large as 0 if $X_3$ is small and 1 if $X_3$ is large. Take the product of this indicator variable with the other 3 $X_1, X_2, X_3$. The numerator degrees of freedom for the model now goes from 4 to 7. The interaction terms' coefficients represent a difference in coefficient slopes when $X_3$ is large. When the interaction term is of opposite sign but less than the original coefficient, it represents a decrease in effect. If they are of the same sign, the effect is larger in that large domain.
Per your scientific description of the trend: if the data resemble the process you have described, maximizing the likelihood is all you need to do. The interaction with x3large and x1, x2 will be negative to attenuate their effect. The interaction with x3large and x3 will be positive to "ramp up" it's effect.
Now I advise stopping here. If the optimal fit to the data is not as you describe, this is an interesting result. We assumed a trend and results were found otherwise.
It is possible however to fit models which are constrained to achieve effects only as you describe. The first method is constrained optimization. You can add a lagrange multiplier to the likelihood to offset the cases when the interaction terms are not of the desired sign. Similarly, you can conduct a Bayesian analysis with 0 prior probability on those values. The predictions from the constrained models could be compared to the unrestricted, full model to make qualitative inference on the validity of either approach.


text:
Q: How to get airflow time zone information from macros? Background
I am trying to run a DAG at 10pm America/New_York once every day from Monday to Friday. The script which the DAG runs takes as input the day it runs on for its
time zone (10pm Mon-Fri). When I run this scrip as an Airflow DAG, the date is derived from the macro {{ ds_nodash }}
The problem
When Airflow runs, by the time it's 10pm NY time, it's already the next day on UTC time. Since Airflow uses UTC, the execution date is one day ahead, so when my DAG uses the macro {{ ds_nodash }}, it is one day ahead.
Question:
Is there a way to get the time-zone adjusted date as a macro on airflow or is the only solution to my problem to adjust the macro myself?

A: According to the airflow documentation, the default variables (such as {{ ds_nodash }}) are in UTC. So, we need to convert them ourselves. It can go something like this:
# ...
local_ds_nodash = '{{ dag.timezone.convert(execution_date).strftime("%Y%m%d") }}'
# ...
create_file = BashOperator(
    task_id='create_file',
    bash_command=f'touch {local_ds_nodash}.txt'
)

A: I supposed that you may mess up with two different concepts in airflow.

*

*Actually, 'ds' is not the date which the tasks are running, it is the previous period of tasks running. for example, for ds is 3/25/2019, it would be running on 3/26/2019 rather than 3/25. So if you want your tasks running exactly on Mon-Fri, you need to set the schedule_interval as '0 22 * * 1-5'. The weekday settings should be '1-5' instead of '2-6'.

*For timezone, kaxil's answer has explained very well. But if for some reason, you cannot change the airflow server configuration, what you need to do is to adjust schedule_interval as '0 2 * * 2-6'. Then the tasks will run as you expected.

A: Timezone feature is now available in Airflow. Have a look at https://airflow.readthedocs.io/en/1.10.2/timezone.html and adjust your config in airflow.cfg accordingly.
By default it is
[core]
default_timezone = utc

adjust it to
[core]
default_timezone = America/New_York

The execution_date will then contain TZ info as well which you would be able to extract. Try it in a test environment before you roll out to your production environment.


text:
Q: Modifiers on image processed with ImageAnalysisInteraction for Live Text on iOS 16 Prior to iOS 16, I displayed my SwiftUI app's images with the following modifiers, which set the size accordingly, and allowed for pinch-to-zoom.
Image(uiImage: UIImage(data: self.image ) ?? UIImage(imageLiteralResourceName: "placeholder"))
   .resizable()
   .aspectRatio(contentMode: .fill)
   .if(project.cardSize == 1) { $0.frame(width: screenWidth, height: 540) }
   .if(project.cardSize == 2) { $0.frame(width: screenWidth, height: 300) }
   .if(project.cardSize == 3) { $0.frame(width: screenWidth, height: 380) }
   .cornerRadius(4)
   .pinchToZoom()

Now I'm integrating Live Text into my app using VisionKit / ImageAnalysisInteraction per https://developer.apple.com/wwdc22/10026.
I have it working, however none of the modifiers work on the new Image View:
LiveTextInteraction(imageName: self.image)
How can I properly size my image and set these modifiers while also using Live Text? I tried adding imageView.frame to the makeUIView function in my LiveTextInteraction.swift per below, but it doesn't appear to work.
func makeUIView(context: Context) -> some UIView {
    imageView.image = UIImage(data: imageName)

    imageView.addInteraction(interaction)
    imageView.frame = CGRect(x: 0, y: 0, width: 50, height: 50) <<<<<<< HERE
    imageView.contentMode = .scaleAspectFill

    return imageView
}

Thanks!


text:
Q: IoC using Autofac: How to new up during runtime? To achieve IoC I used to set up instances using DI as following:
class Foo
{
    IBar _bar

    public foo(IBar bar)
    {
        _bar = bar;
    }
}

Anything that is newed up is then done by autofac. But how do I (or can I) use autofac to achieve independency when assigning new instances isn't possible at startup?
E.g.
class Foo
{
    List<IBar> _barList;

    public foo(List<IBar> barList)
    {
        _barList = barList;
    }

    FooFunction()
    {
        _barList.Add(new Bar(new qux));
    }
}

public class Baz : IBaz
{
    Iqux _qux;

    Baz(Iqux qux)
    {
        _qux = qux;
    }
}

Here I added "qux" as well to show what I likely want to achieve. No problem if everything is set up at startup. But because I don't now the numbers of "buz" items the list is going to have at startup I have to add "buz" items during runtime (that requires "qux").
Well, the very goal is to get testable modules. Therefore I don't want to mention the class but only its interface, which is not possible if I have to new up something (or am I wrong?).


text:
Q: Show alias replacement text in .bash_history file Given that I have the following alias in one of my bash initialization files (.bash_profile etc.):
alias gs='git status'

How can I get my .bash_history file to show the replacement text: 'git status' instead of the alias: 'gs'?

A: I don't think that this is (easily) possible.
I tried this:
alias foo="echo foo;fc -e /home/hl/tmp/testscript.sh 0"
start cmd:> cat /home/hl/tmp/testscript.sh
#! /bin/bash

set -x

# simple case
#test -f "$1" || exit 1
#echo ": alias replacement : echo foo" >"$1"

# complex case
IFS= read -r line <"$1"
: line: _"$line"_
case "$line" in
        foo)
                echo ": alias replacement : echo foo" >"$1"
        ;;
        bar)
                echo ": alias replacement : echo bar" >"$1"
        ;;
        *)
                echo ": alias replacement error" >"$1"
        ;;
esac

The idea was: Run the actual command and immediately afterwards correct the command history which can be done by the bash builtin fc. There are two problems:

*

*fc allows you to edit the file but executes it afterwards. This can partly be solved by writing a dummy command (e.g. prepend :).

*The history is based on lines not on executed commands. Thus the command to be modified is not even on the stack yet. This could maybe be addressed by some evil hack like putting the code into $PS1 but I don't feel like trying...
history builtin
There may be a better way which shares the "not yet on the stack" problem with the above approach. I wasn't aware of the builtin history. This command allows to write and read the history file. Thus this could be done:

*

*write the file

*modify the file with e.g. sed: sed -i 's/^gs$/git status/' ~/.bash_history

*read the file

The history stack problem may be adressed this way (I didn't try, though):
alias foo="echo foo;(sleep 1; history ...) &"


text:
Q: How to troubleshoot how resource governed query is being throttled in SQL 2012? I have a parallelized query on SQL 2012 SP1 (ent) that is running in a user defined resource governor pool much much slower (2 seconds versus 125 to 140 seconds under user defined pool = ~75 times slower) than the same query that runs in the default resource pool.
The query plan hash is identical between the two executions and statistics io returns same values for all operations. I've confirmed that execution plan does not have additional spill warnings (both have one), and that the memory grant for the queries are identical.
User defined pool workload group
<QueryPlan DegreeOfParallelism="4" MemoryGrant="2384096" CachedPlanSize="384" CompileTime="3608" CompileCPU="2712" CompileMemory="15672">
        <ThreadStat Branches="5" UsedThreads="20">
          <ThreadReservation NodeId="0" ReservedThreads="20" />
        </ThreadStat>
        <MemoryGrantInfo SerialRequiredMemory="5632" SerialDesiredMemory="2360768" RequiredMemory="28960" DesiredMemory="2384096" RequestedMemory="2384096" GrantWaitTime="0" GrantedMemory="2384096" MaxUsedMemory="93872" />
        <OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="209715" EstimatedPagesCached="104857" EstimatedAvailableDegreeOfParallelism="4" />

Default pool
<QueryPlan DegreeOfParallelism="4" MemoryGrant="2384096" CachedPlanSize="384" CompileTime="3016" CompileCPU="2660" CompileMemory="15672">
            <ThreadStat Branches="5" UsedThreads="20">
              <ThreadReservation NodeId="0" ReservedThreads="20" />
            </ThreadStat>
            <MemoryGrantInfo SerialRequiredMemory="5632" SerialDesiredMemory="2360768" RequiredMemory="28960" DesiredMemory="2384096" RequestedMemory="2384096" GrantWaitTime="0" GrantedMemory="2384096" MaxUsedMemory="88768" />
            <OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="209715" EstimatedPagesCached="104857" EstimatedAvailableDegreeOfParallelism="4" />

Total_worker_time is nearly identical between the queries. Only thing that seems different is the total_elapsed_time. Wait is cxpacket. At this point, I must think this is something that resource governor is doing to throttle the CPU and/or memory. I can't find any evidence of the throttling though. CPU throttled counter does not budge, neither does memory suboptimal plans/sec.
For the workload group I've played with increasing memory grant beyond default (25%), and have played with max dop settings. Nothing makes a difference to execution time unless I make the query execute serially. If I change maxdop of workload group to 1 (serial execution) the query runs in ~3 seconds once in cache (1 second slower than default group). All other levels of maxdop result in ~70 and 75 times slower).
Server info:
2 socket x 6 core server. Server MaxDop = 4. CPU is relatively at rest (~12% utilization) when I execute the tests. Memory on server is not under pressure (~6GB free on 24GB box).
Resource pool configuration
100% max memory
50% CPU (increasing to 100% didn't make any difference)
75% CPU CAP
Workload group
MaxDop 0 (and have tried 0,1,4,7)
Memory Grant (25% - and have tried SQL recommended maximum of 70%)
Any ideas on how to narrow down what is doing the throttling?
I do not see anything obvious from the Microsoft link for troubleshooting it
http://technet.microsoft.com/en-us/library/cc627395(v=sql.105).aspx
Full plan for Default Pool (quick) execution - http://pastebin.com/y0P9J61f
Full plan for User Pool (slow) execution - http://pastebin.com/20hnFSTW
The problem query is second statement in the plans (first one is inconsequential and doesn't run parallel anyways...)

A: An update - I still don't know how best to detect what type of throttling has gone on, but I did find the culprit in my case. It does seem that the CPU CAP to 75% was causing a much higher decrease in performance than a 25% drop should suggest. Raising the CPU Cap to 100% fixed the problem.
A connect article seems to validate this might be a problem with the CPU Cap implementation itself.
Its not the best answer to this question, and if someone still wants to answer the original "how to tell what throttling is going on..." question. I'd be amenable.
If you are struggling to understand why your queries are being throttled so severely, this might be a solution worth trying for it.
http://connect.microsoft.com/SQLServer/feedback/details/781335/resource-governor-feature-cap-cpu-percent-does-not-work-as-expected


text:
Q: Serialization with relationships very slow with Marshmallow I have the following example table in my DB which I manage mit Flask_SQLAlchemy.
class Employee(db.Model):
    __tablename__ = 'employee'
    id = db.Column(db.Integer, primary_key=True)
    salutation = db.Column(db.String(250), nullable=False)
    first_name = db.Column(db.String(250), nullable=False)
    last_name = db.Column(db.String(250), nullable=False)

    employments = db.relationship('Employment', foreign_keys='Employment.employee_id', backref="employee", lazy=True)

my Schema for Flask looks like this:
class EmployeeSchema(mm.SQLAlchemyAutoSchema):
    class Meta:
        model = DB_employee.Employee
        include_fk = True
        include_relationships = True

The following is my routing for GET of the employees:
class EmployeesListAPI(Resource):
    def __init__(self):
        self.reqparse_get = reqparse.RequestParser()
        self.reqparse_get.add_argument('employee_id', type=int, action='append', required=False, location='args')
        self.reqparse_get.add_argument('salutation', type=str, action='append', required=False, location='args')
        self.reqparse_get.add_argument('first_name', type=str, required=False, location='args')
        self.reqparse_get.add_argument('last_name', type=str, required=False, location='args')

        super(EmployeesListAPI, self).__init__()

    def get(self):
        get_args = self.reqparse_get.parse_args()
        employees = get_list_employee(get_args)

        employees_output = EmployeeSchema(many=True, only=get_args['return_fields']).dump(employees)

        return employees_output, 200

if I now run this, the query with SQL-Alhchemy takes about 0.01 seconds which is ok for me, but the serialization with Flask_Marshmallow takes about 1.3 seconds.
if I change the Schema as following: include_relationships = False and run the serialization manually:
for employee, output in zip(employees, employees_output):
            if get_args['show_employments']:
                output['employments'] = [e.id for e in employee.employments]

the serialization with marshmallow takes about 0.02 seconds and the manually added employments-relationships takes about 1.2 seconds.
In my real case, I have much more then just one relationship an the serialization of the data takes an astonishing 32 seconds.
is there a way to speed up the serialization with marshmallow? Am I doing something wrong?
Thank you for your support.


text:
Q: tkinter avoid GUI from freezing I developed a simple Python application doing some stuff, then I decided to add a simple GUI using Tkinter.
The problem is that, while the I call a function called startprocess and begin doing stuff which is processor heavy and the window freezes.
I know it's a common problem and I've already read that I should use multithreads (very complicated, because the function updates the GUI too) or divide my code in different function, each one working for a little time. anyways is there any modification needed in below code to avoid GUI freezing?
import threading
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
import os, datetime, sys, subprocess
import parselog_v1

# diplay messagebox window
def MessageBox(windowLable,msg):
   messagebox.showinfo(windowLable, msg)

# check if Dir empty
def checkDirEmpty(work_path):
    if os.path.isdir(work_path):
        if not os.listdir(work_path):
            print ("No Files found in directory")
            MessageBox('Log Parser', 'No Files found in directory.')
        else:
            return True

# launch app in center of screen
def center_window(width=300, height=200):
    # get screen width and height
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    # calculate position x and y coordinates
    x = (screen_width/2) - (width/2)
    y = (screen_height/2) - (height/2)
    root.geometry('%dx%d+%d+%d' % (width, height, x, y))

# application frame

class Application(tk.Frame):

    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack()
        self.createWidgets()
        self.master.title("Log Parser")

    def createWidgets(self):
        self.Run_Main = tk.Button(self)
        self.Run_Main["text"] = "Browse for logs"
        self.Run_Main["fg"] = "blue"
        self.Run_Main["command"] = self.startProcess
        self.Run_Main.pack(side='left',padx=0)

        self.QUIT = tk.Button(self)
        self.QUIT["text"] = "Quit!"
        self.QUIT["fg"]   = "red"
        self.QUIT["command"] =  self.quit
        self.QUIT.pack(side='right',padx=5)

    def startProcess(self):
        global Src_foldername
        Src_foldername = filedialog.askdirectory()
        Src_foldername = Src_foldername.replace("/", "\\")
        print("Source folder: " + Src_foldername)
        if checkDirEmpty(Src_foldername):
            # process logs
            # multithread
            print("Processing...")
            self.refresh()
            threading.Thread(target=parselog_v1.main(Src_foldername))

# scroll text inside application frame
class scrollTxtArea:

    def __init__(self, root):
        frame = tk.Frame(root)
        frame.pack()
        self.textPad(frame)
        return

    class IORedirector(object):
        '''A general class for redirecting I/O to this Text widget.'''
        def __init__(self, text_area):
            self.text_area = text_area

    class StdoutRedirector(IORedirector):
        '''A class for redirecting stdout to this Text widget.'''

    def textPad(self, frame):
        # add a frame and put a text area into it
        textPad = tk.Frame(frame)
        self.text = tk.Text(textPad, height=21, width=68)
        self.text.config()
        # add a vertical scroll bar to the text area
        scroll = tk.Scrollbar(textPad)
        self.text.configure(yscrollcommand=scroll.set,background="black", foreground="green")
        # pack everything
        self.text.pack(side=tk.LEFT, pady=2)
        scroll.pack(side=tk.RIGHT, fill=tk.Y)
        textPad.pack(side=tk.TOP)
        self.text.insert("end", "Begin by selecting log folder..." + "\n")
        self.text.configure(state='disabled') # disable text editing
        sys.stdout = (self) # to begin logging stdio to GUI
        return

    def write(self, txt):
        self.text.configure(state='normal')
        self.text.insert('end', txt)
        self.text.configure(state='disabled')

root = tk.Tk()
root.resizable(width=False, height=False)
center_window(500, 300) # launch in center of screen
app = Application(master=root)
scrollFrame = scrollTxtArea(root)
app.mainloop()
root.destroy()

A: You use thread in wrong way.
First: target= needs function name without () and arguments.
You can assign arguments to args= (it have to be tuple even if you have only one argument)
threading.Thread(target=parselog_v1.main, args=(Src_foldername,) )

Now your code runs parselog_v1.main as normal function, waits for result  and it will assign this result as function name to taget= - so you have something like this:
result = parselog_v1.main(Src_foldername)
threading.Thread(target=result)

It stops mainloop so it can't get mouse/keyboard events, refresh window, etc. so it looks like window freeze.
Second: after you create thread correctly you have to start it
my_thread = threading.Thread(target=parselog_v1.main, args=(Src_foldername,) )
my_thread.start()


text:
Q: Selenium tests(in C#) failing when run from the command line but not VS I'm having an issue with some Selenium tests I have written using C# in visual studio. When I run them(MSTest) from from VS they all pass fine, however if I run the tests from the command line some fail. I've tried a few times and it seems as though the tests fail at random as the number that fail and the individual tests that fail are different each time, this confuses me!. As things stand the tests are failing on our build server and I need to figure out the issue.
Any ideas or suggestions would be greatly appreciated!

A: The tests are executed faster in VS than in the IDE if you are trying to assert elements of the page that has not been loaded yet. Try adding more pauses or increase the time paused in you test cases.
Is there any pattern to where the test fails although it seems random?


text:
Q: Why is this configurable property not deletable? Configurable properties seem to be deletable:
var o = {};
Object.defineProperty(o, 'prop', {
    configurable: true,
    value: 'val'
});
delete o.prop; // true
o.prop;        // undefined

But it doesn't work in the following case, at least on Firefox and Chrome:
var form = document.createElement('form'),
    input = document.createElement('input');
form.appendChild(input);
var elems = form.elements;
Object.getOwnPropertyDescriptor(form, 0)
      .configurable; // true <────────────────────── !!!
delete elems[0];     // false                         │
elems[0];            // input                         │
(function(){ 'use strict'; //                         V
    delete elems[0]; // TypeError: property 0 is non-configurable
})();                // and can't be deleted

But this seems to contradict the spec.
The delete operator is defined like this:

11.4.1 - The delete Operator
The production UnaryExpression : delete UnaryExpression is
  evaluated as follows:

*

*Let ref be the result of evaluating UnaryExpression.

*[...]

*If IsPropertyReference(ref) is true, then

*

*Return the result of calling the [[Delete]] internal method on ToObject(GetBase(ref)) providing
  GetReferencedName(ref) and IsStrictReference(ref) as the
  arguments.

So the result of using delete depends on [[Delete]]. Now let's see what [[Delete]] does:

8.12.7 - [[Delete]] (P, Throw)
When the [[Delete]] internal method of O is called with property
  name P and the Boolean flag Throw, the following steps are taken:

*

*Let desc be the result of calling the [[GetOwnProperty]] internal method of O with property name P.

*If desc is undefined, then return true.

*If desc.[[Configurable]] is true, then

*

*Remove the own property with name P from O.

*Return true.

*Else if Throw, then throw a TypeError exception.

*Return false.

Therefore, if the property is configurable, it should be deletable.
But wait, maybe Object.getOwnPropertyDescritor is a troll and says that a property is configurable, but [[Configurable]] is false. Let's see:

15.2.3.3 - Object.getOwnPropertyDescriptor ( O, P )
When the getOwnPropertyDescriptor function is called, the
  following steps are taken:

*

*If Type(O) is not Object throw a TypeError exception.

*Let name be ToString(P).

*Let desc be the result of calling the [[GetOwnProperty]] internal method of O with argument name.

*Return the result of calling FromPropertyDescriptor(desc).

So it also uses [[GetOwnProperty]], like [[Delete]]. Maybe the troll is FromPropertyDescriptor?

8.10.4 FromPropertyDescriptor ( Desc )
When the abstract operation FromPropertyDescriptor is called with
  property descriptor Desc, the following steps are taken:

*

*If Desc is undefined, then return undefined.

*Let obj be the result of creating a new object as if by the expression new Object() where Object is the standard built-in
  constructor with that name.

*...

*Call the [[DefineOwnProperty]] internal method of obj with arguments "configurable", Property Descriptor {[[Value]]:
  Desc.[[Configurable]], [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true}, and false.

*Return obj.

So no, it is not a troll neither. The configurable property of the property descriptor is set to the [[Configurable]] value.
How is it possible, then, that a configurable property can't be deleted?

A: Effectively, configurable properties are deletable.
But there is a big problem: that only applies to native objects, but not to host objects.
As explained in 8.6.2 - Object Internal Properties and Methods,

Host objects may support these internal properties with any
  implementation-dependent behaviour as long as it is consistent with
  the specific host object restrictions stated in this document.

For those, [[GetOwnProperty]] must behave differently:

If a property is described as a data property and it may return
  different values over time, then either or both of the [[Writable]]
  and [[Configurable]] attributes must be true even if no mechanism
  to change the value is exposed via the other internal methods.

In your example, form.elements is a HTMLFormControlsCollection instance defined by the HTML spec, so it's a host object.
Therefore, the situation is

*

*It has a custom [[GetOwnProperty]] which says that the property '0' is configurable because its value may change.

*It also has a custom [[Delete]] which doesn't delete the property, even if [[GetOwnProperty]] says it's configurable.


text:
Q: Topology induced on an interval $[a,b] \subset \mathbb{R}$ and connected set definition. This is a stupid question.
Am I right when I say that the interval $[a,b]$ is not an open set w.r.t. the topology of $\mathbb{R}$ but it is an open set if I consider $[a,b]$ as a topological subspace of $\mathbb{R}$?
The reason I'm asking is because of the definition of connected set in a topological space, which according to this link means that the set cannot be partitioned in two open sets in the subspace topology I think.

A: To allay confusion, I would word this much more carefully, with care taken to match the general wording of open subsets.
When a topological space $X$ is given (with its topology specified somehow), one can ask whether a subset $A \subset X$ is open in $X$.
So, for example, when the topological space $\mathbb R$ is given (with its standard topology), its subset $[a,b] \subset \mathbb R$ is not open in $\mathbb R$.
But when the topological space $[a,b]$ is given (with the subspace topology that it inherits from $\mathbb R$), its subset $[a,b] \subset [a,b]$ is open in $[a,b]$.

A: Every topological space is an open subset of itself. So, yes, $[a,b]$ is an open subset of $[a,b]$ if we see $[a,b]$ as a topological space of $\mathbb R$.


text:
Q: Resolve colliding rotated rectangles by moving along vector I have a javascript program that places rectangles one at a time along walls in a room in counter-clockwise order. I use the coordinates of the rectangles corners for collision detection. It skips the placement of a rectangle if it intersects with another rectangle in the room.

(the room can be any shape so collisions can happen on any side of the rectangle)

However, I want to move the rectangle along the wall until it is no longer colliding instead of skipping it. My current idea is to move the rectangle 1 coordinate at a time in a loop until it no longer intersects, but it does not seem like a good solution for performance.

Is there a way to mathematically know how far in a given direction the rotated rectangle needs to be moved in order to no longer intersect another rotated rectangle?

A: Consider using of Separating Axis Theorem.
Two boxes (polygons in wide sense) don't intersect, if there exists some axis parallel to some box side, separating boxes, so the lie at distinct sides of this axis.

I've got arbitrary paper with good picture. At pages 16-17 we can see two boxes and some formulas to check for intersection.
You can express T - difference vector between box center as
T.x = pb.x - pa.x + t * dx
T.y = pb.y - pa.y + t * dy

where t is parameter (0 in the starting moment), and (dx, dy) is direction vector for B box moving (along the slanted wall at your picture).
Substituting T components into formula (note I changed > sign to =) we can get equation for parameter t corresponding to moment when Ax becomes separating axis.
| T • Ax | = WA + | ( WB*Bx ) • Ax  | + |( HB*By ) • Ax |

If we make the same for other axes (Ay, Bx, By), we get 4 values of t, and the smallest positive one corresponds to minimal diplacement needed to separate the boxes.
Note that right part contains only constant values (for given setup), and we can easily calculate it using abs function, but left part contains variable, so we have to consider two cases (negative and positive dot product T • Ax) to find solution(s). Two possible solutions correspond to "left and right" box separation (anyway, you need smaller positive result)


text:
Q: Had to increase http.globalAgent.maxSockets for iOS simulator, but why? I have a proxy server built in nodejs. It was working fine, until I tried browsing the web through it via the iOS iPhone simulator. Then it would load a few requests and hang indefinitely.
I narrowed it down to this:
var req = http.request({...}, function(){
  // this is not being called for some requests
})

...which in turn let me to discover this:
req.on('socket', function(){
  // this is not being called for some requests
})

Suspecting trouble with pooling of sockets, I set http.globalAgent.maxSockets = 50 and that indeed fixed it. (The default is 5.) But I feel like I've only fixed the symptom of a deeper problem. It only happened when I browsed from within the iOS simulator, via xcode. Using desktop Chrome, not in the simulator but using that same proxy instance, there were no problems.


text:
Q: Sequence within trait of FactoryGirl factory does not use main sequence counter I have the following factory:
FactoryGirl.define do
  factory :foo do
    sequence(:name) { |n| "Foo #{n}" }

    trait :y do
      sequence(:name) { |n| "Fooy #{n}" }
    end
  end
end

If I run
create :foo
create :foo
create :foo, :y

I get Foo 1, Foo 2, Fooy 1. But I want Foo1, Foo2, Fooy 3. How can I achieve this?

A: After a couple of hints from smile2day's answer and this answer, I came to the following solution:
FactoryGirl.define do
  sequence :base_name do |n|
    " #{n}"
  end

  factory :foo do
    name { "Foo " + generate(:base_name) }

    trait :y do
      name { "Fooy " + generate(:base_name) }
    end
  end
end

A: You defined two different sequence generators since they are not within the same scope.
I would not use :name for the generator. A name that implies a number seems more suitable.
sequence :seq_number

Include a transient attribute in the factory and assign the generated sequence nunber.
transient do
  seq_no { generate(:seq_number) }
end

Use the transient attribute for the 'name' attribute. The same applied to the trait version of 'name'.
name { "Foo #{seq_no}" }

trait :y do
  name { "Fooy #{seq_no}" }
end

Cheers,
Eugen


text:
Q: solving a trig identities using formula $x^4+y^4$ but there is also a -1 what can i solve it I want to know if I can use the formula $x^4+y^4$ even if it is $-1$ in the following expression
$$\frac{\sin^4 x+\cos^4 x -1}{\sin^6 x+\cos^6 x -1}=\frac{2}{3}$$

A: $$\begin{align*} \frac{\sin^4x+\cos^4x-1}{\sin^6x+\cos^6x-1}&=\frac{(1-\cos^2x)^2+\cos^4x-1}{(1-\cos^2x)^3+\cos^6x-1}\\
&=\frac{1-2\cos^2x+\cos^4x+\cos^4x-1}{1-3\cos^2x+3\cos^4x-\cos^6x+\cos^6x-1}=\frac{2\cos^4x-2\cos^2x}{3\cos^4x-3\cos^2x}\\
&=\frac23
\end{align*}$$
So it holds for every $x$.


text:
Q: MySQL returning multiple rows that does not match search criteria I have MySQL installed locally, running SELECT VERSION() returns this value: 5.6.43-84.3
When I run a query it is returning multiple rows when it should only return 1 row. Let me set it up, it's easier to explain that way.

*

*Create a test table:

    CREATE TABLE test_table
    (
        test_val VARCHAR(255)
    )
    ;

*Load 3 values into the table:

    INSERT INTO test_table (test_val)
    VALUES
    ('9671986020630615'),
    ('9671986020630616'),
    ('9671986020630617')
    ;

*Run this query (This query returns 1 row which is expected):

    SELECT *
    FROM test_table
    WHERE test_val = '9671986020630615'
    ;

*Run this query (This query returns 3 rows, which it shouldn't):

    SELECT *
    FROM test_table
    WHERE test_val = 9671986020630615
    ;

Here's what I have observed about this situation:

*

*The first query surrounds the value in the WHERE clause with single quotes.

*The second query does not surround the value in the WHERE clause with single tics.

*The column in the test table is defined as VARCHAR(255)

*It makes sense that the first query returns just one row because it's comparing a string from the WHERE clause to a string value in the test table (VARCHAR(255))

*Something is happening when MySQL compares the numerical value in the WHERE clause of the second query to the string value in the test table (VARCHAR(255)) which is causing MySQL to return 3 rows instead of just 1.

It makes sense that the first query returns the correct result because it is comparing a string to a string.
It also makes a degree of sense that the second query is returning a bad dataset (3 rows as opposed to the 1 row it should return).
But my question is why is MySQL doing this? Why when it compares a number to 3 different VARCHAR(255) values does it return all 3 rows when the true value of the numerical value in the WHERE clause only matches 1 row?
So, in essence for the first query MySQL is saying:

'9671986020630615' = '9671986020630615',
'9671986020630615' <> '9671986020630616',
'9671986020630615' <> '9671986020630617'

but for the second query it is saying:

9671986020630615 = '9671986020630615',
9671986020630615 = '9671986020630616',
9671986020630615 = '9671986020630617'

Any help will be much appreciated.

A: MySQL handles all numbers internally the same way Javascript does, with IEEE double-precision floating point representation.
When you omit the quotation marks from your long numeric strings, that is you write 9671986020630615 in place of '9671986020630615 ', MySQL uses the number. Then, when it runs the WHERE part of your query, it silently coerces each column value to a double precision number.
But due to the machine epsilon -- the limit of precision -- of double precision,  9671986020630615, 9671986020630616, and 9671986020630617 all have the same value. So the WHERE finds all three.
CAST(9671986020630615 AS DOUBLE) CAST(9671986020630616 AS DOUBLE) CAST(9671986020630617 AS DOUBLE)
     9.671986020630616e15             9.671986020630616e15             9.671986020630616e15 |

See how all three integers have the same representation as DOUBLE?


text:
Q: MS Access / Outlook 2010 - how to choose which account to send email from? I am trying to send emails from a specific account but it always sends from my main no matter how much code I try or what I do. Is there any way to tell it to send it from a particular account? I am writing my code in MS Access, but using Outlook objects.
Sub testEmail()
    On Error Resume Next
    Set outapp = GetObject(, "Outlook.Application")

    If outapp Is Nothing Then
        Set outapp = CreateObject("Outlook.Application")
    End If

    Set oMail = outapp.CreateItem(olMailItem)

    With oMail
        .To = "randomaddress@randomdomain.com"
        .Subject = "test2"

        .Send
    End With

    Set outapp = Nothing
    Set oMail = Nothing

End Sub

Updated code:
Option Compare Database

Sub testEmail()
    On Error Resume Next
    Set oApp = CreateObject("Outlook.Application")
    Set oMail = oApp.CreateItem(olMailItem)
    Set olAccount = oApp.Account
    Set olAccountTemp = oApp.Account
    Dim foundAccount As Boolean
    Dim strFrom As String
    strFrom = "FROMADDY@randomaddress.com"

    foundAccount = False
    Set olAccounts = oApp.Application.Session.Accounts
    For Each olAccountTemp In olAccounts
        Debug.Print olAccountTemp.smtpAddress
        If (olAccountTemp.smtpAddress = strFrom) Then
            Set olAccount = olAccountTemp
            foundAccount = True
            Exit For
        End If
    Next

    If foundAccount Then
        Debug.Print "ACCT FOUND!"
        With oMail
            .To = "randomaddress@random.com"
            .Body = "Message!"
            .Subject = "test3"
            .sendusingaccount = olAccount
        End With
    Else
        Debug.Print "No acct found"
    End If

    Set oApp = Nothing
    Set oMail = Nothing
    Set olAccounts = Nothing
    Set olAccount = Nothing
    Set olAccountTemp = Nothing
End Sub

A: Try using
Set oMail.sendusingaccount=olAccount

instead of
oMail.sendusingaccount=olAccount

It worked for me, your code is perfect, just the Set is missing.

A: It is also much easier when the user can select the email address rather than account number. sendCaller loops through the accounts until it finds this email address. From there on it will call sendFile from where the message will be sent.
Sub sendCaller()
'creates outlook application
'chooses an email address and finds the corresponding account number

    Dim OutApp As Object
    Dim i As Integer, accNo As Integer

    Set OutApp = CreateObject("Outlook.Application")
    emailToSendTo = "name@domain.com"  'put required email address

'if smtp address=email we want to send to, acc no we are looking for is identified
   For i = 1 To OutApp.Session.Accounts.Count
      'Uncomment the Debug.Print command to see all email addresses that belongs to you
       '''Debug.Print "Acc name: " & OutApp.Session.Accounts.Item(i) & " Acc number: " & i & " email: " & OutApp.Session.Accounts.Item(i).smtpAddress
       If OutApp.Session.Accounts.Item(i).smtpAddress = emailToSendTo Then accNo = i
    Next i

    sendFile accNo

End Sub

Sub sendFile(accountNo As Integer)
    Dim OutApp As Object
    Dim OutMail As Object

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    With OutMail

        .To = "recipient@domain.com"
        .Subject = "Test"
        .Body = "Body"
        Set .SendUsingAccount = OutApp.Session.Accounts.Item(accountNo)
        .Send
    End With
End Sub


text:
Q: Lambdas in unevaluated context (requires expressions) I know there are several questions about this topic but hear me out, please.
I'm aware that we can use capture-less lambdas in unevaluated contexts (like decltype), but what about lambdas that do capture?
I couldn't find anything in the current C++ standard that would suggest that this is at all a problem since C++20, but I'm by no means a language lawyer.
What I see though, is that the major compilers differ in their results.
Are these concepts valid?
template <typename T>
concept C1 = requires { []{}; };

template <typename T>
concept C2 = requires(T t) { [&t]{}; };

A:
I'm aware that we can use capture-less lambdas in unevaluated contexts

This is not restricted to stateless lambdas. P0315R4 (Wording for lambdas in unevaluated contexts) removed the restrictions for lambdas (not just stateless ones) to not appear in unevaluated lambdas, whilst modifying the wording for some sections relating to the original intent for the restriction:

The core language changes introduced in this paper are a bit tricky. The reason is that we remove many restrictions on lambda expressions, yet we still want to keep closure types out of the signature of external functions, which would be a nightmare for implementations.

The paper introduces no particular constraints on lambdas w.r.t. concepts, and we may simply turn to [temp.concept]/6 to govern this case:

The constraint-expression of a concept-definition is an unevaluated operand ([expr.context]).

As there is no longer any general restriction on lambas (stateless or not) to not appear as the operand in unevaluated contexts, and there is moreover no explicit restriction in the context of concepts, both concepts C1 and C2 are well-formed.
And indeed, as compared to the restriction on closure types in some declarations, concepts are not instantiated, as per [temp.concept]/5, and does fall under the ODR-considerations that are considered "a bit tricky" in  P0315R4.


text:
Q: Python. Trouble adding values to nested Dictionaries from a for loop I guess I have two questions. First is "is the path I'm going down below the right way, and if not, what should I be doing?" and second is "how do I stop overwriting the values".
In the code below, how do I make "monthdict" output the same as "report"?
Report is a list of values where (e.g.) january week1 monday bread is 1, but february week1 monday bread is 31. When I try to recreate it programattically it makes ALL the breads 53.
My real world usage has actual data that's coming in from an API that I can only 7 items from at a time. So I need to call jan week 1 monday, week 1 tuesday, week 1 wednesday in order, jan week 2 monday etc. repeatedly and return the values
report = {
    "january" : {
        "week1" : {
            "monday" : {
                 "bread" : 1,
                 "cheese" : 2,
                 "milk" : 3
                 },
            "tueday" : {
                 "bread" : 4,
                 "cheese" : 5,
                 "milk" : 6
                 },
            "wednesday" : {
                 "bread" : 7,
                 "cheese" : 8,
                 "milk" : 9
                 },
        },
        "week2" : {
            "monday" : {
                 "bread" : 11,
                 "cheese" : 12,
                 "milk" : 13
                 },
            "tueday" : {
                 "bread" : 14,
                 "cheese" : 15,
                 "milk" : 16
                 },
            "wednesday" : {
                 "bread" : 17,
                 "cheese" : 18,
                 "milk" : 19
                 },
        },
        "week3" : {
            "monday" : {
                 "bread" : 21,
                 "cheese" : 22,
                 "milk" : 23
                 },
            "tueday" : {
                 "bread" : 24,
                 "cheese" : 25,
                 "milk" : 26
                 },
            "wednesday" : {
                 "bread" : 27,
                 "cheese" : 28,
                 "milk" : 29
                 },
        },
    },
    "february" : {
        "week1" : {
            "monday" : {
                 "bread" : 31,
                 "cheese" : 32,
                 "milk" : 33
                 },
            "tueday" : {
                 "bread" : 34,
                 "cheese" : 35,
                 "milk" : 36
                 },
            "wednesday" : {
                 "bread" : 37,
                 "cheese" : 38,
                 "milk" : 39
                 },
        },
        "week2" : {
            "monday" : {
                 "bread" : 111,
                 "cheese" : 112,
                 "milk" : 113
                 },
            "tueday" : {
                 "bread" : 114,
                 "cheese" : 115,
                 "milk" : 116
                 },
            "wednesday" : {
                 "bread" : 117,
                 "cheese" : 118,
                 "milk" : 119
                 },
        },
        "week3" : {
            "monday" : {
                 "bread" : 121,
                 "cheese" : 122,
                 "milk" : 123
                 },
            "tueday" : {
                 "bread" : 124,
                 "cheese" : 125,
                 "milk" : 126
                 },
            "wednesday" : {
                 "bread" : 127,
                 "cheese" : 128,
                 "milk" : 129
                 },
        }
    }
}

print("\nreport:\n", report, "\n\n")

months = ["january", "february"]
weeks = ["week1", "week2", "week3"]
days = ["monday", "tuesday", "wednesday"]
food = ["bread", "cheese", "milk"]
values = []

for i in range(1,129):
    values.append(i)

x = 0

fooddict = {}
daydict = {}
weekdict = {}
monthdict= {}

for m in months:
    for w in weeks:
        for d in days:
            for f in food:
                fooddict[f] = values[x]
                x += 1
                print(x, ") adding ", values[x], " to ", f)
            daydict[d] = fooddict
        weekdict[w] = daydict
    monthdict[m] = weekdict

print(monthdict)

A: Try this
monthdict= {}
for m in months:
    weekdict = {}
    for w in weeks:
        daydict = {}
        for d in days:
            fooddict = {}
            for f in food:
                fooddict[f] = values[x]
                x += 1
                print(x, ") adding ", values[x], " to ", f)
            daydict[d] = fooddict
        weekdict[w] = daydict
    monthdict[m] = weekdict

Otherwise, you are sharing the values from the previous month, week, and days (instead, they should start as empty for each new iteration).


text:
Q: Python dictionary key order when printing s={
        'userName': "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf",
        'userNameMin': "\u4e0d\u80fd\u5c0f\u4e8e4\u4e2a\u5b57",
        'userNameMax': "\u4e0d\u80fd\u8d85\u8fc712\u4e2a\u5b57",
        'userNameExist': "\u8be5\u7528\u6237\u540d\u5df2\u88ab\u6ce8\u518c\u4e86\uff0c\u8bf7\u6362\u6362",
        'userNameInvalid': "\u53ea\u652f\u6301\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf",
        'userNameStartInvalid': "\u7528\u6237\u540d\u4e0d\u80fd\u4ee5\u4e0b\u5212\u7ebf\u5f00\u5934",
        'nickName': "6\u4f4d\u4ee5\u5185\u4e2d\u6587\u621612\u4f4d\u4ee5\u5185\u82f1\u6587\u5b57\u7b26",
        'nickNameMin': "\u4e0d\u80fd\u5c0f\u4e8e1\u4e2a\u5b57",
        'nickNameMax': "\u4e0d\u80fd\u8d85\u8fc76\u4e2a\u6c49\u5b57\u621612\u4e2a\u82f1\u6587\u5b57\u7b26",
        'nickNameExist': "\u8be5\u540d\u5b57\u5df2\u88ab\u5360\u7528\uff0c\u8bf7\u6362\u6362",
        'nickNameInvalid': "\u53ea\u652f\u6301\u4e2d\u6587\u3001\u5b57\u6bcd\u6216\u6570\u5b57\uff0c\u4e0d\u652f\u6301\u7a7a\u683c\u548c\u7279\u6b8a\u7b26\u53f7",
        'nickNameError': "\u540d\u5b57\u4e2d\u542b\u6709\u8fdd\u7981\u8bcd\uff0c\u8bf7\u4fee\u6539\uff0c\u671b\u8c05\u89e3",
        'password': "6-16\u4f4d\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf",
        'passwordMin': "\u4e0d\u80fd\u5c0f\u4e8e6\u4e2a\u5b57\u7b26",
        'passwordMax': "\u4e0d\u80fd\u8d85\u8fc716\u4e2a\u5b57\u7b26",
        'passwordInvalid': "\u53ea\u652f\u6301\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf",
        'password1': "\u8bf7\u518d\u786e\u8ba4\u4e00\u6b21\u4f60\u8f93\u5165\u7684\u5bc6\u7801",
        'password1Invalid': "\u4e24\u6b21\u5bc6\u7801\u8f93\u5165\u4e0d\u4e00\u81f4",
        'email': "\u8bf7\u8f93\u5165\u4f60\u5e38\u7528\u7684Email",
        'emailExist': "\u8be5Email\u5df2\u88ab\u6ce8\u518c",
        'emailInvalid': "Email\u683c\u5f0f\u4e0d\u6b63\u786e",
        'sex': "\u8bf7\u9009\u62e9\u4f60\u7684\u6027\u522b",
        'validateCode': "\u8bf7\u8f93\u5165\u56fe\u50cf\u4e2d\u7684\u6587\u5b57",
        'validateCodeInvalid': "\u9a8c\u8bc1\u7801\u9519\u8bef",
        'loading': ' \u6b63\u5728\u68c0\u67e5\u552f\u4e00\u6027',
        'checkCode': ' \u6b63\u5728\u68c0\u67e5\u9a8c\u8bc1\u7801',
        'ok': '',
        'required': "\u5fc5\u586b"
    }

for i,j in s.items():
        print i,j.decode('unicode-escape')

output:
password1 请再确认一次你输入的密码
required 必填
userNameExist 该用户名已被注册了,请换换
nickNameMax 不能超过6个汉字或12个英文字符
checkCode  正在检查验证码
userNameMin 不能小于4个字
userNameMax 不能超过12个字
userNameInvalid 只支持英文字母、数字和下划线
sex 请选择你的性别
nickNameExist 该名字已被占用,请换换
emailExist 该Email已被注册
passwordMax 不能超过16个字符
emailInvalid Email格式不正确
loading  正在检查唯一性
userNameStartInvalid 用户名不能以下划线开头
passwordInvalid 只支持英文字母、数字和下划线
validateCode 请输入图像中的文字
passwordMin 不能小于6个字符
nickName 6位以内中文或12位以内英文字符
email 请输入你常用的Email
nickNameError 名字中含有违禁词,请修改,望谅解
password 6-16位英文字母、数字和下划线
userName 4-12个英文字母、数字和下划线
ok
nickNameMin 不能小于1个字
password1Invalid 两次密码输入不一致
nickNameInvalid 只支持中文、字母或数字,不支持空格和特殊符号
validateCodeInvalid 验证码错误

My question is: the order is disturbed
how does Output sequence.
thanks

A: Use OrderedDict on python 2.7+
Or change dict to tuple or list, something like this
[
    ('userName', "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf"),
    ('userNameMin', "\u4e0d\u80fd\u5c0f\u4e8e4\u4e2a\u5b57"),
    ....
]

And use s instead of s.items()
for i,j in s:
        print i,j.decode('unicode-escape')

A: dicts are unsorted. If you need keys to be output in a specific order then use a list to hold them, then index the dict by each of the keys in order.

A: you could always do a sort before you print ?
for k in sorted(s.keys()):
      print k,s[k].decode('unicode-escape')

A: Use tuple () or array [] instead of dictionary/map {} - tuples and arrays keep their sequence but do not allow using keys, dictionaries do not keep their sequence but allow using keys.
s=(
    ('userName', "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf"),
    ('userNameMin', "\u4e0d\u80fd\u5c0f\u4e8e4\u4e2a\u5b57"),
    ('userNameMax', "\u4e0d\u80fd\u8d85\u8fc712\u4e2a\u5b57"),
    .
    .
    .
)

for (i,j) in s:
    print i,j.decode('unicode-escape')


text:
Q: X-axis of sliding/window correlation I am trying to perform sliding correlation with window=11years.
Here's my code:
library(gtools)
var1<-rnorm(52,0.010,0.05)
var2<-rnorm(52,0.015,0.01)
dat<-merge(var1,var2)
dat$year<-seq(1961,2012,1)

rc<-running(dat$x,dat$y,fun=cor, width=11)

I want to plot the output as a simple line plot like this:
plot(rc,type="l")

My problem is the x-axis. How do I match the correlation value with the years? Something like adding a filler value "0"?
Any suggestions on how I can do this correctly in R.
I'll appreciate any help.
Many thanks in advance.

A: rc <- running(var1, var2, fun = cor, width = 11)
plot(1971:2012, rc, type="l")


text:
Q: Regular Expressions for a password with politics My password has to have at least 6 characters with upper and lower case letters and at least one number or a special character, I do not know how to make them one or the other, i made this regular expression but if i don´t put a number and a special character it don´t send
var password=/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]/

A: In order to achieve what you are trying to do, by assuming minimum characters 6 and maximum 20, you can try the following regex:

var regex = /^(?=.*[0-9])|(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,20}$/;


text:
Q: org.eclipse.jgit.api.errors.TransportException: https://gitlab.com/: cannot open git-upload-pack I am trying to "list remote branches/tags without a local repository". I am using jgit for this. The code snippet is as follows:
     try {
          Git.lsRemoteRepository()
              .setCredentialsProvider(new UsernamePasswordCredentialsProvider("username", "password"))
              .setRemote("https://gitlab.com/<projectname>").call();
          System.out.println("validatation successfull");
        }
        catch (GitAPIException e) {
          System.out.println(e);
        }

The code works fine when I run in eclipse as java program. But when I build a jar and try to run that in command line I get TransportException.
org.eclipse.jgit.api.errors.TransportException: https://gitlab.com/<projectname>: cannot open git-upload-pack
        at org.eclipse.jgit.api.LsRemoteCommand.execute(LsRemoteCommand.java:222)
        at org.eclipse.jgit.api.LsRemoteCommand.call(LsRemoteCommand.java:161)
        at com.bosch.rtc.git.sync.main.GitLabTest.main(GitLabTest.java:25)
Caused by: org.eclipse.jgit.errors.TransportException: https://gitlab.com/<Projectname>: cannot open git-upload-pack
        at org.eclipse.jgit.transport.TransportHttp.connect(TransportHttp.java:626)
        at org.eclipse.jgit.transport.TransportHttp.openFetch(TransportHttp.java:392)
        at org.eclipse.jgit.api.LsRemoteCommand.execute(LsRemoteCommand.java:200)
        ... 2 more
Caused by: java.net.UnknownHostException: gitlab.com
        at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:220)
        at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:403)
        at java.base/java.net.Socket.connect(Socket.java:609)
        at java.base/sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:289)
        at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:177)
        at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:474)
        at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:569)
        at java.base/sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:265)
        at java.base/sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:372)
        at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
        at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1232)
        at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1081)
        at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
        at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1592)
        at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1520)
        at java.base/java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:527)
        at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:334)
        at org.eclipse.jgit.transport.http.JDKHttpConnection.getResponseCode(JDKHttpConnection.java:115)
        at org.eclipse.jgit.util.HttpSupport.response(HttpSupport.java:229)
        at org.eclipse.jgit.transport.TransportHttp.connect(TransportHttp.java:540)
        ... 4 more
https://gitlab.com/<projectname>.git: cannot open git-upload-pack


text:
Q: how to fetch sorted data use namequery for fetching sorted value from db using hibernate, I use this NamedQuery:
@NamedQuery(
    name = "searchnearestdesc",
    query = "select t FROM Result t WHERE t.indec=:e"
        + "t.var<=:f ORDER BY var DESC"
    )

But, I get exception,
what is my error?

A: You need a AND between your clauses, also don't forget the trailing space when concatening strings ;)
@NamedQuery(
name = "searchnearestdesc",
query = "select t FROM Result t WHERE t.indec=:e AND "
    + "t.var<=:f ORDER BY var DESC"
)


text:
Q: Issue upgrading to latest C# MongoDB Driver I have a .NET Application that uses a MongoDB so I am using mongo c# driver.  Current version I am using is 1.9.2.
I am trying to update this to latest C# mongodb driver - 2.7.0.  I have had to make numerous code changes so far for breaking changes.  I am stumped with a few at the minute - may raise new questions for the others in due course but the one below has been causing the App to not even load when debugging.
This was my original code with the 1.9.2 driver:
    /// <summary>
    /// Since the current Mongo driver does not support database side Select
    /// projections, we need to use this custom function to achieve the same.
    /// </summary>
    /// <param name="criteria"></param>
    /// <param name="fields"></param>
    /// <returns></returns>
    public IEnumerable<T> Get(Expression<Func<T, bool>> criteria,
        params Expression<Func<T, object>>[] fields)
    {
        return this.Collection.FindAs<T>(Query<T>.Where(criteria)).SetFields
                 (Fields<T>.Include(fields));
    }

This is what I have attempted with the latest C# driver:
    /// <summary>
    /// Since the current Mongo driver does not support database side Select
    /// projections, we need to use this custom function to achieve the same.
    /// </summary>
    /// <param name="criteria"></param>
    /// <param name="fields"></param>
    /// <returns></returns>
    public IEnumerable<T> Get(Expression<Func<T, bool>> criteria,
        params Expression<Func<T, object>>[] fields)
    {
        return this.Collection.Find<T>(criteria).Project(Builders<T>.Projection.Include(FilterDefinitionBuilder<T>.(fields)));
    }

however I am getting a red build error on the .(fields))); saying incorrect primary expression but not sure what the correct fix is for this.
UPDATE
I added the code from mickl answer below and now when run the app I am getting the following exception:
"An error occurred while deserializing the Id property of class MyApp.Domain.Models.EntityBase: Cannot deserialize a 'String' from BsonType 'ObjectId'."

I had a BsonClassRegistration class with my old C# Driver Mongo code - the original code in it was below:
        BsonClassMap.RegisterClassMap<EntityBase>(cm =>
        {
            cm.AutoMap();
            cm.SetIdMember(cm.GetMemberMap(x => x.Id).SetIdGenerator(StringObjectIdGenerator.Instance));
            cm.GetMemberMap(c => c.Id).SetRepresentation(BsonType.ObjectId);
        });

To fix this with the upgrade to the latest C# driver I changed the code to the below:
        BsonClassMap.RegisterClassMap<EntityBase>(cm =>
        {
            cm.AutoMap();
            cm.SetIdMember(cm.GetMemberMap(x => x.Id).SetIdGenerator(StringObjectIdGenerator.Instance));
            cm.GetMemberMap(c => c.Id).SetSerializer(new StringSerializer(BsonType.ObjectId));
        });

Would this be the reason for the failure I am now seeing in the Get method

A: You can use Builders<T>.Projection just like you tried but you have to dynamically build ProjectionDefinition<T> instance which can be done like below:
public IEnumerable<T> Get(Expression<Func<T, bool>> criteria, params Expression<Func<T, object>>[] fields)
{
    var find = Collection.Find<T>(criteria);

    var builder = Builders<T>.Projection;
    var definition = (ProjectionDefinition<T>)null;

    foreach(var field in fields)
    {
        definition = definition?.Include(field) ?? builder.Include(field);
    }

    if (definition == null) return find.ToList();

    return find.Project<T>(definition).ToList();
}


text:
Q: Difference between singleton and eagersingleton for Gin or Guice? I was wondering what is the different between singleton and eagersingleton for Gin or Guice?

A: From Guice's Wiki

Eager singletons reveal initialization problems sooner, and ensure end-users get a consistent, snappy experience. Lazy singletons enable a faster edit-compile-run development cycle. Use the Stage enum to specify which strategy should be used.

*

*Eager: "create an instance of this class when the Module is being run"

*Lazy: "create an instance of this class when it's first requested for dependency injection"


text:
Q: Add days to date in Go I'm trying to add a number of days (actually a number of weeks) to an existing date in Go. I have tried
myDate.Add(time.Hour * 24 * 7 * weeksToAdd)
But I get an error when I try to build: invalid operation: time.Hour * startAdd (mismatched types time.Duration and float64)
So weeksToAdd is currently a float64, but I can change it to an int or whatever. Changing it to an int only changed my error to say that int and Duration can't be multiplied.
How do I add days to a date?

A: You need to convert weeksToAdd into a time.Duration:
myDate.Add(time.Hour * 24 * 7 * time.Duration(weeksToAdd))

In Go, type aliases cannot be used interchangeably even though time.Duration is technically an int64.
Also, here, even though the numeric constants 24 and 7 are not explicitly typed, they can still be used as-is, see https://blog.golang.org/constants for an in-depth explanation.
See http://play.golang.org/p/86TFFlixWj for a running example.
As mentioned in comments and another answer, the use of time.AddDate() is preferable to time.Add() when working on duration superior to 24 hours, since time.Duration basically represents nanoseconds. When working with days, weeks, months and years, a lot of care has to be taken because of things such as daylight saving times, leap years, and maybe potentially leap seconds.
The documentation for time.Duration type and the associated constants representing units emphasize this issue (https://golang.org/pkg/time/#Duration):

There is no definition for units of Day or larger to avoid confusion across daylight savings time zone transitions.

A: Use Time.AddDate():
func (t Time) AddDate(years int, months int, days int) Time

Example:
myDate.AddDate(0, 0, 7 * weeksToAdd)