text:
Q: Please explain &, and * pointers There have been multiple instances where the compiler throws an error when I try to pass variables as arguments inside Go functions. I've been able to debug this sometimes by using a pointer in front of the variable. Both &, and * pointers seem to clear the error. Though, I'd like to understand why. I'm wondering what the difference between &, and * is, and when each should be used. Thank you!
func (ctx *NewContext) SendNotification(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {

    decoder := json.NewDecoder(req.Body)

    var u User

    if err := decoder.Decode(&u); err != nil {
        http.Error(rw, "could not decode request", http.StatusBadRequest)
        return
    }
}

A: In your example above you defined u as type User, but not a pointer to a User. So you need the &u because the Decode function in the json package is expecting an address or pointer.
If you created the instance of User like this: u := new(User) it would be a pointer since the new function returns a pointer. You could also create a pointer to a user like this: var u *User. If you did either of those, you would have to take out the & in the call to Decode for it to work.
Pointers are basically variables that hold addresses. When you put the & in front of a variable it returns the address. The * could be read as 'redirect of'. So when you create a pointer like this:
var x *int
This can be read as x will redirect to an int. And when you assign a value to x you would give it an address like this:
y := 10
x = &y
Where y is some int. So if you were to print out x, you would get the address of y, but if you printed out *x you would redirect to the what x points to which is y's value which is 10. If you were to print out &x, you would get the address of the pointer, x, itself.
If you tried to print out *y, which is just an int, not a pointer, it would throw an error because you would be redirecting with some value that is not an address to redirect to.
Run the below for some pointer fun:
package main

import "fmt"

func main() {
    var y int
    var pointerToY *int
    var pointerToPointerToInt **int

    y = 10
    pointerToY = &y
    pointerToPointerToInt = &pointerToY

    fmt.Println("y: ", y)
    fmt.Println("pointerToY: ", pointerToY)
    fmt.Println("pointerToPointerToInt: ", pointerToPointerToInt)

    fmt.Println("&y: ", &y)     // address of y
    fmt.Println("&pointerToY: ", &pointerToY)// address of pointerToY
    fmt.Println("&pointerToPointerToInt: ", &pointerToPointerToInt) // address of pointerToPointerToInt

    // fmt.Println(*y) throws an error because
    // you can't redirect without an address..
    // y only has int value of 10
    fmt.Println("*pointerToY: ", *pointerToY) // gives the value of y
    fmt.Println("*pointerToPointerToInt: ", *pointerToPointerToInt)     // gives the value of pointerToY which is the address of y

    fmt.Println("**pointerToPointerToInt: ", **pointerToPointerToInt)    // this gives 10, because we are redirecting twice to get y

    if pointerToY == *pointerToPointerToInt {
        fmt.Println("'pointerToY == *pointerToPointerToInt' are the same!")
    }

    if pointerToY == &y {
        fmt.Println("'pointerToY == &y' are the same!")
    }

    if &pointerToY == pointerToPointerToInt {
        fmt.Println("'&pointerToY == pointerToPointerToInt' are the same!")
    }

    if y == **pointerToPointerToInt {
        fmt.Println("'y == **pointerToPointerToInt' are the same!")
    }

    if pointerToY == *pointerToPointerToInt {
        fmt.Println("'pointerToY == *pointerToPointerToInt' are the same!")
    }

}

Hope this helps!

A: A simple example showing the code execution sequence.
   import (
        "fmt"
    )

    func main() {
        x := 0
        fmt.Println("Step 1", x)
        foo(&x)
        fmt.Println("Step 4", x)
    }

    func foo(y *int) {

        fmt.Println("Step 2", *y)
        *y = 100
        fmt.Println("Step 3", *y)
    }
/*
 Steps  Result
   1      0
   2      0
   3      100
   4      100
 */

A: pointer is used to point towards address and it stores the memory address
Adding one example to help understand pointer vs address:
Demo code
package main

import "fmt"

func main() {
    var y int
    var pointerToY *int
    var x int
    //var willThrowErrorVariable int

    y = 10
    pointerToY = &y
    //willThrowErrorVariable = &y
    x = *pointerToY

    fmt.Println("y: ",y)
    fmt.Println("y's address using pointerToY: ",pointerToY)

    y = 4
    fmt.Println("====================================================")
    fmt.Println("Address of y after its value is changed: ",pointerToY)
    fmt.Println("value of y using pointer after its value is changed: ",*pointerToY)
    fmt.Println("Value of x after y value is changed: ",x)
}

output

y:  10
y's address using pointerToY:  0x414020
====================================================
Address of y after its value is changed:  0x414020
value of y using pointer after its value is changed:  4
Value of x after y value is changed:  10

As we can see, the value might change but the address(&) remains same and so the pointer(*) points to the value of address.
In above example,

*

*pointerToY holds the pointer to refer address of y.

*x holds the value which we pass to it using pointer to address of y.

*After changing the value of y , the x still has 10 but if we try to access the value using pointer to address (pointerToY) , we get 4

A: I will quote one smart dude:

& in front of variable name is used to retrieve the address of where
  this variable's value is stored. That address is what the pointer is
  going to store.
* in front of a type name, means that the declared variable will store an address of another variable of that type (not a value of that
  type).
* in front of a variable of pointer type is used to retrieve a value stored at given address. In Go speak this is called dereferencing.

source: http://piotrzurek.net/2013/09/20/pointers-in-go.html

A: For this answer I will try to explain it with a variable value. A pointer can point also to a struct value.
& returns a pointer, which points to a variable value.
* reads the variable value to which the pointer is pointing.
Example:
func zero(xPointer *int) {
  *xPointer = 0
  fmt.Println(*xPointer)
}

func main() {
  x := 1
  zero(&x)
  fmt.Println(x) // x is 0
}

A: I would like to explain the concept of pointers(* and &) with an example:
Think of an example where we want to increment a variable by 1 with help of a function.
package main

import (
    "fmt"
)

func main() {
    x := 7
    fmt.Print(inc(x))
}
func inc(x int) int {
    return x + 1
}

Explanation of above: We have a function func inc(x int) int which takes an integer and returns an integer with performing an increment.

Note: Kindly pay attention that func inc(x int) int  returns an int, Now what happens if we do not have a return type with that
function?? This is solved by the pointer.

Look at the below code:
package main

import (
    "fmt"
)

func main() {
    x := 7
    inc(&x)
    fmt.Print(x)

}
func inc(x *int) {
    *x++
}

Explanation of the above code:
Now as our function func inc(x *int) does not have a return type we cannot get any incremented value from this function but what we can do is that we can send a location(address) to this function and tell it to increment the value at this location by one and now we can access that location from inside main() and our job is done.
A quick tip: * in front of a variable means what is stored in that variable?? and & in front of a variable means what is the internal address of that variable?


text:
Q: Using \return command in python function I'm trying to document a function in my python code and want to include the \return command. Lets say like this:
## \file
# File description

## Function to show you the problem.
#
# \return boolean True
def retTrue():
  return True

When I run doxygen on this it creates an entry in the corresponding file, but it just places the text "Function to show you the problem." next to the function. The function itself isn't linked and the \return command isn't used.
If I set EXTRACT_ALL = YES it works (means the function name is linked and a description block also showing the return text is created), but I'm sure there's a more elegant way to get this done without having every file of the project listed.
I tried \return for a class method, there it works immediately, so I guess I just can't figure out which is the correct option to set. The other EXTRACT_ options didn't work for me.
I'd really appreciate it if someone could tell me the magic setting.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linker error when including an .h file but disappears when including the correspondent .cpp file This is strange. How can it possibly be that I get an error when I'm including an .h file (GeneralSearch.h) but everything seems to work just fine when, instead, I include the .cpp file (GeneralSearch.cpp)?
.h file
#ifndef GENERALSEARCH_H_
#define GENERALSEARCH_H_

#include "Problem.h"
#include "Node.h"

template <class T>
class GeneralSearch
{
public:

    const Node* treeSearch(const Problem &problem) const;
    const Node* graphSearch(const Problem &problem, T &fringe = T()) const;

private:
    void expand(const Node &node, const Problem &problem, list<const Node*> &out) const;
};

#endif

.cpp file
#include "GeneralSearch.h"
template <class T>
void GeneralSearch<T>::expand(const Node &node, const Problem &problem, list<const Node*> &out) const
{
...
}

template <typename T>
const Node* GeneralSearch<T>::treeSearch(const Problem &problem) const
{
...
}

template <typename T>
const Node* GeneralSearch<T>::graphSearch(const Problem &problem, T &fringe = T()) const
{
...
}

the program file - WORKING
#include "GeneralSearch.cpp"
#include "DummyProblem.h"
#include "DepthFirstSearch.h"
#include <queue>

int main (int argc, char* argv[]){}

the program file - NOT WORKING
#include "GeneralSearch.h"
#include "DummyProblem.h"
#include "DepthFirstSearch.h"
#include <queue>

int main (int argc, char* argv[]){}

A: The linker tries to find the definitions of unresolved names while linking. In the second case, the linker is not able to find the definitions of the member functions of the class GeneralSearch and hence you get the error.


text:
Q: Referencing a helper class I am trying to write a helper class for my module. The helper class will provide two methods with various functionality. Can I put this helper class beside the other helper class in my .../Helper/Data.php file or should I put it somewhere else? Also, how should I reference it from other parts of Magento in order to get access to its methods?

A: You can create a new file with your helper-Class in the /Helper folder of your module. You can load your own helper in the same way as you load the Data-Helper.
If you configured your helpers in etc/config.xml like the following:
<helpers>
   <mynamespace_mymodule>
      <class>MyNamespace_MyModule_Helper</class>
   </mynamespace_mymodule>
</helpers>

...you can load your custom helper MyNamespace_MyModule_Helper_Custom (located in /app/code/local/MyNamespace/MyModule/Helper/Custom.php) by:
Mage::helper('mynamespace_mymodule/custom')

The required MyNamespace_MyModule_Helper_Data can be loaded by:
Mage::helper('mynamespace_mymodule')

or
Mage::helper('mynamespace_mymodule/data')

Why?
public function getHelperClassName($helperName)
{
    if (strpos($helperName, '/') === false) {
        $helperName .= '/data';
    }
    return $this->getGroupedClassName('helper', $helperName);
}

A: You can create as many helpers as you want in your module.
Let's say your module name is Namespace_Module.
The config.xml of your module should contain this inside the <global> tag:
<helpers>
    <module>
       <class>Namespace_Module_Helper</class>
    </module>
</helpers>

Now let's say you want to create a helper called Something.
You should place the code in Namespace/Module/Helper/Something.php:
<?php
class Namespace_Module_Helper_Something extends Mage_Core_Helper_Abstract { //or any other helper

    public function doSomething(){
        ....
    }
}

You can call your new helper anywhere like this:
Mage::helper('module/something')->doSomething();

Basically Mage::helper('module'); is the same thing as Mage::helper('module/data');


text:
Q: Type ... is not assignable to type 'never'.(2322) The following code snippet reports an error Type 'string' is not assignable to type 'never'.(2322) in the line obj[prop] = value and I struggle understanding why?
interface fooType {
    s: string,
    n: number,
}

function bar(value: string, obj: fooType, prop: keyof fooType) {
    if (typeof value === 'string') {
        obj[prop] = value;
    }
}

const foo = {s: '', n: 0};

bar('s', foo, 's');

console.log(foo);

A: fooType['s'] is type string, fooType['n'] is type number, so obj[prop] is type string & number because it's the only type assignable to obj[prop]. And string & number = never

A: prop: keyof fooType means that prop could be "s" or "n". But those two property values have incompatible types. So typescript tries to infer a value that could be assignable to both by finding the intersection of the types of the properties .s and .n. So it does: string & number, which have no overlap, so the type is never.
If you want to type an argument as a union (like "s" | "n") and you need to know which member of that union it is, then you need generics.
For generic parameters you need at least two here. One for the property name (we'll use K for key) you wish to update, and one for the value to make sure the it matches the property's type (we'll use V for value).
You can now drop the typeof value === 'string' because typescript will ensure the value is the right type for the property.
function bar<
    K extends keyof fooType,
    V extends fooType[K]
>(
    value: V,
    obj: fooType,
    prop: K
) {
    obj[prop] = value;
}

const foo = {s: '', n: 0};

bar('string', foo, 's'); // works
bar(123, foo, 'n'); // works

// Should be type errors:
bar('string', foo, 'n') // '"string"' is not assignable to parameter of type 'number'
bar(123, foo, 's') // '123' is not assignable to parameter of type 'string'.

A: you need to use generics here, then it can match the types correctly.
interface fooType {
    s: string,
    n: number,
}

function bar<
  OBJ extends fooType,
  KEY extends keyof OBJ,
  VAL extends OBJ[KEY]
>(value: VAL, obj: OBJ, prop: KEY) {
  obj[prop] = value;
}

const foo = {s: '', n: 0};

bar('s', foo, 's');

console.log(foo);


text:
Q: Can not add user to a group with Ldap in Java I am new with using Ldap API for Java and I want to add a user to a group but I'm failing all the time.
I am using this code for adding specific user to a specific group:
private void insertUserToGroup(List<DistinguishedName> memberOf, DistinguishedName newUserDN) {
    try
    {
        // Loop all groups to put the user in.
        for(DistinguishedName groupDn : memberOf) {

            String encodedGroupDn = groupDn.encode(); // Example: "cn=GROUP_SKL, ou=roles"
            String encodedUserDn = newUserDN.encode(); // Example: "cn=user_dfh, ou=external"

            // Now. Add user to a group.
            ModificationItem member[] = new ModificationItem[1];
            member[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("member", encodedUserDn));
            ldapTemplate.modifyAttributes(encodedGroupDn, member);
        }
    } catch ( InvalidAttributeValueException exc ) {
        throw exc;
    } catch ( NameAlreadyBoundException exc ) {
        throw exc;
    } catch ( NameNotFoundException exc ) {
        throw exc;
    } catch (Exception exc) {
        throw exc;
    }
}

The input arguments is list of groups and the user and you can see in the example comments how the DistinguishedName will look like.
1. And the exception i get when i run ldapTemplate.modifyAttributes(encodedGroupDn, member); is:
org.springframework.ldap.NameNotFoundException: [LDAP: error code 32 - 00000525: NameErr: DSID-031A11CC, problem 2001 (NO_OBJECT), data 0, best match of:
    ''
];
nested exception is javax.naming.NameNotFoundException: [LDAP: error code 32 - 00000525: NameErr: DSID-031A11CC, problem 2001 (NO_OBJECT), data 0, best match of:
        ''
];
remaining name 'cn=GROUP_SKL, ou=roles'
2. I have tried to run modifyAttributes(...) with other attributes like "description", "company" and that works for both Groups and Users but not the attribute "member".
3. So the question is. What name do it expect? Is the DistinguishedName wrong? Or is this way to add a user to a group totally wrong? Or is it some details I am missing?

A: Now I found the error.
All I needed was to use the full address for the User DN. So I think that 'member' attribute for the group must have the full address. So both DN looks like this now:
encodedGroupDn = "cn=GROUP_SKL, ou=roles"
encodedUserDn = "cn=user_dfh, ou=external, ou=main, dc=nr, dc=company, dc=local"
And that works!


text:
Q: ArrayLists With Zero and Two Outcomes for Junit Tests I need help with this piece of code. I need to write a test just like testfindOverviewByStatus() example in the code below but I need to write it for 2 pieces of data and 0 pieces. testfindOverviewByStatus() is a test for if there is only one piece of data in the list. I tried writing the two different tests I need at the end of the code but was unsuccessful in doing so. Can anyone help me?
package com.primatics.greensight.dashboard.controller;

import static org.junit.Assert.assertEquals;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringRunner;

import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import com.primatics.greensight.dashboard.UnitTest;
import com.primatics.greensight.dashboard.model.Overview;
import com.primatics.greensight.dashboard.repositories.ScenarioDashboardRepository;
import com.primatics.greensight.dashboard.repositories.impl.ScenarioDashboardRepositoryImpl;
import com.primatics.greensight.dashboard.services.ScenarioDashboardService;
import com.primatics.greensight.dashboard.services.impl.ScenarioDashboardServiceImpl;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ScenarioDashboardServiceImpl.class)
@AutoConfigureMockMvc
@EnableAutoConfiguration
@Category(UnitTest.class)
public class ScenarioDashboardServiceImplUnitTest {

    @Configuration
    static class AccountServiceTestContextConfiguration {
        @Bean
        public ScenarioDashboardRepositoryImpl scenarioDashboardService() {
            return new ScenarioDashboardRepositoryImpl();
        }

        @Bean
        public ScenarioDashboardRepository scenarioDashboardtRepository() {
            return Mockito.mock(ScenarioDashboardRepositoryImpl.class);
        }
    }

    @Mock
    private ScenarioDashboardService scenarioDashboardService;

    @Before
    public void doSetUp() {
        List<Overview> scenarioListTest = new ArrayList<Overview>();

        String name = "first_scenario-test";
        ISO8601DateFormat df = new ISO8601DateFormat();
        Date estimationDate = null;
        try {
            estimationDate = df.parse("2017-01-28T22:25:51Z");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date creationDate = null;
        try {
            creationDate = df.parse("2017-02-28T22:25:51Z");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Double balance = 131750000.0;
        Double individualReviewImpairment = 1000.00;
        Map<String, Double> baseline = new HashMap<String, Double>();
        baseline.put("complete", 1000.0);

        Map<String, Double> macroAdjustment = new HashMap<String, Double>();
        macroAdjustment.put("complete", 2000.0);

        Map<String, Double> qualitativeAdjustment = new HashMap<String, Double>();
        qualitativeAdjustment.put("complete", 3000.0);

        Date positionDate = null;
        try {
            positionDate = df.parse("2017-01-28T22:25:51Z");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date lossHistoryDate = null;
        try {
            lossHistoryDate = df.parse("2017-01-28T22:25:51Z");
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String status = "active";

        Map<String, Integer> period = new HashMap<String, Integer>();
        period.put("Q1", 2017);

        boolean publish = true;

        Overview ac = new Overview(4, name, estimationDate, creationDate, balance, individualReviewImpairment, baseline,
                macroAdjustment, qualitativeAdjustment, positionDate, lossHistoryDate, status, period, publish);

        scenarioListTest.add(ac);

        Mockito.when(scenarioDashboardService.getOverviewByStatus("active")).thenReturn(scenarioListTest);

    }

    @Before
    public void getTwoOverviews() {

        List<Overview> scenarioListTest2 = new ArrayList<Overview>();

        String name = "first_scenario-test";
        ISO8601DateFormat df = new ISO8601DateFormat();
        Date estimationDate = null;
        try {
            estimationDate = df.parse("2017-01-28T22:25:51Z");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date creationDate = null;
        try {
            creationDate = df.parse("2017-02-28T22:25:51Z");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Double balance = 131750000.0;
        Double individualReviewImpairment = 1000.00;
        Map<String, Double> baseline = new HashMap<String, Double>();
        baseline.put("complete", 1000.0);

        Map<String, Double> macroAdjustment = new HashMap<String, Double>();
        macroAdjustment.put("complete", 2000.0);

        Map<String, Double> qualitativeAdjustment = new HashMap<String, Double>();
        qualitativeAdjustment.put("complete", 3000.0);

        Date positionDate = null;
        try {
            positionDate = df.parse("2017-01-28T22:25:51Z");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date lossHistoryDate = null;
        try {
            lossHistoryDate = df.parse("2017-01-28T22:25:51Z");
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String status = "active";

        Map<String, Integer> period = new HashMap<String, Integer>();
        period.put("Q1", 2017);

        boolean publish = true;

        Overview ac = new Overview(4, name, estimationDate, creationDate, balance, individualReviewImpairment, baseline,
                macroAdjustment, qualitativeAdjustment, positionDate, lossHistoryDate, status, period, publish);

        scenarioListTest2.add(ac);

        Mockito.when(scenarioDashboardService.getOverviewByStatus("active")).thenReturn(scenarioListTest2);
    }

    @Test
    public void testfindOverviewByStatus() {
        List<Overview> scenarioListTest = scenarioDashboardService.getOverviewByStatus("active");
        assertEquals(1, scenarioListTest.size());

        String scenarioName = scenarioListTest.get(0).getScenarioName();
        assertEquals("first_scenario-test", scenarioName);
    }

    @Test
    public void testfindOverviewByStatusTwo() {

        List<Overview> scenarioList = scenarioDashboardService.getOverviewByStatus("active");
        assertEquals(2, scenarioList.size());

        String scenarioName = scenarioList.get(0).getScenarioName();
        String scenarioName2 = scenarioList.get(1).getScenarioName();
        assertEquals("first_scenario-test", scenarioName);
        assertEquals("second_scenario-test", scenarioName2);
    }

    @Test
    public void testfindOverviewByStatusNull() {

        List<Overview> scenarioListNull = scenarioDashboardService.getOverviewByStatus("active");
        assertEquals(0, scenarioListNull.size());
    }
}

A: The problem is with the layout of your test. You have multiple @Before methods which all mock scenarioDashboardService.getOverviewByStatus("active")
The simplest way to get your tests working would be to remove the @Before annotations and instead invoke them methods in the @Test method.
So for example:
public void getTwoOverviews() {
    //Contents of method
}

@Test
public void testfindOverviewByStatusTwo() {
    //Setup
    getTwoOverviews();

    List<Overview> scenarioList = scenarioDashboardService.getOverviewByStatus("active");
    assertEquals(2, scenarioList.size());

    String scenarioName = scenarioList.get(0).getScenarioName();
    String scenarioName2 = scenarioList.get(1).getScenarioName();
    assertEquals("first_scenario-test", scenarioName);
    assertEquals("second_scenario-test", scenarioName2);
}

As I mentioned this would be the simplest way but in the long run there most likely is a better way to layout your test class.

A: In situations where Mockito is already a dependency you might find it easier to use a custom argument matcher for this:
private class isListOfSize extends ArgumentMatcher<List<Overview>> {
    int size;

    isListOfSize(int size) {
        this.size = size;
    }

    @Override
    public boolean matches(Object list) {
        return ((List) list).size() == size;
    }
}

Usage:
assertThat(scenarioList, argThat(new isListOfSize(2)))


text:
Q: Can you use combineReducers to compose deep state reducers? Redux docs suggest using normalizr to design the shape of the state like this:
{
  entities: {
    cards: {
      42: {
        id: 42,
        text: 'Hello',
        category: 2
      },
      43: {
        id: 53,
        text: 'There?',
        category: 1
      },
    }
    categories: {
      1: {
        id: 1,
        name: 'Questions'
      }
      2: {
        id: 2,
        name: 'Greetings'
      },
    }
  },
  filter: 'SHOW_ALL',
  allCardsList: {
    isFetching: false,
    items: [ 42, 43 ]
  },
}

Naturally, this would split into three composable reducers (filter, allThingsList and entities), but it seems to me that I'd want to write separate reducers for entities.cards and entities.categories.
Is there a way to split management of entities into subreducers that would allow composition like this:
let rootReducer = combineReducers({
   entities: {
      things,
      categories
   },
   filter,
   allCardsList
});

Are there any advantages to keeping the cards and categories in entities, instead of keeping on the root level (which will allow composition using combineReducers)?
{
  cards: { ... },
  categories: { ... },
  filter: 'SHOW_ALL',
  allCardsList: { ... }
}

A:
Is there a way to split management of entities into subreducers that would allow composition like this?

Sure! combineReducers() just gives you a reducer so you can use it several times:
let rootReducer = combineReducers({
   entities: combineReducers({
      things,
      categories
   }),
   filter,
   allCardsList
});

The shopping-cart example in Redux repo demonstrates this approach.

Are there any advantages to keeping the cards and categories in entities, instead of keeping on the root level?

It's up to you but I find the structure you suggest easier to work with. It's indeed easier for understanding to group all entities under a single key, and it is possible with combineReducers() as I show above.


text:
Q: Is there a simple enough formula for this geometric series problem? A friend of mine has recently started a challenge in which he starts by doing 22 pressups and then nominates somebody else to do 22 pressups the next day. This continues every day in which those who have not exceeded 22 nominations (22 days) continue to do their pressups and make their nominations.
What is the geometric formula for this progression? This assumes no one asks the same person twice and everyone accepts their nomination. Additionally how long before the number of people involved will exceed the population of the Earth at ~7.4 billion?
This begins as a simple 2^n progression however after the 22nd day it gets complicated as my friend is no longer involved, and those that have exceeded their 22 day period no longer participate.
Ideally I would like to say how many people will be doing pressups on day 50/60/70 etc, is it possible to derive a formula that I can plug these number into to work this out? It would be easy to create a program to compute this but I wondered if it could be worked out by simple pen and paper and perhaps a calculator alone.

A: This can be modeled with a linear recurrence.
The first person to begin starts on Day $1$, which means we can treat him as if he were nominated on Day $0$, since anyone who is nominated begins the challenge starting the following day.
Let $T(n)$ be the number of people participating on day $n$ (i.e. the number of people who are doing pressups / giving out nominations on that day):
$$T(n) = \sum_{k=1}^{22} T(n-k)$$
Base cases: $T(n)=0$ for $n<0$, $T(0) = 1$, and $T(n) = 2^{n-1}$ for $1 \leq n \leq 22$.
This is similar to the Fibonacci sequence, except instead of degree $2$, it's degree $22$.
Day $34$ is when the total number of participants exceeds the planet's population, at $T(34) = 8589921280$.
Here is a table of results:
\begin{array} {|r|r|}
\hline
n &T(n)\\
\hline
1 & 1 \\
\hline
2 & 2 \\
\hline
3 & 4 \\
\hline
4 & 8 \\
\hline
5 & 16 \\
\hline
6 & 32 \\
\hline
7 & 64 \\
\hline
8 & 128 \\
\hline
9 & 256 \\
\hline
10 & 512 \\
\hline
11 & 1024 \\
\hline
12 & 2048 \\
\hline
13 & 4096 \\
\hline
14 & 8192 \\
\hline
15 & 16384 \\
\hline
16 & 32768 \\
\hline
17 & 65536 \\
\hline
18 & 131072 \\
\hline
19 & 262144 \\
\hline
20 & 524288 \\
\hline
21 & 1048576 \\
\hline
22 & 2097152 \\
\hline
23 & 4194303 \\
\hline
24 & 8388605 \\
\hline
25 & 16777208 \\
\hline
26 & 33554412 \\
\hline
27 & 67108816 \\
\hline
28 & 134217616 \\
\hline
29 & 268435200 \\
\hline
30 & 536870336 \\
\hline
31 & 1073740544 \\
\hline
32 & 2147480832 \\
\hline
33 & 4294961152 \\
\hline
34 & 8589921280 \\
\hline
35 & 17179840512 \\
\hline
36 & 34359676928 \\
\hline
37 & 68719345664 \\
\hline
38 & 137438674944 \\
\hline
39 & 274877317120 \\
\hline
40 & 549754568704 \\
\hline
\end{array}
Python 2.x script:
DEGREE = 22

cache = {}

def T(n):
    if n<0:
        return 0
    if n==0:
        return 1
    if n in cache:
        return cache[n]
    cache[n] = sum(T(n-k) for k in xrange(1, DEGREE+1))
    return cache[n]

for n in xrange(1, 41):
    print "n = %s, T(n) = %s" % (n, T(n))

A: One way to approach this is through generating functions.
Let $a_n$ be the number of people participating on day $n$, starting with 1 person on day one ($a_0=1$) who participates on days 0,...,21, and who invites 22 new participants who start on days 1,...,22.
We represent this sequence $a_n$ through a generating function: $A(x)=\sum_{i=0}^\infty a_n x^n.$ This is just a formal power series, so we don't even require that it converge, although it will in our case.
Now, the first person participates on days 0,...,21, which contribute the sum $1+x+\cdots+x^21$ to $A(x)$. The person invited to start on day $k=1,\ldots,22$ will start a new chain of invitation, leading to $a_n$ participants on day $k+n$, which contributes $x^kA(x)$ for each $k$. So this makes the total
$$
A(x)=(1+x+\cdots x^{21})+(x+\cdots+x^{22})A(x)
=\frac{1-x^{22}}{1-x}\cdot(1+xA(x))
$$
which solves to
$$
A(x)=\frac{1-x^{22}}{1-2x+x^{23}}.
$$
If we rewrite this as $A(x)\cdot(1-2x+x^{23})=1-x^{22}$, we get $a_n=2^n$ for $n=0,\ldots,21$, $a_{22}=2^{22}-1$ as the first participant leaves, and thereafter we get $a_n=2a_{n-1}-a_{n-23}$.
In the long run, I would expect $a_n\sim C\cdot 1.999999762^n$ based on the roots of $1-2x+x^{23}$ (haven't checked this properly).


text:
Q: Vue - composition API Array inside reactive is not updating in the DOM I have an Array of posts inside reactive() and I want it to be updated onMounted.
How can I do this?
TEMPLATE:
<q-card>
  <board-item-list :items="items" v-if="items.length" />
  <board-empty v-else />
</q-card>

SCRIPT
import { reactive, onMounted } from "vue";
import { posts } from "./fake-data.js";
export default {
  setup() {
    let items = reactive([]);
    ...
    onMounted(() => {
      // to fill the items with posts.
      items.values = posts; // I tried this not working
      items = posts; //I tried this not working
      console.log(items);
    });
    ...
    return {
      ...
      items,
    };
  },
};

A: Try to use ref instead of reactive or define items as nested field in a reactive state like :
import { reactive, onMounted } from "vue";
import { posts } from "./fake-data.js";
export default {
  setup() {
    let state= reactive({items:[]});
    ...
    onMounted(() => {

      state.items = posts;
      console.log(state.items);
    });
    ...
    return {
      ...
      state,
    };
  },
};

in template :
<q-card>
  <board-item-list :items="state.items" v-if="state.items.length" />
  <board-empty v-else />
</q-card>

if you want to get rid of state in the template you could use toRefs:
import { reactive, onMounted,toRefs } from "vue";
import { posts } from "./fake-data.js";
export default {
  setup() {
    let state= reactive({items:[]});
    ...
    onMounted(() => {

      state.items = posts;
      console.log(state.items);
    });
    ...
    return {
      ...toRefs(state),//you should keep the 3 dots
    };
  },
};

A: composition api is very frustrating, vue2 was much better.
composition api is much more complex with basically no tangible benefit
composition api has so many reactivity problems like the above, proxy objects, pointless wrapper, total waste of space imho, vue3 is a great example of developers wrecking a good project.


text:
Q: Diacritic Replacement in VBScript using the "Unicode Collation Algorithm" I am writing a function to normalize diacritic (and other non-a-zA-Z0-9 chars) in a string.
In this comment in a related post, tchrist suggests not hard-coding any mappings e.g. "p̈"="p", and instead, to use the Unicode Collation Algorithm.
How can one implement this in vbscript?


text:
Q: Log4net traceappender not logging anything I'd like to redirect everything logged by log4net to the System.Diagnostics Trace classes. My understanding of what I should be doing is pointing log4net at system.diagnostics.traceappender, then I configure system.diagnostics. Here's important parts in my web.config:
<log4net>
<appender name="trace" type="log4net.Appender.TraceAppender, log4net">
  <immediateFlush value="true" />
  <layout type="log4net.Layout.PatternLayout,log4net">
    <param name="ConversionPattern"
         value="%d{ABSOLUTE} %-5p %c{1}:%L - %m%n" />
  </layout>
</appender>

<root>
  <priority value="DEBUG"/>
  <appender-ref ref="trace"/>
</root>
</log4net>

<system.diagnostics>
<sources>

  <source name="Console" switchName="DefaultSwitch">
    <listeners>
      <add type="System.Diagnostics.DefaultTraceListener" name="Default">
        <filter type="" />
      </add>
    </listeners>
  </source>

  <source name="Metabase" switchName="MetabaseSwitch">
    <listeners>
      <add name="MetabaseListener" />
      <remove name="Default" />
    </listeners>
  </source>

  <source name="TextFile" switchName="TextFileSwitch">
    <listeners>
      <add name="TextFileListener" />
      <remove name="Default" />
    </listeners>
  </source>

</sources>
<sharedListeners>
  <!--<add name="ConsoleListener" type="XXX.Manufacturing.Utilities.Diagnostics.ColorConsoleTraceListener,XXX.Manufacturing.Utilities" />-->
  <add name ="TextFileListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="TextFile.log" />
  <add name="MetabaseListener" type="XXX.Manufacturing.Utilities.Diagnostics.MetabaseTraceListener,XXX.Metabase.Proxies" />
</sharedListeners>
<switches>
  <add name="MetabaseSwitch" value="Information" />
  <add name="DefaultSwitch" value="Verbose" />
  <add name="TextFileSwitch" value="Verbose"/>
</switches>
</system.diagnostics>

Did I miss a crucial step linking things up? If I bypass log4net and just create a new tracesource it will log to my sources.

A: Did you call the XmlConfigurator.Configure(); method?
If that is not the problem then you can either turn on internal debugging (explained here) or maybe configure a console appender and see if that is working.
Edit: I am not that familiar with the trace system, but if you configure a trace listener as follows you should get the log4net output:
<system.diagnostics>
  <trace autoflush="true">
    <listeners>
      <add
         name="textWriterTraceListener"
         type="System.Diagnostics.TextWriterTraceListener"
         initializeData="C:\temp\log4net.txt" />
    </listeners>
  </trace>
</system.diagnostics>

A: I added the call to XmlConfigurator.Configure() and turned on internal logging. What I saw was log4net was logging, but nothing was reaching the trace system. After playing with my app.config for a while I found a configuration that worked, most notable changes seemed to be ditching the sources in my Systems.Diagnostics config and making sure the  log4net level attribute was set. Working config sections:
<log4net>
  <appender name="trace" type="log4net.Appender.TraceAppender, log4net">
    <immediateFlush value="true" />
    <layout type="log4net.Layout.PatternLayout,log4net">
      <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p %c{1}:%L - %m%n" />
    </layout>
  </appender>

  <root>
    <level value="ALL"/>
    <appender-ref ref="trace"/>
  </root>
</log4net>

<system.diagnostics>
  <trace autoflush="true" >
    <listeners>
      <add name="TextFileListener" />
      <add name="MetabaseListener" />
    </listeners>
  </trace>
  <sharedListeners>
    <add name ="TextFileListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="TextFile.log" />
    <add name="MetabaseListener" type="XXXX.Manufacturing.Utilities.Diagnostics.MetabaseTraceListener, XXXX.Metabase.Proxies" />
  </sharedListeners>
</system.diagnostics>


text:
Q: jQuery Sortable - Keep it in original list Does anyone know if jQuery UI's Sortable has built-in functionality to keep the original dropped item in it's original list?
For example, you have two lists (one 'source' and one 'group').  I'd like to select from the source and drop into the group, but keep the item in the source.
Make sense?
Thank you!

A: You can see my solution in action on jsfiddle. I simply amended this jQuery draggable/droppable interaction to suit your needs.
HTML

List 1

Drag me down

Drag me down

List 2

Item 1

Item 2

Item 3

Item 4

Item 5

jQuery
$(function() {
    $("#sortable").sortable({
        revert: true
    });
    $(".draggable").draggable({
        connectToSortable: "#sortable",
        helper: "clone",
        revert: "invalid"
    });
    $("ul, li").disableSelection();
});

CSS
.demo ul { list-style-type: none; margin: 0; padding: 0; margin-bottom: 20px; }
.demo li { margin: 5px; padding: 5px; width: 150px; border: 1px solid black; }


text:
Q: How to loop and get serialized values from database with php I'm developing a pizza's restaurant ecommerce and now I'm trying to get the size (Familiar) and the ingredients (Pernil dol�, Bac�, Emmental) of a pizza that was ordered previously. The data I want to get (the italic values in this paragraph) becomes serialized from database:
a:4:{s:10:"attributes";a:2:{s:6:"Tamany";a:1:{i:3;s:8:"Familiar";}s:11:"Ingredients";a:3:{i:318;s:12:"Pernil dol�";i:270;s:5:"Bac�";i:294;s:8:"Emmental";}}s:9:"shippable";s:1:"0";s:4:"type";s:5:"pizza";s:6:"module";s:10:"uc_product";}array(4) { ["attributes"]=> array(2) { ["Tamany"]=> array(1) { [3]=> string(8) "Familiar" } ["Ingredients"]=> array(3) { [318]=> string(11) "Pernil dol�" [270]=> string(4) "Bac�" [294]=> string(8) "Emmental" } } ["shippable"]=> string(1) "0" ["type"]=> string(5) "pizza" ["module"]=> string(10) "uc_product" }

I discovered 'unserialized' php method and I tried this:
$attr = $row['data']; // data from database
$data = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $attr); // I did this because I get some errors...

After I did that, I got this multidimensional array (a bit more human readable):
array(4) { ["attributes"]=> array(2) { ["Tamany"]=> array(1) { [3]=> string(8) "Familiar" } ["Ingredients"]=> array(3) { [318]=> string(11) "Pernil dol�" [270]=> string(4) "Bac�" [294]=> string(8) "Emmental" } } ["shippable"]=> string(1) "0" ["type"]=> string(5) "pizza" ["module"]=> string(10) "uc_product" }

Next step was try to loop the resulting data with a foreach loop, like the following:
foreach($data['attributes'] as $item)
  {
    print '
';

    foreach($item as $value)
    {
        print_r('
' . $value . '
');
    }

    print '
';
  }

I'm a php beginner PHP developer and I can't figure out how can I loop this array in order to get the values I need. I'm getting this error:
Warning: Invalid argument supplied for foreach() in /home/my_host/public_html/dev.mysite.com/inc/file.php on line 79

Can anybody tell me how I have to loop this array to get the data?
Any help will be very, very appreciated.
Best regards,

A: I created this example for you.  First I declared an array which believe mimics the array you have to parse.  Then I looped through and outputed the contents of the array.
<?php

$array = array(
    0 => array(
        '0' => 'John Doe',
        '1' => 'john@example.com'
    ),
    1 => array(
        '0' => 'Jane Doe',
        '1' => 'jane@example.com'
    ),
);

foreach ($array as $key => $value) {

    $thisArray = $array[$key];

    print_r('
');
    foreach ($thisArray as $key2 => $value){
      print_r('
'.$thisArray[$key2].'
');
    }
    print_r('
');
}
?>

A: Finally, and based on the answer of @Gregory Hart, I reached my goal. This is the final code that makes it possible in my particular case:
$data = $row['data'];
  $attrib = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $data);
  $attr = unserialize($attrib);

  foreach ($attr as $key => $value)
  {
      print_r('
');
      $thisArray = $attr[$key];

      foreach ($thisArray as $key2 => $value2)
      {
        print_r('
' . $key2 . ': ');
        $thisArray2 = $attr[$key][$key2];

        foreach ($thisArray2 as $key3 => $value3)
        {
          if ($key2 == 'Tamany')
            print_r('' . utf8_encode($thisArray2[$key3]) . ' ');
          if ($key2 == 'Ingredients')
            print_r('' . utf8_encode($thisArray2[$key3]) . ' ');
          if ($key2 == 'Salsa')
            print_r('' . utf8_encode($thisArray2[$key3]) . ' ');
        }
        print '
';
      }
      print_r('
');
  }

Thanks for you help!

A: Try this logic:
   $data_unserialize = unserialize($row->data);
    foreach ($data_unserialize as $data_key => $data_value) {
    if($data_key =='size')
{

$thisArray = $data_unserialize[$data_key ];

   foreach ($thisArray as $key2 => $value2){

   if($key2=='attributes')
   {
    switch ($value2)
    {
      case "Pernil dol�":
         echo'Pernil dol �';
        break;
      case "Emmental":
        echo'Emmental';
        break;

      default:
        echo 'Nothing';
     }
    }

   }
   }

  }

NB:- And remove the break; from switch statement to display all ingrediants.


text:
Q: Site Collection Confusion Sharepoint 2007 I am bit confused with Site Collection concept in Sharepoint 2007, So when we deploy/develop a new sharepoint, do we must have to have a root site collection and then we will create sub - site collections.. and so on

A: Site collections are one of the logical boundaries in the SharePoint environment.  A web application is made up of several site collections which are made up of sites.  Everyone's organizational architecture differ.
Ours is very flat, we have many site collections as they serve specific purposes, thus warrant their own boundary from other sites. Others may go very deep.
This article helps explain it reasonably well, http://www.siolon.com/blog/understanding-the-sharepoint-hierarchy/.


text:
Q: How can I change Locale within the app itself How to change soft keyboard language within the app itself. I want to change only the soft keyboard language.

A: seems this also does the trick:

// creating locale
Locale locale2 = new Locale(loc);
Locale.setDefault(locale2);
Configuration config2 = new Configuration();
config2.locale = locale2;

// updating locale
mContext.getResources().updateConfiguration(config2, null);


text:
Q: Copy across data in new spreadsheet if it matches criteria from original spreadsheet In Excel 2010
2 different spreadsheets
If Column B (Name) is = to "ABC Co" 'from Sheet2

and
If Column C (Category) is = to "A" 'from Sheet2

Copy "Part#" from Column A (Sheet2) into Sheet1

Note: Duplicate values can be found in column B (Name) and Column C (Category) as per the example on Sheet2, no duplicate in Column A (Part#)
**Sheet2**

            Column A    Column B     Column C
    Row 1   Part#       Name:        Category:
    Row 2   12340000    ABC Co          A
    Row 3   12340001    DDD Inc         A
    Row 4   12340002    Alpha Co        A
    Row 5   12340003    ABC Co          A
    Row 6   12340004    Alpha Co        B
    Row 7   12340005    DDD Inc         B
    Row 8   12340006    ABC Co          B

Output Required:
 *Sheet1*

                 Column A
         Row 1   12340000
         Row 2   12340003

Thank you so much for your help in advance, just an FYI, I have spent a fair bit of time searching for an answer however haven't had any luck, not too familiar with the terminology required to assist with my search and also tweaking to suit my individual case is not my best strength.... hope there are no rules I have overlooked however if so, if you could please let me know I would be happy to correct.

A: You can try this:
I hope i am clear in my comments otherwise just ask me.
Option Explicit
Sub MATCH()

Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Sheet1") 'Change the name of the sheet
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Sheet2") 'Change the name of the sheet
Dim ws2Lastrow As Long, i As Long

ws2Lastrow = ws2.Range("A" & Rows.Count).End(xlUp).Row 'Find the lastrow in the Sheet(2)

With ws2 ' Work within the sheet(2)

For i = 2 To ws2Lastrow 'Start the Loop from row2 until the last row

'Put your two condition in order to copy the value in column Part#
' If the value in column B = "ABC Co" and column C = "A"
        If .Cells(i, "B").Value = "ABC Co" And .Cells(i, "C").Value = "A" Then

        'Past the value in Sheet(1) column A in the first empty cell
            ws1.Cells(ws1.Range("A" & Rows.Count).End(xlUp).Row + 1, "A") = .Cells(i, "A").Value

        End If

Next i

End With

End Sub


text:
Q: customising the date format in java to be in specific order I have the following string variables in which dates are stored in format of dd/mm/yy that is UK format
String s= "04-MAR-15"
String t ="04/03/15"
String p ="04/03/2015"
String w ="04-03-2015"

now i want to convert their format in DD/MM/YYYY format,
 please advise how can I convert their format through simple date format in java and show on console.

A: The process is a two step process:

*

*Convert the String to a Date using the parse method of DateFormat

*Convert the Date to the new String using the method format of a  DateFormat with the desired format

Use the SimpleDateFormat concrete class. See the documentation to understand the desired pattern.

A: Try parsing with each expected format
When you have inputs of various formats, if those formats are mutually exclusive (not ambiguous for one another), simply try parsing each known possible format until one works. When a parsing attempt fails, catch the Exception thrown and try parsing with the next format.
For more information on parsing a string into a date-only object, see How can I change the date format in Java? and many other posts already made on Stack Overflow. Here's a brief example of code.
First, define and collect a series of formatters for each expected format.
Locale locale = Locale.UK ;
List<DateTimeFormatter> formatters = new ArrayList<>( 4 );
formatters.add( DateTimeFormatter.ofPattern( "dd-MMM-uu" , locale ) ) ;
formatters.add( DateTimeFormatter.ofPattern( "dd-MM-uu" , locale ) ) ;
formatters.add( DateTimeFormatter.ofPattern( "dd/MM/uuuu" , locale ) ) ;
formatters.add( DateTimeFormatter.ofPattern( "dd-MM-uuuu" , locale ) ) ;

Try each formatter successively until one succeeds.
LocalDate ld = null ;
for( DateTimeFormatter f : formatters ) {
    try{
        ld = LocalDate.parse( input , f );
        break ; // End this 'for' loop. We succeeded in parsing, so no need to try more formatters.
    } catch ( DateTimeParseException e ) {
        // Swallow this exception as we expect it when trying a series of formatters.
    }
}

Test to see if all the formatters failed to parse. This means we received an input of unexpected format, an error situation.
if( null == ld ) {  // All the formatters were tried but failed.
    … // Deal with unexpected input.
}

Generate a new String as your output using DateTimeFormatter. Consider using the ofLocalized… method rather than specify a particular format.
ISO 8601
Personally, I recommend against ever using a two-digit year. That causes no end of confusion being ambiguous with the month and day-of-month. Memory is cheap enough, and screens big enough, that we can easily afford the bits and pixels to support the luxury of 4-digit years.
Also, consider avoiding your patterns entirely. For data exchange, use only the standard ISO 8601 formats. For a date only that would be YYYY-MM-DD such as 2017-01-23.

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, and later

*

*Built-in.

*Part of the standard Java API with a bundled implementation.

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

*See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


text:
Q: Upstart - unable to read /etc/shadow unless sudo In the following script in Upstart, I'm unable to read /etc/shadow in pre-script phase, unless I use $(echo mypass | sudo -S cat /etc/shadow | grep myusername)
The script works fine if I provide my sudo pass, but I'm wondering if there is a way to do this without having to write my pass in the conf file?

# node-example.conf
description     "Starting Node with Upstart and Forever"

start on filesystem or runlevel [2345]

stop on runlevel [06]

expect fork

respawn

respawn limit 5 30

console output

setuid myusername

env HOME=/home/myusername

env ARGS_FILE=/etc/shadow

. /etc/shadow

script

cd $HOME

exec forever start -a -l /tmp/forever.log -o /tmp/forever.stdout.log -e /tmp/forever.stderr.log --watch --watchDirectory /home/myusername/myapp/server /home/myusername/myapp/server/server.js

end script

pre-start script

ori='myusername:$6$P...'

**# cur=$(echo mypass | sudo -S cat /etc/shadow | grep myusername) -> this works**

**cur=$(cat $ARGS_FILE | grep myusername) -> this doesn't work**

if [ "$ori" = "$cur" ]

then encfs code

else rm -rf somefile

fi

end script


text:
Q: Issue recalling method. unsure of where im going wrong Below is my code and I have notes beside where my errors are showing. Im unsure where I am going wrong when recalling my method or if that is even the issue.
import java.util.Scanner;

public class HurlerUse
{
    static Hurler[] hurlerArray;

    // find lowest score (static method)
    public static int findLow(Hurler[] hurlerArray)
    {
         for(int i = 0; i < hurlerArray.length; i++)
         {
            int lowest = 0;
            int index = 0;
            for(int j=0; j<hurlerArray.length; j++)
            {
                int current = hurlerArray[i].totalPoints();// issue with         my method 'totalPoints'
            if(current < lowest)
            {
                lowest = current;
                index = i;
            }
        }
            return index;
    }

}

//main code
public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    Hurler[] hurlerArray = new Hurler[5];

    for (int i = 0; i <4; i++)
    {
        hurlerArray[i] = new Hurler();
        System.out.println ("Enter Hurler Name:");
        hurlerArray[i].setName(sc.nextLine());
        hurlerArray[i].setGoalsScored(sc.nextInt());
        System.out.println("Enter the hurler's goals scored");
        hurlerArray[i].setPointsScored(sc.nextInt());
        System.out.println("Enter the hurler's points scored");
    }

    for(int i=0;i< hurlerArray.length; i++)
    {
        hurlerArray[i] = new Hurler(MyName, MyGoalsScored, MyPointsScored);// issue with all 3 objects in the brackets but im unsure of how to fix them
    }

    System.out.println("The lowest scoring hurler was " + hurlerArray[findLow(hurlerArray)].getName());// error with my code here I  think it is in the method
}

}//end of class

I know the nyName, myGoalsScored, myPointsScored is incorrect but can anyone explain why?
This is the class page that accompanies it
public class Hurler
{

private String name;
private int goalsScored;
private int pointsScored;

public Hurler() //constructor default
{
    name ="";
    goalsScored = 0;
    pointsScored = 0;
}

public Hurler(String myName, int myGoalsScored, int myPointsScored) // specific constructor
{
    name = myName;
    goalsScored = myGoalsScored;
    pointsScored = myPointsScored;

}

//get and set name
public String getMyName()
{
    return name;
}

    public void setName(String myName)
{
    name = myName;
}

//get and set goals scored
public int getGoalsScored()
{
    return goalsScored;
}

public void setGoalsScored(int myGoalsScored)
{
    goalsScored = myGoalsScored;
}

// get and set points scored
public int getPointsScored()
{
    return pointsScored;
}

public void setPointsScored(int myPointsScored)
{
    pointsScored = myPointsScored;
}

public int totalPoints(int myGoalsScored, int myPointsScored)
{
    int oneGoal = 3;
    int onePoint = 1;
    int totalPoints = ((goalsScored * oneGoal) + (pointsScored * onePoint));
    {
        return totalPoints;
    }
}

}//end of class

A: *

*You call totalPoints() without parameters while method totalPoints(int, int) in Hurler class expects two int parameters.

*Objects MyName, MyGoalsScored, MyPointsScored are not declared at all.

*You call getName() method, while in Hurler class you do not have one. There is method getMyName(), maybe you want to call that one.


text:
Q: How to simultaneously set a property on multiple buttons? I've created a small game which includes a bunch of simple buttons which change color when tapped:
class LetterButton extends StatefulWidget {
  final String caption;

  LetterButton(this.caption);

  @override
  _LetterButtonState createState() => _LetterButtonState();
}

class _LetterButtonState extends State<LetterButton> {
  Color _buttonColor = Colors.white; //initial state

  void clear() {
    _buttonColor = Colors.white;
  }

  void buttonColor() {
    if (_buttonColor == Colors.white) {
      _buttonColor = Colors.yellow;
    } else if (_buttonColor == Colors.yellow) {
      _buttonColor = Colors.red;
    } else if (_buttonColor == Colors.red) {
      _buttonColor = Colors.green;
    } else if (_buttonColor == Colors.green) {
      _buttonColor = Colors.white;
    } else
      _buttonColor = Colors.white;
  }

  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text(widget.caption),
      onPressed: () {
        buttonColor();
        setState(() {});
      },
      color: _buttonColor,
      padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
    );
  }
}

The buttons are created in main's build method (this is an excerpt):
Wrap(
              children: <Widget>[
                LetterButton('A'),
                LetterButton('B'),
                LetterButton('C'),
                LetterButton('D'),
                LetterButton('E'),
                LetterButton('F'),
                LetterButton('G'),
                LetterButton('H'),
                LetterButton('I'),
                LetterButton('J'),
                LetterButton('K'),
                LetterButton('L'),
                LetterButton('M'),
                LetterButton('N'),
                LetterButton('O'),
                LetterButton('P'),
                LetterButton('Q'),
                LetterButton('R'),
                LetterButton('S'),
                LetterButton('T'),
                LetterButton('U'),
                LetterButton('V'),
                LetterButton('W'),
                LetterButton('X'),
                LetterButton('Y'),
                LetterButton('Z'),
              ],
            ),

How can I reset or clear all the buttons simultaneously (i.e., change all the buttons to color: Colors.white)?

A: I find a way of doing that using the rxDart package.
First, add the package going to pubspec.yaml and adding
rxdart: ^0.23.1 to your dependencies, you can see how here.
Now the HomeScreen, where we need to create the BehaviorSubject object to controll the color:
class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  List<String> alphabet = [
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'I',
    'J',
    'K',
    'L',
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z',
  ];

  BehaviorSubject color = BehaviorSubject<Color>();

  Function(Color) get changeColor => color.sink.add;     //using to change the color  easily

  @override
  void initState() {
    super.initState();
    changeColor(Colors.white);
  }

  @override
  void dispose() {
    color.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          Container(
            height: MediaQuery.of(context).size.height,
            child: GridView.count(
              crossAxisCount: 4,
              childAspectRatio: 2,
              children: List.generate(alphabet.length, (index) {
                return LetterButton(
                  caption: alphabet[index],
                  resetButtonColor: color,
                );
              })
                ..add(
                  RaisedButton(
                    onPressed: () {
                      setState(() {                     //the reset button
                        changeColor(Colors.white);
                      });
                    },
                  ),
                ),
            ),
          ),
        ],
      ),
    );
  }
}

And the LetterButton with some changes:
class LetterButton extends StatefulWidget {
  final String caption;
  final BehaviorSubject<Color> resetButtonColor;

  LetterButton({this.caption, this.resetButtonColor});

  @override
  _LetterButtonState createState() => _LetterButtonState();
}

class _LetterButtonState extends State<LetterButton> {

  BehaviorSubject<Color> currentButtonColor = BehaviorSubject<Color>(); //new object

  @override
  void initState() {
    super.initState();

    currentButtonColor.sink.add(Colors.white);

    widget.resetButtonColor.stream.listen((color){
      currentButtonColor.value = color;      //now everyone's color will just change when the reset button
    });                            //is clicked, preventing the error of getting the last color of the stream always

  }

  @override
  void dispose() {
    currentButtonColor.close();
    super.dispose();
  }

  void buttonColor() {
    if (currentButtonColor.value == Colors.white) {
      currentButtonColor.sink.add(Colors.yellow);
    } else if (currentButtonColor.value == Colors.yellow) {
      currentButtonColor.sink.add(Colors.red);
    } else if (currentButtonColor.value == Colors.red) {
      currentButtonColor.sink.add(Colors.green);
    } else if (currentButtonColor.value == Colors.green) {
      currentButtonColor.sink.add(Colors.white);
    } else
      currentButtonColor.value = Colors.white;
  }

  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text(widget.caption),
      onPressed: () {
        buttonColor();
        setState(() {});
      },
      color: currentButtonColor.value,
      padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
    );
  }
}

The UI:


text:
Q: Firebase functions promises not firing correctly I'm having a hard time understanding promises in Firebase functions. I have a function that listens for new files in a storage bucket and then emails the user as well as sending them a Discord message. I'm getting inconsistent results and I'm pretty sure its to do with promises and callbacks being setup incorrectly.
exports.sendSetup = functions.storage.bucket('*the-bucket-id*').object().onFinalize((object) => {
      // Get a URL for the new config file
      console.log('New conf file: ' + object.name);
      const { Storage } = require('@google-cloud/storage');

  const storage = new Storage({
    projectId: '*the-project-id*',
    keyFilename: 'googleServiceAccountKey.json'
  });
  var bucket = storage.bucket('*the-bucket-name*');

  const file = bucket.file(object.name);
  console.log('Generating download url for file ' + object.name);
  return file.getSignedUrl({
    promptSaveAs: '*the-file-name*',
    action: 'read',
    expires: '03-09-2491'
  }).then(signedUrls => {
    var split = object.name.split("/");
    var env = split[0];
    var customer_id = split[1];
    getCustomerDetails(customer_id, signedUrls[0], env);
  });
});

function getCustomerDetails(customer_id, fileUrl, env) {
  console.log('Retrieving customer details for customer id ' + customer_id + ' from Stripe');
  var stripe = stripeLive;
  if (env == 'test') {
    stripe = stripeTest;
  }

  stripe.customers.retrieve(
    customer_id,
    function (err, customer) {
      if (err == null) {
        sendMail(fileUrl, customer.email, customer_id, customer.metadata.name);
        console.log('discordId= ' + customer.metadata.discordId);
        if (customer.metadata.discordId != 'undefined') {
          sendDiscord(fileUrl, customer.metadata.discordId, customer.metadata.discordName);
        }
        console.log('Finished');
      } else {
        console.log(err);
      }
    }
  );
}

function sendDiscord(fileUrl, discordId, discordName) {
  console.log('Attempting to send a discord message to Discord id ' + discordId);
  const Discord = require('discord.js');
  const client = new Discord.Client();
  client.login('*discord-api-key*');
  client.once('ready', () => {
    console.log('Discord client ready');
    client.fetchUser(discordId)
      .then((User) => {
        console.log('Got Discord user object. Attempting to send message');
        return User.send({
          embed: {
            color: 3447003,
            fields: [
              {
                name: 'Hey ' + discordName + '!',
                value: 'Below are the instructions to get you up and running'
              },
              {
                name: '**Step 1**',
                value: 'some instructions'
              }
            ]
          }
        });
      })
      .catch((err) => {
        console.log(err);
      })
  });
}

function sendMail(fileUrl, customer_email, customer_id, customer_name) {
  console.log('customer_name in sendMail function = ' + customer_name);
  var firstName = customer_name.substring(0, customer_name.indexOf(' '));
  console.log(firstName);

  const sgMail = require('@sendgrid/mail');
  sgMail.setApiKey(*sendGridApiKey*);
  sgMail.setSubstitutionWrappers('{{', '}}'); // Configure the substitution tag wrappers globally

  const msg = {
    to: customer_email,
    subject: 'Welcome!',
    from: {
      email: 'noreply@example.com.au',
      name: 'me'
    },
    text: 'Let\'s get you setup...',
    html: '

',
    templateId: '*template-id*',
    substitutions: {
      first_name: firstName,
      file_url: fileUrl
    },
  };
  console.log('Sending email to ' + customer_email + ' customer id:' + customer_id);
  sgMail.send(msg);
}

I've read a heap of articles about promises and callbacks but can't seem to wrap my head around it. The "sendSetup" function actually returns OK but appears to stop right at the start of the getCustomerDetails function. Appreciate any assistance! I'm a bit lost!


text:
Q: Inserting and retrieving images into mysql through python I used this code to insert an image into mysql database and retrieve back the image.
This code works perfectly with no errors , but the problem is even after inserting an image into img table , when I execute the command select  * from img ; in the mysql command line it shows no records.
Table created in database;
create table img(images blob not null);

import mysql.connector
import sys
from PIL import Image
import base64
import cStringIO
import PIL.Image

db = mysql.connector.connect(user='root', password='abhi',
                              host='localhost',
                              database='cbir')

#image = Image.open('C:\Users\Abhi\Desktop\cbir-p\images.jpg')
with open("C:\Users\Abhi\Desktop\cbir-p\images.jpg", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

#blob_value = open('C:\Users\Abhi\Desktop\cbir-p\images.jpg', 'rb').read()
sql = 'INSERT INTO img(images) VALUES(%s)'
args = (encoded_string, )
cursor=db.cursor()
cursor.execute(sql,args)
sql1='select * from img'
cursor.execute(sql1)
data=cursor.fetchall()
#print type(data[0][0])
data1=base64.b64decode(data[0][0])
file_like=cStringIO.StringIO(data1)
img=PIL.Image.open(file_like)
img.show()

db.close()

A: import mysql.connector
import sys
from PIL import Image
import base64
import cStringIO
import PIL.Image

db = mysql.connector.connect(user='root', password='abhi',
                              host='localhost',
                              database='cbir')

image = Image.open('C:\Users\Abhi\Desktop\cbir-p\images.jpg')
blob_value = open('C:\Users\Abhi\Desktop\cbir-p\images.jpg', 'rb').read()
sql = 'INSERT INTO img(images) VALUES(%s)'
args = (blob_value, )
cursor=db.cursor()
cursor.execute(sql,args)
sql1='select * from img'
db.commit()
cursor.execute(sql1)
data=cursor.fetchall()
print type(data[0][0])
file_like=cStringIO.StringIO(data[0][0])
img=PIL.Image.open(file_like)
img.show()

db.close()

This code works fine

A: import mysql.connector
import base64
import io

import PIL.Image
with open('lemonyellow_logo.jpg', 'rb') as f:
    photo = f.read()
encodestring = base64.b64encode(photo)
db= mysql.connector.connect(user="root",password="lyncup",host="localhost",database="demo")
mycursor=db.cursor()
sql = "insert into sample values(%s)"
mycursor.execute(sql,(encodestring,))
db.commit()
sql1="select * from sample"
mycursor.execute(sql1)
data = mycursor.fetchall()
data1=base64.b64decode(data[0][0])
file_like=io.BytesIO(data1)
img=PIL.Image.open(file_like)
img.show()
db.close()

A: import mysql.connector
import pyautogui
import time
import base64

def byte_string(image_name):
      with open(image_name, 'rb') as image_file:
          encoded_string = base64.b64encode(image_file.read())
      return encoded_string

def insertBLOB(image_id, image_name, image):
    print("Inserting BLOB into my_images table")
    try:
        connection = mysql.connector.connect(host="localhost",
                        user="root",
                        password="Rushi@2001",
                        database = 'my_images',
                        port = 3306)

        cursor = connection.cursor()
        sql_insert_blob_query = " INSERT INTO image_data (image_id, image_name, image) VALUES (%s,%s,%s)"

        binary_image = byte_string(image)
        print(len(binary_image))

        # Convert data into tuple format
        insert_blob_tuple = (image_id, image_name, binary_image)
        result = cursor.execute(sql_insert_blob_query, insert_blob_tuple)
        connection.commit()
        print("Image and file inserted successfully as a BLOB into my_images table", result)

    except mysql.connector.Error as error:
        print("Failed inserting BLOB data into MySQL table {}".format(error))

    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()
            print("MySQL connection is closed")

insertBLOB(1,'img0',"C:\\Users\\hulag\\OneDrive\\Desktop\\python_sql\\images\\img0.png")


text:
Q: Selectmenu Jquery UI change event on pageload I'm currently using JQuery UI SelectMenu Widget in my application. The options in the selectMenu are filled at runtime based on some values in sql tables.
Based on the option selected in the selectedMenu a datatable needs to be filtered on a specific column.
.Js snippet
$(document).ready(function() {
    var table = $('.tableContent').DataTable({
        "columnDefs" : [ {
            "className" : "dt-center",
            "targets" : "_all"
        } ]
    });

    $("#osFamilySelect1").selectmenu({
        change : function(event, ui) {
            dropdownSelect = ui.item.value;
            table.column(9).search(dropdownSelect, false, true, true).draw();
        }
    });
});

The above works when something is selected, but does not work when the page is first loaded i.e the table is not filtered when the page is first loaded.
How to achieve the same.

A: Resolved the problem using below:
$(function() { // Shorthand for $(document).ready(function() {
      var table = $('.tableContent').DataTable({...});
      $('#osFamilySelect1').selectmenu({...});
      table.column(9).search($('#osFamilySelect1').val(), false, true, true).draw();
});


text:
Q: ACS with Google provider: error 500 I keep getting same error while trying to login with my Google account to Sharepoint through ACS.
I followed this tutorial: "http://www.fusecollaboration.com/blog/using-google-to-authenticate-with-sharepoint-2013".
The error message I'm getting:
Error Message
It's not really useful, does anybody have some experience with this error?

A: As it turns out, I had to enable Google+ API. This is the post that helped: OWIN's GetExternalLoginInfoAsync Always Returns null.


text:
Q: htacess, .{0,10} works, .+ doesn't for redirects, giving error 500 I'd like to serve any request using files from within a subdirectory. Example:
Browser requests localhost/style.css,
Server responds (without redirecting the browser!) from localhost/static/style.css
This works flawlessly using the following .htacess file:
RewriteEngine on
RewriteRule ^(.{0,10})$ static/$1

But when I do
RewriteEngine on
RewriteRule ^(.+)$ static/$1

It fails with "Internal Server Error".

A: /var/log/apache2/error.log said something like

Request exceeded the limit of 10 internal redirects

I guess it was redirecting from style.css to static/style.css, then to static/static/style.css, and so on. The solution was to use:
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/static/
RewriteRule ^(.+)$ static/$1

the RewriteCond line prevents the next RewriteRule to redirect when the url starts with static/
This here is also quite helpful: https://stackoverflow.com/a/6800150/4417769
htacess iterates over the rules again after the redirect, so it gets applied recursively and [L] cannot stop it.

another solution would be
RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}/static/%{REQUEST_URI} -f
RewriteRule ^(.+)$ static/$1

which only redirects if the url after the redirect matches a file that exists


text:
Q: Unable to read client's message using AnyEvent::Socket and tcp_connect (to a UNIX domain socket) Running the following server and client scripts:
Server (updated):
#!/usr/bin/perl

use strict;
use warnings;
use feature 'say' ;
use AnyEvent ;
use AnyEvent::Socket ;
use AnyEvent::Handle ;

tcp_server 'unix/', '/tmp/.mysocket', sub {
    my ( $fh, @args ) = @_ ;
    say "Received request" ;
    my $hdl = AnyEvent::Handle->new( fh => $fh ) ;
    $hdl->push_read(
        line =>  sub {
            my ( $hdl, $line ) = @_ ;
            say "Received $line" ;
        }
    ) ;
}, sub {
    my ( $fh, @sock ) = @_ ;
    say "Bound to @sock" ;
} ;

AnyEvent->condvar->recv ;

exit ;

Client (updated):
#!/usr/bin/perl

use strict;
use warnings;
use feature 'say' ;
use AnyEvent ;
use AnyEvent::Socket ;
use AnyEvent::Handle ;

my $done = AnyEvent->condvar ;
tcp_connect "unix/", "/tmp/.mysocket", sub {
    my ( $fh ) = @_ or die "unable to connect: $!" ;
    say "Connected" ;
    my $hdl = AnyEvent::Handle->new( fh => $fh ) ;
    $hdl->push_write( "Hello world!\n" ) ;
    $done->send ;
}  ;

$done->recv ;
say $! ;

exit ;

the server receives and accepts the connection request but the client gets an "Illegal seek" error, skips the callback defined in tcp_connect and exits without sending the "Hello world" message to the server.
What am I doing wrong?
Update
Ok.. I figured out that due to the async nature of the AnyEvent module the client gets the "Illegal seek" because the script ends.
Adding a condvar variable I solved that (non)problem, but the server still doesn't receives the message sent by client.

A: I am not sure what causes the "illegal seek error" yet, but I found something that at least works for now. The client needs to use a condition variable in the connection callback:
my $client_done = AnyEvent->condvar;
tcp_connect "unix/", "/tmp/.mysocket", sub {
    my ( $fh ) = @_ or die "unable to connect: $!" ;
    say "Connected" ;
    my $hdl = AnyEvent::Handle->new( fh => $fh ) ;
    $hdl->push_write( "Hello world!\n" ) ;
    $client_done->send;
};
$client_done->recv;
say "Done";

In addition, the server should not use a on_read callback but instead use push_read() method:
my $server_done = AnyEvent->condvar;
tcp_server 'unix/', '/tmp/.mysocket', sub {
    my ( $fh, @args ) = @_ ;
    say "Received request" ;
    my $hdl ;
    $hdl = AnyEvent::Handle->new(
        fh      => $fh,
        on_eof   => sub {
            say "server_eof";
            $server_done->send;
            undef $hdl;
        }
    );
    $hdl->push_read (
        line => sub {
            say "server got line <$_[1]>";
        }
    );
}, sub {
    my ( $fh, @sock ) = @_ ;
    say "Bound to @sock" ;
};
say "Waiting for server done..";
$server_done->recv;


text:
Q: When do purchasable upgrades take effect in Desktop Defender? In Desktop Defender, you can either upgrade a tower by spending money in game or by spending coins out of game (in the metagame).  When do the out of game upgrades take effect?  Do they affect level 1 towers, or do you have to upgrade those towers in game before they do anything?

A: You have to upgrade those towers in game; what the out-of-game upgrades do is basically unlock in-game tower ranks, but you must still upgrade in-game to the new rank.


text:
Q: Missing required get parameter angular 4 I'm getting the console log as follows: "'Missing required 'page' parameter".
I'm trying to set it as the parameters in my get request, and it seems to work, as I can get the console to print out the params as an array.
What am I missing?
Photo of the console:
Thanks!
Service:
export class StoriesService implements OnInit {

  private apiUrl = 'https://dev-api.byrd.news/v1/stories';

  constructor(private http: Http) {
    console.log("Yo! Stories!")
  }

  ngOnInit() { }

  getToken() {
    return Observable.fromPromise(firebase.auth().currentUser.getIdToken(true)
      .then((idToken) => {
        return idToken;
      }))
  }

  getData(page: string, feed: string, hits: string): Observable<any> {
    return this.getToken()
      .flatMap(idToken => {
        let headers = new Headers();
        headers.append('user_token', idToken);
        let params = new HttpParams()
          .set('page', page)
          .set('feed', feed)
          .set('hits', hits);
        let options = new RequestOptions({ headers: headers, params: params });
        // console.log(this.idToken, options);
        console.log("Token: " + idToken);
        console.log(headers, params);
        return this.http
          .get(this.apiUrl, { params, headers })
          .map((response: Response) => {
            console.log("Breakthrough!")
            return response.json() || {};
          })
      })
      .catch(this.handleError);
  }

  private handleError(error: Response) {
    return Observable.throw(error.statusText);
  }

Component:
  getStories() {
    this.storiesService.getData('0', 'latest', '6')
    .subscribe(data => {
      console.log(data);
      console.log("Ikke mere data")
    })
  }

Edit:
This is the URL I get. The params look a little funny to me, or is it just because its unparsed?
"https://dev-api.byrd.news/v1/stories?updates=%7B%22param%22:%22page%22,%22value%22:%220%22,%22op%22:%22s%22%7D&updates=%7B%22param%22:%22feed%22,%22value%22:%22latest%22,%22op%22:%22s%22%7D&updates=%7B%22param%22:%22hits%22,%22value%22:%226%22,%22op%22:%22s%22%7D&cloneFrom=%7B%22updates%22:null,%22cloneFrom%22:null,%22encoder%22:%7B%7D,%22map%22:null%7D&encoder=%7B%7D&map=null"

A: It looks like the server is just sending that to you. The problem then isn't with Angular, it's with the request you're making.
EDIT: The request does look a bit weird. The docs for RequestOptions seem to say that params should be a URLSearchParams, not an HttpParams. Maybe that's the problem.


text:
Q: Buscar e imprimir en consola datos desde un .txt en C# Hola :) Bueno es un programa sencillo en el que se maneja un .txt, el programa tiene la opción de ingresar datos, imprimirlos y buscar....
Mi problema es en la tercera parte: Buscar, los datos que se guardan en el txt son: Clave, Nombre y Puesto de la siguiente manera:

123 Carlos Dayan Rodriguez Perez Administrador
  -Espacio- 234 Diego Antonio Rodriguez Perez Programador
  -Espacio- 456 Juan Camaney Tester
  -Espacio-

Noten que dice -Espacio- con eso indico que en vez de un salto de linea vació cada que termina un "registro" hay un espacio, ya viene el porque de esto......
El código:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Programa1_Agenda
{
    class Program
    {
        static StreamReader Leer;
        static StreamWriter Escribir;

        static void Main(string[] args)
        {
            int Op;
            int op_1 = 0;
            do
            {
                Console.Clear();
                Console.WriteLine("AGENDA 2018\n\n");
                Console.WriteLine("1) Ingresar datos\n2) Mostrar datos\n3) Buscar persona\n4) Salir\n\nTu opcion: ");
                Op = int.Parse(Console.ReadLine());

                if (Op == 1)
                {
                    do
                    {
                        int DUI;
                        string nombre;
                        string puesto;
                        Console.Clear();
                        Console.WriteLine("Escribir un nuevo registro\n\n");
                        Escribir = new StreamWriter("Archivo_Agenda.txt", true);
                        //INGRESA DATOS
                        Console.Write("\n* Ingresar nueva clave DUI (3 Digitos enteros): ");
                        DUI = int.Parse(Console.ReadLine());
                        Escribir.WriteLine(DUI);
                        Console.Write("\n* Ingresar nombre completo: ");
                        nombre = Console.ReadLine();
                        Escribir.WriteLine(nombre);
                        Console.Write("\n* Ingresar puesto: ");
                        puesto = Console.ReadLine();
                        Escribir.WriteLine(puesto);
                        Console.WriteLine("\n\n");
                        String Cadena = Console.ReadLine();
                        Escribir.WriteLine(Cadena);
                        Escribir.Close();

                        Console.WriteLine("El registro se ha creado exitosamente.\n\n5) Regresar al menu principal\n6) Ingresar un nuevo usuario");
                        Console.Write("\nTu opcion: ");
                        op_1 = int.Parse(Console.ReadLine());
                    } while (op_1 == 6);
                }

                if (Op == 2)
                {
                    string Linea;
                    int contador = 0;
                    Console.Clear();
                    Leer = new StreamReader("Archivo_Agenda.txt", true);
                    Console.WriteLine("Mostrando todos los registros:\n\n");
                    while((Linea = Leer.ReadLine()) != null)
                    {
                        Console.WriteLine(Linea);
                        contador++;
                    }
                    Leer.Close();

                    Console.WriteLine("\nEl registro se mostro exitosamente.\n\n5) Regresar al menu principal\n");
                    Console.Write("\nTu opcion: ");
                    op_1 = int.Parse(Console.ReadLine());
                }

                if (Op == 3)
                {
                    string Linea;
                    int contador = 0;
                    string result_s;
                    Console.Clear();
                    Leer = new StreamReader("Archivo_Agenda.txt", true);
                    Console.WriteLine("Buscar registro por medio de clave DUI:\n\n");
                    Console.Write("Ingresa la clave DUI: ");
                    result_s = Console.ReadLine();
                    if((Linea = Leer.ReadLine()) == result_s)
                    {
                        do
                        {
                            Console.WriteLine(Linea);
                            contador++;
                        } while ((Linea = Leer.ReadLine()) != " ");
                    }
                    Leer.Close();

                    Console.WriteLine("\nEl registro se mostro exitosamente.\n\n5) Regresar al menu principal\n");
                    Console.Write("\nTu opcion: ");
                    op_1 = int.Parse(Console.ReadLine());
                }
                Console.ReadKey();
            } while (op_1 == 5);
        }
    }
}

Lo que intento hacer en la opción 3, es que al pedir la clave DUI y ser detectada en el archivo se imprima en pantalla los datos siguientes hasta que se encuentre un espacio (y esta es la razón del porque...)
Esto lo hace con si se ingresa el primer registro: 123, e imprime lo correcto:
123
Carlos Dayan Rodriguez Perez
Administrador
Pero si ingreso cualquiera de los otros 2 no se imprime nada... :(
Por favor ayuda, ya no se que hacer xd

A: Muy buenas Carlos,
como bien comenta Raul, el problema es que debes usar un primer bucle  para encontrar la clave(si existe), y una vez encontrada  entonces ya puedes utilizar el bucle que tienes para imprimir por consola la información.
Te dejo un ejemplo de la Opcion 3 funcionando usando dos bucles do-while:
   if (Op == 3)
    {
        string Linea;
        int contador = 0;
        string result_s;
        Console.Clear();
        Leer = new StreamReader("Archivo_Agenda.txt", true);
        Console.WriteLine("Buscar registro por medio de clave DUI:\n\n");
        Console.Write("Ingresa la clave DUI: ");
        result_s = Console.ReadLine();
        do
        {
            Linea = Leer.ReadLine();
        } while (Linea != result_s && Linea!= null);

        if ((Linea == result_s))
        {
            do
            {
                Console.WriteLine(Linea);
                Linea = Leer.ReadLine();

            } while (Linea !=" ");
        }
        Leer.Close();

        Console.WriteLine("\nEl registro se mostro exitosamente.\n\n5) Regresar al menu principal\n");
        Console.Write("\nTu opcion: ");
        op_1 = int.Parse(Console.ReadLine());
    }


text:
Q: How to append big HTML snippets into DOM with Javascript? I have an app which uses EJS templating to populate data.
In order to add new projects I have made a simple input form which takes all required parameters.
After an input completed an Ajax request being sent, on success I want to inject this snippet into DOM.
In simple words - After new project added I want to display play instantly by injecting into DOM without reloading the page
Is there an elegant way of inserting this div ladder as a template into DOM? It works,

                <i data-id="<%=project.id%>" class="projectDeadline far fa-calendar-alt fa-2x" data-toggle="tooltip" data-placement="top" title="Set Deadline">

            <h5 class="projectName <%=project.id%>" data-toggle="tooltip" data-placement="top" title="Deadline <%=deadline%>" style="align-items: center;">
              <%=project.name%>

            <%}%>

          <i id="editProjectName" class="editProject fas fa-pencil-alt" data-name="<%=project.name%>" data-id="<%=project.id%>">

                " class="deleteProject far fa-trash-alt" data-id="<%=project.id%>">

What I have tried is recreating the entire div ladder in string and append it to parent node.
Like this:
    // Add new Project
    $('#addNewProjectBtn').on("click", function() {
    $("#newProjectModal").on('show.bs.modal', function() {
      $(".confirmNewList").on("click", function(event) {
          var url = '/addNewList';
          var newListTitle = $("#newListNameInput").val()
          event.preventDefault();
          $.post({
            url: url,
            data: {
              listName: newListTitle
            },
            success: function(result) {
              $("#newProjectModal").modal('hide')
              $("#newListNameInput").val('');
              var id = result.data.id
              var name = result.data.name

//Append new project
                  $(".projects").append("

 ...and so on until the end")
                },
                error: function(err) {
                  console.log(err);
                }
              })
            }
          }
        })
       })
  })

In simple words - After new project added I want to display play instantly by injecting into DOM without reloading the page
Is there an more elegant and specially efficient way of inserting this div ladder as a template into DOM?
The method which I have tried above - works, But on attempt to interact with it by calling modals - modals do not get it's data-*, as well the bootstrap tooltips don't work.

A: *

*you can try create new html file instead, and append like this in your page
$.get("yourfile.html", function (data) {
  $("#appendToThis").append(data);    // or use .html();
});

*OR you can directly pass this HTML structure from your backend, so you can directly use append function.

A: After some research I discovered that the event handler can be delegated.
Since the html snippet I am trying to append to projects is added after document.ready (document is loaded and handlers are bind) the only thing required to make the new snippet be active on event is to delegate the event handler to the parent of element that is appended.
Like this :
$("body").delegate("#addNewProjectBtn", "click", function() {
$("#newProjectModal").on('show.bs.modal', function() {
      $(".confirmNewList").on("click", function(event) {
          var url = '/addNewList';
          var newListTitle = $("#newListNameInput").val()
          event.preventDefault();
          $.post({
            url: url,
            data: {
              listName: newListTitle
            },
            success: function(result) {
              $("#newProjectModal").modal('hide')
              $("#newListNameInput").val('');
              var id = result.data.id
              var name = result.data.name

                 //Append new project

                  $(".projects").append("

 ...and so on until the end")
                },
                error: function(err) {
                  console.log(err);
                }
              })
            }
          }
        })
       })
  })

By delegating the event handler to it's parent - the event handler is preserved in the parent.


text:
Q: Proof Verification:$\lim\limits_{n\to \infty} a_n=- \infty $ and $ \lim\limits_{n\to \infty}b_n = b <0 $, show $ a_n b_n \longrightarrow +\infty $ Problem: Given that $ \lim\limits_{n \to \infty} a_n = - \infty $ and $ \lim\limits_{n \to \infty} b_n = b <0 $, show  $ a_n b_n \longrightarrow +\infty $
Note: there's an answer to the problem here  Prove that $\lim\limits_{n\rightarrow \infty}{a_nb_n}=+\infty$ , but I tried proving the theorem and erroneously got that $ a_n b_n \longrightarrow -\infty $, I can't figure out where is the error in my attempt of proof, maybe you can help please?
My attempt:
Suppose $ \lim\limits_{n \to \infty} a_n = - \infty $ and $ \lim\limits_{n \to \infty} b_n = b <0 $. Meaning,
For every $ \epsilon > 0$ exists  $ N_1 \in \mathbb{N} $ s.t. $ |b_n - b| < \epsilon  \iff b-\epsilon < b_n < b + \epsilon $.
For every $ M' > 0 $ exists $ N_2 \in \mathbb{N} $ s.t. $ a_n < -M' $.
Let $ M > 0 $. Choose $ \epsilon = -\frac{5b}{2} = \frac{5|b|}{2}  $ ( since $ b<0 $ ). Choose $ M' = \frac{2M}{3|b|} $. Thus, there exists $ N_1, N_2 \in \mathbb{N} $, denote $ N = max\{N_1,N_2\} $ and we have for all $ n > N $, $ -\frac{7|b|}{2}<b_n < \frac{3|b|}{2} $  and $ a_n < -\frac{2M}{3|b|} $, Hence:
$ a_n b_n < a_n \cdot \frac{  3|b|}{2} < (-\frac{2M}{3|b|}) \cdot (\frac{3|b|}{2} ) = -M $,  Therefore since $ M>0 $ was arbitrary, we have $ a_n b_n \longrightarrow -\infty $

A: The error lies in taking $\varepsilon=\frac{5b}2$. You cannot do that, since $\frac{5b}2<0$.
Taking $\varepsilon=-\frac b2>0$, you will easily prove that $\lim_{n\to\infty}a_nb_n=\infty$.


text:
Q: javascript conditional returning unexpected result I'm doing a simple number comparison on the keyUp event of an input field.  For some reason, I'm not getting the expected result, and I can't figure out why.  What should happen is that if the user-entered number is larger than that stored in the html attribute, the background should turn red, otherwise it stays white.  Simply entering '9' will turn the background red. ??
var admin = $('input[name="diskStorage"]').attr('data-adminstorage'); // 2097152000

$('#new-user input[name="diskStorage"]').keyup(function(){

    if(admin < $(this).val())
        $(this).css('background','red');
    else
        $(this).css('background','white');
});

When I debug these values, if(2097152000 < 549) is returning true. Here's the html, in case that makes any difference:
<form action="administrate.php" method="post" id="new-user">

...

    Disk Storage Limit:

   <input type="text" data-adminStorage="2097152000" name="diskStorage" value="" /> megaBytes

...

Here it is live: http://jsfiddle.net/JMC_Creative/dqAJj/2/

A: .attr and .val() return String objects - use the unary + operator to convert it to a numeric value.
var admin = $('input[name="diskStorage"]').attr('data-adminstorage');
admin = +admin;

if(admin < +$(this).val()) {
   //...
}

A: Try adding a /1 after retrieving the admin value, to make it a number not a string.
var admin = $('input[name="diskStorage"]').attr('data-adminstorage')/1;

Edit: also on the this.val:
$(this).val()/1;

A: They are probably both strings. You should convert them to numbers first:
var admin = Number($('input[name="diskStorage"]').attr('data-adminstorage')); // 2097152000

$('#new-user input[name="diskStorage"]').keyup(function(){

    if(admin < Number($(this).val()))
        $(this).css('background','red');
    else
        $(this).css('background','white');
});


text:
Q: When testing a single attribute in rails, get "can't be nil" errors for all other attributes So, I have an unusual problem I don't really know how to fix. By nature, it's difficult to search for, so I'll try to describe as best I can and provide examples. When I test a single attribute in rspec for any model with a specific thing like numericality or uniqueness, I get an error saying that the other attributes cannot be blank instead of the one error rspec is expecting. I'll post my user model, as this is the simplest.
Model:
class User < ActiveRecord::Base
  validates :name, :email, :password, presence: true
  # validates :email, uniqueness: true
end

Factory:
FactoryGirl.define do
  factory :user do
    name { "Sir Artorias" }
    email { "test@email.com" }
    password { "AGreatPassword!" }
  end
end

Spec:
require "spec_helper"

describe User do
  describe "attributes" do
    user = FactoryGirl.create(:user)
    it { should validate_presence_of(:name) }
    it { should validate_presence_of(:email) }
    it { should validate_uniqueness_of(:email) }
    it { should allow_value("e@e").for(:email) }
    it { should_not allow_value("emailatexample.com").for(:email) }
    it "stores all emails as downcase with white space truncated" do
      user = create(:user, email: " Jo hn.Do e @exa mp le.c om ")
      user.email.should == "john.doe@example.com"
    end
    it { should validate_presence_of(:password) }
    it { should ensure_length_of(:password).is_at_least(8) }
  end

  describe "password is encrypted" do
    user = FactoryGirl.create(:user)
    subject { user.password }
    it { should_not == "AGreatPassword!" }
  end
end

Error example from using above spec:
  5) User attributes should ensure password has a length of at least 8
     Failure/Error: it { should ensure_length_of(:password).is_at_least(8) }

       Expected errors to include "is too short (minimum is 8 characters)" when password is set to "xxxxxxx", got errors: ["name can't be blank (nil)", "email can't be blank (nil)"]

     # ./spec/models/user_spec.rb:17:in `block (3 levels) in <top (required)>'

And this is what I'm referring to. I try to test a length restriction on password, and it errors out telling me that name cannot be nil and email cannot be nil. But I am using a factory above, and other tests which validate the presence of, say, name, don't fail.
Help would be very much appreciated. I can also post anything else you're curious about and think would help, i.e.; gemfile, rspec config, etc.

A: It's not telling you those errors are a problem, it's telling you it expected an entry saying the password was too short, but didn't.  It then dumps the errors the array did contain so you can inspect.
Which makes sense, because in your model you are not validating length:
validates :name, :email, :password, presence: true

Try adding this to your User class:
validates_length_of :password, minimum: 8


text:
Q: I can't find user by id all my valors is empty in cake php hello i need find user by id for my reports this is my code.
Now in this part of my code.
<?php echo $this->Html->link('soya existencia', array('controller' => 'Reportesoyaexistencias', 'action' => 'export_xls', $soyareporte['Soyareporte']['id'])); ?>

I set the id of user because just a need the report of this user.In my index just I do a link,this link set my id to reporteexistenciassoya where i need that just show me the id sent and  all records . this is all code:
SoyareportesController.php
index.ctp

                <?php echo $this->Paginator->sort('username', 'Nombre de Usuario');?>
                <?php echo $this->Paginator->sort('nombre', 'Nombre (s)');?>
                <?php echo $this->Paginator->sort('apellido', 'Apellido (s)');?>
                <?php echo $this->Paginator->sort('email', 'Email');?>
                <?php echo $this->Paginator->sort('Grupo.categoria', 'Categoria');?>
                <?php echo $this->Paginator->sort('Grupo.subcategoria', 'Sub-Categoria');?>
                <?php echo $this->Paginator->sort('Perfil.codigogeneral', 'Codigo General');?>
                Soya report

        <?php $count=0; ?>
        <?php foreach ($soyareportes as $soyareporte): ?>
        <?php $count ++;?>
        <?php if($count % 2): echo '
'; else: echo '
' ?>
        <?php endif; ?>
                <?php echo $soyareporte['Soyareporte']['username']; ?>
                <?php echo $soyareporte['Soyareporte']['nombre']; ?>
                <?php echo $soyareporte['Soyareporte']['apellido']; ?>
                <?php echo $soyareporte['Soyareporte']['email']; ?>
                <?php echo $soyareporte['Grupo']['categoria']; ?>
                <?php echo $soyareporte['Grupo']['subcategoria']; ?>
                <?php echo $soyareporte['Perfil']['codigogeneral']; ?>
                <?php echo $this->Html->link('soya existencia', array('controller' => 'Reportesoyaexistencias', 'action' => 'export_xls', $soyareporte['Soyareporte']['id'])); ?>

          <?php endforeach; ?>
        <?php unset($soyarreporte); ?>

Now in this part of my code. I receipt values the id but when I want to display the valors, but all values are empty.
Reportesoyaexistencias.php
<?php
class ReportesoyaexistenciasController extends AppController {

    var $name = 'Reportesoyaexistencias';
    function export_xls($id = null) {
        $this->loadModel("Reportesoyaexistencia");
        //$this->Reportesoyaexistencia->recursive = 1;

        $data = $this->Reportesoyaexistencia->findById($id);

        if (!$this->request->data) {
                $this->request->data = $data;
        }

        $this->set('soyaexistencias',$data);

        //$this->render('export_xls','export_xls');
    }

}
?>