问:
Add to linked list via tail pointer without 3 levels of indirection
I am working on a project that requires an implementation of a linked list. Before I started the project, I was reviewing the classic method of creating a linked list.

I realized that in the past, I had been adding elements to a linked list via the head pointer that traverses the list until it reaches the null pointer.

I figured out that there is no need to do it this way, and to implement it in a way that involves a tail pointer, but the only way I could think of is a one that involves a triple pointer or a global pointer. I was wondering, is there an easier approach that uses less levels of indirection?

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct list {
    int val;
    struct list *next;
} list;

void printlist(list *head);
void freelist(list *head);

void AddList(list ***tail, int val);

int main(void)
{
    /* create first node */
    list *head = (list *)malloc(sizeof(*head));

    /* assign members of first node */
    head->val = 1;
    head->next = NULL;

    /* create tail */
    list **tail = &head->next;

    /* add values to list */
    AddList(&tail, 2);
    AddList(&tail, 3);
    AddList(&tail, 4);
    AddList(&tail, 5);
    AddList(&tail, 6);
    AddList(&tail, 7);
    AddList(&tail, 8);
    AddList(&tail, 9);

    /* print list */
    printlist(head);

    /* free list */
    freelist(head);

    /* exit program */
    system("pause");
    return 0;
}

void AddList(list ***tail, int val)
{
    list *node = (list *)malloc(sizeof(*node));

    node->val = val;
    node->next = NULL;

    **tail = node;

    *tail = &node->next;
}

void printlist(list *head)
{
    while (head) {
        printf("%d\n", head->val);
        head = head->next;
    }
}

void freelist(list *head)
{
    list *tmp = head;
    while (head) {
        head = head->next;
        free(tmp);
        tmp = head;
    }
}
</code>```

答:
You can do:</p>

```<code>#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *next;
};

typedef struct node NODE;

struct llist {
    unsigned int count;
    NODE *head;
    NODE *tail;
};

typedef struct llist LLIST;

LLIST *create_list() {
    LLIST *llist = malloc(sizeof(LLIST));
    if (llist == NULL)
        exit(EXIT_FAILURE);

    llist->head = NULL;
    llist->tail = NULL;
    llist->count = 0;
    return llist;
}

NODE *create_ll_node(int data) {
    NODE *node = malloc(sizeof(NODE));
    if (node == NULL)
        exit(EXIT_FAILURE);

    node->data = data;
    node->next = NULL;
    return node;
}

void add_list_head(LLIST *llist, int data) {
    NODE *node = create_ll_node(data);
    if (llist->head == NULL) {
        llist->head = node;
        llist->tail = node;
    } else {
        node->next = llist->head;
        llist->head = node;
    }
    llist->count++;
}

void add_list_tail(LLIST *llist, int data) {
    NODE *node = create_ll_node(data);
    if (llist->tail == NULL) {
        llist->head = node;
        llist->tail = node;
    } else {
        llist->tail->next = node;
        llist->tail = node;
    }
    llist->count++;
}

void delete_list_elements(NODE *llist_head) {
    NODE *node, *tmp;
    if (llist_head == NULL) {
        printf ("List is empty.\n");
        return;
    }

    node = llist_head;
    while(node) {
        tmp = node->next;
        free(node);
        node = tmp;
    }
}

void delete_list(LLIST *llist) {
    if (llist == NULL) {
        printf ("Invalid list.\n");
        return;
    }

    delete_list_elements(llist->head);
    free(llist);
}

void display_list(const LLIST *llist) {
    if (llist == NULL) {
        printf ("Invalid list.\n");
        return;
    }
    if (llist->head == NULL) {
        printf ("List is empty.\n");
        return;
    }

    NODE *node = llist->head;
    while(node) {
        printf ("data: %d\n", node->data);
        node = node->next;
    }
}

unsigned int get_list_element_count(const LLIST *llist) {
    if (llist == NULL)
        return 0;

    return llist->count;
}

int main() {
    LLIST *llist = create_list();

    add_list_head(llist, 5);
    add_list_head(llist, 4);
    add_list_head(llist, 3);
    add_list_head(llist, 2);
    add_list_head(llist, 1);
    add_list_tail(llist, 6);
    add_list_tail(llist, 7);
    add_list_tail(llist, 8);
    add_list_tail(llist, 9);
    add_list_tail(llist, 10);

    display_list(llist);

    printf ("Total elements in list : %u\n", get_list_element_count(llist));

    delete_list(llist);

    return 0;
}
</code>```

Body:
I am working on a project that requires an implementation of a linked list. Before I started the project, I was reviewing the classic method of creating a linked list.

I realized that in the past, I had been adding elements to a linked list via the head pointer that traverses the list until it reaches the null pointer.

I figured out that there is no need to do it this way, and to implement it in a way that involves a tail pointer, but the only way I could think of is a one that involves a triple pointer or a global pointer. I was wondering, is there an easier approach that uses less levels of indirection?

#include <stdio.h>
#include <stdlib.h>

typedef struct list {
    int val;
    struct list *next;
} list;

void printlist(list *head);
void freelist(list *head);

void AddList(list ***tail, int val);

int main(void)
{
    /* create first node */
    list *head = (list *)malloc(sizeof(*head));

    /* assign members of first node */
    head->val = 1;
    head->next = NULL;

    /* create tail */
    list **tail = &head->next;

    /* add values to list */
    AddList(&tail, 2);
    AddList(&tail, 3);
    AddList(&tail, 4);
    AddList(&tail, 5);
    AddList(&tail, 6);
    AddList(&tail, 7);
    AddList(&tail, 8);
    AddList(&tail, 9);

    /* print list */
    printlist(head);

    /* free list */
    freelist(head);

    /* exit program */
    system("pause");
    return 0;
}

void AddList(list ***tail, int val)
{
    list *node = (list *)malloc(sizeof(*node));

    node->val = val;
    node->next = NULL;

    **tail = node;

    *tail = &node->next;
}

void printlist(list *head)
{
    while (head) {
        printf("%d\n", head->val);
        head = head->next;
    }
}

void freelist(list *head)
{
    list *tmp = head;
    while (head) {
        head = head->next;
        free(tmp);
        tmp = head;
    }
}

Body:
You can do:

#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *next;
};

typedef struct node NODE;

struct llist {
    unsigned int count;
    NODE *head;
    NODE *tail;
};

typedef struct llist LLIST;

LLIST *create_list() {
    LLIST *llist = malloc(sizeof(LLIST));
    if (llist == NULL)
        exit(EXIT_FAILURE);

    llist->head = NULL;
    llist->tail = NULL;
    llist->count = 0;
    return llist;
}

NODE *create_ll_node(int data) {
    NODE *node = malloc(sizeof(NODE));
    if (node == NULL)
        exit(EXIT_FAILURE);

    node->data = data;
    node->next = NULL;
    return node;
}

void add_list_head(LLIST *llist, int data) {
    NODE *node = create_ll_node(data);
    if (llist->head == NULL) {
        llist->head = node;
        llist->tail = node;
    } else {
        node->next = llist->head;
        llist->head = node;
    }
    llist->count++;
}

void add_list_tail(LLIST *llist, int data) {
    NODE *node = create_ll_node(data);
    if (llist->tail == NULL) {
        llist->head = node;
        llist->tail = node;
    } else {
        llist->tail->next = node;
        llist->tail = node;
    }
    llist->count++;
}

void delete_list_elements(NODE *llist_head) {
    NODE *node, *tmp;
    if (llist_head == NULL) {
        printf ("List is empty.\n");
        return;
    }

    node = llist_head;
    while(node) {
        tmp = node->next;
        free(node);
        node = tmp;
    }
}

void delete_list(LLIST *llist) {
    if (llist == NULL) {
        printf ("Invalid list.\n");
        return;
    }

    delete_list_elements(llist->head);
    free(llist);
}

void display_list(const LLIST *llist) {
    if (llist == NULL) {
        printf ("Invalid list.\n");
        return;
    }
    if (llist->head == NULL) {
        printf ("List is empty.\n");
        return;
    }

    NODE *node = llist->head;
    while(node) {
        printf ("data: %d\n", node->data);
        node = node->next;
    }
}

unsigned int get_list_element_count(const LLIST *llist) {
    if (llist == NULL)
        return 0;

    return llist->count;
}

int main() {
    LLIST *llist = create_list();

    add_list_head(llist, 5);
    add_list_head(llist, 4);
    add_list_head(llist, 3);
    add_list_head(llist, 2);
    add_list_head(llist, 1);
    add_list_tail(llist, 6);
    add_list_tail(llist, 7);
    add_list_tail(llist, 8);
    add_list_tail(llist, 9);
    add_list_tail(llist, 10);

    display_list(llist);

    printf ("Total elements in list : %u\n", get_list_element_count(llist));

    delete_list(llist);

    return 0;
}


来源: stackexchange

问:
Install4j - autoupdate from 'external launcher'
Is there any way how to put autoupdate feature working with 'external launcher' or with installer without laucnher? Or autoupdate feature works with 'generated launcher' only? </p>

答: While you can call the update downloader from an external launcher, the update downloader has no way to shut down the launcher in case it needs to execute an update installer.</p>

ContentLicense: CC BY-SA 3.0


问:
Split an array into 2 based on objects property AngularJS
I'm having an array of objects These objects are coming from two different input fields on my form. They are identified by ids.

Field one is id:1 and field two is id:2. How can I split them into two arrays based on their ids. For example id:1 objects to be stored in array1 and id:2 in array2. I don't want to hardcode as if more input fields were created this would make some mess.

```<code>"values":[{"id":"1","description":"123"},
          {"id":"1","description":"456"},
          {"id":"2","description":"456"}]
</code>```

答:
In this case you need to use groupBy as filter, if you interesting to figure out how it works read it

angular-filter#groupby

Remember
  you don't need to make a new filter or other models to handle it just use it! save your time

but solution is so easy:

```<code>var result = $filter("groupBy")(values, 'id');
//this result will return 1: [{"id":"1","description":"123"},{"id":"1","description":"456"}] & 2: [{"id":"2","description":"456"}]
for(var item in result){
   //item return all keys (ids) => 1, 2
   //result[item] return all objects related to a key OR id
   //so you can do anything here
}
</code>```

Body:
I'm having an array of objects These objects are coming from two different input fields on my form. They are identified by ids.

Field one is id:1 and field two is id:2. How can I split them into two arrays based on their ids. For example id:1 objects to be stored in array1 and id:2 in array2. I don't want to hardcode as if more input fields were created this would make some mess.

"values":[{"id":"1","description":"123"},
          {"id":"1","description":"456"},
          {"id":"2","description":"456"}]

Body:
In this case you need to use groupBy as filter, if you interesting to figure out how it works read it

angular-filter#groupby

Remember
  you don't need to make a new filter or other models to handle it just use it! save your time

but solution is so easy:

var result = $filter("groupBy")(values, 'id');
//this result will return 1: [{"id":"1","description":"123"},{"id":"1","description":"456"}] & 2: [{"id":"2","description":"456"}]
for(var item in result){
   //item return all keys (ids) => 1, 2
   //result[item] return all objects related to a key OR id
   //so you can do anything here
}


ContentLicense: CC BY-SA 2.5

Title: How to use this regular expression in JavaScript?

Body:
I am trying to use the following regular expression to test for a valid date.

^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$

which I got from

http://regexlib.com/REDetails.aspx?regexp_id=1071

My JavaScript test code is:

var date='1/1/1965';
var re = new RegExp('^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$');
alert(re.test(date));

I keep getting "false" rather than "true" for this valid test date.

Body:
Try this:

var date='1/1/1965';
var re = /^(((0?[1-9]|1[012])\/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])\/(29|30)|(0?[13578]|1[02])\/31)\/(19|[2-9]\d)\d{2}|0?2\/29\/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$/;
alert(re.test(date));


问:
Postgres - Rank based on consecutive values
How can I create a rank that restarts at 1 when the consecutive sequence is broken?

(Click on the Image below)

The table below represent the flow of a User. His total journey consists of 8 steps, the page indicates which page he is on during each step. I would like to create a rank, that resets when the page changes. The tricky part is getting the rank in (step 6, page 1) to reset to 1 and not continue at 4. Partitioning by Page is not enough, as I want the rank to restart when the user changes back to Page 1 and continue. The table contains the results I would like to achieve, I just do not know how to do this in Postgres.

答:
You can assign a group using the difference of row numbers approach and then use row_number() to assign the ranking:

```<code>select step, page,
       row_number() over (partition by page, seqnum - seqnum_p order by step) as ranking
from (select t.*,
             row_number() over (order by step) as seqnum,
             row_number() over (partition by page order by step) as seqnum_p
      from t
     ) t;
</code>```

To understand why this works, look at the results of the subquery.  You will see how the difference between the two seqnum values identifies consecutive rows with the same value.

Body:
You can assign a group using the difference of row numbers approach and then use row_number() to assign the ranking:

select step, page,
       row_number() over (partition by page, seqnum - seqnum_p order by step) as ranking
from (select t.*,
             row_number() over (order by step) as seqnum,
             row_number() over (partition by page order by step) as seqnum_p
      from t
     ) t;

To understand why this works, look at the results of the subquery.  You will see how the difference between the two seqnum values identifies consecutive rows with the same value.


问:
Directory.EnumerateFiles not retrieving the actual path
Am trying to loop through a folder and read all the XML files within it.

Am using the Directory.EnumerateFiles to read from the path.

My .cs file and the XML files folder lies in same path

"C:\User\Documents\Projects\TestTool"

Am using the below code to get read the files.

```<code>string path = @"..\TestCases\";

foreach(string file in Directory.EnumerateFiles(path, "*.xml"))
{

}
</code>```

Using this am getting exception stating

Could not find path "C:\Program Files(x86)\Common Files\Microsoft
  Shared\DevServer\TestCases"

This is pointing to the WebDev.WebServer20 path instead of the actual path.

Not sure why it is pointing to a completely different folder

I tried string path = @"\TestCases\"; But when I try like this it is throwing an exceptiopn stating

Could not find path "C:\TestCases"

What is the mistake am making? Please help

答:
Try it:</p>

```<code>    string path = "..\\TestCases\\";

    foreach (FileInfo file in new DirectoryInfo(path).EnumerateFiles("*.xml"))
    {
        string filePath = file.FullName;
    }
</code>```

Body:
Am trying to loop through a folder and read all the XML files within it.

Am using the Directory.EnumerateFiles to read from the path.

My .cs file and the XML files folder lies in same path

"C:\User\Documents\Projects\TestTool"

Am using the below code to get read the files.

string path = @"..\TestCases\";

foreach(string file in Directory.EnumerateFiles(path, "*.xml"))
{

}

Using this am getting exception stating

Could not find path "C:\Program Files(x86)\Common Files\Microsoft
  Shared\DevServer\TestCases"

This is pointing to the WebDev.WebServer20 path instead of the actual path.

Not sure why it is pointing to a completely different folder

I tried string path = @"\TestCases\"; But when I try like this it is throwing an exceptiopn stating

Could not find path "C:\TestCases"

What is the mistake am making? Please help

Body:
Try it:

    string path = "..\\TestCases\\";

    foreach (FileInfo file in new DirectoryInfo(path).EnumerateFiles("*.xml"))
    {
        string filePath = file.FullName;
    }


问:
Dynamically add CORS Mappings to Rest Controller at runtime

Hi! I am a beginner in Spring Boot. I have a simple Java Spring Boot Application which uses a Rest Controller. Some of the controller's endpoints are exposed to CORS requests. I've found out that it is possible to allow CORS requests by adding @CrossOrigin(origins ="..") annotations above the methods.

My problem is that I don't know all the origins at the moment and will have to add some of them later during the runtime of my Spring Boot Application.

Is it possible to have a method to manually add new origin-addresses to some endpoints of my Rest Controller? E.g. to have an endpoint in my Rest Controller that allows a particular user (e.g.Admin) to add new cors-origins to a rest endpoint? If yes: Please give a simple example.
</p>

答:
```<code>@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");

    if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
        LOG.trace("Sending Header....");
        // CORS "pre-flight" request
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");

        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        response.addHeader("Access-Control-Max-Age", "1");
    }

    filterChain.doFilter(request, response);
}
</code>```

please use the filter cros_filter

Body:
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");

    if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
        LOG.trace("Sending Header....");
        // CORS "pre-flight" request
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");

        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        response.addHeader("Access-Control-Max-Age", "1");
    }

    filterChain.doFilter(request, response);
}

please use the filter cros_filter


问:
Accelerator character not shown for TPopupMenu items, a windows settings issue or what?
Well, this sounds a like newbie question, but somehow I couldn't get the accelerator keys appears for the standard TPopupMenu items, how to fix that?

Below are two screenshots I created by creating a new VCL forms application without any coding.

Design time, OK:

Run time, no underlines:

The system is win7 Home with latest updates.

答:
This is the default behaviour of Windows. Accelerator keys are hidden so long as you interact with menus using the mouse. Once you start using the keyboard to interact with them then the accelerator keys will be displayed.

You can see this in action by invoking the menu using the popup menu key that is typically found to the right of the space bar. Alternatively Shift + F10 can be used to invoke the popup menu from the keyboard. Main menus behave in the same way, this is not limited to popup menus.

There is a Windows setting that allows this behaviour to be changed. This setting allows you to request that accelerator keys are always show, irrespective of how the menu was invoked.


问:
PHP autoload MVC
I came across the __autoload function in PHP and would like to use it with my MVC folder structure. The function itsself is pretty easy, but how do I achieve a dynamic folder scanning after some kind of naming, please see example:

```<code>-application
--controller
--models
---entities
----house
---factories
----houseFactory
--views
-library
-public
</code>```

As you maybe recognise its very close based on zend framework or other frameworks -as I come from those, however I would like to develop a website without framework and just started to write bootsrap file.

Maybe sombody could help me with the autoload in this - i think - advanced usage.

My Classnames will be like
Model_Entities_House
or
Model_Factory_HouseFactory

witch can be applied to the folder structure.

答:
What I do mostly is use the SPL autoload function, which will help you to accomplish this quite easily. It should be something like this:

```<code>spl_autoload_register("MyClass::Autoloader");
</code>```

Then, you can do something like this

```<code>class MyClass
{
  public static function Autoloader($className)
  {
    //parse $className and decide where to load from...
  }
}
</code>```

If you´re using a naming convention, then you should be available to load the required file by just using the name.

Title: PHP autoload MVC

Body:
I came across the __autoload function in PHP and would like to use it with my MVC folder structure. The function itsself is pretty easy, but how do I achieve a dynamic folder scanning after some kind of naming, please see example:

-application
--controller
--models
---entities
----house
---factories
----houseFactory
--views
-library
-public

As you maybe recognise its very close based on zend framework or other frameworks -as I come from those, however I would like to develop a website without framework and just started to write bootsrap file.

Maybe sombody could help me with the autoload in this - i think - advanced usage.

My Classnames will be like
Model_Entities_House
or
Model_Factory_HouseFactory

witch can be applied to the folder structure.

Body:
What I do mostly is use the SPL autoload function, which will help you to accomplish this quite easily. It should be something like this:

spl_autoload_register("MyClass::Autoloader");

Then, you can do something like this

class MyClass
{
  public static function Autoloader($className)
  {
    //parse $className and decide where to load from...
  }
}

If you´re using a naming convention, then you should be available to load the required file by just using the name.


答:
use cross join</p>

```<code>select TR.ID_Request,TR.participant_no,TR.invited_by from Table_Request TR cross join Table_Participant TP where TR.invited_by = TP.invited_by
</code>```

Title: How to get multiple values

Body:
I have two tables:

table request : content of request data

table participant : content of employee who invited

Table Request:

ID_Request   emp_no  invited_by
-------------------------------
BTR1370      101240  101240
BTR1371      100259  101240
BTR1372      100308  101240
BTR1373      100626  101240

Table Participant:

ID_Participant ID_Request  participant_no   invited_by
------------------------------------------------------
1              BTR1370     100259           101240
2              BTR1370     100308           101240
3              BTR1370     100626           101240

I want to join those tables, and expect to get this result here:

ID_Request  participant_no  invited_by
---------------------------------------
BTR1370     100259          101240
BTR1370     100308          101240
BTR1370     100626          101240
BTR1371     100259          101240
BTR1371     100308          101240
BTR1371     100626          101240
BTR1372     100259          101240
BTR1372     100308          101240
BTR1372     100626          101240
BTR1373     100259          101240
BTR1373     100308          101240
BTR1373     100626          101240

How can I join those two tables? I'm using SQL Server 2012.

I am very grateful for your help

Body:
use cross join

select TR.ID_Request,TR.participant_no,TR.invited_by from Table_Request TR cross join Table_Participant TP where TR.invited_by = TP.invited_by


问:
Pingdom Tools 503 server not available error. Can someone explain the error and possible resolutions to this?
I am getting below error descriptions when checking the site at pingdom tools. Can someone explain the possible cause behind this error and how to resolve it?</p>

```<code>Response Headers 503
Server: Apache
Connection: Close
X-Powered-By: PHP/5.4.45
Transfer-Encoding: chunked
Retry-After: 86400
Content-Type: text/html; charset=UTF-8

Request Headers
Pragma: no-cache
Accept-Encoding: gzip, deflate, sdch
Host: www.dummyname.com
Accept-Language: en-US,en;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Cache-Control: no-cache
Connection: keep-alive
</code>```

答:
Every errors 5xx are server-side, that means there is nothing much you can do for fix it.

If you take a look at the error codes messages you can check this:

503 Service Unavailable The server is currently unavailable (because
  it is overloaded or down for maintenance). Generally, this is a
  temporary state.[63]

pingdom is a big server, so surely it has several servers working on, the one your computer just used seems down, keep retrying may help

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Body:
I am getting below error descriptions when checking the site at pingdom tools. Can someone explain the possible cause behind this error and how to resolve it?

Response Headers 503
Server: Apache
Connection: Close
X-Powered-By: PHP/5.4.45
Transfer-Encoding: chunked
Retry-After: 86400
Content-Type: text/html; charset=UTF-8

Request Headers
Pragma: no-cache
Accept-Encoding: gzip, deflate, sdch
Host: www.dummyname.com
Accept-Language: en-US,en;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Cache-Control: no-cache
Connection: keep-alive


答:
Use should use CROSS JOIN just like Gordon linoff says:
You may include a where clause to make it behave like an inner join - Ie. where a.invited_By = b.invited_by

```<code>    declare @myt1 table (id_request nvarchar(50),emp_no int, invited_by int)
insert into @myt1
values

('BTR1370',  101240  ,101240),
('BTR1371',  100259  ,101240),
('BTR1372',  100308  ,101240),
('BTR1373',  100626  ,101240)

declare @myt2 table ( id_participant int,id_request nvarchar(50),participant_no int, invited_by int)
insert into @myt2
values

(1  ,'BTR1370',  100259 , 101240 ),
(2  ,'BTR1370',  100308 , 101240 ),
(3  ,'BTR1370',  100626 , 101240 )

select a.id_request,b.participant_no,a.invited_by from @myt1 a
cross join @myt2  b

order by a.id_request
</code>```

Result

Title: How to get multiple values

Body:
Use should use CROSS JOIN just like Gordon linoff says:
You may include a where clause to make it behave like an inner join - Ie. where a.invited_By = b.invited_by

    declare @myt1 table (id_request nvarchar(50),emp_no int, invited_by int)
insert into @myt1
values

('BTR1370',  101240  ,101240),
('BTR1371',  100259  ,101240),
('BTR1372',  100308  ,101240),
('BTR1373',  100626  ,101240)

declare @myt2 table ( id_participant int,id_request nvarchar(50),participant_no int, invited_by int)
insert into @myt2
values

(1  ,'BTR1370',  100259 , 101240 ),
(2  ,'BTR1370',  100308 , 101240 ),
(3  ,'BTR1370',  100626 , 101240 )

select a.id_request,b.participant_no,a.invited_by from @myt1 a
cross join @myt2  b

order by a.id_request

Result


问:
How to show a specific unit of data from a record queried in rails?
I am really stuck with dealing with querys from multiple tables in rails. If this is my controller:

```<code> def show
    @user = User.find(params[:id])
    @entry = Entry.joins(:event, :user).where(users: { id: '2' })
    @event = Event.find(1)
  end
</code>```

and this is my models

```<code>class Entry < ApplicationRecord
  belongs_to :user
  belongs_to :event

class User < ApplicationRecord
   has_many :entries, dependent: :destroy

class Event < ApplicationRecord
    has_many :entries, dependent: :destroy
</code>```

The query runs happily in rails console and returns the records but I don't know how to access specific units like entry.course in my embeded ruby.

Update

To clarify On a page I woulk like to output somthing for all the entries assosiated with the user logged in to the page.

eventName eventLocation eventDate course siCard

The schema:

```<code>ActiveRecord::Schema.define(version: 20171204183458) do

    # These are extensions that must be enabled in order to support this
  database
  enable_extension "plpgsql"

create_table "entries", force: :cascade do |t|
  t.string "course"
  t.string "siCard"
  t.bigint "user_id"
  t.bigint "event_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.index ["event_id"], name: "index_entries_on_event_id"
  t.index ["user_id", "created_at"], name:
  "index_entries_on_user_id_and_created_at"
  t.index ["user_id"], name: "index_entries_on_user_id"
 end

create_table "events", force: :cascade do |t|
 t.string "eventName"
 t.string "location"
 t.date "eventDate"
 t.text "description"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
 t.string "eventLink"
 t.string "eventCoordinates"
 t.index ["eventName"], name: "index_events_on_eventName", unique: true
end

create_table "users", force: :cascade do |t|
  t.string "name"
  t.string "email"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.string "password_digest"
  t.string "firstName"
  t.string "remember_digest"
  t.boolean "admin"
  t.index ["email"], name: "index_users_on_email", unique: true
end

add_foreign_key "entries", "events"
add_foreign_key "entries", "users"
end
</code>```

答:
You can find it in 2 ways

1)

```<code> @entries = Entry.includes(:user,:event).where(user: { id: (params[:id]) })
</code>```

2)

```<code> @entries = User.includes(entries: :event).find(params[:id]).entries
</code>```

Than in the loop of entries you can access value course of particular entry

e.g.

```<code>@entries.each do |entry|
  puts "#{entry.course}"
  puts "#{entry.event&.name}"
end
</code>```

Body:
I am really stuck with dealing with querys from multiple tables in rails. If this is my controller:

 def show
    @user = User.find(params[:id])
    @entry = Entry.joins(:event, :user).where(users: { id: '2' })
    @event = Event.find(1)
  end

and this is my models

class Entry < ApplicationRecord
  belongs_to :user
  belongs_to :event

class User < ApplicationRecord
   has_many :entries, dependent: :destroy

class Event < ApplicationRecord
    has_many :entries, dependent: :destroy

The query runs happily in rails console and returns the records but I don't know how to access specific units like entry.course in my embeded ruby.

Update

To clarify On a page I woulk like to output somthing for all the entries assosiated with the user logged in to the page.

eventName eventLocation eventDate course siCard

The schema:

ActiveRecord::Schema.define(version: 20171204183458) do

    # These are extensions that must be enabled in order to support this
  database
  enable_extension "plpgsql"

create_table "entries", force: :cascade do |t|
  t.string "course"
  t.string "siCard"
  t.bigint "user_id"
  t.bigint "event_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.index ["event_id"], name: "index_entries_on_event_id"
  t.index ["user_id", "created_at"], name:
  "index_entries_on_user_id_and_created_at"
  t.index ["user_id"], name: "index_entries_on_user_id"
 end

create_table "events", force: :cascade do |t|
 t.string "eventName"
 t.string "location"
 t.date "eventDate"
 t.text "description"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
 t.string "eventLink"
 t.string "eventCoordinates"
 t.index ["eventName"], name: "index_events_on_eventName", unique: true
end

create_table "users", force: :cascade do |t|
  t.string "name"
  t.string "email"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.string "password_digest"
  t.string "firstName"
  t.string "remember_digest"
  t.boolean "admin"
  t.index ["email"], name: "index_users_on_email", unique: true
end

add_foreign_key "entries", "events"
add_foreign_key "entries", "users"
end

Body:
You can find it in 2 ways

1)

 @entries = Entry.includes(:user,:event).where(user: { id: (params[:id]) })

2)

 @entries = User.includes(entries: :event).find(params[:id]).entries

Than in the loop of entries you can access value course of particular entry

e.g.

@entries.each do |entry|
  puts "#{entry.course}"
  puts "#{entry.event&.name}"
end


问:
Get value from array in lua
I have the following array

```<code>local Array = {}
Array[1] = {"Value_A", "Value_B", "Value_C", "Value_D"}
Array[2] = {"Value_E", "Value_F", "Value_G", "Value_H"}
Array[3] = {"Value_I", "Value_J", "Value_K", "Value_L"}
</code>```

and I know I can print the values of every array item at once with

```<code>for k, v in ipairs(Array) do
  print(k, v[1], v[2], v[3], v[4])
end
</code>```

but I'd like to print the values of specific array items.

How can I do that?

答:
From reading your post and comments it seems to me you want to print every value separately instead of it all being on one line.

To do this you would need another for loop to iterate through all the values.

```<code>for k, v in ipairs(Array) do
          print(k)
          for i=1, #v do print(v[i]) end
          print() // This will just print a new line
end
</code>```

Output:

```<code>1
Value_A
Value_B
Value_C
Value_D

2
Value_E
Value_F
Value_G
Value_H

3
Value_I
Value_J
Value_K
Value_L
</code>```

Title: Get value from array in lua

Body:
I have the following array

local Array = {}
Array[1] = {"Value_A", "Value_B", "Value_C", "Value_D"}
Array[2] = {"Value_E", "Value_F", "Value_G", "Value_H"}
Array[3] = {"Value_I", "Value_J", "Value_K", "Value_L"}

and I know I can print the values of every array item at once with

for k, v in ipairs(Array) do
  print(k, v[1], v[2], v[3], v[4])
end

but I'd like to print the values of specific array items.

How can I do that?

Body:
From reading your post and comments it seems to me you want to print every value separately instead of it all being on one line.

To do this you would need another for loop to iterate through all the values.

for k, v in ipairs(Array) do
          print(k)
          for i=1, #v do print(v[i]) end
          print() // This will just print a new line
end

Output:

1
Value_A
Value_B
Value_C
Value_D

2
Value_E
Value_F
Value_G
Value_H

3
Value_I
Value_J
Value_K
Value_L

ContentLicense: CC BY-SA 4.0


答:
If a CROSS JOIN is not what you are after, and not being able to see more sample data, I can only assume you want an inner join</p>

```<code>SELECT r.ID_Request, p.participant_no, r.invited_by
FROM Table_Request r
    INNER JOIN Table_Participant p
        ON r.ID_Request = p.ID_Request
</code>```

Title: How to get multiple values

Body:
If a CROSS JOIN is not what you are after, and not being able to see more sample data, I can only assume you want an inner join

SELECT r.ID_Request, p.participant_no, r.invited_by
FROM Table_Request r
    INNER JOIN Table_Participant p
        ON r.ID_Request = p.ID_Request


问:
Advantages to implement LDA(latent dirichlet allocation) with tensorflow
I wanted to implement LDA with tensorflow as a practice, and I think the tensorflow version may have the advantages below:

Fast. If I can use the built-in ops to express the sampling process.

Easy to parallelize. Many ops have been implemented with optimizations for parallelization, so this lda should be easy to run on gpus or distributed clusters.

Shorter and cleaner code. Like many other models, especially NNs, building such models with tensorflow involves less code.

While after I inspected some python implementations of lda(for example, https://github.com/ariddell/lda/), I have no idea what ops of tensorflow can be used, what kind of graph should be built and what optimizer should I choose. Because the process of the gibbs sampling looks like all about element-wise updating of the doc-topics, the topic-words matrices and the topic counting table. So what can tensorflow do to simplify and optimze this process?

And can I treat the likelihood of the generated doc to the real input doc as the optimization target and utilize a gradient boost optimizer to minimize the negative of the likelihood, thus get alpha, beta and doc-topics distributions? Because if this is tractable, tensorflow definitely can be used here.

答:
I have run these two models, so I think i have some ideas from practice.
LDA's outputs are the topic distribution and the word distribution, which inputs are the words in documents. Word2Vec's output is the vector expression of sentence. In your application scene, your aim is to recommend the similar topic, instead of the similar meaning of sentence. For examples, "I find a very cute cat.", "My uncle's cat is fat and I feed it foods, I'm satisfied." these two sentences has different meanings, but these sentences includes the same topic-cat.
Hope it helpful.</p>


问:
Can't close mail view controller when clicking Cancel, Save Draft or Delete Draft
I'm implementing a mail controller in my app but I can't figure out why it won't close when clicking save draft or delete draft. The window gets stuck on the email screen and I can't click "Cancel" a second time either.</p>

```<code>@IBAction func emailButtonTapped(_ sender: UIButton) {
    guard MFMailComposeViewController.canSendMail() else {
        if !MFMailComposeViewController.canSendMail() {
            print("Can not send email")
            return
        }
        return
    }

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        dismiss(animated: true, completion: nil)
    }

    let mailComposer = MFMailComposeViewController()
    mailComposer.mailComposeDelegate = self

    mailComposer.setToRecipients(["example@example.com"])
    mailComposer.setSubject("Look at this")
    mailComposer.setMessageBody("Hello, this is an email from the app I made.", isHTML: false)

    present(mailComposer, animated: true, completion: nil)
}
</code>```

答:
```<code>Check the following Code.

@IBAction func sendEmailButtonTapped(sender: AnyObject) {
            let mailComposeViewController = configuredMailComposeViewController()
            if MFMailComposeViewController.canSendMail() {
                self.presentViewController(mailComposeViewController, animated: true, completion: nil)
            } else {
                self.showSendMailErrorAlert()
            }
    }
        func configuredMailComposeViewController() -> MFMailComposeViewController {
            let mailComposerVC = MFMailComposeViewController()
            mailComposerVC.mailComposeDelegate = self

            mailComposerVC.setToRecipients([])
            mailComposerVC.setSubject("Sending In-App Email")
            mailComposerVC.setMessageBody("Sending Email through your app in Swift", isHTML: false)

            return mailComposerVC
        }
        func showSendMailErrorAlert() {
            let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send Email.  Please check Email configuration and try again.", delegate: self, cancelButtonTitle: "OK")
            sendMailErrorAlert.show()
        }
        // MFMailComposeViewControllerDelegate Method
        func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
            controller.dismissViewControllerAnimated(true, completion: nil)
        }
</code>```

Body:
I'm implementing a mail controller in my app but I can't figure out why it won't close when clicking save draft or delete draft. The window gets stuck on the email screen and I can't click "Cancel" a second time either.

@IBAction func emailButtonTapped(_ sender: UIButton) {
    guard MFMailComposeViewController.canSendMail() else {
        if !MFMailComposeViewController.canSendMail() {
            print("Can not send email")
            return
        }
        return
    }

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        dismiss(animated: true, completion: nil)
    }

    let mailComposer = MFMailComposeViewController()
    mailComposer.mailComposeDelegate = self

    mailComposer.setToRecipients(["example@example.com"])
    mailComposer.setSubject("Look at this")
    mailComposer.setMessageBody("Hello, this is an email from the app I made.", isHTML: false)

    present(mailComposer, animated: true, completion: nil)
}


问:
MVC 5 for..loop ActionLink breaks html
The ActionLink not rendered well inside Foreach , when i remove it all thing works fine.

My Code

```<code><tbody>
    @foreach (TBaseModel record in Model.Records.List())
    {

        <tr>
            <td>@record["RowID"].value</td>
            <td>@record["Usr_Username"].value</td>
            <td>@record["Usr_FullName"].value</td>
            <td>@record["Usr_Sec_Level_Label"].value</td>
            <td>@record["Usr_Department_Label"].value</td>
            <td>@record["Usr_Active_Label"].value</td>
            <td>
                <a href="@Html.Action("Admin_New_User", "Admin", new { id = @record["id"].value })" class="btn btn-xs btn-success"><i class="fa fa-edit"></i> Edit </a>
            </td>
        </tr>
    }

</tbody>
</code>```

What the problem is ?

答:
Html Action is used to render view not to create link , check here : Html.Action And Html.RenderAction In ASP.NET MVC

you are trying to create a by your self than you should use

```<code><a href="@Url.Action("actionName", "controllerName", new { id = "<id>" })">
  Edit
</a>
</code>```

or just use

```<code>@Html.ActionLink("Edit", "ActionMethod", "Controller",new { id = "<id>" }, null)
</code>```

will generate

```<code><a href="/controllerName/ActionMethod/<id>">Edit</a>
</code>```

Title: MVC 5 for..loop ActionLink breaks html

Body:
The ActionLink not rendered well inside Foreach , when i remove it all thing works fine.

My Code

    @foreach (TBaseModel record in Model.Records.List())
    {

            @record["RowID"].value
            @record["Usr_Username"].value
            @record["Usr_FullName"].value
            @record["Usr_Sec_Level_Label"].value
            @record["Usr_Department_Label"].value
            @record["Usr_Active_Label"].value

                 Edit

    }

What the problem is ?

Body:
Html Action is used to render view not to create link , check here : Html.Action And Html.RenderAction In ASP.NET MVC

you are trying to create a by your self than you should use

<a href="@Url.Action("actionName", "controllerName", new { id = "<id>" })">
  Edit
</a>

or just use

@Html.ActionLink("Edit", "ActionMethod", "Controller",new { id = "<id>" }, null)

will generate

<a href="/controllerName/ActionMethod/<id>">Edit</a>


问:
-[UIViewController tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0x7ff437517770
I don't quite understand this error or why I am receiving it. I have had a look at a couple other SO questions on this and have tinkered with my storyboard in attempt to fix the issue, but have had no success. Here is my code:

```<code>class Home: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var images = [String]()
    var names = [String]()

    func getNames(array: inout Array<String>){
        for dict in State.event {
            array.append(dict["name"] as! String)
        }
    }

    func getImages(array: inout Array<String>){
        for dict in State.event {
            let cover = dict["cover"] as! NSDictionary
            let pictureURL = cover["source"] as! String

            array.append(pictureURL)
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return State.token.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        getNames(array: &names)
        getImages(array: &images)
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell

        let url = URL(string: images[indexPath.row])
        let imageData = try? Data(contentsOf: url!)
        cell.eventImage.image = UIImage(data: imageData!)
        cell.eventName.text = names[indexPath.row]

        return cell
    }

}
</code>```

error: -[UIViewController tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0x7ff437517770

答: This is happened because you have set DataSource from Storyboard. but I think you have forgot to set Home as Class in Storyboard

Body:
I don't quite understand this error or why I am receiving it. I have had a look at a couple other SO questions on this and have tinkered with my storyboard in attempt to fix the issue, but have had no success. Here is my code:

class Home: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var images = [String]()
    var names = [String]()

    func getNames(array: inout Array<String>){
        for dict in State.event {
            array.append(dict["name"] as! String)
        }
    }

    func getImages(array: inout Array<String>){
        for dict in State.event {
            let cover = dict["cover"] as! NSDictionary
            let pictureURL = cover["source"] as! String

            array.append(pictureURL)
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return State.token.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        getNames(array: &names)
        getImages(array: &images)
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell

        let url = URL(string: images[indexPath.row])
        let imageData = try? Data(contentsOf: url!)
        cell.eventImage.image = UIImage(data: imageData!)
        cell.eventName.text = names[indexPath.row]

        return cell
    }

}

error: -[UIViewController tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0x7ff437517770


问:
ConstraintLayout-Params are ignored
i want to create an calendar Day-View like the one Google has.
For that i want to create dynamically the timelines. Thats the way i do it right now:

```<code>TextView nextTime = new TextView(this);
View nextView = new View(this);
View nextLine = new View(this);

ConstraintLayout.LayoutParams lineParams = new
ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
ConstraintLayout.LayoutParams timeParams = new
ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
ConstraintLayout.LayoutParams viewParams = new
ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);

viewParams.topToBottom = firstView.getId();
viewParams.leftToLeft = firstView.getId();
viewParams.height = Utils.changeDPItoPX(26, displayMetrics);
viewParams.width = Utils.changeDPItoPX(0, displayMetrics);
viewParams.setMargins(0, Utils.changeDPItoPX(16, displayMetrics),0,0);
nextView.setLayoutParams(viewParams);
constraintLayout.addView(nextView);

timeParams.topToTop = nextView.getId();
timeParams.bottomToBottom = nextView.getId();
timeParams.leftToLeft = nextView.getId();
timeParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
timeParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
timeParams.setMargins(Utils.changeDPItoPX(16, displayMetrics), 0,0,0);
nextTime.setLayoutParams(timeParams);
constraintLayout.addView(nextTime);

lineParams.height = Utils.changeDPItoPX(2, displayMetrics);
lineParams.bottomToBottom = nextTime.getId();
lineParams.endToEnd = nextView.getId();
lineParams.startToEnd = nextTime.getId();
lineParams.topToTop = nextTime.getId();
lineParams.setMargins(Utils.changeDPItoPX(8, displayMetrics), 0,
Utils.changeDPItoPX(8, displayMetrics), 0);
lineParams.width = Utils.changeDPItoPX(0, displayMetrics);
nextLine.setLayoutParams(lineParams);
constraintLayout.addView(nextLine);
</code>```

In my layout xml for the activity i already have the first timestamp. So this code should add the next one. And it looks like this:

|  00:00 --------------------------  |

|  01:--0--0 -----------------------|

The timeLine is over my time and it also goes to end of the screen.
But it should look like the timeStamp above.

What am i doing wrong? Why does it ignore the constraints?

答:
Ok i got it figured out. So what you basically have to do when you want to add a view dynamically and then constraint it to other views is this:

First get your constraint layout in which you for example already have a view

```<code>constraintLayout = (ConstraintLayout) findViewById(R.id.mainframe);
View firstView = findViewById(R.id.firstView);
</code>```

Create new view you want to add

```<code>View nextView = new View(this);
nextView.setBackgroundColor(0xFF00FF00);
</code>```

Now add the view to your constraint layout

```<code>constraintLayout.addView(nextView);
</code>```

For the last step you clone your constraint layout then add the constraints you want to add and apply them to your constraint layout

```<code>constraintSet.clone(constraintLayout);
constraintSet.connect(nextView.getId(),ConstraintSet.TOP,
firstView.getId(), ConstraintSet.BOTTOM, 16);
constraintSet.applyTo(constraintLayout);
</code>```

I hope i can help with that if someone has the same problem.

Title: ConstraintLayout-Params are ignored

Body:
i want to create an calendar Day-View like the one Google has.
For that i want to create dynamically the timelines. Thats the way i do it right now:

TextView nextTime = new TextView(this);
View nextView = new View(this);
View nextLine = new View(this);

ConstraintLayout.LayoutParams lineParams = new
ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
ConstraintLayout.LayoutParams timeParams = new
ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
ConstraintLayout.LayoutParams viewParams = new
ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);

viewParams.topToBottom = firstView.getId();
viewParams.leftToLeft = firstView.getId();
viewParams.height = Utils.changeDPItoPX(26, displayMetrics);
viewParams.width = Utils.changeDPItoPX(0, displayMetrics);
viewParams.setMargins(0, Utils.changeDPItoPX(16, displayMetrics),0,0);
nextView.setLayoutParams(viewParams);
constraintLayout.addView(nextView);

timeParams.topToTop = nextView.getId();
timeParams.bottomToBottom = nextView.getId();
timeParams.leftToLeft = nextView.getId();
timeParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
timeParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
timeParams.setMargins(Utils.changeDPItoPX(16, displayMetrics), 0,0,0);
nextTime.setLayoutParams(timeParams);
constraintLayout.addView(nextTime);

lineParams.height = Utils.changeDPItoPX(2, displayMetrics);
lineParams.bottomToBottom = nextTime.getId();
lineParams.endToEnd = nextView.getId();
lineParams.startToEnd = nextTime.getId();
lineParams.topToTop = nextTime.getId();
lineParams.setMargins(Utils.changeDPItoPX(8, displayMetrics), 0,
Utils.changeDPItoPX(8, displayMetrics), 0);
lineParams.width = Utils.changeDPItoPX(0, displayMetrics);
nextLine.setLayoutParams(lineParams);
constraintLayout.addView(nextLine);

In my layout xml for the activity i already have the first timestamp. So this code should add the next one. And it looks like this:

|  00:00 --------------------------  |

|  01:--0--0 -----------------------|

The timeLine is over my time and it also goes to end of the screen.
But it should look like the timeStamp above.

What am i doing wrong? Why does it ignore the constraints?

Body:
Ok i got it figured out. So what you basically have to do when you want to add a view dynamically and then constraint it to other views is this:

First get your constraint layout in which you for example already have a view

constraintLayout = (ConstraintLayout) findViewById(R.id.mainframe);
View firstView = findViewById(R.id.firstView);

Create new view you want to add

View nextView = new View(this);
nextView.setBackgroundColor(0xFF00FF00);

Now add the view to your constraint layout

constraintLayout.addView(nextView);

For the last step you clone your constraint layout then add the constraints you want to add and apply them to your constraint layout

constraintSet.clone(constraintLayout);
constraintSet.connect(nextView.getId(),ConstraintSet.TOP,
firstView.getId(), ConstraintSet.BOTTOM, 16);
constraintSet.applyTo(constraintLayout);

I hope i can help with that if someone has the same problem.


问:
Seeking constructive criticism on monad implementation
I'm learning monads, this is my first working one (aside from the trivial monad). Feel free to criticize everything in it ruthlessly. I'm especially interested in "more idiomatic" and "more elegant" kind of responses.

This monad counts the number of binds performed.

```<code>data C a = C {value :: a, count :: Int} deriving (Show)

instance Monad C where
    (>>=) (C x c) f = C (value $ f x) (c + 1)
    return x = C x 0

add :: (Num a) => a -> a -> C a
add x y = return $ x + y

-- Simpler way to do this? foldM is obviously something different.
mysum [x] = return x
mysum (x:xs) = mysum xs >>= add x
</code>```

答:
Stylistically this is very nice.  In the real world, I would expect a 60% chance of this notation instead of the one you gave:

```<code>C x c >>= f = C (value $ f x) (c + 1)
</code>```

But that is so minor it is hardly worth mentioning.

On a more serious note, not stylistic but semantic: this is not a monad.  In fact, it violates all three of the monad laws.

```<code>(1) return x >>= f  =  f x
(2) m >>= return    = m
(3) m >>= (f >=> g) = (m >>= f) >>= g
</code>```

(Where (>=>) is defined as f >=> g  =  \x -> f x >>= g.  If (>>=) is considered an "application" operator, then (>=>) is the corresponding composition operator. I like to state the third law using this operator because it brings out the third law's meaning: associativity.)

With these computations:

(1):

```<code>return 0 >>= return
  = C 0 0 >>= return
  = C (value $ return 0) 1
  = C 0 1
Not equal to return 0 = C 0 0
</code>```

(2):

```<code>C 0 0 >>= return
  = C (value $ return 0) 1
  = C 0 1
Not equal to C 0 0
</code>```

(3)

```<code>C 0 0 >>= (return >=> return)
  = C (value $ (return >=> return) 0) 1
  = C (value $ return 0 >>= return) 1
  = C (value $ C 0 1) 1
  = C 0 1

Is not equal to:

(C 0 0 >>= return) >>= return
  = C (value $ return 0) 1 >>= return
  = C 0 1 >>= return
  = C (value $ return 0) 2
  = C 0 2
</code>```

This isn't just an error in your implementation -- there is no monad that "counts the number of binds".  It must violate laws (1) and (2).  The fact that yours violates law (3) is an implementation error, however.

The trouble is that f in the definition of (>>=) might return an action that has more than one bind, and you are ignoring that.  You need to add the number of binds from the left and right arguments:

```<code>C x c >>= f = C y (c+c'+1)
   where
   C y c' = f x
</code>```

This will correctly count the number of binds, and will satisfy the third law, which is the associativity law.  It won't satisfy the other two.  However, if you drop the +1 from this definition, then you do get a real monad, which is equivalent to the Writer monad over the + monoid.  This basically adds together the results of all subcomputations.  You could use this to count the number of somethings, just not binds -- bind is too special to count.  But, for example:

```<code>tick :: C ()
tick = C () 1
</code>```

Then C will count the number of ticks that occurred in the computation.

In fact, you can replace Int with any type and (+) with any associative operator and get a monad.  This is what a Writer monad is in general.  If the operator is not associative, then this will fail the third law (can you see why?).

Body:
I'm learning monads, this is my first working one (aside from the trivial monad). Feel free to criticize everything in it ruthlessly. I'm especially interested in "more idiomatic" and "more elegant" kind of responses.

This monad counts the number of binds performed.

data C a = C {value :: a, count :: Int} deriving (Show)

instance Monad C where
    (>>=) (C x c) f = C (value $ f x) (c + 1)
    return x = C x 0

add :: (Num a) => a -> a -> C a
add x y = return $ x + y

-- Simpler way to do this? foldM is obviously something different.
mysum [x] = return x
mysum (x:xs) = mysum xs >>= add x

Body:
Stylistically this is very nice.  In the real world, I would expect a 60% chance of this notation instead of the one you gave:

C x c >>= f = C (value $ f x) (c + 1)

But that is so minor it is hardly worth mentioning.

On a more serious note, not stylistic but semantic: this is not a monad.  In fact, it violates all three of the monad laws.

(1) return x >>= f  =  f x
(2) m >>= return    = m
(3) m >>= (f >=> g) = (m >>= f) >>= g

(Where (>=>) is defined as f >=> g  =  \x -> f x >>= g.  If (>>=) is considered an "application" operator, then (>=>) is the corresponding composition operator. I like to state the third law using this operator because it brings out the third law's meaning: associativity.)

With these computations:

(1):

return 0 >>= return
  = C 0 0 >>= return
  = C (value $ return 0) 1
  = C 0 1
Not equal to return 0 = C 0 0

(2):

C 0 0 >>= return
  = C (value $ return 0) 1
  = C 0 1
Not equal to C 0 0

(3)

C 0 0 >>= (return >=> return)
  = C (value $ (return >=> return) 0) 1
  = C (value $ return 0 >>= return) 1
  = C (value $ C 0 1) 1
  = C 0 1

Is not equal to:

(C 0 0 >>= return) >>= return
  = C (value $ return 0) 1 >>= return
  = C 0 1 >>= return
  = C (value $ return 0) 2
  = C 0 2

This isn't just an error in your implementation -- there is no monad that "counts the number of binds".  It must violate laws (1) and (2).  The fact that yours violates law (3) is an implementation error, however.

The trouble is that f in the definition of (>>=) might return an action that has more than one bind, and you are ignoring that.  You need to add the number of binds from the left and right arguments:

C x c >>= f = C y (c+c'+1)
   where
   C y c' = f x

This will correctly count the number of binds, and will satisfy the third law, which is the associativity law.  It won't satisfy the other two.  However, if you drop the +1 from this definition, then you do get a real monad, which is equivalent to the Writer monad over the + monoid.  This basically adds together the results of all subcomputations.  You could use this to count the number of somethings, just not binds -- bind is too special to count.  But, for example:

tick :: C ()
tick = C () 1

Then C will count the number of ticks that occurred in the computation.

In fact, you can replace Int with any type and (+) with any associative operator and get a monad.  This is what a Writer monad is in general.  If the operator is not associative, then this will fail the third law (can you see why?).


问:
Can't unit test redux-saga with selector function using Jest
Problem Explanation:

I want to unit test a redux-saga using Jest. I'm doing this the way it is described in the example provided within the redux-saga docs: https://redux-saga.js.org/docs/advanced/Testing.html

Within my Saga I'm calling a selector function selectSet that returns a specific object from the application store:

```<code>export const selectSet = state => state.setStore.set
</code>```

In my saga I'm trying to yield this selector function:

```<code>import { put, select } from 'redux-saga/effects'
import { selectSet } from '../selectors'

export function* getSet() {
  try {
    const set = yield select(selectSet)
    yield put({ type: 'SET_SUCCESS', payload: { set } })
  } catch (error) {
    yield put({ type: 'SET_ERROR', payload: { error } })
  }
}
</code>```

Within my test there is no valid application store so I'd have to mock the function to return the expected object:

```<code>import assert from 'assert'
import * as AppRoutines from './AppRoutines'
import { put, select } from 'redux-saga/effects'

describe('getSet()', () => {
    it('should trigger an action type "SET_SUCCESS" with a payload containing a valid set', () => {
        const generator = AppRoutines.getSet()

        const set = {
          id: 1,
          slots: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }],
        }

        const selectSet = jest.fn()
        selectSet.mockReturnValue(set)

        // Saga step 1
        const actualFirst = generator.next().value
        const expectedFirst = select(selectSet)

        assert.deepEqual(
          actualFirst,
          expectedFirst,
          'it should retreive a valid set from the store using the selectSet selector'
        )
    })
})
</code>```

However - if I assert the saga to return a specific generator value using deepEqual and my mocked function, it expects my selector function to have the original selectSet constructor. But since I'm mocking the function with jest.fn() the constructor is actually equal to mockConstructor - which makes my test fail:

```<code>Expected value to deeply equal to:
    {"@@redux-saga/IO": true, "SELECT": {"args": Array [], "selector": [Function mockConstructor]}}
Received:
    {"@@redux-saga/IO": true, "SELECT": {"args": Array [], "selector": [Function selectSet]}}
</code>```

Question: How can I make an assert.deepEqual containing a mock function without conflicting constructor types?

Alternative Question: Is there a way to make my assertion expect a mockConstructor instead of the actual selectSet constructor?

答:
You should not need to mock the selector at all, as in a saga test of this nature, the selector is never actually called, instead you are testing the declarative instructions that are created for the redux saga middleware to act upon are as you expect

This is the instruction that the saga will create {"@@redux-saga/IO": true, "SELECT": {"args": Array [], "selector": [Function selectSet]}}, but as the middleware is not running during this test scenario selectSelect will never actually get called

If you need to mock results that your selector returns for your action, then you do so by passing the mock data into the next step...

```<code>    const set = {
      id: 1,
      slots: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }],
    }

    // Saga step 1
    const firstYield = generator.next().value
    assertDeepEqual(firstYield, select(selectSet))

    // Step 2 - successful so dispatch action
    // mock data from the previous yield by passing into this step via `next(stubbedYieldedData)`
    const secondYield = generator.next(set).value
    assertDeepEqual(secondYield, put({type: 'SET_SUCCESS', payload: {set} }))
</code>```

Body:
Problem Explanation:

I want to unit test a redux-saga using Jest. I'm doing this the way it is described in the example provided within the redux-saga docs: https://redux-saga.js.org/docs/advanced/Testing.html

Within my Saga I'm calling a selector function selectSet that returns a specific object from the application store:

export const selectSet = state => state.setStore.set

In my saga I'm trying to yield this selector function:

import { put, select } from 'redux-saga/effects'
import { selectSet } from '../selectors'

export function* getSet() {
  try {
    const set = yield select(selectSet)
    yield put({ type: 'SET_SUCCESS', payload: { set } })
  } catch (error) {
    yield put({ type: 'SET_ERROR', payload: { error } })
  }
}

Within my test there is no valid application store so I'd have to mock the function to return the expected object:

import assert from 'assert'
import * as AppRoutines from './AppRoutines'
import { put, select } from 'redux-saga/effects'

describe('getSet()', () => {
    it('should trigger an action type "SET_SUCCESS" with a payload containing a valid set', () => {
        const generator = AppRoutines.getSet()

        const set = {
          id: 1,
          slots: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }],
        }

        const selectSet = jest.fn()
        selectSet.mockReturnValue(set)

        // Saga step 1
        const actualFirst = generator.next().value
        const expectedFirst = select(selectSet)

        assert.deepEqual(
          actualFirst,
          expectedFirst,
          'it should retreive a valid set from the store using the selectSet selector'
        )
    })
})

However - if I assert the saga to return a specific generator value using deepEqual and my mocked function, it expects my selector function to have the original selectSet constructor. But since I'm mocking the function with jest.fn() the constructor is actually equal to mockConstructor - which makes my test fail:

Expected value to deeply equal to:
    {"@@redux-saga/IO": true, "SELECT": {"args": Array [], "selector": [Function mockConstructor]}}
Received:
    {"@@redux-saga/IO": true, "SELECT": {"args": Array [], "selector": [Function selectSet]}}

Question: How can I make an assert.deepEqual containing a mock function without conflicting constructor types?

Alternative Question: Is there a way to make my assertion expect a mockConstructor instead of the actual selectSet constructor?

Body:
You should not need to mock the selector at all, as in a saga test of this nature, the selector is never actually called, instead you are testing the declarative instructions that are created for the redux saga middleware to act upon are as you expect

This is the instruction that the saga will create {"@@redux-saga/IO": true, "SELECT": {"args": Array [], "selector": [Function selectSet]}}, but as the middleware is not running during this test scenario selectSelect will never actually get called

If you need to mock results that your selector returns for your action, then you do so by passing the mock data into the next step...

    const set = {
      id: 1,
      slots: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }],
    }

    // Saga step 1
    const firstYield = generator.next().value
    assertDeepEqual(firstYield, select(selectSet))

    // Step 2 - successful so dispatch action
    // mock data from the previous yield by passing into this step via `next(stubbedYieldedData)`
    const secondYield = generator.next(set).value
    assertDeepEqual(secondYield, put({type: 'SET_SUCCESS', payload: {set} }))


问:
Custom UIView without Storyboard
Now I'm practicing build IOS app without using storyboard , but I have a problem want to solve , I created a custom UIView called BannerView and added a background(UIView) and a title(UILabel) , and called this BannerView in the MainVC , but run this app , it crashes at the function setupSubviews() and I don't know why.

```<code>import UIKit
import SnapKit

class BannerView: UIView {

    var background: UIView!
    var title: UILabel!

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupSubviews()
    }

    convenience init() {
        self.init(frame: CGRect.zero)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupSubviews()
    }

    func setupSubviews() {
        background.backgroundColor = .gray
        title.text = "INHEART"

        self.addSubview(background)
        self.addSubview(title)
    }

    override func layoutSubviews() {
        background.snp.makeConstraints { make in
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(BannerHeight)
            make.left.top.right.equalTo(0)
        }

        title.snp.makeConstraints { make in
            make.width.equalTo(100)
            make.center.equalTo(background.snp.center)
        }
    }

}

class MainVC: UIViewController {

    var bannerView:BannerView!

    override func viewDidLoad() {
        super.viewDidLoad()
        bannerView = BannerView(frame: CGRect.zero)
        view.addSubview(bannerView)
    }

}
</code>```

答:
Your properties do not appear to be initialised

```<code>var background: UIView!
var title: UILabel!
</code>```

You should initialize these in your init method

```<code>self.background = UIView()
self.title = UILabel()
</code>```

If you use force unwrapping on a class property you must initialize in the init method. XCode should be complaining to you about this and your error message should show a similar error

Title: Custom UIView without Storyboard

Body:
Now I'm practicing build IOS app without using storyboard , but I have a problem want to solve , I created a custom UIView called BannerView and added a background(UIView) and a title(UILabel) , and called this BannerView in the MainVC , but run this app , it crashes at the function setupSubviews() and I don't know why.

import UIKit
import SnapKit

class BannerView: UIView {

    var background: UIView!
    var title: UILabel!

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupSubviews()
    }

    convenience init() {
        self.init(frame: CGRect.zero)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupSubviews()
    }

    func setupSubviews() {
        background.backgroundColor = .gray
        title.text = "INHEART"

        self.addSubview(background)
        self.addSubview(title)
    }

    override func layoutSubviews() {
        background.snp.makeConstraints { make in
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(BannerHeight)
            make.left.top.right.equalTo(0)
        }

        title.snp.makeConstraints { make in
            make.width.equalTo(100)
            make.center.equalTo(background.snp.center)
        }
    }

}

class MainVC: UIViewController {

    var bannerView:BannerView!

    override func viewDidLoad() {
        super.viewDidLoad()
        bannerView = BannerView(frame: CGRect.zero)
        view.addSubview(bannerView)
    }

}

Body:
Your properties do not appear to be initialised

var background: UIView!
var title: UILabel!

You should initialize these in your init method

self.background = UIView()
self.title = UILabel()

If you use force unwrapping on a class property you must initialize in the init method. XCode should be complaining to you about this and your error message should show a similar error


问:
Change Compiler Options in Intel PIN
How can I change g++ options while compiling a Pin tool? For example, is it possible to prevent warnings from being treated as errors or is it possible to link the tool with an external library such as bfd?</p>

答:
Linking Pin to precompiled libraries is discouraged. Pin uses a different libc and linking will either fail or cause issues while running. If you wish to use an external library either compile it against pin's runtime or use it in a separate process.

To build specific files in a nonstandard way, add a rule to the Build rules section of the relevant makefile.

In general it is a bad idea to modify pin's default flags. They all serve a purpose.

Title: Change Compiler Options in Intel PIN


问:
find the min and max values of nested list by index of element in nested list
I have a nested list like the following:

```<code>x = [[1,  5, 3,  4],
     [5, 10, 7,  8],
     [9,  9, 2, 12]]
</code>```

I need to find to find the min and max values of the nested list transposed such that the result for min is:

```<code>1, 5, 2, 4  # 1 is the min of first column (1, 5, 9) a.s.o
</code>```

and the max should be:

```<code>9, 10, 7, 12
</code>```

I tried to convert it into a dataframe first and then doing max and min on the different axis but all doesn't come up as the result I want.

答:
You can use list comprehension or other way:

```<code>print([min(item) for item in zip(*x)])
</code>```

is same as:

```<code>min_list=[]
for i in zip(*x):
    min_list.append(min(i))
print(min_list)
</code>```

output:

```<code>[1, 5, 2, 4]
</code>```

For max:

```<code>print([max(item) for item in zip(*x)])
</code>```

is same as:

```<code>max_list=[]
for i in zip(*x):
    max_list.append(max(i))

print(max_list)
</code>```

output:

```<code>[9, 10, 7, 12]
</code>```

Body:
I have a nested list like the following:

x = [[1,  5, 3,  4],
     [5, 10, 7,  8],
     [9,  9, 2, 12]]

I need to find to find the min and max values of the nested list transposed such that the result for min is:

1, 5, 2, 4  # 1 is the min of first column (1, 5, 9) a.s.o

and the max should be:

9, 10, 7, 12

I tried to convert it into a dataframe first and then doing max and min on the different axis but all doesn't come up as the result I want.

Body:
You can use list comprehension or other way:

print([min(item) for item in zip(*x)])

is same as:

min_list=[]
for i in zip(*x):
    min_list.append(min(i))
print(min_list)

output:

[1, 5, 2, 4]

For max:

print([max(item) for item in zip(*x)])

is same as:

max_list=[]
for i in zip(*x):
    max_list.append(max(i))

print(max_list)

output:

[9, 10, 7, 12]


问:
Creating tags on posts RAILS
I am making something that's like that autocomplete tags field for the posts on stackoverflow.com

I want to make it so that when you make a blog post, you can tag it with words in a database, similar to SO.

For the posts, it belongs_to_and_has_many tags
For the tags, it belongs_to_and_has_many posts

However it is a problem for me to do it on the same page because @post would be nil.

How can I implement this?

(If someone can give me the code for the stackoverflow ask question page that would be AWESOME)

答:
It looks for me like you want to generate tags automatically.

You could create

class Post

     before_save :create_tags

private

     def create_tags

      # get your tags somehow

      self.tags << Tag.new(:text=>"...")

     end

   end

method in models/post.rb and build them there.

Title: Creating tags on posts RAILS


问:
Using JSch, is there a way to tell if a remote file exists without doing an ls?
Using JSch, is there a way to tell if a remote file exists without doing an ls and looping through the files to find a name match?

Thanks

答:
Actually in my project ls working without loops. I just pass to the ls call path with filename.

```<code>private static boolean exists(ChannelSftp channelSftp, String path) {
    Vector res = null;
    try {
        res = channelSftp.ls(path);
    } catch (SftpException e) {
        if (e.id == SSH_FX_NO_SUCH_FILE) {
            return false;
        }
        log.error("Unexpected exception during ls files on sftp: [{}:{}]", e.id, e.getMessage());
    }
    return res != null && !res.isEmpty();
}
</code>```

For example there a file file.txt with an url sftp://user@www.server.comm/path/to/some/random/folder/file.txt. I pass to function exists path as /path/to/some/random/folder/file.txt

Body:
Actually in my project ls working without loops. I just pass to the ls call path with filename.

private static boolean exists(ChannelSftp channelSftp, String path) {
    Vector res = null;
    try {
        res = channelSftp.ls(path);
    } catch (SftpException e) {
        if (e.id == SSH_FX_NO_SUCH_FILE) {
            return false;
        }
        log.error("Unexpected exception during ls files on sftp: [{}:{}]", e.id, e.getMessage());
    }
    return res != null && !res.isEmpty();
}

For example there a file file.txt with an url sftp://user@www.server.comm/path/to/some/random/folder/file.txt. I pass to function exists path as /path/to/some/random/folder/file.txt


问:
How to render a View within a View without impacting styling
So I'm rendering a View that will display a number of components. Everything looks the way it should when I'm not using the nestedContainer. Each component is spaced out the way it should and it's aligned properly. Now if I add the View with the nestedContainer style, it no longer applies space-around to the HandRolledIcon and UserName component. How do I work around this and make sure those components within the nested View uses the styles I want?

(This question is related to my other question which contains more details)

```<code><View style={styles.container}>
  <View style={styles.nestedContainer>
    <HandRolledIcon style={styles.hrIcon} />
    <UserName style={styles.userName} />
  </View>
</View>

container: {
    flex: 1,
    justifyContent: 'space-around',
    flexDirection: 'column',
    alignItems: 'center',
  },
nestedContainer: {
    alignItems: 'center',
    justifyContent: 'space-around',
  },
hrIcon: {
    alignItems: 'center',
  },
userName: {
    alignItems: 'center',
  }
</code>```

答:
I actually don't know what you're trying to achieve, But I feel u must brush up your flex-box knowledge.

Check out these links it might help you

https://tympanus.net/codrops/css_reference/flexbox/

https://facebook.github.io/yoga/docs/getting-started/

One way of achieving your result is giving flexGrow:1 (flex: 1 kind of works the same in react-native) to your nested container, which will make your nested container view to occupy all the extra space.

```<code>nestedContainer: {
    flexGrow: 1,
    alignItems: 'center', // <--- This can be removed based on your requirements since its already given to the parent view
    justifyContent: 'space-around',
  },
</code>```

NOTE: This is just one way, other ways might be possible just go through the flex-box docs thoroughly.

Body:
So I'm rendering a View that will display a number of components. Everything looks the way it should when I'm not using the nestedContainer. Each component is spaced out the way it should and it's aligned properly. Now if I add the View with the nestedContainer style, it no longer applies space-around to the HandRolledIcon and UserName component. How do I work around this and make sure those components within the nested View uses the styles I want?

(This question is related to my other question which contains more details)

<View style={styles.container}>
  <View style={styles.nestedContainer>
    <HandRolledIcon style={styles.hrIcon} />
    <UserName style={styles.userName} />
  </View>
</View>

container: {
    flex: 1,
    justifyContent: 'space-around',
    flexDirection: 'column',
    alignItems: 'center',
  },
nestedContainer: {
    alignItems: 'center',
    justifyContent: 'space-around',
  },
hrIcon: {
    alignItems: 'center',
  },
userName: {
    alignItems: 'center',
  }

Body:
I actually don't know what you're trying to achieve, But I feel u must brush up your flex-box knowledge.

Check out these links it might help you

https://tympanus.net/codrops/css_reference/flexbox/

https://facebook.github.io/yoga/docs/getting-started/

One way of achieving your result is giving flexGrow:1 (flex: 1 kind of works the same in react-native) to your nested container, which will make your nested container view to occupy all the extra space.

nestedContainer: {
    flexGrow: 1,
    alignItems: 'center', // <--- This can be removed based on your requirements since its already given to the parent view
    justifyContent: 'space-around',
  },

NOTE: This is just one way, other ways might be possible just go through the flex-box docs thoroughly.