问:
HTTP Proxy server in C#
My company is experimenting with writing a proxy server using the .NET Fx 3.5 and C#.  From our research I have read that HttpListener is not a good candidate for a proxy server though I am unsure as to why.

We are currently working with the Mentalis proxy example source code though that will involve, among other things, implementing our own logging and performance counters.  Using HttpListener will wrap Http.sys which will give us some of the performance statistics we require out of the box.

So why is HttpListener a bad candidate for HTTP proxy work?

(And yes we are considering Squid 3.1 by writing or configuring an ICAP server as well.)

答:
HttpListener is in .NET to provide a major building block for a simple HTTP server. Where simple includes not supporting high operation rates.

Typically HTTP proxies need to be very low overhead to support many concurrent connections as well as providing the proxy's function (which depends on the type of proxy).

Proxies are detailed in RFC 2616 §8.1.3) and that immediately provides one item that (if I understand HttpListener correctly) is not possible:

The proxy server MUST signal persistent connections separately with its clients and the origin servers (or other proxy servers) that it connects to. Each persistent connection applies to only one transport link.

OwnerDisplayName: cfeduke

ContentLicense: CC BY-SA 2.5

Title: HTTP Proxy server in C#

OwnerDisplayName: Richard


来源: stackexchange

问:
JQuery + table issue with IE
I have a dynamic table with a delete button and several input elements on each row. Each row has an ID. When i push the delete button I use jQuery to delete the row and then update the ID's. Like this

```<code>function deleteRow(row) {
    var num = $("#table>tbody>tr").length;
    if (num > 1) {
        $(row).closest("tr").remove();
    }
    updateIds();
}

function updateIds() {
        var counter = 0;
        var num = $("#myTable>tbody>tr").length;
        $("#myTable>tbody>tr").each(function(){
            $("input",this).each(function(){
                var currentId = $(this).attr("id");
                var newId = currentId.substring(0,currentId.indexOf(('_'))+1);
                $(this).attr("id",newId+counter);
                var currentPath = $(this).attr("name");

                var front = currentPath.substring(0,currentPath.indexOf('[')+1);
                var back = currentPath.substring(currentPath.indexOf(']'));

                $(this).attr("name",front+counter+back);

            })

            counter++;
        })
    }
</code>```

This works Fine in FF and Chrome but in IE 7 I am having some trubble after running these two functions. When i focus on an input element in a tr the cursor jumps up one row. Its like its trying to fucus on the tr that was just deleted.

Anybody have any ideas

答:
Well, you can manually set the focus with:

```<code>$(element).focus();
</code>```

Get the element using the index of the row/cell you want the focus to be. Does that help?

ContentLicense: CC BY-SA 3.0

Title: JQuery + table issue with IE

Body:
I have a dynamic table with a delete button and several input elements on each row. Each row has an ID. When i push the delete button I use jQuery to delete the row and then update the ID's. Like this

function deleteRow(row) {
    var num = $("#table>tbody>tr").length;
    if (num > 1) {
        $(row).closest("tr").remove();
    }
    updateIds();
}

function updateIds() {
        var counter = 0;
        var num = $("#myTable>tbody>tr").length;
        $("#myTable>tbody>tr").each(function(){
            $("input",this).each(function(){
                var currentId = $(this).attr("id");
                var newId = currentId.substring(0,currentId.indexOf(('_'))+1);
                $(this).attr("id",newId+counter);
                var currentPath = $(this).attr("name");

                var front = currentPath.substring(0,currentPath.indexOf('[')+1);
                var back = currentPath.substring(currentPath.indexOf(']'));

                $(this).attr("name",front+counter+back);

            })

            counter++;
        })
    }

This works Fine in FF and Chrome but in IE 7 I am having some trubble after running these two functions. When i focus on an input element in a tr the cursor jumps up one row. Its like its trying to fucus on the tr that was just deleted.

Anybody have any ideas

Body:
Well, you can manually set the focus with:

$(element).focus();

Get the element using the index of the row/cell you want the focus to be. Does that help?


问:
xml won't build, how other possible way
I could not build my project due to this xml code, but cannot figure out where exactly lays the problem. I first used scrollView, I did delete it, and used ListView instead. Since then could not run my project.
the error I am getting is this:

ParseError at [row,col]:[118,54]
Message: http://www.w3.org/TR/1999/REC-xml-names-19990114#AttributeNSNotUnique?ListView&layout_width&http://schemas.android.com/apk/res/android*

here is the code

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:anddroid="http://schemas.android.com/apk/res/android"
    android:background="#FFFCEC">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#0BA811"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginBottom="48dp"
        android:layout_weight="1"
        android:orientation="vertical"
        android:layoutDirection="rtl"
        app:layout_constraintBottom_toBottomOf="@+id/tab_layout" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="310dp"
        android:layout_height="49dp"
        android:text="Here where your friends are!"
        android:textColor="#127A00"
        android:textSize="24sp"
        android:textStyle="italic"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.495"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.832" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="270dp"
        android:layout_height="88dp"
        android:text="theFinder"
        android:textColor="#127A00"
        android:textSize="60sp"
        android:textStyle="bold|italic"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.496"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.729" />

    <Button
        android:id="@+id/btnscan"
        android:layout_width="408dp"
        android:layout_height="75dp"
        android:backgroundTint="#127A00"
        android:text="press to Scan"
        android:textColor="#EDFFFFFF"
        android:textColorHighlight="#FFFFFFFF"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.996" />

    <ProgressBar
        android:id="@+id/pBar"
        style="@android:style/Widget.ProgressBar.Large"
        android:layout_width="113dp"
        android:layout_height="77dp"
        android:indeterminate="true"
        android:indeterminateOnly="true"
        android:max="100"
        android:progress="10"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.578" />

    <TextView
        android:id="@+id/tView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textColor="#1E7822"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.566" />

    <ListView
        android:id="@+id/lst_view"
        anddroid:layout_width="409dp"
        android:layout_width="396dp"
        anddroid:layout_height="328dp"
        android:layout_height="244dp"
        android:background="#D80E1127"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.141" />```
```

答:
Your root element specifies two aliases for the same namespace:

xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:anddroid="http://schemas.android.com/apk/res/android"

Then in the ListView with an ID of @+id/lst_view you specify layout_height and layout_width twice, once with each alias:

        anddroid:layout_width="409dp"
        android:layout_width="396dp"
        anddroid:layout_height="328dp"
        android:layout_height="244dp"
```

That means you're specifying the same namespace-qualified attribute twice for each of width and height. That's not allowed.

Just remove the anddroid typo-alias, and remove the two attributes using it.

ContentLicense: CC BY-SA 4.0

Title: xml won't build, how other possible way

Body:
I could not build my project due to this xml code, but cannot figure out where exactly lays the problem. I first used scrollView, I did delete it, and used ListView instead. Since then could not run my project.
the error I am getting is this:

ParseError at [row,col]:[118,54]
Message: http://www.w3.org/TR/1999/REC-xml-names-19990114#AttributeNSNotUnique?ListView&layout_width&http://schemas.android.com/apk/res/android*

here is the code

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:anddroid="http://schemas.android.com/apk/res/android"
    android:background="#FFFCEC">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#0BA811"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginBottom="48dp"
        android:layout_weight="1"
        android:orientation="vertical"
        android:layoutDirection="rtl"
        app:layout_constraintBottom_toBottomOf="@+id/tab_layout" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="310dp"
        android:layout_height="49dp"
        android:text="Here where your friends are!"
        android:textColor="#127A00"
        android:textSize="24sp"
        android:textStyle="italic"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.495"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.832" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="270dp"
        android:layout_height="88dp"
        android:text="theFinder"
        android:textColor="#127A00"
        android:textSize="60sp"
        android:textStyle="bold|italic"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.496"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.729" />

    <Button
        android:id="@+id/btnscan"
        android:layout_width="408dp"
        android:layout_height="75dp"
        android:backgroundTint="#127A00"
        android:text="press to Scan"
        android:textColor="#EDFFFFFF"
        android:textColorHighlight="#FFFFFFFF"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.996" />

    <ProgressBar
        android:id="@+id/pBar"
        style="@android:style/Widget.ProgressBar.Large"
        android:layout_width="113dp"
        android:layout_height="77dp"
        android:indeterminate="true"
        android:indeterminateOnly="true"
        android:max="100"
        android:progress="10"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.578" />

    <TextView
        android:id="@+id/tView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textColor="#1E7822"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.566" />

    <ListView
        android:id="@+id/lst_view"
        anddroid:layout_width="409dp"
        android:layout_width="396dp"
        anddroid:layout_height="328dp"
        android:layout_height="244dp"
        android:background="#D80E1127"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.141" />```

Body:
Your root element specifies two aliases for the same namespace:

xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:anddroid="http://schemas.android.com/apk/res/android"

Then in the ListView with an ID of @+id/lst_view you specify layout_height and layout_width twice, once with each alias:

        anddroid:layout_width="409dp"
        android:layout_width="396dp"
        anddroid:layout_height="328dp"
        android:layout_height="244dp"

That means you're specifying the same namespace-qualified attribute twice for each of width and height. That's not allowed.

Just remove the anddroid typo-alias, and remove the two attributes using it.


问:
How can I render angle brackets <> in wordpress blog page
I'm new to WordPress, I just started a blog on it a few days ago and my contents contain code blocks. The problem I'm having is that I have some code that contains Generics like JpaRepository<Customer, Long> But the <> could not be rendered when I view the blog page. How can I fix this problem, please, any suggestion is appreciated.

The output on the blog post:
This is what is displayed on the blog page

The blog post can be viewed here for a clear understanding of the problem. Thanks.

答:
try this php native function:

https://www.php.net/manual/en/function.htmlentities.php

and here is a live example

https://www.w3schools.com/php/func_string_htmlentities.asp


问:
Error with angular & angular/cli versions
I have this error on angular docker project:

```<code>industrialareas_angular_ctnr | This version of CLI is only compatible with Angular versions ^13.0.0-next || >=13.0.0 <14.0.0,
industrialareas_angular_ctnr | but Angular version 12.2.16 was found instead.
</code>```

My Dockerfile-angular file is:

```<code>FROM node:14
WORKDIR /usr/src/app
RUN npm uninstall -g @angular/cli
RUN npm uninstall @angular/cli
RUN npm i @angular/cli@12.2.8
RUN npm cache clean --force
COPY ./project/package*.json .
RUN npm install
RUN npm link @angular/cli
COPY ./project .
EXPOSE 4200
CMD npm start
</code>```

My docker-compose.yml file is:

```<code>version: '3.7'
services:
  angular:
    container_name: industrialareas_angular_ctnr
    build:
      context: .
      dockerfile: Dockerfile-angular
    restart: unless-stopped
    volumes:
      - ./project/src:/usr/src/app/src
    ports:
      - 4200:4200
</code>```

And the package.json file is:

```<code>...
"dependencies": {
  ...
  "@angular/core": "~12.2.0",
  ...
},
"devDependencies": {
  ...
  "@angular/cli": "~12.2.8",
  ...
</code>```

I have checked compatibility versions on this link

Anybody could help me please ? Thanks in advance.

答:
The problem was that node brings the latest predefined version of angular cli, specifically @angular/cli@13.2.3 and the docker command took that by default.

Replace this line on Dockerfile:

```<code>RUN npm link @angular/cli
</code>```

to this:

```<code>RUN npm link @angular/cli@12.2.8
</code>```

and all works ok !

Body:
I have this error on angular docker project:

industrialareas_angular_ctnr | This version of CLI is only compatible with Angular versions ^13.0.0-next || >=13.0.0 <14.0.0,
industrialareas_angular_ctnr | but Angular version 12.2.16 was found instead.

My Dockerfile-angular file is:

FROM node:14
WORKDIR /usr/src/app
RUN npm uninstall -g @angular/cli
RUN npm uninstall @angular/cli
RUN npm i @angular/cli@12.2.8
RUN npm cache clean --force
COPY ./project/package*.json .
RUN npm install
RUN npm link @angular/cli
COPY ./project .
EXPOSE 4200
CMD npm start

My docker-compose.yml file is:

version: '3.7'
services:
  angular:
    container_name: industrialareas_angular_ctnr
    build:
      context: .
      dockerfile: Dockerfile-angular
    restart: unless-stopped
    volumes:
      - ./project/src:/usr/src/app/src
    ports:
      - 4200:4200

And the package.json file is:

...
"dependencies": {
  ...
  "@angular/core": "~12.2.0",
  ...
},
"devDependencies": {
  ...
  "@angular/cli": "~12.2.8",
  ...

I have checked compatibility versions on this link

Anybody could help me please ? Thanks in advance.

Body:
The problem was that node brings the latest predefined version of angular cli, specifically @angular/cli@13.2.3 and the docker command took that by default.

Replace this line on Dockerfile:

RUN npm link @angular/cli

to this:

RUN npm link @angular/cli@12.2.8

and all works ok !


问:
Change the color of particular card on taping it in flutter?
I am using flutter I want to change the color of a particular card when I tap on it, not all the cards at the same time. The code is attached below. I am glad if someone helps.
...

```<code>Widget options(context,String title,String subtitle,String price,

  String info, String plan) {
return GestureDetector(
  child: Container(
    height: 166,
    width: 119,
    child: Card(
      color: Colors.white,
      elevation: 3,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          Container(
            width: 120,
            decoration: BoxDecoration(
              color: Colors.black,
              borderRadius: BorderRadius.only(
                topLeft: const Radius.circular(7),
                topRight: const Radius.circular(7),
              ),
            ),
            child: Padding(
              padding: const EdgeInsets.only(bottom: 8, top: 8),
              child: Text(
                title,
                textAlign: TextAlign.center,
                style: TextStyle(
                    color: Color.fromRGBO(255, 255, 255, 1),
                    fontSize: 15,
                    fontFamily: 'CeroPro',
                    fontWeight: FontWeight.bold),
              ),
            ),
            ),
          )
        ],
      ),
    ),
  ),
);
</code>```

}
}
...

答:
You can try this also:</p>
```<code>import 'package:flutter/material.dart';

class Testing extends StatefulWidget {
    const Testing({Key? key}) : super(key: key);

 @override
  State<Testing> createState() => _TestingState();
}

class _TestingState extends State<Testing> {
  bool isColor1Changed = false;
  bool isColor2Changed = false;
  bool isColor3Changed = false;
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.yellow,
      child: Row(
        children: [
          GestureDetector(
            onTap: () {
              setState(() {
                isColor1Changed = !isColor1Changed;
              });
            },
            child: options(context, "POPULAR", "Monthly", "\$4.99",
                "3 Days Free Trail", "plan", isColor1Changed),
          ),
          const SizedBox(width: 6),
          GestureDetector(
            onTap: () {
              setState(() {
                isColor2Changed = !isColor2Changed;
              });
            },
            child: options(context, "83% OFF", "YEARLY", "\$9.99",
                "\$0.83 / MONTH", "plan", isColor2Changed),
          ),
          const SizedBox(width: 6),
          GestureDetector(
            onTap: () {
              setState(() {
                isColor3Changed = !isColor3Changed;
              });
            },
            child: options(context, "50% OFF", "LIFE TIME", "\$19.99",
                "\$39.98", "plan", isColor3Changed),
          ),
        ],
      ),
    );
  }

  Widget options(context, String title, String subtitle, String price,
      String info, String plan, bool isChangeColor) {
    return GestureDetector(
      child: Container(
        height: 166,
        width: 119,
        child: Card(
          color: isChangeColor ? Colors.lightBlue : Colors.white,
          elevation: 3,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            children: [
              Container(
                width: 120,
                decoration: const BoxDecoration(
                  color: Colors.black,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(7),
                    topRight: Radius.circular(7),
                  ),
                ),
                child: Padding(
                  padding: const EdgeInsets.only(bottom: 8, top: 8),
                  child: Text(
                    title,
                    textAlign: TextAlign.center,
                    style: const TextStyle(
                        color: Color.fromRGBO(255, 255, 255, 1),
                        fontSize: 15,
                        fontFamily: 'CeroPro',
                        fontWeight: FontWeight.bold),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

Body:
I am using flutter I want to change the color of a particular card when I tap on it, not all the cards at the same time. The code is attached below. I am glad if someone helps.
...

Widget options(context,String title,String subtitle,String price,

  String info, String plan) {
return GestureDetector(
  child: Container(
    height: 166,
    width: 119,
    child: Card(
      color: Colors.white,
      elevation: 3,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          Container(
            width: 120,
            decoration: BoxDecoration(
              color: Colors.black,
              borderRadius: BorderRadius.only(
                topLeft: const Radius.circular(7),
                topRight: const Radius.circular(7),
              ),
            ),
            child: Padding(
              padding: const EdgeInsets.only(bottom: 8, top: 8),
              child: Text(
                title,
                textAlign: TextAlign.center,
                style: TextStyle(
                    color: Color.fromRGBO(255, 255, 255, 1),
                    fontSize: 15,
                    fontFamily: 'CeroPro',
                    fontWeight: FontWeight.bold),
              ),
            ),
            ),
          )
        ],
      ),
    ),
  ),
);

}
}
...

Body:
You can try this also:

import 'package:flutter/material.dart';

class Testing extends StatefulWidget {
    const Testing({Key? key}) : super(key: key);

 @override
  State<Testing> createState() => _TestingState();
}

class _TestingState extends State<Testing> {
  bool isColor1Changed = false;
  bool isColor2Changed = false;
  bool isColor3Changed = false;
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.yellow,
      child: Row(
        children: [
          GestureDetector(
            onTap: () {
              setState(() {
                isColor1Changed = !isColor1Changed;
              });
            },
            child: options(context, "POPULAR", "Monthly", "\$4.99",
                "3 Days Free Trail", "plan", isColor1Changed),
          ),
          const SizedBox(width: 6),
          GestureDetector(
            onTap: () {
              setState(() {
                isColor2Changed = !isColor2Changed;
              });
            },
            child: options(context, "83% OFF", "YEARLY", "\$9.99",
                "\$0.83 / MONTH", "plan", isColor2Changed),
          ),
          const SizedBox(width: 6),
          GestureDetector(
            onTap: () {
              setState(() {
                isColor3Changed = !isColor3Changed;
              });
            },
            child: options(context, "50% OFF", "LIFE TIME", "\$19.99",
                "\$39.98", "plan", isColor3Changed),
          ),
        ],
      ),
    );
  }

  Widget options(context, String title, String subtitle, String price,
      String info, String plan, bool isChangeColor) {
    return GestureDetector(
      child: Container(
        height: 166,
        width: 119,
        child: Card(
          color: isChangeColor ? Colors.lightBlue : Colors.white,
          elevation: 3,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            children: [
              Container(
                width: 120,
                decoration: const BoxDecoration(
                  color: Colors.black,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(7),
                    topRight: Radius.circular(7),
                  ),
                ),
                child: Padding(
                  padding: const EdgeInsets.only(bottom: 8, top: 8),
                  child: Text(
                    title,
                    textAlign: TextAlign.center,
                    style: const TextStyle(
                        color: Color.fromRGBO(255, 255, 255, 1),
                        fontSize: 15,
                        fontFamily: 'CeroPro',
                        fontWeight: FontWeight.bold),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


问:
TypeError: Cannot read property 'type' of undefined Jest react testing
I am using jest and enzyme to test the  app components written using material UI library. Then in one of my package I got this error
Click here to see the error</p>

答:
I solved the above problem by following the below steps

1.create a folder and add the below code inside setupFilesAfterEnv.js

```<code>jest.mock('@material-ui/core/styles/colorManipulator', () => ({

  fade: jest.fn(),

}));
</code>```

2.import the path of the above file in jest.config.js which is in your package folder

```<code> setupFilesAfterEnv: [require.resolve('../../test/setupEnzymeAdapter.js'),
<rootDir>../tests/setupFilesAfterEnv.js
</code>```

My issue got fixed with this.

Body:
I solved the above problem by following the below steps

1.create a folder and add the below code inside setupFilesAfterEnv.js

jest.mock('@material-ui/core/styles/colorManipulator', () => ({

  fade: jest.fn(),

}));

2.import the path of the above file in jest.config.js which is in your package folder

 setupFilesAfterEnv: [require.resolve('../../test/setupEnzymeAdapter.js'),
<rootDir>../tests/setupFilesAfterEnv.js

My issue got fixed with this.


问:
Java getter vs Kotlin getter - any difference?
Lets have these two getters in Kotlin:

data class Foo(var id: String){
  val reference get() = Reference("Patient/$id")
}
```
<pre class="lang-kotlin prettyprint-override"><code>data class Foo(var id: String){
  fun getReference(){ return Reference("Patient/$id") }
}
</code>```

Does the first one have some performance cons? I like it more, but I am not sure if they are built into same bytecode, or the first one adds more things, because I am basically delaring new variable and not just method.

答:
In your example, they are equivalent behind the scenes (but obviously, you need different syntax for using the property vs. the method). Specifically, Kotlin will generate a backing field if any of the accessors use the field identifier, and the autogenerated get and set accessors do use field. So in order to avoid a backing field, you need to supply your own get accessor and (in the case of a var property) a set accessor, and none of them must use field.

Whether a property has a backing field or not, reading the property turns into a method call to get() behind the scenes, and if it's a var, assigning to the property turns into a method call to set().

Note that it's possible to get into weird situations with var if your accessors are inconsistent: var foo: Int = 3; get() = 42 will always return 42 when you read it, irrespective of the initial value and whatever you might assign to it, because you will get an autogenerated backing field since you omitted the setter, and that's what the autogenerated setter will set.

Using properties instead of Java-style getter/setter methods is strongly preferred in Kotlin.

(Thanks to @AlexeyRomanov for pointing out the specific rules.)

Body:
Lets have these two getters in Kotlin:

data class Foo(var id: String){
  val reference get() = Reference("Patient/$id")
}

data class Foo(var id: String){
  fun getReference(){ return Reference("Patient/$id") }
}

Does the first one have some performance cons? I like it more, but I am not sure if they are built into same bytecode, or the first one adds more things, because I am basically delaring new variable and not just method.


问:
Automate the Boring Stuff - Coin Flip Streaks - How to optimize my answer?
I've been going through automate the boring stuff, and am trying the practice problems.
I came up with this solution to the project on the lists chapter - Coin Flip Streaks.

The objective of the problem is the following:
''For this exercise, we’ll try doing an experiment. If you flip a coin 100 times and write down an “H” for each heads and “T” for each tails, you’ll create a list that looks like “T T T T H H H H T T.” If you ask a human to make up 100 random coin flips, you’ll probably end up with alternating head-tail results like “H T H T H H T H T T,” which looks random (to humans), but isn’t mathematically random. A human will almost never write down a streak of six heads or six tails in a row, even though it is highly likely to happen in truly random coin flips. Humans are predictably bad at being random.

Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails. Your program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it. Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row. As a hint, the function call random.randint(0, 1) will return a 0 value 50% of the time and a 1 value the other 50% of the time.''
And this is my code.

```<code>numberOfStreaks = 0
experiment = []
n = 0
for experimentNumber in range(1000):
    experimentNumber = experimentNumber + 1
    for test in range(100):
        selector = random.randint(0,1)
        if selector == 0:
            experiment = experiment + ['H']
        elif selector == 1:
            experiment = experiment + ['T']

    for n in range(94):
        if experiment[n:n+6] == ['T', 'T', 'T', 'T', 'T', 'T']:
            numberOfStreaks = numberOfStreaks + 1
        elif experiment[n:n+6] == ['H', 'H', 'H', 'H', 'H', 'H']:
            numberOfStreaks = numberOfStreaks + 1
        else:
            numberOfStreaks = numberOfStreaks
print((numberOfStreaks / 100000) * 100)
</code>```

I can only run this solution efficiently for 1000 experiments, and the book says to run for 10000, but it takes too long.
I think this derives from the inneficiency of the algorithm I came up with.

How do I make this algorithm more efficient?

答:
You can simplify it by only having one for loop, this also removes the need to append to a list and speeds things up a lot. (10000 in < 1second)</p>
```<code>import random

numberOfStreaks = 0
experiment = []
n = 0
for experimentNumber in range(1000):
    heads=0
    tails=0

    for test in range(100):

        if random.randint(0,1):
            heads += 1
            tails = 0
        else:
            tails += 1
            heads = 0

        if heads >= 6 or tails >= 6:
            numberOfStreaks += 1

print((numberOfStreaks / 100000) * 100)
</code>```

Body:
I've been going through automate the boring stuff, and am trying the practice problems.
I came up with this solution to the project on the lists chapter - Coin Flip Streaks.

The objective of the problem is the following:
''For this exercise, we’ll try doing an experiment. If you flip a coin 100 times and write down an “H” for each heads and “T” for each tails, you’ll create a list that looks like “T T T T H H H H T T.” If you ask a human to make up 100 random coin flips, you’ll probably end up with alternating head-tail results like “H T H T H H T H T T,” which looks random (to humans), but isn’t mathematically random. A human will almost never write down a streak of six heads or six tails in a row, even though it is highly likely to happen in truly random coin flips. Humans are predictably bad at being random.

Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails. Your program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it. Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row. As a hint, the function call random.randint(0, 1) will return a 0 value 50% of the time and a 1 value the other 50% of the time.''
And this is my code.

numberOfStreaks = 0
experiment = []
n = 0
for experimentNumber in range(1000):
    experimentNumber = experimentNumber + 1
    for test in range(100):
        selector = random.randint(0,1)
        if selector == 0:
            experiment = experiment + ['H']
        elif selector == 1:
            experiment = experiment + ['T']

    for n in range(94):
        if experiment[n:n+6] == ['T', 'T', 'T', 'T', 'T', 'T']:
            numberOfStreaks = numberOfStreaks + 1
        elif experiment[n:n+6] == ['H', 'H', 'H', 'H', 'H', 'H']:
            numberOfStreaks = numberOfStreaks + 1
        else:
            numberOfStreaks = numberOfStreaks
print((numberOfStreaks / 100000) * 100)

I can only run this solution efficiently for 1000 experiments, and the book says to run for 10000, but it takes too long.
I think this derives from the inneficiency of the algorithm I came up with.

How do I make this algorithm more efficient?

Body:
You can simplify it by only having one for loop, this also removes the need to append to a list and speeds things up a lot. (10000 in < 1second)

import random

numberOfStreaks = 0
experiment = []
n = 0
for experimentNumber in range(1000):
    heads=0
    tails=0

    for test in range(100):

        if random.randint(0,1):
            heads += 1
            tails = 0
        else:
            tails += 1
            heads = 0

        if heads >= 6 or tails >= 6:
            numberOfStreaks += 1

print((numberOfStreaks / 100000) * 100)


问:
Is it possible to delete records from Hive external table with AWS S3 bucket as location?
Is it possible to delete records from Hive external table with AWS S3 bucket as location using IICS.

For example : DELETE FROM MY_HIVE_TABLE WHERE COLUMN1='TEST1';

答:
You can not delete from hive(unless they are kudu).

As per your comment, i think you can add a filter transformation right before target hive S3 table with condition COLUMN1<>'TEST1'

And then overwrite the hive target table in S3 using IICS.

This will overwrite same table with everything but COLUMN1=TEST1 i.e. deleting the data.


问:
Liquibase run part of a changeset?
I have the below changeset but, I may want to add additional inserts in the future. It could be in the hundreds or thousands.

```<code>--changeset author:changesetid endDelimiter:;
INSERT INTO "MY_TABLE" (id, name) VALUES (1, 'bob');
INSERT INTO "MY_TABLE" (id, name) VALUES (2, 'jim');
INSERT INTO "MY_TABLE" (id, name) VALUES (3, 'mick');
</code>```

I can't execute previous inserts because that would throw errors about that data already existing. Similarly, I don't want to have dozens or hundreds of individual changesets with their own combination of different inserts overtime. I would like everything consolidated under 1 changeset.

Maybe I could use some type of precondition with this attribute but, I wouldn't want to keep checking the table size (or have to update the precondition value) everytime I need to update the changeset.

```<code>--preconditions onFail:WARN
</code>```

答: Does your target database support an UPSERT or MERGE statement?  If so, you could make your SQL script so if the record is already found in the table nothing happens, and if not found the record is inserted.  This would make your script more complicated, but should achieve what you are looking for if you set the changeset to runOnChange.</p>

Title: Liquibase run part of a changeset?

Body:
I have the below changeset but, I may want to add additional inserts in the future. It could be in the hundreds or thousands.

--changeset author:changesetid endDelimiter:;
INSERT INTO "MY_TABLE" (id, name) VALUES (1, 'bob');
INSERT INTO "MY_TABLE" (id, name) VALUES (2, 'jim');
INSERT INTO "MY_TABLE" (id, name) VALUES (3, 'mick');

I can't execute previous inserts because that would throw errors about that data already existing. Similarly, I don't want to have dozens or hundreds of individual changesets with their own combination of different inserts overtime. I would like everything consolidated under 1 changeset.

Maybe I could use some type of precondition with this attribute but, I wouldn't want to keep checking the table size (or have to update the precondition value) everytime I need to update the changeset.

--preconditions onFail:WARN


问:
is It possible to develop common business logic that run in both android and iOS platform?
I have iOS and android application already developed. I just want to add offline support on both platforms but I want to write business logic at once for both platform weather it will be written in NodeJs, Js or any other language that communicates with the local database as well.

Is that possible to implement such functionality? if possible then how? which language is most preferable for such situation?

Any tutorial, reference link will be appreciate.

Thanks

答:
C++ can be used as common code to run on both the platforms. Meta (FB) is already doing it.

https://engineering.fb.com/2015/06/15/android/under-the-hood-building-moments/


问:
How to know if your input is unique and doesn't have duplicates?

The underlined sentences are what I'm having trouble adding in my code, I do know how to typecast numbers, but I don't know when in my code to do it.

```<code>gamblers = input().split()
winnings = 0
winnums =  ('10','11','8','1','5','20')
lim = len(gamblers)

for num in gamblers:
    if num in winnums:
        winnings+=100
if lim == 7:
    if winnings > 0:
        print(f"{gamblers[0]} won {winnings} pesos!")
    if winnings == 0:
        print (f"{gamblers[0]} won nothing!")
else:
    print("Should be 6 numbers")
</code>```

答:
To convert your inputs into a name and 6 numbers try:

name = gamblers[0]
lotto_numbers = [int(x) for x in gamblers[1:]]
```
<p>Note that this is a bit fragile in the sense that numbers that don't cast to <code>int</code> will throw an exception.</p>
<p>To test if you have 6 unique integers in that list you can:</p>
```duplicates_found = (len(lotto_numbers) != len(set(lotto_numbers)))
```

Casting to a set() will remove duplicates and hopefully after the cast we have the same number of numbers as we started with.

Body:
The underlined sentences are what I'm having trouble adding in my code, I do know how to typecast numbers, but I don't know when in my code to do it.

gamblers = input().split()
winnings = 0
winnums =  ('10','11','8','1','5','20')
lim = len(gamblers)

for num in gamblers:
    if num in winnums:
        winnings+=100
if lim == 7:
    if winnings > 0:
        print(f"{gamblers[0]} won {winnings} pesos!")
    if winnings == 0:
        print (f"{gamblers[0]} won nothing!")
else:
    print("Should be 6 numbers")

Body:
To convert your inputs into a name and 6 numbers try:

name = gamblers[0]
lotto_numbers = [int(x) for x in gamblers[1:]]

Note that this is a bit fragile in the sense that numbers that don't cast to int will throw an exception.

To test if you have 6 unique integers in that list you can:

duplicates_found = (len(lotto_numbers) != len(set(lotto_numbers)))

Casting to a set() will remove duplicates and hopefully after the cast we have the same number of numbers as we started with.


问:
Why does std::condition_variable::wait_for() return with timeout if duration too large?
The following behavior was seen under g++ 11.2.1 . The std::condition_variable wait_for method returns immediately if the timeout variable is too large. In particular in the program below, if num_years==1, then the program hangs waiting as expected (presumably for 1 year), but if the variable num_years==1000 then the program returns immediatly.

Why does this happen? Is this a bug in g++? And a related question, how do you make the cv.wait_for() wait indefinitely, instead of guessing a large timeout value?

//  This is 'cv_wait.cc' compile with:
//
//    g++ -o cv_wait -std=c++2a cv_wait.cc
//
// An example showing that wait_for() returns immediately with a timeout
// return value if the duration variable is "too large".
//

#include <iostream>
#include <condition_variable>
#include <chrono>

int main(int argc, char **argv)
{
  std::condition_variable cv;
  std::mutex cv_m;

  // If num_years is "too large", e.g. 1000, then cv.wait_for()
  // returns immediately with a timeout condition!
  int num_years = 1;  // If 1000 then cv.wait_for() returns immediately!
  std::chrono::seconds timeout((uint64_t)3600 * 24 * 365 * num_years);
  std::unique_lock<std::mutex> lock(cv_m);
  if (cv.wait_for(lock, timeout, [] { return false; }))
      std::cerr << "No timeout!\n";
  else
      std::cerr << "Timeout!\n";
}

```

答:
This is an overflow bug under the hood of condition_variable::wait_for.  Internally it is waiting using steady_clock which counts nanoseconds.  This clock overflows at +/-292 years.  So when 1000 years gets converted to nanoseconds, it is overflowing.

This looks like a standards bug as opposed to an implementation bug: http://eel.is/c++draft/thread.condition#condvar-24

The implementation should check for overflows of this type and in case found, just wait for the maximum time it is capable of waiting for.


问:
How to add the ripple effect in Xamarin label or image?
I am looking at implementing a ripple effect on label text or in image.So how to add the ripple effect on any label or in image?</p>

答:
Use XamarinCommunityToolkit   Documentation YouTube Resources

In your xaml

```<code>xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
</code>```

Use exactly NativeAnimation

```<code><Frame xct:TouchEffect.NativeAnimation="True"> </Frame>
</code>```

Body:
Use XamarinCommunityToolkit   Documentation YouTube Resources

In your xaml

xmlns:xct="http://xamarin.com/schemas/2020/toolkit"

Use exactly NativeAnimation

<Frame xct:TouchEffect.NativeAnimation="True"> </Frame>


问:
Concatenating Multiple Linked Lists (Hash Tables) into a New, Single, Linked List
I'm just getting into linked lists and hashing, and I am having trouble figuring out how to concatenate hash tables into a single linked list.
Simple example, data entry that is hashed: 1, 2, 3, 4, 5, 6

List 0:
2

List 1:
3

List 2:
5

List 3:
4

List 4:
1
6

Basically, I am trying to output a new, concatenated list with the lists in reverse (4, 3, 2, 1, 0):

CAT'd List:
1 6 4 5 3 2

The only function causing me trouble is linkedListCat(); full program below.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>  // malloc(), free(), exit()
#include <string.h>

#define NUMPOINTERS 5

typedef struct node STUDENTREC;
struct node
{
    char id[10];
    struct node* next;
};

// Function Declarations
int hash(char id[]);
STUDENTREC* insert(char id[], STUDENTREC* student_body[], int hashval);
void traverse(STUDENTREC* student_body[]);
void displayLL(STUDENTREC* list, char* description);

STUDENTREC* linkedListCat(STUDENTREC* student_body[]);

int main(void)
{
    STUDENTREC* student_body[NUMPOINTERS] = { NULL };
    STUDENTREC* person;
    STUDENTREC* oneList;
    char id[10];
    int hashval;

    printf(" ~*~ Hashing using collision resolution by chaining ~*~\n");
    printf("\t Enter Student ID (or quit): ");
    scanf("%s", id);
    while (strcmp(id, "quit"))
    {
        hashval = hash(id);
        person = insert(id, student_body, hashval);
        if (person) // not NULL => duplicate
        {
            printf("Duplicate record!\n");
        }
        printf("\t Enter Student ID (or quit): ");
        scanf("%s", id);
    }
    traverse(student_body);
    oneList = linkedListCat(student_body);
    displayLL(oneList, "Concatenation Result");
    traverse(student_body);
    return 0;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 Creates one big linked list by concatenating the linked list
 in the hash table beginning with the last linked list and
 finishing with the first linked list.
 */

STUDENTREC* linkedListCat(STUDENTREC* student_body[])
{
    STUDENTREC* one = NULL;
    STUDENTREC** mover = &one;
    int i;

    for (i = NUMPOINTERS - 1; i > 0; i--)
    {
        *mover = student_body[i];
        while (*mover) // Expected: While !NULL, point mover to next node
        {
            mover = &((*mover)->next);

        }
        if ((*mover = (STUDENTREC*)malloc(sizeof(STUDENTREC))) == NULL)
        {
            printf("Malloc error in concatenate.\n");
            exit(1);
        }
        strcpy((*mover)->id, student_body[i]->id);
        /* Expected copy student_body node id value to the end... but I think
           this line is redundant now that I look at it?
           (*mover = student_body[i]; <- does the same thing) */
    }

    return one;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Hash Student ID by summing the cubes
    of the ASCII value of characters and then take
    the modulo of this sum.
*/
int hash(char id[])
{
    long sum = 0;

    while (*id) // != '\0'
    {
        sum += *id * *id * *id;
        id++;
    }
    return sum % NUMPOINTERS;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Insert a new Student ID into the
    array of student records, at index equal to
    hashvalue
*/
STUDENTREC* insert(char id[],
    STUDENTREC* student_body[],
    int hashval)
{
    STUDENTREC** mover; // Use ** to write elegant code

    mover = &student_body[hashval];
    while (*mover)
    {
        if (strcmp(id, (*mover)->id) == 0) return *mover;
        mover = &((*mover)->next);
    }
    if ((*mover = (STUDENTREC*)malloc(sizeof(STUDENTREC))) == NULL)
    {
        printf("Malloc error in insert!\n");
        exit(1);
    }
    strcpy((*mover)->id, id);
    (*mover)->next = NULL;    // set the link of the new node to NULL
    printf("%s has been placed in the list at location %d.\n", (*mover)->id, hashval);

    return NULL;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Traversing the lists in a hash table
*/
void traverse(STUDENTREC* student_body[])
{
    int i;

    for (i = 0; i < NUMPOINTERS; i++)
    {
        printf("Contents of list %2d\n", i);
        printf("--------------------\n");

        displayLL(student_body[i], NULL);
        printf("\n");
    }
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Traversing a linked list
*/
void displayLL(STUDENTREC* list, char* description)
{
    if (list) // != NULL
    {
        if (description) // != NULL
        {
            printf("%s\n", description);
            printf("--------------------\n");
        }
        STUDENTREC** mover; // Use ** for fun and practice
                            // not needed for traverse
        for (mover = &list; *mover; mover = &(*mover)->next)
        {                                          // &((*mover)->next)
            printf("%s\n", (*mover)->id);
        }
    }
    else
        printf("Empty!");

    printf("\n");
}
```
<p>I've figured out the rest of the program; it's just linkedListCat() that's stumping me. The output results in: 1 6 4 5 3 3 rather than 1 6 4 5 3 2, and has a runtime error. This is consistently the case where the final value is incorrect, as long as all the lists have at least one data member. I also noticed that if any list is not occupied by a data member (one list is empty), it breaks completely (my function to print out the new concatenated list fails to print, program doesn't continue).
Again, I'm completely new to LL's and hash, and I've spent a while trying to figure this out but this is my best attempt so far.</p>
<p>EDIT: After Ian's comment, this is the updated function:</p>
<pre class="lang-c prettyprint-override"><code>STUDENTREC* linkedListCat(STUDENTREC* student_body[])
{
    STUDENTREC* one = NULL;
    STUDENTREC** mover = &one;
    int i;

    for (i = NUMPOINTERS - 1; i >= 0; i--)
    {
        *mover = student_body[i];
        while (*mover)
        {
            mover = &((*mover)->next);
        }
        if ((*mover = (STUDENTREC*)malloc(sizeof(STUDENTREC))) == NULL)
        {
            printf("Malloc error.\n");
            exit(1);
        }
    }

    //
    return one;
}
}
</code>```

答:
The current implementation of linkedListCat (with the off-by-one correction in the for loop condition) has the following problems:

It modifies the hash table lists, linking them into a single list.

It replaces the last node of each hash list with a new malloced node.  The original version copied the wrong ID into this new node.  The "corrected" version leaves the ID in the new node uninitialized.

It leaks memory due to replacing the last node of each hash list.

I think there are two approaches to fixing it:

Construct the concatenated list from a copy of all the nodes in the hash lists; or:

Add an extra link to each node so that it can be on two lists at the same time.

An advantage is that no new nodes need to be allocated.

A disadvantage is that different functions are needed for each type of list.

An implementation using the "list copy" approach is shown below:

```<code>
#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>  // malloc(), free(), exit()
#include <string.h>

#define NUMPOINTERS 5

typedef struct node STUDENTREC;
struct node
{
    char id[10];
    struct node* next;
};

// Function Declarations
int hash(char id[]);
STUDENTREC* insert(char id[], STUDENTREC* student_body[], int hashval);
void traverse(STUDENTREC* student_body[]);
void displayLL(STUDENTREC* list, char* description);

STUDENTREC* linkedListCat(STUDENTREC* student_body[]);
STUDENTREC* linkedListCopy(STUDENTREC* head);
void linkedListFree(STUDENTREC* head);

int main(void)
{
    STUDENTREC* student_body[NUMPOINTERS] = { NULL };
    STUDENTREC* person;
    STUDENTREC* oneList;
    char id[10];
    int hashval;

    printf(" ~*~ Hashing using collision resolution by chaining ~*~\n");
    printf("\t Enter Student ID (or quit): ");
    scanf("%s", id);
    while (strcmp(id, "quit"))
    {
        hashval = hash(id);
        person = insert(id, student_body, hashval);
        if (person) // not NULL => duplicate
        {
            printf("Duplicate record!\n");
        }
        printf("\t Enter Student ID (or quit): ");
        scanf("%s", id);
    }
    traverse(student_body);
    oneList = linkedListCat(student_body);
    displayLL(oneList, "Concatenation Result");
    traverse(student_body);
    return 0;
}

void linkedListFree(STUDENTREC* head)
{
    while (head)
    {
        STUDENTREC* tmp = head;

        head = head->next;
        free(tmp);
    }
}

STUDENTREC* linkedListCopy(STUDENTREC* head)
{
    STUDENTREC* one = NULL;
    STUDENTREC** mover = &one;

    while (head)
    {
        *mover = malloc(sizeof(STUDENTREC));
        if (!*mover)
        {
            printf("Malloc error in list copy.\n");
            linkedListFree(one);
            one = NULL;
            exit(1);
        }
        memcpy(*mover, head, sizeof(STUDENTREC));
        head = head->next;
        mover = &(*mover)->next;
    }
    return one;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 Creates one big linked list by concatenating the linked list
 in the hash table beginning with the last linked list and
 finishing with the first linked list.
 */

STUDENTREC* linkedListCat(STUDENTREC* student_body[])
{
    STUDENTREC* one = NULL;
    STUDENTREC** mover = &one;
    int i;

    for (i = NUMPOINTERS - 1; i >= 0; i--)
    {
        *mover = linkedListCopy(student_body[i]);
        while (*mover) // Expected: While !NULL, point mover to next node
        {
            mover = &((*mover)->next);
        }
    }
    return one;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Hash Student ID by summing the cubes
    of the ASCII value of characters and then take
    the modulo of this sum.
*/
int hash(char id[])
{
    long sum = 0;

    while (*id) // != '\0'
    {
        sum += *id * *id * *id;
        id++;
    }
    return sum % NUMPOINTERS;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Insert a new Student ID into the
    array of student records, at index equal to
    hashvalue
*/
STUDENTREC* insert(char id[],
    STUDENTREC* student_body[],
    int hashval)
{
    STUDENTREC** mover; // Use ** to write elegant code

    mover = &student_body[hashval];
    while (*mover)
    {
        if (strcmp(id, (*mover)->id) == 0) return *mover;
        mover = &((*mover)->next);
    }
    if ((*mover = (STUDENTREC*)malloc(sizeof(STUDENTREC))) == NULL)
    {
        printf("Malloc error in insert!\n");
        exit(1);
    }
    strcpy((*mover)->id, id);
    (*mover)->next = NULL;    // set the link of the new node to NULL
    printf("%s has been placed in the list at location %d.\n", (*mover)->id, hashval);

    return NULL;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Traversing the lists in a hash table
*/
void traverse(STUDENTREC* student_body[])
{
    int i;

    for (i = 0; i < NUMPOINTERS; i++)
    {
        printf("Contents of list %2d\n", i);
        printf("--------------------\n");

        displayLL(student_body[i], NULL);
        printf("\n");
    }
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Traversing a linked list
*/
void displayLL(STUDENTREC* list, char* description)
{
    if (list) // != NULL
    {
        if (description) // != NULL
        {
            printf("%s\n", description);
            printf("--------------------\n");
        }
        STUDENTREC** mover; // Use ** for fun and practice
                            // not needed for traverse
        for (mover = &list; *mover; mover = &(*mover)->next)
        {                                          // &((*mover)->next)
            printf("%s\n", (*mover)->id);
        }
    }
    else
        printf("Empty!");

    printf("\n");
}
</code>```

An implementation using the "two lists" approach is shown below:

```<code>
#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>  // malloc(), free(), exit()
#include <string.h>

#define NUMPOINTERS 5

typedef struct node STUDENTREC;
struct node
{
    char id[10];
    struct node* next_h;    /* hash list */
    struct node* next_a;    /* all list */
};

// Function Declarations
int hash(char id[]);
STUDENTREC* insert(char id[], STUDENTREC* student_body[], int hashval);
void traverse(STUDENTREC* student_body[]);
void displayLL_h(STUDENTREC* list, char* description);
void displayLL_a(STUDENTREC* list, char* description);

STUDENTREC* linkedListCat(STUDENTREC* student_body[]);

int main(void)
{
    STUDENTREC* student_body[NUMPOINTERS] = { NULL };
    STUDENTREC* person;
    STUDENTREC* oneList;
    char id[10];
    int hashval;

    printf(" ~*~ Hashing using collision resolution by chaining ~*~\n");
    printf("\t Enter Student ID (or quit): ");
    scanf("%s", id);
    while (strcmp(id, "quit"))
    {
        hashval = hash(id);
        person = insert(id, student_body, hashval);
        if (person) // not NULL => duplicate
        {
            printf("Duplicate record!\n");
        }
        printf("\t Enter Student ID (or quit): ");
        scanf("%s", id);
    }
    traverse(student_body);
    oneList = linkedListCat(student_body);
    displayLL_a(oneList, "Concatenation Result");
    traverse(student_body);
    return 0;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 Creates one big linked list by concatenating the linked list
 in the hash table beginning with the last linked list and
 finishing with the first linked list.
 */

STUDENTREC* linkedListCat(STUDENTREC* student_body[])
{
    STUDENTREC* one = NULL;
    STUDENTREC** mover = &one;
    int i;

    for (i = NUMPOINTERS - 1; i >= 0; i--)
    {
        *mover = student_body[i];
        while (*mover) // Expected: While !NULL, point mover to next node
        {
            (*mover)->next_a = (*mover)->next_h;
            mover = &((*mover)->next_a);
        }
    }
    return one;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Hash Student ID by summing the cubes
    of the ASCII value of characters and then take
    the modulo of this sum.
*/
int hash(char id[])
{
    long sum = 0;

    while (*id) // != '\0'
    {
        sum += *id * *id * *id;
        id++;
    }
    return sum % NUMPOINTERS;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Insert a new Student ID into the
    array of student records, at index equal to
    hashvalue
*/
STUDENTREC* insert(char id[],
    STUDENTREC* student_body[],
    int hashval)
{
    STUDENTREC** mover; // Use ** to write elegant code

    mover = &student_body[hashval];
    while (*mover)
    {
        if (strcmp(id, (*mover)->id) == 0) return *mover;
        mover = &((*mover)->next_h);
    }
    if ((*mover = (STUDENTREC*)malloc(sizeof(STUDENTREC))) == NULL)
    {
        printf("Malloc error in insert!\n");
        exit(1);
    }
    strcpy((*mover)->id, id);
    (*mover)->next_h = NULL;    // set the link of the new node to NULL
    (*mover)->next_a = NULL;
    printf("%s has been placed in the list at location %d.\n", (*mover)->id, hashval);

    return NULL;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Traversing the lists in a hash table
*/
void traverse(STUDENTREC* student_body[])
{
    int i;

    for (i = 0; i < NUMPOINTERS; i++)
    {
        printf("Contents of list %2d\n", i);
        printf("--------------------\n");

        displayLL_h(student_body[i], NULL);
        printf("\n");
    }
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Traversing a hash table linked list
*/
void displayLL_h(STUDENTREC* list, char* description)
{
    if (list) // != NULL
    {
        if (description) // != NULL
        {
            printf("%s\n", description);
            printf("--------------------\n");
        }
        STUDENTREC** mover; // Use ** for fun and practice
                            // not needed for traverse
        for (mover = &list; *mover; mover = &(*mover)->next_h)
        {                                          // &((*mover)->next_h)
            printf("%s\n", (*mover)->id);
        }
    }
    else
        printf("Empty!");

    printf("\n");
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Traversing a concatenated linked list
*/
void displayLL_a(STUDENTREC* list, char* description)
{
    if (list) // != NULL
    {
        if (description) // != NULL
        {
            printf("%s\n", description);
            printf("--------------------\n");
        }
        STUDENTREC** mover; // Use ** for fun and practice
                            // not needed for traverse
        for (mover = &list; *mover; mover = &(*mover)->next_a)
        {                                          // &((*mover)->next_a)
            printf("%s\n", (*mover)->id);
        }
    }
    else
        printf("Empty!");

    printf("\n");
}
</code>```

Body:
I'm just getting into linked lists and hashing, and I am having trouble figuring out how to concatenate hash tables into a single linked list.
Simple example, data entry that is hashed: 1, 2, 3, 4, 5, 6

List 0:
2

List 1:
3

List 2:
5

List 3:
4

List 4:
1
6

Basically, I am trying to output a new, concatenated list with the lists in reverse (4, 3, 2, 1, 0):

CAT'd List:
1 6 4 5 3 2

The only function causing me trouble is linkedListCat(); full program below.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>  // malloc(), free(), exit()
#include <string.h>

#define NUMPOINTERS 5

typedef struct node STUDENTREC;
struct node
{
    char id[10];
    struct node* next;
};

// Function Declarations
int hash(char id[]);
STUDENTREC* insert(char id[], STUDENTREC* student_body[], int hashval);
void traverse(STUDENTREC* student_body[]);
void displayLL(STUDENTREC* list, char* description);

STUDENTREC* linkedListCat(STUDENTREC* student_body[]);

int main(void)
{
    STUDENTREC* student_body[NUMPOINTERS] = { NULL };
    STUDENTREC* person;
    STUDENTREC* oneList;
    char id[10];
    int hashval;

    printf(" ~*~ Hashing using collision resolution by chaining ~*~\n");
    printf("\t Enter Student ID (or quit): ");
    scanf("%s", id);
    while (strcmp(id, "quit"))
    {
        hashval = hash(id);
        person = insert(id, student_body, hashval);
        if (person) // not NULL => duplicate
        {
            printf("Duplicate record!\n");
        }
        printf("\t Enter Student ID (or quit): ");
        scanf("%s", id);
    }
    traverse(student_body);
    oneList = linkedListCat(student_body);
    displayLL(oneList, "Concatenation Result");
    traverse(student_body);
    return 0;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 Creates one big linked list by concatenating the linked list
 in the hash table beginning with the last linked list and
 finishing with the first linked list.
 */

STUDENTREC* linkedListCat(STUDENTREC* student_body[])
{
    STUDENTREC* one = NULL;
    STUDENTREC** mover = &one;
    int i;

    for (i = NUMPOINTERS - 1; i > 0; i--)
    {
        *mover = student_body[i];
        while (*mover) // Expected: While !NULL, point mover to next node
        {
            mover = &((*mover)->next);

        }
        if ((*mover = (STUDENTREC*)malloc(sizeof(STUDENTREC))) == NULL)
        {
            printf("Malloc error in concatenate.\n");
            exit(1);
        }
        strcpy((*mover)->id, student_body[i]->id);
        /* Expected copy student_body node id value to the end... but I think
           this line is redundant now that I look at it?
           (*mover = student_body[i]; <- does the same thing) */
    }

    return one;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Hash Student ID by summing the cubes
    of the ASCII value of characters and then take
    the modulo of this sum.
*/
int hash(char id[])
{
    long sum = 0;

    while (*id) // != '\0'
    {
        sum += *id * *id * *id;
        id++;
    }
    return sum % NUMPOINTERS;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Insert a new Student ID into the
    array of student records, at index equal to
    hashvalue
*/
STUDENTREC* insert(char id[],
    STUDENTREC* student_body[],
    int hashval)
{
    STUDENTREC** mover; // Use ** to write elegant code

    mover = &student_body[hashval];
    while (*mover)
    {
        if (strcmp(id, (*mover)->id) == 0) return *mover;
        mover = &((*mover)->next);
    }
    if ((*mover = (STUDENTREC*)malloc(sizeof(STUDENTREC))) == NULL)
    {
        printf("Malloc error in insert!\n");
        exit(1);
    }
    strcpy((*mover)->id, id);
    (*mover)->next = NULL;    // set the link of the new node to NULL
    printf("%s has been placed in the list at location %d.\n", (*mover)->id, hashval);

    return NULL;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Traversing the lists in a hash table
*/
void traverse(STUDENTREC* student_body[])
{
    int i;

    for (i = 0; i < NUMPOINTERS; i++)
    {
        printf("Contents of list %2d\n", i);
        printf("--------------------\n");

        displayLL(student_body[i], NULL);
        printf("\n");
    }
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Traversing a linked list
*/
void displayLL(STUDENTREC* list, char* description)
{
    if (list) // != NULL
    {
        if (description) // != NULL
        {
            printf("%s\n", description);
            printf("--------------------\n");
        }
        STUDENTREC** mover; // Use ** for fun and practice
                            // not needed for traverse
        for (mover = &list; *mover; mover = &(*mover)->next)
        {                                          // &((*mover)->next)
            printf("%s\n", (*mover)->id);
        }
    }
    else
        printf("Empty!");

    printf("\n");
}

I've figured out the rest of the program; it's just linkedListCat() that's stumping me. The output results in: 1 6 4 5 3 3 rather than 1 6 4 5 3 2, and has a runtime error. This is consistently the case where the final value is incorrect, as long as all the lists have at least one data member. I also noticed that if any list is not occupied by a data member (one list is empty), it breaks completely (my function to print out the new concatenated list fails to print, program doesn't continue).
Again, I'm completely new to LL's and hash, and I've spent a while trying to figure this out but this is my best attempt so far.

EDIT: After Ian's comment, this is the updated function:

STUDENTREC* linkedListCat(STUDENTREC* student_body[])
{
    STUDENTREC* one = NULL;
    STUDENTREC** mover = &one;
    int i;

    for (i = NUMPOINTERS - 1; i >= 0; i--)
    {
        *mover = student_body[i];
        while (*mover)
        {
            mover = &((*mover)->next);
        }
        if ((*mover = (STUDENTREC*)malloc(sizeof(STUDENTREC))) == NULL)
        {
            printf("Malloc error.\n");
            exit(1);
        }
    }

    //
    return one;
}
}

Body:
The current implementation of linkedListCat (with the off-by-one correction in the for loop condition) has the following problems:

It modifies the hash table lists, linking them into a single list.

It replaces the last node of each hash list with a new malloced node.  The original version copied the wrong ID into this new node.  The "corrected" version leaves the ID in the new node uninitialized.

It leaks memory due to replacing the last node of each hash list.

I think there are two approaches to fixing it:

Construct the concatenated list from a copy of all the nodes in the hash lists; or:

Add an extra link to each node so that it can be on two lists at the same time.

An advantage is that no new nodes need to be allocated.

A disadvantage is that different functions are needed for each type of list.

An implementation using the "list copy" approach is shown below:

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>  // malloc(), free(), exit()
#include <string.h>

#define NUMPOINTERS 5

typedef struct node STUDENTREC;
struct node
{
    char id[10];
    struct node* next;
};

// Function Declarations
int hash(char id[]);
STUDENTREC* insert(char id[], STUDENTREC* student_body[], int hashval);
void traverse(STUDENTREC* student_body[]);
void displayLL(STUDENTREC* list, char* description);

STUDENTREC* linkedListCat(STUDENTREC* student_body[]);
STUDENTREC* linkedListCopy(STUDENTREC* head);
void linkedListFree(STUDENTREC* head);

int main(void)
{
    STUDENTREC* student_body[NUMPOINTERS] = { NULL };
    STUDENTREC* person;
    STUDENTREC* oneList;
    char id[10];
    int hashval;

    printf(" ~*~ Hashing using collision resolution by chaining ~*~\n");
    printf("\t Enter Student ID (or quit): ");
    scanf("%s", id);
    while (strcmp(id, "quit"))
    {
        hashval = hash(id);
        person = insert(id, student_body, hashval);
        if (person) // not NULL => duplicate
        {
            printf("Duplicate record!\n");
        }
        printf("\t Enter Student ID (or quit): ");
        scanf("%s", id);
    }
    traverse(student_body);
    oneList = linkedListCat(student_body);
    displayLL(oneList, "Concatenation Result");
    traverse(student_body);
    return 0;
}

void linkedListFree(STUDENTREC* head)
{
    while (head)
    {
        STUDENTREC* tmp = head;

        head = head->next;
        free(tmp);
    }
}

STUDENTREC* linkedListCopy(STUDENTREC* head)
{
    STUDENTREC* one = NULL;
    STUDENTREC** mover = &one;

    while (head)
    {
        *mover = malloc(sizeof(STUDENTREC));
        if (!*mover)
        {
            printf("Malloc error in list copy.\n");
            linkedListFree(one);
            one = NULL;
            exit(1);
        }
        memcpy(*mover, head, sizeof(STUDENTREC));
        head = head->next;
        mover = &(*mover)->next;
    }
    return one;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 Creates one big linked list by concatenating the linked list
 in the hash table beginning with the last linked list and
 finishing with the first linked list.
 */

STUDENTREC* linkedListCat(STUDENTREC* student_body[])
{
    STUDENTREC* one = NULL;
    STUDENTREC** mover = &one;
    int i;

    for (i = NUMPOINTERS - 1; i >= 0; i--)
    {
        *mover = linkedListCopy(student_body[i]);
        while (*mover) // Expected: While !NULL, point mover to next node
        {
            mover = &((*mover)->next);
        }
    }
    return one;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Hash Student ID by summing the cubes
    of the ASCII value of characters and then take
    the modulo of this sum.
*/
int hash(char id[])
{
    long sum = 0;

    while (*id) // != '\0'
    {
        sum += *id * *id * *id;
        id++;
    }
    return sum % NUMPOINTERS;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Insert a new Student ID into the
    array of student records, at index equal to
    hashvalue
*/
STUDENTREC* insert(char id[],
    STUDENTREC* student_body[],
    int hashval)
{
    STUDENTREC** mover; // Use ** to write elegant code

    mover = &student_body[hashval];
    while (*mover)
    {
        if (strcmp(id, (*mover)->id) == 0) return *mover;
        mover = &((*mover)->next);
    }
    if ((*mover = (STUDENTREC*)malloc(sizeof(STUDENTREC))) == NULL)
    {
        printf("Malloc error in insert!\n");
        exit(1);
    }
    strcpy((*mover)->id, id);
    (*mover)->next = NULL;    // set the link of the new node to NULL
    printf("%s has been placed in the list at location %d.\n", (*mover)->id, hashval);

    return NULL;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Traversing the lists in a hash table
*/
void traverse(STUDENTREC* student_body[])
{
    int i;

    for (i = 0; i < NUMPOINTERS; i++)
    {
        printf("Contents of list %2d\n", i);
        printf("--------------------\n");

        displayLL(student_body[i], NULL);
        printf("\n");
    }
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Traversing a linked list
*/
void displayLL(STUDENTREC* list, char* description)
{
    if (list) // != NULL
    {
        if (description) // != NULL
        {
            printf("%s\n", description);
            printf("--------------------\n");
        }
        STUDENTREC** mover; // Use ** for fun and practice
                            // not needed for traverse
        for (mover = &list; *mover; mover = &(*mover)->next)
        {                                          // &((*mover)->next)
            printf("%s\n", (*mover)->id);
        }
    }
    else
        printf("Empty!");

    printf("\n");
}

An implementation using the "two lists" approach is shown below:

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>  // malloc(), free(), exit()
#include <string.h>

#define NUMPOINTERS 5

typedef struct node STUDENTREC;
struct node
{
    char id[10];
    struct node* next_h;    /* hash list */
    struct node* next_a;    /* all list */
};

// Function Declarations
int hash(char id[]);
STUDENTREC* insert(char id[], STUDENTREC* student_body[], int hashval);
void traverse(STUDENTREC* student_body[]);
void displayLL_h(STUDENTREC* list, char* description);
void displayLL_a(STUDENTREC* list, char* description);

STUDENTREC* linkedListCat(STUDENTREC* student_body[]);

int main(void)
{
    STUDENTREC* student_body[NUMPOINTERS] = { NULL };
    STUDENTREC* person;
    STUDENTREC* oneList;
    char id[10];
    int hashval;

    printf(" ~*~ Hashing using collision resolution by chaining ~*~\n");
    printf("\t Enter Student ID (or quit): ");
    scanf("%s", id);
    while (strcmp(id, "quit"))
    {
        hashval = hash(id);
        person = insert(id, student_body, hashval);
        if (person) // not NULL => duplicate
        {
            printf("Duplicate record!\n");
        }
        printf("\t Enter Student ID (or quit): ");
        scanf("%s", id);
    }
    traverse(student_body);
    oneList = linkedListCat(student_body);
    displayLL_a(oneList, "Concatenation Result");
    traverse(student_body);
    return 0;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 Creates one big linked list by concatenating the linked list
 in the hash table beginning with the last linked list and
 finishing with the first linked list.
 */

STUDENTREC* linkedListCat(STUDENTREC* student_body[])
{
    STUDENTREC* one = NULL;
    STUDENTREC** mover = &one;
    int i;

    for (i = NUMPOINTERS - 1; i >= 0; i--)
    {
        *mover = student_body[i];
        while (*mover) // Expected: While !NULL, point mover to next node
        {
            (*mover)->next_a = (*mover)->next_h;
            mover = &((*mover)->next_a);
        }
    }
    return one;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Hash Student ID by summing the cubes
    of the ASCII value of characters and then take
    the modulo of this sum.
*/
int hash(char id[])
{
    long sum = 0;

    while (*id) // != '\0'
    {
        sum += *id * *id * *id;
        id++;
    }
    return sum % NUMPOINTERS;
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Insert a new Student ID into the
    array of student records, at index equal to
    hashvalue
*/
STUDENTREC* insert(char id[],
    STUDENTREC* student_body[],
    int hashval)
{
    STUDENTREC** mover; // Use ** to write elegant code

    mover = &student_body[hashval];
    while (*mover)
    {
        if (strcmp(id, (*mover)->id) == 0) return *mover;
        mover = &((*mover)->next_h);
    }
    if ((*mover = (STUDENTREC*)malloc(sizeof(STUDENTREC))) == NULL)
    {
        printf("Malloc error in insert!\n");
        exit(1);
    }
    strcpy((*mover)->id, id);
    (*mover)->next_h = NULL;    // set the link of the new node to NULL
    (*mover)->next_a = NULL;
    printf("%s has been placed in the list at location %d.\n", (*mover)->id, hashval);

    return NULL;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Traversing the lists in a hash table
*/
void traverse(STUDENTREC* student_body[])
{
    int i;

    for (i = 0; i < NUMPOINTERS; i++)
    {
        printf("Contents of list %2d\n", i);
        printf("--------------------\n");

        displayLL_h(student_body[i], NULL);
        printf("\n");
    }
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Traversing a hash table linked list
*/
void displayLL_h(STUDENTREC* list, char* description)
{
    if (list) // != NULL
    {
        if (description) // != NULL
        {
            printf("%s\n", description);
            printf("--------------------\n");
        }
        STUDENTREC** mover; // Use ** for fun and practice
                            // not needed for traverse
        for (mover = &list; *mover; mover = &(*mover)->next_h)
        {                                          // &((*mover)->next_h)
            printf("%s\n", (*mover)->id);
        }
    }
    else
        printf("Empty!");

    printf("\n");
}

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Traversing a concatenated linked list
*/
void displayLL_a(STUDENTREC* list, char* description)
{
    if (list) // != NULL
    {
        if (description) // != NULL
        {
            printf("%s\n", description);
            printf("--------------------\n");
        }
        STUDENTREC** mover; // Use ** for fun and practice
                            // not needed for traverse
        for (mover = &list; *mover; mover = &(*mover)->next_a)
        {                                          // &((*mover)->next_a)
            printf("%s\n", (*mover)->id);
        }
    }
    else
        printf("Empty!");

    printf("\n");
}


问:
how to download large files without memory issues in java
When I am trying to download a large file which is of 260MB from server, I get this error: java.lang.OutOfMemoryError: Java heap space. I am sure my heap size is less than 252MB. Is there any way I can download large files without increasing heap size?

How I can download large files without getting this issue? My code is given below:

```<code>String path= "C:/temp.zip";
response.addHeader("Content-Disposition", "attachment; filename=\"test.zip\"");
byte[] buf = new byte[1024];
try {

             File file = new File(path);
             long length = file.length();
             BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
             ServletOutputStream out = response.getOutputStream();

             while ((in != null) && ((length = in.read(buf)) != -1)) {
             out.write(buf, 0, (int) length);
             }
             in.close();
             out.close();
</code>```

答:
Unfortunately you have not mentioned what type out is. If you have memory issues I guess it is ByteArrayOutpoutStream. So, replace it by FileOutputStream and write the byte you are downloading directly to file.

BTW, do not use read() method that reads byte-by-byte. Use read(byte[] arr) instead. This is much faster.

Body:
When I am trying to download a large file which is of 260MB from server, I get this error: java.lang.OutOfMemoryError: Java heap space. I am sure my heap size is less than 252MB. Is there any way I can download large files without increasing heap size?

How I can download large files without getting this issue? My code is given below:

String path= "C:/temp.zip";
response.addHeader("Content-Disposition", "attachment; filename=\"test.zip\"");
byte[] buf = new byte[1024];
try {

             File file = new File(path);
             long length = file.length();
             BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
             ServletOutputStream out = response.getOutputStream();

             while ((in != null) && ((length = in.read(buf)) != -1)) {
             out.write(buf, 0, (int) length);
             }
             in.close();
             out.close();


问:
Synchronising with mutex and relaxed memory order atomic
I have a shared data structure that is already internally synchronised with a mutex. Can I use an atomic with memory order relaxed to signal changes. A very simplified view of what I mean in code

Thread 1

shared_conf.set("somekey","someval");
is_reconfigured.store(true, std::memory_order_relaxed);
```
<p>Thread 2</p>
```if (is_reconfigured.load(std::memory_order_relaxed)) {
  inspect_shared_conf();
}
```

Is it guaranteed that I'll see updates in the shared_map?; the shared map itself internally synchronises every write/read call with a mutex

答:
Relaxed order means that ordering of atomics and external operations only happens with regard to operations on the specific atomic object (and even then, the compiler is free to re-order them outside of the program-defined order). Thus, a relaxed store has no relationship to any state in external objects. So a relaxed load will not synchronize with your other mutexes.

The whole point of acquire/release semantics is to allow an atomic to control visibility of other memory. If you want an atomic load to mean that something is available, it must be an acquire and the value it acquired must have been released.

Body:
I have a shared data structure that is already internally synchronised with a mutex. Can I use an atomic with memory order relaxed to signal changes. A very simplified view of what I mean in code

Thread 1

shared_conf.set("somekey","someval");
is_reconfigured.store(true, std::memory_order_relaxed);

Thread 2

if (is_reconfigured.load(std::memory_order_relaxed)) {
  inspect_shared_conf();
}

Is it guaranteed that I'll see updates in the shared_map?; the shared map itself internally synchronises every write/read call with a mutex


问:
boto3 connects from EC2 instance to secrets manager but unable to connect from inside docker container after IMDSv2 required upgrade
boto3 connects from EC2 instance with the following command returns a result.

```<code>session = boto3.session.Session()
client = session.client(service_name = 'secretmanager', region_name = 'us-east-1')
get_secret_value_response = client.get_secret_value(secretId = secret_name)
</code>```

However, when I run the same set of commands from inside a docker container deployed on the EC2 instance it fails with the No credentials error. EC2 instance has an IAM role attached to be able to fetch passwords from secrets manager.

答:
It sounds like you need to increase the hop limit.

What are hops, and why are they significant?

To ensure IP packets have a limited lifetime on the network, all IP
packets have an 8 bit Time to Live (IPv4) or Hop Limit (IPv6) header
field and value which specifies the maximum number of layer three hops
(typically routers) that can be traversed on the path to their
destination.

Each time the packet arrives at a layer three network device (a Hop),
the value is reduced by one before it gets routed onward. When the
value eventually reaches one, the packet gets discarded by the device
that receives it (as the value would get reduced to zero).

So the docker networking layer will just drop the response from IMDSv2
calls!

We now increase the hop count using the following command.

```<code>aws ec2 modify-instance-metadata-options  --instance-id i-XXXXXXXXXXXX --http-put-response-hop-limit 3
</code>```

This AWS documentation says:

By default, the response to PUT requests has a response hop limit
(time to live) of 1 at the IP protocol level. You can adjust the hop
limit using the modify-instance-metadata-options command if you need
to make it larger. For example, you might need a larger hop limit for
backward compatibility with container services running on the
instance. For more information, see modify-instance-metadata-options
in the AWS CLI Command Reference.

Also related: https://aws.amazon.com/about-aws/whats-new/2020/08/amazon-eks-supports-ec2-instance-metadata-service-v2/

Body:
boto3 connects from EC2 instance with the following command returns a result.

session = boto3.session.Session()
client = session.client(service_name = 'secretmanager', region_name = 'us-east-1')
get_secret_value_response = client.get_secret_value(secretId = secret_name)

However, when I run the same set of commands from inside a docker container deployed on the EC2 instance it fails with the No credentials error. EC2 instance has an IAM role attached to be able to fetch passwords from secrets manager.

Body:
It sounds like you need to increase the hop limit.

What are hops, and why are they significant?

To ensure IP packets have a limited lifetime on the network, all IP
packets have an 8 bit Time to Live (IPv4) or Hop Limit (IPv6) header
field and value which specifies the maximum number of layer three hops
(typically routers) that can be traversed on the path to their
destination.

Each time the packet arrives at a layer three network device (a Hop),
the value is reduced by one before it gets routed onward. When the
value eventually reaches one, the packet gets discarded by the device
that receives it (as the value would get reduced to zero).

So the docker networking layer will just drop the response from IMDSv2
calls!

We now increase the hop count using the following command.

aws ec2 modify-instance-metadata-options  --instance-id i-XXXXXXXXXXXX --http-put-response-hop-limit 3

This AWS documentation says:

By default, the response to PUT requests has a response hop limit
(time to live) of 1 at the IP protocol level. You can adjust the hop
limit using the modify-instance-metadata-options command if you need
to make it larger. For example, you might need a larger hop limit for
backward compatibility with container services running on the
instance. For more information, see modify-instance-metadata-options
in the AWS CLI Command Reference.

Also related: https://aws.amazon.com/about-aws/whats-new/2020/08/amazon-eks-supports-ec2-instance-metadata-service-v2/


问:
Is there a reason to name parameters in forward declaration?
Say I have this:

```<code>// Forward Declaration of the sum()
void sum(int, int);

// Usage of the sum
void sum(int a, int b)
{
    // Body
}
</code>```

It could also be done like this:

```<code>// Forward Declaration of the sum()
void sum(int a, int b);

// Usage of the sum
void sum(int a, int b)
{
    // Body
}
</code>```

Is the latter version just a waste of space?  I see it both ways.

答:
No you don't need to.

You could even rename your function to

```<code>void _(int, int);
</code>```

(in both places of course). But then it's harder to follow still. In other words the parameter and function names are important for readability. Given most program documentation appears in header files, and most forward declarations are in header files, it makes sense to include the function parameter names as used in the function definition.

Remember that program source code has two users. The compiler is one, the programmer is the other.

Body:
Say I have this:

// Forward Declaration of the sum()
void sum(int, int);

// Usage of the sum
void sum(int a, int b)
{
    // Body
}

It could also be done like this:

// Forward Declaration of the sum()
void sum(int a, int b);

// Usage of the sum
void sum(int a, int b)
{
    // Body
}

Is the latter version just a waste of space?  I see it both ways.

Body:
No you don't need to.

You could even rename your function to

void _(int, int);

(in both places of course). But then it's harder to follow still. In other words the parameter and function names are important for readability. Given most program documentation appears in header files, and most forward declarations are in header files, it makes sense to include the function parameter names as used in the function definition.

Remember that program source code has two users. The compiler is one, the programmer is the other.


问:
Most efficient way to search for object in an array by a specific property's value
What would be the fastest, most efficient way to implement a search method that will return an object with a qualifying id?

Sample object array:

```<code>$array = [
    (object) ['id' => 'one', 'color' => 'white'],
    (object) ['id' => 'two', 'color' => 'red'],
    (object) ['id' => 'three', 'color' => 'blue']
];
</code>```

What do I write inside of:

```<code>function findObjectById($id){

}
</code>```

The desired result would return the object at $array[0] if I called:

```<code>$obj = findObjectById('one')
</code>```

Otherwise, it would return false if I passed 'four' as the parameter.

答:
The thing with performance of data structures is not only how to get but mostly how to store my data.

If you are free to design your array, use an associative array:

```<code>$array['one']->id = 'one';
$array['one']->color = 'white';
$array['two']->id = 'two';
$array['two']->color = 'red';
$array['three']->id = 'three';
$array['three']->color = 'blue';
</code>```

Finding is then the most cheap: $one = $array['one];

UPDATE:

If you cannot modify your array constitution, you could create a separate array which maps ids to indexes. Finding an object this way does not cost any time:

```<code>$map['one'] = 0;
$map['two'] = 1;
$map['three'] = 2;
...
</code>```

getObjectById() then first lookups the index of the id within the original array and secondly returns the right object:

```<code>$index = $map[$id];
return $array[$index];
</code>```

Body:
What would be the fastest, most efficient way to implement a search method that will return an object with a qualifying id?

Sample object array:

$array = [
    (object) ['id' => 'one', 'color' => 'white'],
    (object) ['id' => 'two', 'color' => 'red'],
    (object) ['id' => 'three', 'color' => 'blue']
];

What do I write inside of:

function findObjectById($id){

}

The desired result would return the object at $array[0] if I called:

$obj = findObjectById('one')

Otherwise, it would return false if I passed 'four' as the parameter.

Body:
The thing with performance of data structures is not only how to get but mostly how to store my data.

If you are free to design your array, use an associative array:

$array['one']->id = 'one';
$array['one']->color = 'white';
$array['two']->id = 'two';
$array['two']->color = 'red';
$array['three']->id = 'three';
$array['three']->color = 'blue';

Finding is then the most cheap: $one = $array['one];

UPDATE:

If you cannot modify your array constitution, you could create a separate array which maps ids to indexes. Finding an object this way does not cost any time:

$map['one'] = 0;
$map['two'] = 1;
$map['three'] = 2;
...

getObjectById() then first lookups the index of the id within the original array and secondly returns the right object:

$index = $map[$id];
return $array[$index];


问:
How to store and access API keys and passwords with Gatsby?
I am working on a Gatsby app that implements some 3rd party APIs, all requiring personal credentials. Later on I'm planning to also add a DB, so that will require credentials as well.
Since all my code is committed to GitHub, I'm looking for a way to store and access these in a secure way.

While I haven't deployed my app yet, the solution should apply to both local development as well as production.

I'd like to mention that I've never (had the chance to) worked with similar problems in that past, thus I don't even know where to look or what I'm supposed to look for to solve this.

答:
I personally do not love the idea of storing secrets in .env files, so I typically reach for something like AWS Secrets Manager these days.  You can easily set up secrets storage and fetch secret keys with the AWS SDK.  Of course this all assumes you're using AWS at some point, but I like to do it this way because I can control what roles have access to my keys -- so if you're setting up a build pipeline, this might be a good way to do it.  At build time, I might do something like this

import AWS from "aws-sdk";
const region = "us-east-1";

const creds = new AWS.SharedIniFileCredentials({ profile: "some-profile-name" });
AWS.config.credentials = creds;

export class SecretsManagerService {
  private static _client: AWS.SecretsManager;

  static get client(): AWS.SecretsManager {
    if (!SecretsManagerService._client) {
      SecretsManagerService._client = new AWS.SecretsManager({
        region,
      });
    }
    return SecretsManagerService._client;
  }

  static async getSecretValue(secretId: string): Promise<string> {
    try {
      const secret = await SecretsManagerService.client
        .getSecretValue({ SecretId: secretId })
        .promise();
      return secret.SecretString!;
    } catch (e) {
      throw e;
    }
  }
}
```
<p>And, that's all well and good except you'll need to use the secrets in Gatsby, so I do something like this (let's assume that I'm using Contentful as my CMS)</p>
<pre class="lang-js prettyprint-override"><code>import { SecretsManagerService } from "./aws-secrets.service";
import { execSync } from 'child_process';

(async () => {
    const { CONTENTFUL_ENV } = process.env;
    const secretPath = CONTENTFUL_ENV === 'qa' ? 'qa-secret-path' : 'prod-secret-path';
    const values = await SecretsManagerService.getSecretValue(secretPath);
    const parsed = JSON.parse(values);
    process.env.CONTENTFUL_KEY = parsed.contentfulSecretKey;
    const command = CONTENTFUL_ENV === 'qa' ? 'gatsby develop' : 'gatsby build';
    execSync(command, { stdio: 'inherit'});
})();
</code>```

This way I can inherit my environment variables in my Gatsby config like this (again assuming I'm using Contentful as the CMS).

    {
      resolve: "gatsby-source-contentful",
      options: {
        accessToken: process.env.CONTENTFUL_KEY,
        environment: process.env.CONTENTFUL_ENV,
        spaceId: "my-space-id",
      },
    },
```
<p>And modify your package.json scripts to be like this</p>
<pre class="lang-json prettyprint-override"><code>  "scripts": {
    "develop": "CONTENTFUL_ENV=qa ts-node ./tools/index.ts",
    "start": "gatsby develop",
    "build": "CONTENTFUL_ENV=master ts-node ./tools/index.ts",
    "serve": "gatsby serve",
    "clean": "gatsby clean"
  },
</code>```

Body:
I personally do not love the idea of storing secrets in .env files, so I typically reach for something like AWS Secrets Manager these days.  You can easily set up secrets storage and fetch secret keys with the AWS SDK.  Of course this all assumes you're using AWS at some point, but I like to do it this way because I can control what roles have access to my keys -- so if you're setting up a build pipeline, this might be a good way to do it.  At build time, I might do something like this

import AWS from "aws-sdk";
const region = "us-east-1";

const creds = new AWS.SharedIniFileCredentials({ profile: "some-profile-name" });
AWS.config.credentials = creds;

export class SecretsManagerService {
  private static _client: AWS.SecretsManager;

  static get client(): AWS.SecretsManager {
    if (!SecretsManagerService._client) {
      SecretsManagerService._client = new AWS.SecretsManager({
        region,
      });
    }
    return SecretsManagerService._client;
  }

  static async getSecretValue(secretId: string): Promise<string> {
    try {
      const secret = await SecretsManagerService.client
        .getSecretValue({ SecretId: secretId })
        .promise();
      return secret.SecretString!;
    } catch (e) {
      throw e;
    }
  }
}

And, that's all well and good except you'll need to use the secrets in Gatsby, so I do something like this (let's assume that I'm using Contentful as my CMS)

import { SecretsManagerService } from "./aws-secrets.service";
import { execSync } from 'child_process';

(async () => {
    const { CONTENTFUL_ENV } = process.env;
    const secretPath = CONTENTFUL_ENV === 'qa' ? 'qa-secret-path' : 'prod-secret-path';
    const values = await SecretsManagerService.getSecretValue(secretPath);
    const parsed = JSON.parse(values);
    process.env.CONTENTFUL_KEY = parsed.contentfulSecretKey;
    const command = CONTENTFUL_ENV === 'qa' ? 'gatsby develop' : 'gatsby build';
    execSync(command, { stdio: 'inherit'});
})();

This way I can inherit my environment variables in my Gatsby config like this (again assuming I'm using Contentful as the CMS).

    {
      resolve: "gatsby-source-contentful",
      options: {
        accessToken: process.env.CONTENTFUL_KEY,
        environment: process.env.CONTENTFUL_ENV,
        spaceId: "my-space-id",
      },
    },

And modify your package.json scripts to be like this

  "scripts": {
    "develop": "CONTENTFUL_ENV=qa ts-node ./tools/index.ts",
    "start": "gatsby develop",
    "build": "CONTENTFUL_ENV=master ts-node ./tools/index.ts",
    "serve": "gatsby serve",
    "clean": "gatsby clean"
  },


问:
Move any row to bottom of dataframe based on row index in pipe
How do you move any row to the bottom of a dataframe based on the row index using a dplyr pipe?</p>

答:
I am aware that the question specifically states "based on row index", however, I found this thread in the context of trying to figure out how to do this based on a character match and I found no guidance. Hence I figured out something myself (with the help of Oliver Oliver's post here - Thank you!), which I would like to share.

library(dplyr)

df <- tibble(x = letters[1:4], y = 1:4)

df %>%
  bind_rows(slice(., which(x != "b")), slice(., which(x == "b"))) %>%
  tail(nrow(.)/2)
```