问:
WooCommerce coupon usage restriction by allowed user roles
we need to make an automatic discount coupon to be applied if the current user role is ( vendor ), we achieved that by creating a normal coupon then used the snippet below to automatic apply the coupon .. but we need to limit the usage of that coupon to user role (vendor) only .. if another user role even administrators use it they get a message invalid coupon

```<code>    add_action( 'woocommerce_before_cart', 'apply_matched_coupons' );

function apply_matched_coupons() {
    global $woocommerce;

    $coupon_code = 'freeee'; // coupon code

    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

if ( current_user_can('yith_vendor') ) {
        $woocommerce->cart->add_discount( $coupon_code );
        wc_print_notices();
    }

}
</code>```

what we need to achieve now is to limit that coupon usage to user role ( vendors ) only and if another user role even administrator tried to use it they get a message invalid coupon.

答:
The following code adds a new field to the usage restriction tab where you can add allowed user roles.

// Add new field - usage restriction tab
function action_woocommerce_coupon_options_usage_restriction( $coupon_get_id, $coupon ) {
    woocommerce_wp_text_input( array(
        'id' => 'customer_user_role',
        'label' => __( 'User role restrictions', 'woocommerce' ),
        'placeholder' => __( 'No restrictions', 'woocommerce' ),
        'description' => __( 'List of allowed user roles. Separate user roles with commas.', 'woocommerce' ),
        'desc_tip' => true,
        'type' => 'text',
    ));
}
add_action( 'woocommerce_coupon_options_usage_restriction', 'action_woocommerce_coupon_options_usage_restriction', 10, 2 );

// Save
function action_woocommerce_coupon_options_save( $post_id, $coupon ) {
    // Isset
    if ( isset ( $_POST['customer_user_role'] ) ) {
        $coupon->update_meta_data( 'customer_user_role', sanitize_text_field( $_POST['customer_user_role'] ) );
        $coupon->save();
    }
}
add_action( 'woocommerce_coupon_options_save', 'action_woocommerce_coupon_options_save', 10, 2 );

// Valid
function filter_woocommerce_coupon_is_valid( $valid, $coupon, $discount ) {
    // Get meta
    $customer_user_role = $coupon->get_meta('customer_user_role');

    // NOT empty
    if( ! empty( $customer_user_role ) ) {
        // Convert string to array
        $customer_user_role = explode( ', ', $customer_user_role );

        // Get current user role
        $user = wp_get_current_user();
        $roles = ( array ) $user->roles;

        // Compare
        $compare = array_diff( $roles, $customer_user_role );

        // NOT empty
        if ( ! empty ( $compare ) ) {
            $valid = false;

            if ( ! $valid ) {
                throw new Exception( __( 'My custom error message', 'woocommerce' ), 109 );
            }
        }
    }

    return $valid;
}
add_filter( 'woocommerce_coupon_is_valid', 'filter_woocommerce_coupon_is_valid', 10, 3 );
```
<hr />
<p><img src="https://i.stack.imgur.com/YCoMq.jpg" alt="enter image description here" /></p>
<hr />
<p><strong>EDIT:</strong></p>
<p>To automatically apply the coupon on the <em>CART</em> page and hide the delete coupon link (based on user role)</p>
<pre class="lang-php prettyprint-override"><code>function action_woocommerce_before_calculate_totals( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

   if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Only cart
    if( ! is_cart() )
        return;

    /* SETTINGS */

    // Coupon code
    $coupon_code = 'test';

    // Allowed user role
    $allowed_user_role = 'administrator';

    /* END SETTINGS */

    // check current user role
    $user = wp_get_current_user();
    $user_roles = ( array ) $user->roles;

    // ADD js
    $add_js = false;

    // In array user roles
    if ( in_array( $allowed_user_role, $user_roles ) ) {
        // Format
        $coupon_code = wc_format_coupon_code( $coupon_code );

        // Applied coupons
        $applied_coupons = $cart->get_applied_coupons();

        // Is applied
        $is_applied = in_array( $coupon_code, $applied_coupons );

        // NOT applied
        if ( ! $is_applied ) {
            // Apply
            $cart->apply_coupon( $coupon_code );

            // True
            $add_js = true;
        } elseif ( $is_applied ) {
            // True
            $add_js = true;
        }

        // True
        if ( $add_js ) {
            ?>
            <script type="text/javascript">
            jQuery( function($) {
                // Hide remove link
                $( '.woocommerce-remove-coupon' ).hide();
            });
            </script>
            <?php
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );
</code>```

Body:
we need to make an automatic discount coupon to be applied if the current user role is ( vendor ), we achieved that by creating a normal coupon then used the snippet below to automatic apply the coupon .. but we need to limit the usage of that coupon to user role (vendor) only .. if another user role even administrators use it they get a message invalid coupon

    add_action( 'woocommerce_before_cart', 'apply_matched_coupons' );

function apply_matched_coupons() {
    global $woocommerce;

    $coupon_code = 'freeee'; // coupon code

    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

if ( current_user_can('yith_vendor') ) {
        $woocommerce->cart->add_discount( $coupon_code );
        wc_print_notices();
    }

}

what we need to achieve now is to limit that coupon usage to user role ( vendors ) only and if another user role even administrator tried to use it they get a message invalid coupon.

Body:
The following code adds a new field to the usage restriction tab where you can add allowed user roles.

// Add new field - usage restriction tab
function action_woocommerce_coupon_options_usage_restriction( $coupon_get_id, $coupon ) {
    woocommerce_wp_text_input( array(
        'id' => 'customer_user_role',
        'label' => __( 'User role restrictions', 'woocommerce' ),
        'placeholder' => __( 'No restrictions', 'woocommerce' ),
        'description' => __( 'List of allowed user roles. Separate user roles with commas.', 'woocommerce' ),
        'desc_tip' => true,
        'type' => 'text',
    ));
}
add_action( 'woocommerce_coupon_options_usage_restriction', 'action_woocommerce_coupon_options_usage_restriction', 10, 2 );

// Save
function action_woocommerce_coupon_options_save( $post_id, $coupon ) {
    // Isset
    if ( isset ( $_POST['customer_user_role'] ) ) {
        $coupon->update_meta_data( 'customer_user_role', sanitize_text_field( $_POST['customer_user_role'] ) );
        $coupon->save();
    }
}
add_action( 'woocommerce_coupon_options_save', 'action_woocommerce_coupon_options_save', 10, 2 );

// Valid
function filter_woocommerce_coupon_is_valid( $valid, $coupon, $discount ) {
    // Get meta
    $customer_user_role = $coupon->get_meta('customer_user_role');

    // NOT empty
    if( ! empty( $customer_user_role ) ) {
        // Convert string to array
        $customer_user_role = explode( ', ', $customer_user_role );

        // Get current user role
        $user = wp_get_current_user();
        $roles = ( array ) $user->roles;

        // Compare
        $compare = array_diff( $roles, $customer_user_role );

        // NOT empty
        if ( ! empty ( $compare ) ) {
            $valid = false;

            if ( ! $valid ) {
                throw new Exception( __( 'My custom error message', 'woocommerce' ), 109 );
            }
        }
    }

    return $valid;
}
add_filter( 'woocommerce_coupon_is_valid', 'filter_woocommerce_coupon_is_valid', 10, 3 );

EDIT:

To automatically apply the coupon on the CART page and hide the delete coupon link (based on user role)

function action_woocommerce_before_calculate_totals( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

   if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Only cart
    if( ! is_cart() )
        return;

    /* SETTINGS */

    // Coupon code
    $coupon_code = 'test';

    // Allowed user role
    $allowed_user_role = 'administrator';

    /* END SETTINGS */

    // check current user role
    $user = wp_get_current_user();
    $user_roles = ( array ) $user->roles;

    // ADD js
    $add_js = false;

    // In array user roles
    if ( in_array( $allowed_user_role, $user_roles ) ) {
        // Format
        $coupon_code = wc_format_coupon_code( $coupon_code );

        // Applied coupons
        $applied_coupons = $cart->get_applied_coupons();

        // Is applied
        $is_applied = in_array( $coupon_code, $applied_coupons );

        // NOT applied
        if ( ! $is_applied ) {
            // Apply
            $cart->apply_coupon( $coupon_code );

            // True
            $add_js = true;
        } elseif ( $is_applied ) {
            // True
            $add_js = true;
        }

        // True
        if ( $add_js ) {
            ?>
            <script type="text/javascript">
            jQuery( function($) {
                // Hide remove link
                $( '.woocommerce-remove-coupon' ).hide();
            });
            </script>
            <?php
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );


来源: stackexchange

问:
How to import a json file in vuetify?
I am trying to import a json file in script like this:

```<code><script lang="ts">
    import threadsjson from "../../public/sewing-thread.json";
    .....
</script>
</code>```

But a red line shows under "../../public/sewing-thread.json"; in Visual Studio Code. When I hover over "../../public/sewing-thread.json"; it shows:

```<code>Cannot find module '../../public/sewing-thread.json'. Consider using '--resolveJsonModule' to import module with '.json' extensionVetur(2732)
</code>```

How can I solve this problem?

答:
Since yours is a JSON file it will not be having any export statement and hence you cannot use import by name. Instead, you can import everything with * and give it a variable name.
And then you can use the same in data.</p>

```<code>import * as threadsjson from "../../public/sewing-thread.json";

....
....
  data() {
    return {
      threads: threadsjson
    }
  }
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to import a json file in vuetify?

Body:
I am trying to import a json file in script like this:

But a red line shows under "../../public/sewing-thread.json"; in Visual Studio Code. When I hover over "../../public/sewing-thread.json"; it shows:

Cannot find module '../../public/sewing-thread.json'. Consider using '--resolveJsonModule' to import module with '.json' extensionVetur(2732)

How can I solve this problem?

Body:
Since yours is a JSON file it will not be having any export statement and hence you cannot use import by name. Instead, you can import everything with * and give it a variable name.
And then you can use the same in data.

import * as threadsjson from "../../public/sewing-thread.json";

....
....
  data() {
    return {
      threads: threadsjson
    }
  }


问:
Sinon Stub depedent class in node.js module
I have one class as below

```<code>
nx-user.js
class NXUser {
constructor() {}

view(guid, data) {
  //do something
}

}
</code>```

Then I have user controller module as below which has dependency of NxUser class

userController.js

```<code>const userDb = new NXUser();
import NXUser from "../../../persistence/nx-user";
const allUsers = () => {
    return userDb.view()
}
</code>```

export {allUsers }

I have below code written for stubbing view function of NxUser class for controller unit tests. But its not working. It always calling actual one instated of stubbed one

userController-test.js

```<code>let userdb=NXUser();
describe("user controller", function () {
 let stubValue = [{
  "name": "Urvashi Parmar",
  "email": "urvashi.parmar@nationalexpress.com"]}

  it("Should create user", () => {
            sinon.stub(userdb, 'create').resolves(stubValue);
            userController.allUsers ().then((body) => {
                expect(body[0].name).to.equal(stubValue .name);
                done();
            });
        })
}
</code>```

答:
Because I can not comment yet, so I need to give full answer.

Confusion: at your userController-test.js, you are trying to test NXUser.create, while at file nx-user.js has no definition of create.

Assume: you are trying to test NXUser.view.

This example is created based on your code, and is working fine. Console log "Called" will not get called.

Highlight:

Stub NXUser view directly, not userdb.create;

I use async-await inside test.

const sinon = require('sinon');
const { expect } = require('chai');

class NXUser {
  constructor() {}
  view(guid, data) {
    console.log('Called');
    return new Promise((resolve) => resolve([]));
  }
  // Add this only for dummy.
  create() {
    return new Promise((resolve) => resolve([]));
  }
}

const userController = {
  allUsers() {
    const userDb = new NXUser();
    return userDb.view();
  }
}

describe('user controller', function () {
  // Suppose you test view user.
  it('should view user', async function () {
    const stubValue = [{
      name: 'Urvashi Parmar',
      email: 'urvashi.parmar@nationalexpress.com'
    }];
    // Suppose you stub method view and not create.
    const stubUserDBView = sinon.stub(NXUser.prototype, 'view');
    stubUserDBView.resolves(stubValue);

    const body = await userController.allUsers();
    expect(body).to.be.an('array').that.have.lengthOf(1);
    expect(body[0]).to.have.property('name', stubValue[0].name);

    // Restore stub.
    stubUserDBView.restore();
  });
});
```

```$ npx mocha stackoverflow.js

  user controller
    ✓ should view user

  1 passing (11ms)

$
```

Hope this helps.

Body:
I have one class as below

nx-user.js
class NXUser {
constructor() {}

view(guid, data) {
  //do something
}

}

Then I have user controller module as below which has dependency of NxUser class

userController.js

const userDb = new NXUser();
import NXUser from "../../../persistence/nx-user";
const allUsers = () => {
    return userDb.view()
}

export {allUsers }

I have below code written for stubbing view function of NxUser class for controller unit tests. But its not working. It always calling actual one instated of stubbed one

userController-test.js

let userdb=NXUser();
describe("user controller", function () {
 let stubValue = [{
  "name": "Urvashi Parmar",
  "email": "urvashi.parmar@nationalexpress.com"]}

  it("Should create user", () => {
            sinon.stub(userdb, 'create').resolves(stubValue);
            userController.allUsers ().then((body) => {
                expect(body[0].name).to.equal(stubValue .name);
                done();
            });
        })
}

Body:
Because I can not comment yet, so I need to give full answer.

Confusion: at your userController-test.js, you are trying to test NXUser.create, while at file nx-user.js has no definition of create.

Assume: you are trying to test NXUser.view.

This example is created based on your code, and is working fine. Console log "Called" will not get called.

Highlight:

Stub NXUser view directly, not userdb.create;

I use async-await inside test.

const sinon = require('sinon');
const { expect } = require('chai');

class NXUser {
  constructor() {}
  view(guid, data) {
    console.log('Called');
    return new Promise((resolve) => resolve([]));
  }
  // Add this only for dummy.
  create() {
    return new Promise((resolve) => resolve([]));
  }
}

const userController = {
  allUsers() {
    const userDb = new NXUser();
    return userDb.view();
  }
}

describe('user controller', function () {
  // Suppose you test view user.
  it('should view user', async function () {
    const stubValue = [{
      name: 'Urvashi Parmar',
      email: 'urvashi.parmar@nationalexpress.com'
    }];
    // Suppose you stub method view and not create.
    const stubUserDBView = sinon.stub(NXUser.prototype, 'view');
    stubUserDBView.resolves(stubValue);

    const body = await userController.allUsers();
    expect(body).to.be.an('array').that.have.lengthOf(1);
    expect(body[0]).to.have.property('name', stubValue[0].name);

    // Restore stub.
    stubUserDBView.restore();
  });
});

$ npx mocha stackoverflow.js

  user controller
    ✓ should view user

  1 passing (11ms)

$

Hope this helps.


问:
opencv error in the shape [utils] to make the image and the logo come out together
i follow a tutorial to learn how to use opencv which and a practical library with tensorflow notably for the cnn but I have an error

```<code>Traceback (most recent call last): File "watermark.py", line 15, in <module> watermark =
image_resize(logo, height=50) File "C:\Users\HP\Desktop\Private\project\cv\utils.py", line 9, in
image_resize (h, w) = image.shape:2 AttributeError: 'NoneType' object has no attribute 'shape' WARN:0
global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (674)
SourceReaderCB::~SourceReaderCB terminating async callback
</code>```

code
utils.py

```<code>import cv2
import os
def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):
    dim = None
    (h, w) = image.shape[:2]
    if width is None and height is None:
        return image
    if width is None:
        r = height / float(h)
        dim = (int(w * r), height)
    else:
        r = width / float(w)
        dim = (width, int(h * r))
    resized = cv2.resize(image, dim, interpolation = inter)
    return resized
class CFEVideoConf(object):
    STD_DIMENSIONS =  {
        "360p": (480, 360),
        "480p": (640, 480),
        "720p": (1280, 720),
        "1080p": (1920, 1080),
        "4k": (3840, 2160),
    }
    VIDEO_TYPE = {
        'avi': cv2.VideoWriter_fourcc(*'XVID'),
        'mp4': cv2.VideoWriter_fourcc(*'XVID'),
    }

    width           = 640
    height          = 480
    dims            = (640, 480)
    capture         = None
    video_type      = None
    def __init__(self, capture, filepath, res="480p", *args, **kwargs):
        self.capture = capture
        self.filepath = filepath
        self.width, self.height = self.get_dims(res=res)
        self.video_type = self.get_video_type()
    def change_res(self, width, height):
        self.capture.set(3, width)
        self.capture.set(4, height)
    def get_dims(self, res='480p'):
        width, height = self.STD_DIMENSIONS['480p']
        if res in self.STD_DIMENSIONS:
            width, height = self.STD_DIMENSIONS[res]
        self.change_res(width, height)
        self.dims = (width, height)
        return width, height
    def get_video_type(self):
        filename, ext = os.path.splitext(self.filepath)
        if ext in self.VIDEO_TYPE:
          return  self.VIDEO_TYPE[ext]
        return self.VIDEO_TYPE['avi']
</code>```

watermark.py

```<code>import numpy as np
import cv2
from utils import CFEVideoConf, image_resize
cap = cv2.VideoCapture(0)
save_path = 'saved-media/watermark.mp4'
frames_per_seconds = 24
config = CFEVideoConf(cap, filepath=save_path, res='720p')
out = cv2.VideoWriter(save_path, config.video_type, frames_per_seconds, config.dims)
img_path = 'images/logo/1.png'
logo = cv2.imread(img_path, -1)
watermark = image_resize(logo, height=50)
cv2.imshow('watermark',watermark)
while(True):
    ret, frame = cap.read()
    print(frame[50,150])
    color=(255,0,0)
    start_cord_x=50
    start_cord_y=150
    stroke=2
    w=100
    h=200
    end_cord_x=start_cord_x+w
    end_cord_y=start_cord_y+h
    cv2.rectangle(frame,(x,y),(end_cord_x,end_cord_y),color,stroke)
    cv2.imshow('frame',frame)
    if cv2.waitKey(20) & 0xFF == ord('q'):
        break
cap.release()
out.release()
cv2.destroyAllWindows()
</code>```

thanks for helping me found the error
the expected result is that the logo image 1.png when the camera turns on and the video download shows both the logo + the standard result

答:
Here's your problem, you're reading an image from a non-existent file, hence the empty image that has no shape and is NoneType:

```<code>img_path = 'images/logo/1.png'
logo = cv2.imread(img_path, -1)
</code>```

Body:
i follow a tutorial to learn how to use opencv which and a practical library with tensorflow notably for the cnn but I have an error

Traceback (most recent call last): File "watermark.py", line 15, in <module> watermark =
image_resize(logo, height=50) File "C:\Users\HP\Desktop\Private\project\cv\utils.py", line 9, in
image_resize (h, w) = image.shape:2 AttributeError: 'NoneType' object has no attribute 'shape' WARN:0
global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (674)
SourceReaderCB::~SourceReaderCB terminating async callback

code
utils.py

import cv2
import os
def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):
    dim = None
    (h, w) = image.shape[:2]
    if width is None and height is None:
        return image
    if width is None:
        r = height / float(h)
        dim = (int(w * r), height)
    else:
        r = width / float(w)
        dim = (width, int(h * r))
    resized = cv2.resize(image, dim, interpolation = inter)
    return resized
class CFEVideoConf(object):
    STD_DIMENSIONS =  {
        "360p": (480, 360),
        "480p": (640, 480),
        "720p": (1280, 720),
        "1080p": (1920, 1080),
        "4k": (3840, 2160),
    }
    VIDEO_TYPE = {
        'avi': cv2.VideoWriter_fourcc(*'XVID'),
        'mp4': cv2.VideoWriter_fourcc(*'XVID'),
    }

    width           = 640
    height          = 480
    dims            = (640, 480)
    capture         = None
    video_type      = None
    def __init__(self, capture, filepath, res="480p", *args, **kwargs):
        self.capture = capture
        self.filepath = filepath
        self.width, self.height = self.get_dims(res=res)
        self.video_type = self.get_video_type()
    def change_res(self, width, height):
        self.capture.set(3, width)
        self.capture.set(4, height)
    def get_dims(self, res='480p'):
        width, height = self.STD_DIMENSIONS['480p']
        if res in self.STD_DIMENSIONS:
            width, height = self.STD_DIMENSIONS[res]
        self.change_res(width, height)
        self.dims = (width, height)
        return width, height
    def get_video_type(self):
        filename, ext = os.path.splitext(self.filepath)
        if ext in self.VIDEO_TYPE:
          return  self.VIDEO_TYPE[ext]
        return self.VIDEO_TYPE['avi']

watermark.py

import numpy as np
import cv2
from utils import CFEVideoConf, image_resize
cap = cv2.VideoCapture(0)
save_path = 'saved-media/watermark.mp4'
frames_per_seconds = 24
config = CFEVideoConf(cap, filepath=save_path, res='720p')
out = cv2.VideoWriter(save_path, config.video_type, frames_per_seconds, config.dims)
img_path = 'images/logo/1.png'
logo = cv2.imread(img_path, -1)
watermark = image_resize(logo, height=50)
cv2.imshow('watermark',watermark)
while(True):
    ret, frame = cap.read()
    print(frame[50,150])
    color=(255,0,0)
    start_cord_x=50
    start_cord_y=150
    stroke=2
    w=100
    h=200
    end_cord_x=start_cord_x+w
    end_cord_y=start_cord_y+h
    cv2.rectangle(frame,(x,y),(end_cord_x,end_cord_y),color,stroke)
    cv2.imshow('frame',frame)
    if cv2.waitKey(20) & 0xFF == ord('q'):
        break
cap.release()
out.release()
cv2.destroyAllWindows()

thanks for helping me found the error
the expected result is that the logo image 1.png when the camera turns on and the video download shows both the logo + the standard result

Body:
Here's your problem, you're reading an image from a non-existent file, hence the empty image that has no shape and is NoneType:

img_path = 'images/logo/1.png'
logo = cv2.imread(img_path, -1)


问:
do you know of any python component(s) for syntax highlighting?
Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) .</p>

答:
If you're using gtk+, there's a binding of gtksourceview for Python in gnome-python-extras.  It seems to work well in my experience.  The downside:  the documentation is less than perfect.

There's also a binding of QScintilla for Python if PyQt is your thing.

OwnerDisplayName: Geo

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jason Baker

LastEditorDisplayName: Jason Baker


问:
ucwords but ignore words what are in BLOCK capitals?
I was wondering how to format the strings below to uppercase first letter of words but ingore words that are in uppercase already.

Examples

```<code>ABcd Efg = Abcd Efg
abcd EFG = Abcd EFG
</code>```

Could someone please give an example if it is possible.

Thanks

答:
Using a regex to filter the words by allupercaseiness would be an option:</p>

```<code>$text = preg_replace('/\b(?![A-Z]+\b)\w+\b/e', 'ucwords("$0")', $text);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I was wondering how to format the strings below to uppercase first letter of words but ingore words that are in uppercase already.

Examples

ABcd Efg = Abcd Efg
abcd EFG = Abcd EFG

Could someone please give an example if it is possible.

Thanks

Body:
Using a regex to filter the words by allupercaseiness would be an option:

$text = preg_replace('/\b(?![A-Z]+\b)\w+\b/e', 'ucwords("$0")', $text);


问:
ASP.NET MVC Core - Post form to class parameter
```<code>            <form method="post" id="modalForm" action="/Test/TestForm" target="myframe">
                <input type="text" name="id" required />
                <input type="text" name="name" required />
                <input type="submit" value="Post" onsubmit="alert('after post!');" />
            </form>

    [HttpPost]
    public IActionResult TestForm(Test test)
    {
        return View();
    }

    public class Test
    {
        public string id;
        public string name;
    }
</code>```

What needs to be changed, on the form, to get values to the Test class? Currently the values are null? I would like to keep it simple, without ASP.NET Core helpers.

答:
C# provides a way to use short-hand / automatic properties where you only have to write get; and set; inside the property.

```<code>    public class Test
    {
        public string id { get; set; }
        public string name { get; set; }
    }
</code>```

Body:
            <form method="post" id="modalForm" action="/Test/TestForm" target="myframe">
                <input type="text" name="id" required />
                <input type="text" name="name" required />
                <input type="submit" value="Post" onsubmit="alert('after post!');" />
            </form>

    [HttpPost]
    public IActionResult TestForm(Test test)
    {
        return View();
    }

    public class Test
    {
        public string id;
        public string name;
    }

What needs to be changed, on the form, to get values to the Test class? Currently the values are null? I would like to keep it simple, without ASP.NET Core helpers.

Body:
C# provides a way to use short-hand / automatic properties where you only have to write get; and set; inside the property.

    public class Test
    {
        public string id { get; set; }
        public string name { get; set; }
    }


问:
Changing app navigation structure from version 4 to 5 in react native
I was working on an old app using react navigation version 4 the app contains a register and login in page obviously and then the content of the app.

recently I started remaking the content of the app using react navigation version 5 in order to use the shared element animation and the bottom tab navigator and it was fairly simple.

but I struggled with converting the login part to version 5 since the app structure is somewhat complicated and I am somewhat new to react navigation version 5.

i will leave a figure of the app structure bellow a long with samples of the code used.

App.js :

```<code>import { setNavigator } from "./app/navigationRef";
const articleListFlow = createStackNavigator({
  Main: MainScreen, // screen with diffrent articles categories
  ResultsShow: ResultShowScreen, // article details screen
});
const loginFlow = createStackNavigator({
  Signup: SignupScreen,
  Signin: SigninScreen,
});
loginFlow.navigationOptions = () => {
  return {
    headerShown: false,
  };
};

articleListFlow.navigationOptions = {
  title: "News Feed",
  tabBarIcon: ({ tintColor }) => (
    <View>
      <Icon style={[{ color: tintColor }]} size={25} name={"ios-cart"} />
    </View>
  ),
  activeColor: "#ffffff",
  inactiveColor: "#ebaabd",
  barStyle: { backgroundColor: "#d13560" },
};
const switchNavigator = createSwitchNavigator({
  ResolveAuth: ResolveAuthScreen,
  MainloginFlow: createSwitchNavigator({
    //WelcomeScreen: WeclomeScreen,
    loginFlow: loginFlow,
  }),

  mainFlow: createMaterialBottomTabNavigator(
    {
      articleListFlow: articleListFlow,
      ArticleSave: ArticleSaveScreen, // we dont need this one
      Account: AccountScreen,
    },
    {
      activeColor: "#ffffff",
      inactiveColor: "#bda1f7",
      barStyle: { backgroundColor: "#6948f4" },
    }
  ),
});
const App = createAppContainer(switchNavigator);
export default () => {
  return (
    <AuthProvider>
      <App
        ref={(navigator) => {
          setNavigator(navigator);
        }}
      />
    </AuthProvider>
  );
};
</code>```

NavigationRef.js :

```<code>import { NavigationActions } from "react-navigation";

let navigator;

export const setNavigator = (nav) => {
  navigator = nav;
};

export const navigate = (routeName, params) => {
  navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
};

// routename is the name of the routes singin singup accountscreen
// params information we want to pass to the screen we want to show
</code>```

AuthContext.js

```<code>import { AsyncStorage } from "react-native";
import createDataContext from "./createDataContext";
import userAPI from "../api/user";

// using navigate to access the navigator and redirect the user
import { navigate } from "../navigationRef";

// AUTHENTICATION REDUCERS
const authReducer = (state, action) => {
  switch (action.type) {
    case "add_error": {
      return {
        ...state,
        errorMessage: action.payload,
      };
    }

    case "clear_error_message": {
      return {
        ...state,
        errorMessage: "",
      };
    }
    case "signin": {
      return {
        errorMessage: "",
        token: action.payload,
      };
    }

    default:
      return state;
  }
};

// CLEARING ERROR MESSAGES WHEN SWITCHING SIGNIN-SIGNUP
const clearErrorMessage = (dispatch) => () => {
  dispatch({ type: "clear_error_message" });
};

// AUTOMATIC SIGNIN ONLY USING TOKENS ON USER DEVICE
const tryLocalSignin = (dispatch) => async () => {
  const token = await AsyncStorage.getItem("token");
  if (token) {
    // if token exists
    dispatch({ type: "signin", payload: token });

    navigate("Main");
  } else {
    // if token doesnt exist
    navigate("WelcomeScreen");
  }
};

// SIGNUP
const signup = (dispatch) => async ({ email, password }) => {
  try {
    const response = await userAPI.post("/signup", { email, password });
    await AsyncStorage.setItem("token", response.data.token);
    dispatch({ type: "signin", payload: response.data.token });

    // making use of the navigate component to access navigation
    // and redirect the user
    navigate("Main");
  } catch (err) {
    dispatch({
      type: "add_error",
      payload: "Something went wrong with sign up",
    });
  }
};

// SIGNIN
const signin = (dispatch) => async ({ email, password }) => {
  try {
    const response = await userAPI.post("/signin", { email, password });
    await AsyncStorage.setItem("token", response.data.token);
    // using signin since the logic is the same
    dispatch({ type: "signin", payload: response.data.token });

    // making use of the navigate component to access navigation
    // and redirect the user
    navigate("Main");
  } catch (err) {
    console.log(err);
    dispatch({
      type: "add_error",
      payload: "Something went wrong with sign in",
    });
  }
};

// SIGNOUT
const signout = (dispatch) => async () => {
  // removing the token makes identification not work again
  await AsyncStorage.removeItem("token");
  dispatch({ type: "signout" });

  navigate("loginFlow");
};

// CREATING CONTEXT AND PROVIDER OBJECTS FOR AUTHENTICATION
export const { Provider, Context } = createDataContext(
  authReducer,
  {
    signin,
    signup,
    signout,
    clearErrorMessage,
    tryLocalSignin,
  },
  {
    token: null,
    errorMessage: "",
  }
);
</code>```

createDataContext.js

```<code>import React, { useReducer } from "react";

export default (reducer, actions, defaultValue) => {
  const Context = React.createContext();

  const Provider = ({ children }) => {
    const [state, dispatch] = useReducer(reducer, defaultValue);

    const boundActions = {};

    for (let action in actions) {
      // for every action in the actions, call it with dispatch
      boundActions[action] = actions[action](dispatch);
    }

    return (
      <Context.Provider value={{ state, ...boundActions }}>
        {children}
      </Context.Provider>
    );
  };

  return { Context, Provider };
};
</code>```

My appologies for the long code and thank you in advance for anyone who can help.

答:
As per your diagram, I have tried to create Navigation

```<code>const WelcomeStack = createStackNavigator();
const Tab = createBottomTabNavigator();
const ArticleStack = createStackNavigator();
const MainStack = createStackNavigator();

function Welcome(){
return(
    <WelcomeStack.Navigator>
        <WelcomeStack.screen name='SignIn' component={SignIn}/>
        <WelcomeStack.screen name='SignUp' component={SignUp}/>
    </WelcomeStack.Navigator>
)
}

function  Article(){
return(
    <ArticleStack.Navigator>
        <ArticleStack.Screen name='ArtcileList' name={ArticleList}/>
        <ArticleStack.Screen name='ArticleDetail' name={ArtcileDetail}/>
    </ArticleStack.Navigator>
)
}
function TabNav(){
<Tab.Navigator>
    <Tab.Screen name='Article' component={Article}/>
    <Tab.Screen name='Search' component={Search}/>
    <Tab.Screen name='Save' component={Save}/>
    <Tab.Screen name='Account' component={Account}/>
</Tab.Navigator>
}

function App(){
return(
<NavigationContainer>
<MainStack.Navigator>
   {this.state.isLogin ?
   <MainStack.Screen name='Tab' component={TabNav}/>
   :
   <MainStack.Screen name = 'WelcomeStack' component={Welcome}/>
  }
 </MainStack.Navigator>
 </NavigationContainer>
 )
 }
</code>```

In react navigation 5, their is no switch navigator so you have to go with stack navigation + ternary operator.
This is just an idea as per your diagram. You can make it better after some R&D.

Body:
I was working on an old app using react navigation version 4 the app contains a register and login in page obviously and then the content of the app.

recently I started remaking the content of the app using react navigation version 5 in order to use the shared element animation and the bottom tab navigator and it was fairly simple.

but I struggled with converting the login part to version 5 since the app structure is somewhat complicated and I am somewhat new to react navigation version 5.

i will leave a figure of the app structure bellow a long with samples of the code used.

App.js :

import { setNavigator } from "./app/navigationRef";
const articleListFlow = createStackNavigator({
  Main: MainScreen, // screen with diffrent articles categories
  ResultsShow: ResultShowScreen, // article details screen
});
const loginFlow = createStackNavigator({
  Signup: SignupScreen,
  Signin: SigninScreen,
});
loginFlow.navigationOptions = () => {
  return {
    headerShown: false,
  };
};

articleListFlow.navigationOptions = {
  title: "News Feed",
  tabBarIcon: ({ tintColor }) => (
    <View>
      <Icon style={[{ color: tintColor }]} size={25} name={"ios-cart"} />
    </View>
  ),
  activeColor: "#ffffff",
  inactiveColor: "#ebaabd",
  barStyle: { backgroundColor: "#d13560" },
};
const switchNavigator = createSwitchNavigator({
  ResolveAuth: ResolveAuthScreen,
  MainloginFlow: createSwitchNavigator({
    //WelcomeScreen: WeclomeScreen,
    loginFlow: loginFlow,
  }),

  mainFlow: createMaterialBottomTabNavigator(
    {
      articleListFlow: articleListFlow,
      ArticleSave: ArticleSaveScreen, // we dont need this one
      Account: AccountScreen,
    },
    {
      activeColor: "#ffffff",
      inactiveColor: "#bda1f7",
      barStyle: { backgroundColor: "#6948f4" },
    }
  ),
});
const App = createAppContainer(switchNavigator);
export default () => {
  return (
    <AuthProvider>
      <App
        ref={(navigator) => {
          setNavigator(navigator);
        }}
      />
    </AuthProvider>
  );
};

NavigationRef.js :

import { NavigationActions } from "react-navigation";

let navigator;

export const setNavigator = (nav) => {
  navigator = nav;
};

export const navigate = (routeName, params) => {
  navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
};

// routename is the name of the routes singin singup accountscreen
// params information we want to pass to the screen we want to show

AuthContext.js

import { AsyncStorage } from "react-native";
import createDataContext from "./createDataContext";
import userAPI from "../api/user";

// using navigate to access the navigator and redirect the user
import { navigate } from "../navigationRef";

// AUTHENTICATION REDUCERS
const authReducer = (state, action) => {
  switch (action.type) {
    case "add_error": {
      return {
        ...state,
        errorMessage: action.payload,
      };
    }

    case "clear_error_message": {
      return {
        ...state,
        errorMessage: "",
      };
    }
    case "signin": {
      return {
        errorMessage: "",
        token: action.payload,
      };
    }

    default:
      return state;
  }
};

// CLEARING ERROR MESSAGES WHEN SWITCHING SIGNIN-SIGNUP
const clearErrorMessage = (dispatch) => () => {
  dispatch({ type: "clear_error_message" });
};

// AUTOMATIC SIGNIN ONLY USING TOKENS ON USER DEVICE
const tryLocalSignin = (dispatch) => async () => {
  const token = await AsyncStorage.getItem("token");
  if (token) {
    // if token exists
    dispatch({ type: "signin", payload: token });

    navigate("Main");
  } else {
    // if token doesnt exist
    navigate("WelcomeScreen");
  }
};

// SIGNUP
const signup = (dispatch) => async ({ email, password }) => {
  try {
    const response = await userAPI.post("/signup", { email, password });
    await AsyncStorage.setItem("token", response.data.token);
    dispatch({ type: "signin", payload: response.data.token });

    // making use of the navigate component to access navigation
    // and redirect the user
    navigate("Main");
  } catch (err) {
    dispatch({
      type: "add_error",
      payload: "Something went wrong with sign up",
    });
  }
};

// SIGNIN
const signin = (dispatch) => async ({ email, password }) => {
  try {
    const response = await userAPI.post("/signin", { email, password });
    await AsyncStorage.setItem("token", response.data.token);
    // using signin since the logic is the same
    dispatch({ type: "signin", payload: response.data.token });

    // making use of the navigate component to access navigation
    // and redirect the user
    navigate("Main");
  } catch (err) {
    console.log(err);
    dispatch({
      type: "add_error",
      payload: "Something went wrong with sign in",
    });
  }
};

// SIGNOUT
const signout = (dispatch) => async () => {
  // removing the token makes identification not work again
  await AsyncStorage.removeItem("token");
  dispatch({ type: "signout" });

  navigate("loginFlow");
};

// CREATING CONTEXT AND PROVIDER OBJECTS FOR AUTHENTICATION
export const { Provider, Context } = createDataContext(
  authReducer,
  {
    signin,
    signup,
    signout,
    clearErrorMessage,
    tryLocalSignin,
  },
  {
    token: null,
    errorMessage: "",
  }
);

createDataContext.js

import React, { useReducer } from "react";

export default (reducer, actions, defaultValue) => {
  const Context = React.createContext();

  const Provider = ({ children }) => {
    const [state, dispatch] = useReducer(reducer, defaultValue);

    const boundActions = {};

    for (let action in actions) {
      // for every action in the actions, call it with dispatch
      boundActions[action] = actions[action](dispatch);
    }

    return (
      <Context.Provider value={{ state, ...boundActions }}>
        {children}
      </Context.Provider>
    );
  };

  return { Context, Provider };
};

My appologies for the long code and thank you in advance for anyone who can help.

Body:
As per your diagram, I have tried to create Navigation

const WelcomeStack = createStackNavigator();
const Tab = createBottomTabNavigator();
const ArticleStack = createStackNavigator();
const MainStack = createStackNavigator();

function Welcome(){
return(
    <WelcomeStack.Navigator>
        <WelcomeStack.screen name='SignIn' component={SignIn}/>
        <WelcomeStack.screen name='SignUp' component={SignUp}/>
    </WelcomeStack.Navigator>
)
}

function  Article(){
return(
    <ArticleStack.Navigator>
        <ArticleStack.Screen name='ArtcileList' name={ArticleList}/>
        <ArticleStack.Screen name='ArticleDetail' name={ArtcileDetail}/>
    </ArticleStack.Navigator>
)
}
function TabNav(){
<Tab.Navigator>
    <Tab.Screen name='Article' component={Article}/>
    <Tab.Screen name='Search' component={Search}/>
    <Tab.Screen name='Save' component={Save}/>
    <Tab.Screen name='Account' component={Account}/>
</Tab.Navigator>
}

function App(){
return(
<NavigationContainer>
<MainStack.Navigator>
   {this.state.isLogin ?
   <MainStack.Screen name='Tab' component={TabNav}/>
   :
   <MainStack.Screen name = 'WelcomeStack' component={Welcome}/>
  }
 </MainStack.Navigator>
 </NavigationContainer>
 )
 }

In react navigation 5, their is no switch navigator so you have to go with stack navigation + ternary operator.
This is just an idea as per your diagram. You can make it better after some R&D.


问:
Angular binding width to ContentChildren
I am trying to build a table component in Angular.

I have a StackBlitz Demo Here

When I try to bind width of a
 to my column components i get
ExpressionChangedAfterItHasBeenCheckedError

Is there a better way to achieve this

Thanks

答:
I updated your Stackblitz with a private cdr: ChangeDetectorRef in the constructor, which now calls the detechChanges method in the ngOnInit lifecycle hook. Then you will not get any errors.

have look:
https://stackblitz.com/edit/angular-ivy-lvtprr?file=src/column/column.component.ts


问:
Is it possible to pipe a file with quotes and special characters to OpenSSL?
I am trying to write a bash script that will allow the user to input a password, and then pipe stdin (either via terminal commands or a piped file) to ‘openssl enc’ to encrypt it line by line using that password, and then finally pipe it out to an external TCP server.

This is what I have so far, and it mostly works:

```<code>#!/bin/bash
printf "What is your encryption
password?\n"
read -s password </dev/tty
while read line; do echo "$line" | openssl enc -aes-256-cbc -base64 -pass pass:$password -e; done > >(openssl s_client -quiet -connect localhost:3001)
</code>```

You run this via cat file | script.sh.

The problem I’m running into is when the file has quotes or special characters in it and breaks the echo.

Is there a way to get around this?

答:
Both read and some versions of echo will do some kinds of escape/quote/whitespace/etc processing. You can get read to behave with IFS= read -r -- the IFS= prevents it from trimming leading and trailing whitespace (and since it's a prefix, it won't mess other things up like a general assignment to IFS), and -r tells it not to try to parse escape (backslash) characters. echo is hopeless, so use printf '%s\n' instead.

You also have similar problems with the password variable; use the same read tricks, and then expand it in double-quotes to prevent word-splitting and wildcard expansion from doing weird things. Oh, and I prefer to use read -p prompt rather than printing a separate prompt, and send a newline to /dev/tty afterward so it doesn't just sit there at the prompt.

The pipe and openssl themselves shouldn't be any trouble -- these are both binary-safe interfaces, so no quote or anything parsing there. Mind you, you might have some problems on the decrypt side...

Something like this:

```<code>#!/bin/bash
IFS= read -rs -p "What is your encryption password? " password </dev/tty
echo >/dev/tty
while IFS= read -r line; do
    printf '%s\n' "$line" | openssl enc -aes-256-cbc -base64 -pass "pass:$password" -e
done > >(openssl s_client -quiet -connect localhost:3001)
</code>```

Body:
I am trying to write a bash script that will allow the user to input a password, and then pipe stdin (either via terminal commands or a piped file) to ‘openssl enc’ to encrypt it line by line using that password, and then finally pipe it out to an external TCP server.

This is what I have so far, and it mostly works:

#!/bin/bash
printf "What is your encryption
password?\n"
read -s password </dev/tty
while read line; do echo "$line" | openssl enc -aes-256-cbc -base64 -pass pass:$password -e; done > >(openssl s_client -quiet -connect localhost:3001)

You run this via cat file | script.sh.

The problem I’m running into is when the file has quotes or special characters in it and breaks the echo.

Is there a way to get around this?

Body:
Both read and some versions of echo will do some kinds of escape/quote/whitespace/etc processing. You can get read to behave with IFS= read -r -- the IFS= prevents it from trimming leading and trailing whitespace (and since it's a prefix, it won't mess other things up like a general assignment to IFS), and -r tells it not to try to parse escape (backslash) characters. echo is hopeless, so use printf '%s\n' instead.

You also have similar problems with the password variable; use the same read tricks, and then expand it in double-quotes to prevent word-splitting and wildcard expansion from doing weird things. Oh, and I prefer to use read -p prompt rather than printing a separate prompt, and send a newline to /dev/tty afterward so it doesn't just sit there at the prompt.

The pipe and openssl themselves shouldn't be any trouble -- these are both binary-safe interfaces, so no quote or anything parsing there. Mind you, you might have some problems on the decrypt side...

Something like this:

#!/bin/bash
IFS= read -rs -p "What is your encryption password? " password </dev/tty
echo >/dev/tty
while IFS= read -r line; do
    printf '%s\n' "$line" | openssl enc -aes-256-cbc -base64 -pass "pass:$password" -e
done > >(openssl s_client -quiet -connect localhost:3001)


问:
Value error while trying to group by the pandas data frame and get the row having maximum value for one of the columns
I am new to use data frame and trying to group by the below data-frame by the field Name and want to get the rows having maximum value for the column 'high'.

```<code>    Name    date        high    low
0   20MICRONS   06-03-2020  31.55   27.45
1   AGRITECH    06-03-2020  33.2    30.2
2   20MICRONS   09-03-2020  30      26.85
3   AGRITECH    09-03-2020  30.45   26.4
4   AGRITECH    11-03-2020  28.75   26.55
5   INFY        11-03-2020  695.95  669.05
6   20MICRONS   13-03-2020  24.7    19.45
7   AGRITECH    13-03-2020  26.45   22.55
8   INFY        06-03-2020  744     729.1
9   INFY        09-03-2020  725.85  697
10  20MICRONS   11-03-2020  28.25   24.65
11  20MICRONS   12-03-2020  28.7    21.5
12  AGRITECH    12-03-2020  28.5    24.85
13  INFY        12-03-2020  670     627.5
14  INFY        13-03-2020  667     570
</code>```

required output with the maximum of 'high' column for all the stocks group-wise:

```<code>    Name    date        high    low
8   INFY        06-03-2020  744 729.1
1   AGRITECH    06-03-2020  33.2    30.2
0   20MICRONS   06-03-2020  31.55   27.45
</code>```

likewise it would be helpful if I get the minimum as well. i have tried max() and idxmax() functions as below but i recive value error. could you please help me.

```<code>df[['IndexName','date','high']].loc[df[['IndexName','date','high']].reset_index().groupby(['IndexName'])['high'].idxmax()]
</code>```

did not help but.

答:
i am able to solve my problem as below using an additional for loop and comparison.

```<code>grouped=df.reset_index().groupby('Name')

dfinal= pd.DataFrame(columns=['Name','date','high','low'])

if(sys_Arg_highlow==1):

    for group in grouped:
       dfinal = dfinal.append(group[group['high']==group['high'].max()])

else:
    for group in grouped:
      dfinal = dfinal.append(group[group['low']==group['low'].min()])
</code>```

However , i would like to know if there are any better ways of doing this. thank you.

Body:
I am new to use data frame and trying to group by the below data-frame by the field Name and want to get the rows having maximum value for the column 'high'.

    Name    date        high    low
0   20MICRONS   06-03-2020  31.55   27.45
1   AGRITECH    06-03-2020  33.2    30.2
2   20MICRONS   09-03-2020  30      26.85
3   AGRITECH    09-03-2020  30.45   26.4
4   AGRITECH    11-03-2020  28.75   26.55
5   INFY        11-03-2020  695.95  669.05
6   20MICRONS   13-03-2020  24.7    19.45
7   AGRITECH    13-03-2020  26.45   22.55
8   INFY        06-03-2020  744     729.1
9   INFY        09-03-2020  725.85  697
10  20MICRONS   11-03-2020  28.25   24.65
11  20MICRONS   12-03-2020  28.7    21.5
12  AGRITECH    12-03-2020  28.5    24.85
13  INFY        12-03-2020  670     627.5
14  INFY        13-03-2020  667     570

required output with the maximum of 'high' column for all the stocks group-wise:

    Name    date        high    low
8   INFY        06-03-2020  744 729.1
1   AGRITECH    06-03-2020  33.2    30.2
0   20MICRONS   06-03-2020  31.55   27.45

likewise it would be helpful if I get the minimum as well. i have tried max() and idxmax() functions as below but i recive value error. could you please help me.

df[['IndexName','date','high']].loc[df[['IndexName','date','high']].reset_index().groupby(['IndexName'])['high'].idxmax()]

did not help but.

Body:
i am able to solve my problem as below using an additional for loop and comparison.

grouped=df.reset_index().groupby('Name')

dfinal= pd.DataFrame(columns=['Name','date','high','low'])

if(sys_Arg_highlow==1):

    for group in grouped:
       dfinal = dfinal.append(group[group['high']==group['high'].max()])

else:
    for group in grouped:
      dfinal = dfinal.append(group[group['low']==group['low'].min()])

However , i would like to know if there are any better ways of doing this. thank you.


问:
Parsing JSON to JSON in Liquid Template using for loop. How to iterate through lists in JSON using Liquid Template?

```<code>{
"SAP": [
    {% for Record in content %}{
        {% assign res = Record.d['results'] %}
            "SSO ID": "{{ res[0].username }}"
    },
    {% endfor %}
    ]
}
</code>```

Using this - i am only able to get username field of the first element from both results but not the second element. I want to be able to iterate through all the elements both results and get their values..

PLEASE HELP!!

答:
For our requirement, I initialize a variable named "data" and store the below value to simulate your situation.

```<code>{
    "content": [
        {
            "d": {
                "results": [
                    {
                        "username": "hury11",
                        "email": "test@mail.com"
                    },
                    {
                        "username": "hury22",
                        "email": "test@mail.com"
                    },
                    {
                        "username": "hury33",
                        "email": "test@mail.com"
                    }
                ],
                "_count": "17425",
                "_next": ""
            }
        },
        {
            "d": {
                "results": [
                    {
                        "username": "hury44",
                        "email": "test@mail.com"
                    },
                    {
                        "username": "hury55",
                        "email": "test@mail.com"
                    },
                    {
                        "username": "hury66",
                        "email": "test@mail.com"
                    }
                ],
                "_count": "17425",
                "_next": ""
            }
        }
    ]
}
</code>```

Then parse json and use "Transform JSON to JSON" action.

My liquid template shown as below:

```<code>{
    "SAP": [
        {% for Record in content %}
           [
           {% for result in Record.d.results %}
              {
                "SSO ID": "{{result.username}}",
                "email": "{{result.email}}"
              },
           {% endfor %}
           ],
        {% endfor %}
    ]
}
</code>```

If you want the d map in your result json data, the liquid template should be as below:

```<code>{
    "SAP": [
        {% for Record in content %}
        {"d":
           [
           {% for result in Record.d.results %}
              {
                "SSO ID": "{{result.username}}",
                "email": "{{result.email}}"
              },
           {% endfor %}
           ]
        },
        {% endfor %}
    ]
}
</code>```

Hope it helps~

Body:
{
"SAP": [
    {% for Record in content %}{
        {% assign res = Record.d['results'] %}
            "SSO ID": "{{ res[0].username }}"
    },
    {% endfor %}
    ]
}

Using this - i am only able to get username field of the first element from both results but not the second element. I want to be able to iterate through all the elements both results and get their values..

PLEASE HELP!!

Body:
For our requirement, I initialize a variable named "data" and store the below value to simulate your situation.

{
    "content": [
        {
            "d": {
                "results": [
                    {
                        "username": "hury11",
                        "email": "test@mail.com"
                    },
                    {
                        "username": "hury22",
                        "email": "test@mail.com"
                    },
                    {
                        "username": "hury33",
                        "email": "test@mail.com"
                    }
                ],
                "_count": "17425",
                "_next": ""
            }
        },
        {
            "d": {
                "results": [
                    {
                        "username": "hury44",
                        "email": "test@mail.com"
                    },
                    {
                        "username": "hury55",
                        "email": "test@mail.com"
                    },
                    {
                        "username": "hury66",
                        "email": "test@mail.com"
                    }
                ],
                "_count": "17425",
                "_next": ""
            }
        }
    ]
}

Then parse json and use "Transform JSON to JSON" action.

My liquid template shown as below:

{
    "SAP": [
        {% for Record in content %}
           [
           {% for result in Record.d.results %}
              {
                "SSO ID": "{{result.username}}",
                "email": "{{result.email}}"
              },
           {% endfor %}
           ],
        {% endfor %}
    ]
}

If you want the d map in your result json data, the liquid template should be as below:

{
    "SAP": [
        {% for Record in content %}
        {"d":
           [
           {% for result in Record.d.results %}
              {
                "SSO ID": "{{result.username}}",
                "email": "{{result.email}}"
              },
           {% endfor %}
           ]
        },
        {% endfor %}
    ]
}

Hope it helps~


问:
Streaming huge json with Akka Stream
I have a problem of huge http response with a json slab, where only portion is point of interest.
I cannot change the response structure.
here is an example

```<code>{
  "searchString": "search",
  "redirectUrl": "",
  "0": {
    "numRecords": 123,
    "refinementViewModelCollector": {},
//    Lots of data here
    "results": [
      {
        "productCode": "123",
        "productShortDescription": "Desc",
        "brand": "Brand",
        "productReview": {
          "reviewScore": 0
        },
        "priceView": {
          "salePriceDisplayable": false,
        },
        "productImageUrl": "url",
        "alternateImageUrls": [
          "url1"
        ],
        "largeProductImageUrl": "url4",
        "videoUrl": ""
      },
      {
        "productCode": "124",
        "productShortDescription": "Desc",
        "brand": "Brand",
        "productReview": {
          "reviewScore": 0
         },
        "priceView": {
          "salePriceDisplayable": false,
        },
        "preOrder": false,
        "productImageUrl": "url",
        "alternateImageUrls": [
          "url1"
        ],
        "largeProductImageUrl": "url4",
        "videoUrl": ""
      }
    ]
    //lots of data here
  }
}
</code>```

My point of interest is entries in results Jason Array, but the are sitting in the middle of json

I created a small Play WS Client like this:

```<code>val wsClient: WSClient = ???
val ret = wsClient.url("url").stream()
ret.flatMap { response =>
  response.body.via(JsonFraming.objectScanner(1024))
    .map(_.utf8String)
    .runWith(Sink.foreach(println))
}
</code>```

this will not work because it will take whole json slab as Json object. I need to skip some data until "results": entry appear in the stream, then start parsing entries and skip all the rest.
Any ideas how to do this?

答:
I'd love a better, Scala-specific answer to this question, but check out the "Mixed Reads Example" in the documentation for Google's GSON library:

https://sites.google.com/site/gson/streaming

Gson also supports mixed streaming & object model access. This lets your application have the best of both worlds: the productivity of object model access with the efficiency of streaming
  ...
  This code reads a JSON document containing an array of messages. It steps through array elements as a stream to avoid loading the complete document into memory. It is concise because it uses Gson’s object-model to parse the individual messages

This should have great memory-performance (the code reads from a Java InputStream, so the full structure is never in memory), but may require some effort to get your results into Scala case classes.

Title: Streaming huge json with Akka Stream

Body:
I have a problem of huge http response with a json slab, where only portion is point of interest.
I cannot change the response structure.
here is an example

{
  "searchString": "search",
  "redirectUrl": "",
  "0": {
    "numRecords": 123,
    "refinementViewModelCollector": {},
//    Lots of data here
    "results": [
      {
        "productCode": "123",
        "productShortDescription": "Desc",
        "brand": "Brand",
        "productReview": {
          "reviewScore": 0
        },
        "priceView": {
          "salePriceDisplayable": false,
        },
        "productImageUrl": "url",
        "alternateImageUrls": [
          "url1"
        ],
        "largeProductImageUrl": "url4",
        "videoUrl": ""
      },
      {
        "productCode": "124",
        "productShortDescription": "Desc",
        "brand": "Brand",
        "productReview": {
          "reviewScore": 0
         },
        "priceView": {
          "salePriceDisplayable": false,
        },
        "preOrder": false,
        "productImageUrl": "url",
        "alternateImageUrls": [
          "url1"
        ],
        "largeProductImageUrl": "url4",
        "videoUrl": ""
      }
    ]
    //lots of data here
  }
}

My point of interest is entries in results Jason Array, but the are sitting in the middle of json

I created a small Play WS Client like this:

val wsClient: WSClient = ???
val ret = wsClient.url("url").stream()
ret.flatMap { response =>
  response.body.via(JsonFraming.objectScanner(1024))
    .map(_.utf8String)
    .runWith(Sink.foreach(println))
}

this will not work because it will take whole json slab as Json object. I need to skip some data until "results": entry appear in the stream, then start parsing entries and skip all the rest.
Any ideas how to do this?


问:
tau-prolog won't run a prolog code that I use CHR library in although it works on SWI-Prolog
I'm trying to use Tau Prolog to run a CHR code and it gives this error:

```<code>throw(error(existence_error(procedure, '/'(color, 1)), '/'(top_level, 0)))
</code>```

although it works fine on SWI Prolog.

This is the Prolog code:

```<code>:- use_module(library(chr)).

:- chr_constraint(color/1).

color(X), color(Y) <=> mix(X,Y,Z) | color(Z).

color(brown) \ color(_) <=> true.

mix(red,blue,purple).
mix(blue,yellow,green).
mix(yellow,red,orange).
</code>```

this is the query I run:

```<code>?- color(yellow), color(red).
</code>```

This is the JS code I use to run Tau Prolog:

```<code>let res2 = "";
let callbackStr = true;
function postQuery(str) {
  res2 += str + "\n";
  if (str == false)
    callbackStr = false;
}

router.post("/runQuery", async (req, res) => {
  res2 = "";
  let session = pl.create();
  let call = postQuery;
  let query = req.body.sentQuery;
  session.consult(req.body.codeString);
  session.query(query);
  while (callbackStr == true) {
    session.answer(call);
  }
  res.send(res2);
  res2 = "";
  callbackStr = true;
});
</code>```

答:
I think you have little chance of success with :-use_module(library(chr))., at least if nobody ported the code from other more mature Prologs to TAU-Prolog

But Falco Nogatz has a Javascript implementation of CHR that could help you.

As I see it, Prolog and CHR overlap (well, Prolog is larger), so using a different host language for your CHR rules could be easy - and convenient.

Body:
I'm trying to use Tau Prolog to run a CHR code and it gives this error:

throw(error(existence_error(procedure, '/'(color, 1)), '/'(top_level, 0)))

although it works fine on SWI Prolog.

This is the Prolog code:

:- use_module(library(chr)).

:- chr_constraint(color/1).

color(X), color(Y) <=> mix(X,Y,Z) | color(Z).

color(brown) \ color(_) <=> true.

mix(red,blue,purple).
mix(blue,yellow,green).
mix(yellow,red,orange).

this is the query I run:

?- color(yellow), color(red).

This is the JS code I use to run Tau Prolog:

let res2 = "";
let callbackStr = true;
function postQuery(str) {
  res2 += str + "\n";
  if (str == false)
    callbackStr = false;
}

router.post("/runQuery", async (req, res) => {
  res2 = "";
  let session = pl.create();
  let call = postQuery;
  let query = req.body.sentQuery;
  session.consult(req.body.codeString);
  session.query(query);
  while (callbackStr == true) {
    session.answer(call);
  }
  res.send(res2);
  res2 = "";
  callbackStr = true;
});


问:
The update function doesn't work, SQL Server and ASP.NET MVC 5
I have to update a table but it doesn't do anything. In the view for edit my values, it "works", but when I click to submit changes, it doesn't change any values in the data base. I'm really stuck, I check this files but I can't see where the problem is.

This is my .cs file

```<code> public void update(Propietario objPropietario)
 {
        try
        {
            comando = new SqlCommand("spEditarPropietario", objConexion.getConexion());
            comando.CommandType = CommandType.StoredProcedure;

            comando.Parameters.AddWithValue("@id", objPropietario.IdPropietario);
            comando.Parameters.AddWithValue("@Nombre", objPropietario.Nombre);
            comando.Parameters.AddWithValue("@IdTipoDocumento", objPropietario.TipoDocumento);
            comando.Parameters.AddWithValue("@ValorDocumento", objPropietario.ValorDocumentoId);

            objConexion.getConexion().Open();
            comando.ExecuteNonQuery();
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            objConexion.getConexion().Close();
            objConexion.cerrarConexion();
        }
}
</code>```

The table:

```<code>CREATE TABLE [dbo].[Propietario]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [IdTipoDocumento] [int] NOT NULL,
    [Nombre] [varchar](100) NOT NULL,
    [ValorDocumento] [varchar](30) NULL,

    CONSTRAINT [PK_Propietario]
        PRIMARY KEY CLUSTERED ([ID] ASC)
                    WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
                          IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
                          ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Propietario] WITH CHECK
    ADD CONSTRAINT [FK_Propietario_TipoDocumentoId]
        FOREIGN KEY([IdTipoDocumento]) REFERENCES [dbo].[TipoDocumentoId] ([ID])
GO

ALTER TABLE [dbo].[Propietario] CHECK CONSTRAINT [FK_Propietario_TipoDocumentoId]
GO
</code>```

This is the stored procedure that I'm using:

```<code>CREATE PROCEDURE spEditarPropietario
    (@id int,
     @Nombre VARCHAR(100),
     @IdTipoDocumento int,
     @ValorDocumento VARCHAR(30))
AS
BEGIN
    UPDATE [dbo].Propietario
    SET Nombre = @Nombre,
        IdTipoDocumento = @IdTipoDocumento,
        ValorDocumento = @ValorDocumento
    WHERE ID = @id
END
</code>```

This is my controller:

```<code>[HttpGet]
public ActionResult Update(int ID)
{
    Propietario objpropietario = new Propietario(ID);
    objetoPropietario.find(objpropietario);
    return View(objpropietario);
}

[HttpPost]
public ActionResult Update(Propietario objpropietario)
{
    objetoPropietario.update(objpropietario);
    return RedirectToAction("Inicio");
}
</code>```

I have this find method and it works well.

```<code>public bool find(Propietario objpropietario)
{
        bool hayRegistros;

        try
        {
            comando = new SqlCommand("spVerPropietario",
objConexion.getConexion());
            comando.CommandType = CommandType.StoredProcedure;

            comando.Parameters.AddWithValue("@ID",
objpropietario.IdPropietario);

            objConexion.getConexion().Open();

            SqlDataReader read = comando.ExecuteReader();
            hayRegistros = read.Read();

            if (hayRegistros)
            {
                objpropietario.IdPropietario =
Convert.ToInt32(read[0].ToString());
                objpropietario.Nombre = read[1].ToString();
                objpropietario.TipoDocumento =
Convert.ToInt32(read[2].ToString());
                objpropietario.ValorDocumentoId = read[3].ToString();
                objpropietario.EstadoError = 99;
            }
            else
            {
                objpropietario.EstadoError = 1;
            }
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            objConexion.getConexion().Close();
            objConexion.cerrarConexion();
        }
        return hayRegistros;
}
</code>```

This is the stored procedure:

```<code>CREATE PROCEDURE spVerPropietario
    (@ID int)
AS
BEGIN
    SELECT ID, Nombre, IdTipoDocumento, ValorDocumento
    FROM [dbo].Propietario
    WHERE ID = @ID
END
</code>```

答:
I fixed adding a new parameter of the id, to the Update method in controller, because the object changes the id to 0, that's why it didn't work. The solution:

```<code>public ActionResult Update(Propietario objpropietario, int ID)
    {
        objpropietario.IdPropietario = ID;
        objetoPropietario.update(objpropietario);
        //return Content(obj.propietario.Nombre
        //return View(objpropietario);
        return RedirectToAction("Inicio");
    }
</code>```

Only with that, it works fine.

Body:
I have to update a table but it doesn't do anything. In the view for edit my values, it "works", but when I click to submit changes, it doesn't change any values in the data base. I'm really stuck, I check this files but I can't see where the problem is.

This is my .cs file

 public void update(Propietario objPropietario)
 {
        try
        {
            comando = new SqlCommand("spEditarPropietario", objConexion.getConexion());
            comando.CommandType = CommandType.StoredProcedure;

            comando.Parameters.AddWithValue("@id", objPropietario.IdPropietario);
            comando.Parameters.AddWithValue("@Nombre", objPropietario.Nombre);
            comando.Parameters.AddWithValue("@IdTipoDocumento", objPropietario.TipoDocumento);
            comando.Parameters.AddWithValue("@ValorDocumento", objPropietario.ValorDocumentoId);

            objConexion.getConexion().Open();
            comando.ExecuteNonQuery();
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            objConexion.getConexion().Close();
            objConexion.cerrarConexion();
        }
}

The table:

CREATE TABLE [dbo].[Propietario]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [IdTipoDocumento] [int] NOT NULL,
    [Nombre] [varchar](100) NOT NULL,
    [ValorDocumento] [varchar](30) NULL,

    CONSTRAINT [PK_Propietario]
        PRIMARY KEY CLUSTERED ([ID] ASC)
                    WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
                          IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
                          ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Propietario] WITH CHECK
    ADD CONSTRAINT [FK_Propietario_TipoDocumentoId]
        FOREIGN KEY([IdTipoDocumento]) REFERENCES [dbo].[TipoDocumentoId] ([ID])
GO

ALTER TABLE [dbo].[Propietario] CHECK CONSTRAINT [FK_Propietario_TipoDocumentoId]
GO

This is the stored procedure that I'm using:

CREATE PROCEDURE spEditarPropietario
    (@id int,
     @Nombre VARCHAR(100),
     @IdTipoDocumento int,
     @ValorDocumento VARCHAR(30))
AS
BEGIN
    UPDATE [dbo].Propietario
    SET Nombre = @Nombre,
        IdTipoDocumento = @IdTipoDocumento,
        ValorDocumento = @ValorDocumento
    WHERE ID = @id
END

This is my controller:

[HttpGet]
public ActionResult Update(int ID)
{
    Propietario objpropietario = new Propietario(ID);
    objetoPropietario.find(objpropietario);
    return View(objpropietario);
}

[HttpPost]
public ActionResult Update(Propietario objpropietario)
{
    objetoPropietario.update(objpropietario);
    return RedirectToAction("Inicio");
}

I have this find method and it works well.

public bool find(Propietario objpropietario)
{
        bool hayRegistros;

        try
        {
            comando = new SqlCommand("spVerPropietario",
objConexion.getConexion());
            comando.CommandType = CommandType.StoredProcedure;

            comando.Parameters.AddWithValue("@ID",
objpropietario.IdPropietario);

            objConexion.getConexion().Open();

            SqlDataReader read = comando.ExecuteReader();
            hayRegistros = read.Read();

            if (hayRegistros)
            {
                objpropietario.IdPropietario =
Convert.ToInt32(read[0].ToString());
                objpropietario.Nombre = read[1].ToString();
                objpropietario.TipoDocumento =
Convert.ToInt32(read[2].ToString());
                objpropietario.ValorDocumentoId = read[3].ToString();
                objpropietario.EstadoError = 99;
            }
            else
            {
                objpropietario.EstadoError = 1;
            }
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            objConexion.getConexion().Close();
            objConexion.cerrarConexion();
        }
        return hayRegistros;
}

This is the stored procedure:

CREATE PROCEDURE spVerPropietario
    (@ID int)
AS
BEGIN
    SELECT ID, Nombre, IdTipoDocumento, ValorDocumento
    FROM [dbo].Propietario
    WHERE ID = @ID
END

Body:
I fixed adding a new parameter of the id, to the Update method in controller, because the object changes the id to 0, that's why it didn't work. The solution:

public ActionResult Update(Propietario objpropietario, int ID)
    {
        objpropietario.IdPropietario = ID;
        objetoPropietario.update(objpropietario);
        //return Content(obj.propietario.Nombre
        //return View(objpropietario);
        return RedirectToAction("Inicio");
    }

Only with that, it works fine.


问:
Django: Passing argument to parent template
I have templates of this style

```<code>project
- main_templates (including nav bar)
-- app1
--- app1_base_template
--- app1_templates
-- app2
--- app2_base_template
--- app2_templates
</code>```

So when rendering, app2_templates extends app2_base_template which extends main_template.

What I need to do, is have the corresponding nav item be bold when app2's template is being rendered (to show the user where he is).

The easiest would if I could pass a variable in the {% block xxx %} part.
Is this possible ?

What other generic ways are there ?

答:
You can use HttpRequest.resolver_match.

In the parent html template:

```<code><li class="nav-item {% if request.resolver_match.view_name == 'my_simple_blog:homepage' %}active{% endif %}"><a href="{% url 'my_simple_blog:homepage' %}" class="nav-link">Home</a></li>
<li class="nav-item {% if request.resolver_match.view_name == 'my_simple_blog:about' %}active{% endif %}"><a href="{% url 'my_simple_blog:about' %}" class="nav-link">About</a></li>
</code>```

It checks for the current namespace and compare it, if they are the same, add active in the class of the list.

Body:
I have templates of this style

project
- main_templates (including nav bar)
-- app1
--- app1_base_template
--- app1_templates
-- app2
--- app2_base_template
--- app2_templates

So when rendering, app2_templates extends app2_base_template which extends main_template.

What I need to do, is have the corresponding nav item be bold when app2's template is being rendered (to show the user where he is).

The easiest would if I could pass a variable in the {% block xxx %} part.
Is this possible ?

What other generic ways are there ?

Body:
You can use HttpRequest.resolver_match.

In the parent html template:

<li class="nav-item {% if request.resolver_match.view_name == 'my_simple_blog:homepage' %}active{% endif %}"><a href="{% url 'my_simple_blog:homepage' %}" class="nav-link">Home</a></li>
<li class="nav-item {% if request.resolver_match.view_name == 'my_simple_blog:about' %}active{% endif %}"><a href="{% url 'my_simple_blog:about' %}" class="nav-link">About</a></li>

It checks for the current namespace and compare it, if they are the same, add active in the class of the list.


问:
Set URLSession Delegate To Another Swift Class
I am attempting to call an API to login to a website. I currently have all my API calls in a swift class called APICalls. My view controller I'm using to login with is called CreateAccountViewController.

In my API call to login I create a URL session and set the delegate like this:

```<code>let task = URLSession.init(configuration: URLSessionConfiguration.default, delegate: CreateAccountViewController.init(), delegateQueue: nil)

task.dataTask(with: request).resume()
</code>```

Then in my VC class I have this function

```<code>func urlSession(_: URLSession, task: URLSessionTask, didCompleteWithError: Error?) {
    // Check the data returned from API call, ensure user is logged in
}
</code>```

This function is being called when the API is done, but I feel like I'm causing a memory leak or something by using .init in the delegate declaration when creating my URL session. Is there a better way to do this?

Also, how do I access the data from the API call? In completion handlers there's a data response I can get at, but not in this delegate call.

答:
Better is to don't do this by delegating other class in URL Session case ... return data in completion handler and access that in your class

And for data you can use other method

```<code>func urlSession(_ session: URLSession,
                dataTask: URLSessionDataTask,
              didReceive data: Data)
</code>```

Here you will get received data

Body:
I am attempting to call an API to login to a website. I currently have all my API calls in a swift class called APICalls. My view controller I'm using to login with is called CreateAccountViewController.

In my API call to login I create a URL session and set the delegate like this:

let task = URLSession.init(configuration: URLSessionConfiguration.default, delegate: CreateAccountViewController.init(), delegateQueue: nil)

task.dataTask(with: request).resume()

Then in my VC class I have this function

func urlSession(_: URLSession, task: URLSessionTask, didCompleteWithError: Error?) {
    // Check the data returned from API call, ensure user is logged in
}

This function is being called when the API is done, but I feel like I'm causing a memory leak or something by using .init in the delegate declaration when creating my URL session. Is there a better way to do this?

Also, how do I access the data from the API call? In completion handlers there's a data response I can get at, but not in this delegate call.

Body:
Better is to don't do this by delegating other class in URL Session case ... return data in completion handler and access that in your class

And for data you can use other method

func urlSession(_ session: URLSession,
                dataTask: URLSessionDataTask,
              didReceive data: Data)

Here you will get received data


问:
create a tensor proto whose content is larger than 2GB
I created a ndarray (W) which size is (2^22, 256), and I tried to use this array as my initialization of weight matirx using:

```<code>w = tf.Variable(tf.convert_to_tensor(W))
</code>```

then, the tensorflow raised a error:
ValueError: Cannot create a tensor proto whose content is larger than 2GB.

How can I fix this problem?
PS. my weight matrix must using that (2^22, 256) matrix for initializing.
THX :)

答:
for tf v1.14.0 you can solve this with tf.compat.v1.enable_eager_execution()
tf v2.0+ doesn't throw error in situation at all.</p>

Body:
I created a ndarray (W) which size is (2^22, 256), and I tried to use this array as my initialization of weight matirx using:

w = tf.Variable(tf.convert_to_tensor(W))

then, the tensorflow raised a error:
ValueError: Cannot create a tensor proto whose content is larger than 2GB.

How can I fix this problem?
PS. my weight matrix must using that (2^22, 256) matrix for initializing.
THX :)


问:
Ruby on Rails: 'show' route of account
Currently I have two models, Account and User. Account has many users, and users belongs to account. I want to show account page but keep getting No route matches {:action=>"show", :controller=>"accounts"}, missing required keys: [:id] error.

Accounts controller

```<code>def show
   @account = Account.find_by(params[:id])
end
</code>```

Links to account page

```<code><%= link_to "Account Settings", account_path %>
</code>```

Routes

```<code>resources :accounts, only: [:new, :create, :show, :edit, :update]
</code>```

答:
```<code><%= link_to "Account Settings", account_path(@current_user.account_id) %>
</code>```

Title: Ruby on Rails: 'show' route of account

Body:
Currently I have two models, Account and User. Account has many users, and users belongs to account. I want to show account page but keep getting No route matches {:action=>"show", :controller=>"accounts"}, missing required keys: [:id] error.

Accounts controller

def show
   @account = Account.find_by(params[:id])
end

Links to account page

<%= link_to "Account Settings", account_path %>

Routes

resources :accounts, only: [:new, :create, :show, :edit, :update]


问:
can someone please explain REQ in express plz
I dont get how we use req in express. I undrstand that the server can respond back to client,but when it comes to req object im confused. Is req when the server is asking for somethong from the client?

答:
HTTP is an application, client-server protocol. Everytime that a client want the server to perform an action, it has to make a request. The HTTP protocol defines a set of actions or verbs that are available to the client so it can make each request using one specific verb (GET, POST, PATCH, PUT, DELETE, etc). It doesn't matter what verb the client uses, only the client can initiate a comunication with the server using one of that verbs. So this is how exactly an HTTP GET request looks like:

```<code> GET / HTTP/1.1
 Host: example.com
 User-Agent: curl/7.69.1
 Accept: */*

</code>```

The first line contains the verb used, in this case GET, the path requested, in this case /, and the protocol version, in this case HTTP/1.1. The next lines, are a set of key value pairs called the headers of that request, which can define a lot of aspects of the request made by the client to the server. By the way, an HTTP server never could or will start a request to a client, a client always is the one that make the request, and the server is always the one that response that request. One of the aspects of that request for example, is the destination host, that is present in the header host with the value of example.com. Bellow of the headers, all the HTTP requests have a blank line and then the body of the request, which normally contains the data that is sent from the client to the server. In this case, no data body is sent on the request.

Express is an HTTP server based on the HTTP module available on Node.js. Express simplifies the way that the native Node.js HTTP server works. Here is tipically how an Express app looks like:

```<code>const express = require('express');
const app = express();

// This is called a router
app.get('/path', (req, res) => {
    // This router will perform some action with the req object
    // And will send a response to the client
});
</code>```

So, on the example above, the method app.get(...), available on Express applications, allows the server to deal with the GET requests that come from the client. The app.get() method takes two arguments, a path and a callback function. The path argument represent the string that goes after the name server, for example, in the URL www.example.com/test, the hostname is www.example.com, and the path is /test. That method app.get() is also called a Router. So, the router of the example will deal with the  GET requests to that server which also define /path value as the path the request is sent to. Once a request to the server fit those two conditions, that callback will be triggered.

So, finally we get to the answer. The res variable is an object (a set of key-pair values separated by commas and locked into curly braces), that contains the data of the HTTP request, into a friendly legible object. For example, if you want to print to the console the path that the client used, you can print it like this console.log(req.path), or you can get all the headers of that HTTP request, you can use console.log(req.headers). The req object is one of the 5 main objects in Express, in fact the Express documentation defines a ton of methods that you can use with the request object (req). To get deep into the request object, you can see the official Express documentation in this link. The callback defined into the router, can use the req object, to extract information of the client's request, process it and return a response to the client later.

Body:
HTTP is an application, client-server protocol. Everytime that a client want the server to perform an action, it has to make a request. The HTTP protocol defines a set of actions or verbs that are available to the client so it can make each request using one specific verb (GET, POST, PATCH, PUT, DELETE, etc). It doesn't matter what verb the client uses, only the client can initiate a comunication with the server using one of that verbs. So this is how exactly an HTTP GET request looks like:

 GET / HTTP/1.1
 Host: example.com
 User-Agent: curl/7.69.1
 Accept: */*

The first line contains the verb used, in this case GET, the path requested, in this case /, and the protocol version, in this case HTTP/1.1. The next lines, are a set of key value pairs called the headers of that request, which can define a lot of aspects of the request made by the client to the server. By the way, an HTTP server never could or will start a request to a client, a client always is the one that make the request, and the server is always the one that response that request. One of the aspects of that request for example, is the destination host, that is present in the header host with the value of example.com. Bellow of the headers, all the HTTP requests have a blank line and then the body of the request, which normally contains the data that is sent from the client to the server. In this case, no data body is sent on the request.

Express is an HTTP server based on the HTTP module available on Node.js. Express simplifies the way that the native Node.js HTTP server works. Here is tipically how an Express app looks like:

const express = require('express');
const app = express();

// This is called a router
app.get('/path', (req, res) => {
    // This router will perform some action with the req object
    // And will send a response to the client
});

So, on the example above, the method app.get(...), available on Express applications, allows the server to deal with the GET requests that come from the client. The app.get() method takes two arguments, a path and a callback function. The path argument represent the string that goes after the name server, for example, in the URL www.example.com/test, the hostname is www.example.com, and the path is /test. That method app.get() is also called a Router. So, the router of the example will deal with the  GET requests to that server which also define /path value as the path the request is sent to. Once a request to the server fit those two conditions, that callback will be triggered.

So, finally we get to the answer. The res variable is an object (a set of key-pair values separated by commas and locked into curly braces), that contains the data of the HTTP request, into a friendly legible object. For example, if you want to print to the console the path that the client used, you can print it like this console.log(req.path), or you can get all the headers of that HTTP request, you can use console.log(req.headers). The req object is one of the 5 main objects in Express, in fact the Express documentation defines a ton of methods that you can use with the request object (req). To get deep into the request object, you can see the official Express documentation in this link. The callback defined into the router, can use the req object, to extract information of the client's request, process it and return a response to the client later.


问:
how to run autoplay video in owl carousel if it has video?
I use an owl carousel and I want to autoplay the video when I reach to that slide that have a video .and I see similar answers like
Owl Carousel VIDEO Autoplay dosent work
and test in my project but my code and the other codes do not work.and I have a textarea on every slide and I want the slide do not change to the next slide when I am writing a comment in textarea. how can I do it? tnx

```<code>  <div class="owl-carousel  owl-theme slideHeighlight">
              <div class="item">
                 <figure class="fig-highlight">
                    <img src="Images/high1.jpg" />
                       <figcaption>
                       <div class="highlight-cm">
                          <textarea class="txtarea-cm" rows="1" placeholder="send message"></textarea><button type="submit" class="btn btn-send btnhighlight" >send</button>
                       </div>
                    </figcaption>
                 </figure>
              </div>
              <div class="item">
                 <figure class="fig-highlight">
                    <img src="Images/high2.jpg" />
                    <figcaption>
                       <div class="highlight-cm">
                          <textarea class="txtarea-cm" rows="1" placeholder="send message"></textarea><button type="submit" class="btn btn-send btnhighlight" >send</button>
                       </div>
                    </figcaption>
                 </figure>
              </div>
              <div class="item item-video">
                 <figure class="fig-highlight">
                    <video>
                       <source src="Images/video2.mp4" type="video/mp4" />
                    </video>
                  <figcaption>
                       <div class="highlight-cm">
                          <textarea class="txtarea-cm" rows="1" placeholder="send message"></textarea><button type="submit" class="btn btn-send btnhighlight" >send</button>
                       </div>
                    </figcaption>
                 </figure>
              </div>
           </div>
</code>```

my script:

```<code>                $('.slideHeighlight').owlCarousel({
  rtl: true,
  margin: 10,
  nav: true,
  loop: false,
  autoplay: true,
  singleItem: true,
  video: true,
  responsive: {
     0: {
        items:1
     },
     567: {
        items:1
     },
     600: {
        items:1
     },
     900: {
        items: 1
     }

  }
   });

        $(document).on('click', '.slideHeighlight', function () {
       if ($(this).next().hasClass('item-video')) {
        $(this).find(".fig-highlight video").play();
       }
  });
</code>```

答: I found that browsers has permisson to autoplay video and sound automatically and so I put button play for play</p>

Body:
I use an owl carousel and I want to autoplay the video when I reach to that slide that have a video .and I see similar answers like
Owl Carousel VIDEO Autoplay dosent work
and test in my project but my code and the other codes do not work.and I have a textarea on every slide and I want the slide do not change to the next slide when I am writing a comment in textarea. how can I do it? tnx

                          <textarea class="txtarea-cm" rows="1" placeholder="send message"></textarea><button type="submit" class="btn btn-send btnhighlight" >send</button>

                          <textarea class="txtarea-cm" rows="1" placeholder="send message"></textarea><button type="submit" class="btn btn-send btnhighlight" >send</button>

                    <video>
                       <source src="Images/video2.mp4" type="video/mp4" />
                    </video>

                          <textarea class="txtarea-cm" rows="1" placeholder="send message"></textarea><button type="submit" class="btn btn-send btnhighlight" >send</button>

my script:

                $('.slideHeighlight').owlCarousel({
  rtl: true,
  margin: 10,
  nav: true,
  loop: false,
  autoplay: true,
  singleItem: true,
  video: true,
  responsive: {
     0: {
        items:1
     },
     567: {
        items:1
     },
     600: {
        items:1
     },
     900: {
        items: 1
     }

  }
   });

        $(document).on('click', '.slideHeighlight', function () {
       if ($(this).next().hasClass('item-video')) {
        $(this).find(".fig-highlight video").play();
       }
  });


问:
Codeigniter issue with escaping values when passing array to query with "in" in the where clause
I have the function below in my model for a codeigniter project, and the variable $id is an array and for example, contains (1,2,3). Now that i'm revisiting it, I think that i'm not actually escaping my array $id. I think I would have to change the line
$this->db->escape($id)
to
$id = $this->db->escape($id)

If I do that, then it puts single quotes around every element in the array and treats it as one long string like this: '(1,2,3)'.

Can someone confirm that I am not actually escaping my variable and either suggest a solution or let me know if this is a bug within the codeigniter framework?

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

        $this->db->escape($id); // had to manually escape the variable since it's being used in an "in" in the where clause.

        $sql = "select * from toys t
                 where t.toy_id in ($id)";

        $query = $this->db->query($sql, $id);

        if($query->num_rows() > 0)
        {
            return $query->result_array();
        }
        else
        {
            return false;
        }
    }
</code>```

答:
You could try something like this:

```<code>$sql = 'select * from toys t where t.toy_id in ('.
  join(',',array_map(function($i) {
    return $this->db->escape($i);
  }, $id)).');';
</code>```

*Disclaimer: I'm not where I can access my PHP/MySQL server right now, so I haven't validated this.  Some modification and/or tweakage may be necessary.

Body:
I have the function below in my model for a codeigniter project, and the variable $id is an array and for example, contains (1,2,3). Now that i'm revisiting it, I think that i'm not actually escaping my array $id. I think I would have to change the line
$this->db->escape($id)
to
$id = $this->db->escape($id)

If I do that, then it puts single quotes around every element in the array and treats it as one long string like this: '(1,2,3)'.

Can someone confirm that I am not actually escaping my variable and either suggest a solution or let me know if this is a bug within the codeigniter framework?

function get_ratings($id)
    {

        $this->db->escape($id); // had to manually escape the variable since it's being used in an "in" in the where clause.

        $sql = "select * from toys t
                 where t.toy_id in ($id)";

        $query = $this->db->query($sql, $id);

        if($query->num_rows() > 0)
        {
            return $query->result_array();
        }
        else
        {
            return false;
        }
    }

Body:
You could try something like this:

$sql = 'select * from toys t where t.toy_id in ('.
  join(',',array_map(function($i) {
    return $this->db->escape($i);
  }, $id)).');';

*Disclaimer: I'm not where I can access my PHP/MySQL server right now, so I haven't validated this.  Some modification and/or tweakage may be necessary.


问:
Open AppStore through button
Could you guys help me to translate the following code into Swift?

```<code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms://itunes.apple.com/de/app/x-gift/id839686104?mt=8&uo=4"]];
</code>```

(or do I have to take this link: itms://itunes.apple.com/app/id839686104?)

答:
Swift 5.0:

import StoreKit

```<code>extension YourViewController: SKStoreProductViewControllerDelegate {
    func openStoreProductWithiTunesItemIdentifier(_ identifier: String) {
        let storeViewController = SKStoreProductViewController()
        storeViewController.delegate = self

        let parameters = [ SKStoreProductParameterITunesItemIdentifier : identifier]
        storeViewController.loadProduct(withParameters: parameters) { [weak self] (loaded, error) -> Void in
            if loaded {
                self?.present(storeViewController, animated: true, completion: nil)
            }
        }
    }
    private func productViewControllerDidFinish(viewController: SKStoreProductViewController) {
        viewController.dismiss(animated: true, completion: nil)
    }
}

// How to use

openStoreProductWithiTunesItemIdentifier("12345")
</code>```

Title: Open AppStore through button

Body:
Could you guys help me to translate the following code into Swift?

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms://itunes.apple.com/de/app/x-gift/id839686104?mt=8&uo=4"]];

(or do I have to take this link: itms://itunes.apple.com/app/id839686104?)

Body:
Swift 5.0:

import StoreKit

extension YourViewController: SKStoreProductViewControllerDelegate {
    func openStoreProductWithiTunesItemIdentifier(_ identifier: String) {
        let storeViewController = SKStoreProductViewController()
        storeViewController.delegate = self

        let parameters = [ SKStoreProductParameterITunesItemIdentifier : identifier]
        storeViewController.loadProduct(withParameters: parameters) { [weak self] (loaded, error) -> Void in
            if loaded {
                self?.present(storeViewController, animated: true, completion: nil)
            }
        }
    }
    private func productViewControllerDidFinish(viewController: SKStoreProductViewController) {
        viewController.dismiss(animated: true, completion: nil)
    }
}

// How to use

openStoreProductWithiTunesItemIdentifier("12345")


问:
Can I use a randomly generated number as a parameter to a method in Java?
So I'm very new to Java so this question might have a pretty simple answer. I'm trying to create a Magic8 ball program and I want the fortune to depend on the randomly generated number, but it's treated as a method and I'm not sure that a method can have another method as a parameter.

```<code>public int generator(){
    int num = rnd.nextInt(2) + 1;
return num;
}
</code>```

That's my method to generate the random number, is there a way to use the product of this in another method?

答:
while  defining the method you can do normal defining process such as

```<code>public int doStuffWithRandomNumber(int i){
//your code;
}
</code>```

At the time of calling method you can use generator()  method as parameter

```<code>doStuffWithRandomNumber(generator());
</code>```

it will work properly no issue

Body:
So I'm very new to Java so this question might have a pretty simple answer. I'm trying to create a Magic8 ball program and I want the fortune to depend on the randomly generated number, but it's treated as a method and I'm not sure that a method can have another method as a parameter.

public int generator(){
    int num = rnd.nextInt(2) + 1;
return num;
}

That's my method to generate the random number, is there a way to use the product of this in another method?

Body:
while  defining the method you can do normal defining process such as

public int doStuffWithRandomNumber(int i){
//your code;
}

At the time of calling method you can use generator()  method as parameter

doStuffWithRandomNumber(generator());

it will work properly no issue