问:
OpenCv bitwise Operations physical meaning
I have started with OpenCv pretty recently and the online documentation seems to be pretty good. However there is this one tutorial about image addition and "bitwise operations". I am very badly stuck at the following point

```<code> `# Now black-out the area of logo in ROI
  img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)

  # Take only region of logo from logo image.
  img2_fg = cv2.bitwise_and(img2,img2,mask = mask)`
</code>```

I read about bit wise operations and I understood what they are. But I have not been able to find in really simple language what the above 2 lines are doing? What is the argument mask in the above functions doing?

I am following the following tutorial

http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_core/py_image_arithmetics/py_image_arithmetics.html

If anybody can explain me in really simple language what is happening in these  lines of code or if anyone can point me to a good source that explains it from the very basic, I shall be really grateful.

Regards

Nischal

答:
Create filter to remove the color logo from the original image

```<code># Now black-out the area of logo in ROI
 img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)
</code>```

extract only the logo from the original image

```<code># Take only region of logo from logo image.
img2_fg = cv2.bitwise_and(img2,img2,mask = mask)`
</code>```

Add them up to just extract the logo(color)

To get an in depth information you can use

```<code>help(function)
</code>```

inside python console

```<code>>>> help(cv2.bitwise_and)
Help on built-in function bitwise_and:
</code>```

This is what the out you get hope it helps you understand what exactly is happening

```<code>Help on built-in function bitwise_and:

bitwise_and(...)
bitwise_and(src1, src2[, dst[, mask]]) -> dst
.   @brief computes bitwise conjunction of the two arrays (dst = src1 & src2)
.   Calculates the per-element bit-wise conjunction of two arrays or an
.   array and a scalar.
.
.   The function cv::bitwise_and calculates the per-element bit-wise logical conjunction for:
.   *   Two arrays when src1 and src2 have the same size:
.   \f[\texttt{dst} (I) =  \texttt{src1} (I)  \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
.   *   An array and a scalar when src2 is constructed from Scalar or has
.   the same number of elements as `src1.channels()`:
.   \f[\texttt{dst} (I) =  \texttt{src1} (I)  \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]
.   *   A scalar and an array when src1 is constructed from Scalar or has
.   the same number of elements as `src2.channels()`:
.   \f[\texttt{dst} (I) =  \texttt{src1}  \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
.   In case of floating-point arrays, their machine-specific bit
.   representations (usually IEEE754-compliant) are used for the operation.
.   In case of multi-channel arrays, each channel is processed
.   independently. In the second and third cases above, the scalar is first
.   converted to the array type.
.   @param src1 first input array or a scalar.
.   @param src2 second input array or a scalar.
.   @param dst output array that has the same size and type as the input
.   arrays.
.   @param mask optional operation mask, 8-bit single channel array, that
.   specifies elements of the output array to be changed.
</code>```

Body:
I have started with OpenCv pretty recently and the online documentation seems to be pretty good. However there is this one tutorial about image addition and "bitwise operations". I am very badly stuck at the following point

 `# Now black-out the area of logo in ROI
  img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)

  # Take only region of logo from logo image.
  img2_fg = cv2.bitwise_and(img2,img2,mask = mask)`

I read about bit wise operations and I understood what they are. But I have not been able to find in really simple language what the above 2 lines are doing? What is the argument mask in the above functions doing?

I am following the following tutorial

http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_core/py_image_arithmetics/py_image_arithmetics.html

If anybody can explain me in really simple language what is happening in these  lines of code or if anyone can point me to a good source that explains it from the very basic, I shall be really grateful.

Regards

Nischal

Body:
Create filter to remove the color logo from the original image

# Now black-out the area of logo in ROI
 img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)

extract only the logo from the original image

# Take only region of logo from logo image.
img2_fg = cv2.bitwise_and(img2,img2,mask = mask)`

Add them up to just extract the logo(color)

To get an in depth information you can use

help(function)

inside python console

>>> help(cv2.bitwise_and)
Help on built-in function bitwise_and:

This is what the out you get hope it helps you understand what exactly is happening

Help on built-in function bitwise_and:

bitwise_and(...)
bitwise_and(src1, src2[, dst[, mask]]) -> dst
.   @brief computes bitwise conjunction of the two arrays (dst = src1 & src2)
.   Calculates the per-element bit-wise conjunction of two arrays or an
.   array and a scalar.
.
.   The function cv::bitwise_and calculates the per-element bit-wise logical conjunction for:
.   *   Two arrays when src1 and src2 have the same size:
.   \f[\texttt{dst} (I) =  \texttt{src1} (I)  \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
.   *   An array and a scalar when src2 is constructed from Scalar or has
.   the same number of elements as `src1.channels()`:
.   \f[\texttt{dst} (I) =  \texttt{src1} (I)  \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]
.   *   A scalar and an array when src1 is constructed from Scalar or has
.   the same number of elements as `src2.channels()`:
.   \f[\texttt{dst} (I) =  \texttt{src1}  \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
.   In case of floating-point arrays, their machine-specific bit
.   representations (usually IEEE754-compliant) are used for the operation.
.   In case of multi-channel arrays, each channel is processed
.   independently. In the second and third cases above, the scalar is first
.   converted to the array type.
.   @param src1 first input array or a scalar.
.   @param src2 second input array or a scalar.
.   @param dst output array that has the same size and type as the input
.   arrays.
.   @param mask optional operation mask, 8-bit single channel array, that
.   specifies elements of the output array to be changed.


来源: stackexchange

问:
How Do I list all user pools using AWS Lambda in Nodejs
How do I get List of User Pools from Cognito? Also After getting userpool how do I get list of users in particular userpool?

I am using Nodejs Lambda function to fetch the data from the congnito.

答: Using the CognitoIdentityServiceProvider service, you can call the listUserPools() method to list the user pools associated with your AWS account and get the UserPoolId that you can pass to the listUsers() method to list the users in that Amazon Cognito user pool.

ContentLicense: CC BY-SA 3.0


问:
Protractor Error: Failed to connect, please retry
Using Angular 5, CLI v1.5, running e2e tests. I have run ng serve in another terminal window. When I run the test it opens the browser, logs in, then starts executing - but it always gives the error failed to connect, please retry after around 10 seconds.

We have a fake STS login page that is not Angular, so I have disabled and then re enabled Angular. This all works and it logs in and clicks around, but will error after 10 seconds.

app.e2e-spec.ts:

```<code>import { AppPage } from "./page-objects/app.po";
import { OrderPage } from "./page-objects/order.po";

describe("tslint App", () => {
    let homePage: AppPage;
    let orderPage: OrderPage;

    beforeEach(() => {
        homePage = new AppPage();
        orderPage = new OrderPage();
    });

    it("should navigate around orders", () => {
        homePage.disableAngular();
        homePage.navigateToSTS();
        homePage.selectUser();
        homePage.clickSignIn();
        homePage.enableAngular();
        expect(homePage.getParagraphText()).toEqual("First LAST");
        homePage.clickOrder();
        expect(orderPage.selectHeader()).toEqual("Orders");
        orderDashboardPage.clickCreateOrder();

        [.... etc]
    });
});
</code>```

protractor.conf.js:

```<code>// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts

const { SpecReporter } = require("jasmine-spec-reporter");

exports.config = {
    allScriptsTimeout: 21000,
    specs: ["./js/e2e/**/*.e2e-spec.ts"],
    capabilities: {
        browserName: "chrome"
    },
    useAllAngular2AppRoots: true,
    directConnect: true,
    baseUrl: "http://localhost/",
    framework: "jasmine",
    jasmineNodeOpts: {
        showColors: true,
        defaultTimeoutInterval: 30000,
        print: function() {}
    },
    onPrepare() {
        require("ts-node").register({
            project: "./js/e2e/tsconfig.e2e.json"
        });
        jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
    },
    debug: true,
    nodeDebug: true,
    troubleshoot: true,
};
</code>```

Terminal Output:

```<code>C:\Code\>ng e2e -s false
(node:15364) [DEP0022] DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.
[11:28:37] I/update - chromedriver: file exists C:\Code\node_modules\protractor\node_modules\webdriver-manager\selenium\chromedriver_2.33.zip
[11:28:37] I/update - chromedriver: unzipping chromedriver_2.33.zip
[11:28:37] I/update - chromedriver: chromedriver_2.33.exe up to date
[11:28:37] D/launcher - Running with --troubleshoot
[11:28:37] D/launcher - Protractor version: 5.2.0
[11:28:37] D/launcher - Your base url for tests is http://localhost/
Debugger listening on ws://127.0.0.1:9229/13448c66-b08b-448f-8838-0b1ff17c53c5
For help see https://nodejs.org/en/docs/inspector
[11:28:37] I/launcher - Running 1 instances of WebDriver
(node:18304) [DEP0068] DeprecationWarning: `node debug` is deprecated. Please use `node inspect` instead.
connecting to localhost:5858 ...[11:28:38] I/direct - Using ChromeDriver directly...

DevTools listening on ws://127.0.0.1:12608/devtools/browser/3763eefb-c5ae-4f7d-82bd-c99d98aee99c
.[11:28:39] D/runner - WebDriver session successfully started with capabilities Capabilities {
  map_:
   Map {
     'acceptSslCerts' => true,
     'applicationCacheEnabled' => false,
     'browserConnectionEnabled' => false,
     'browserName' => 'chrome',
     'chrome' => { chromedriverVersion: '2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f)',
     userDataDir: 'C:\\Users\\CONTWE~1\\AppData\\Local\\Temp\\scoped_dir20368_5804' },
     'cssSelectorsEnabled' => true,
     'databaseEnabled' => false,
     'handlesAlerts' => true,
     'hasTouchScreen' => false,
     'javascriptEnabled' => true,
     'locationContextEnabled' => true,
     'mobileEmulationEnabled' => false,
     'nativeEvents' => true,
     'networkConnectionEnabled' => false,
     'pageLoadStrategy' => 'normal',
     'platform' => 'Windows NT',
     'rotatable' => false,
     'setWindowRect' => true,
     'takesHeapSnapshot' => true,
     'takesScreenshot' => true,
     'unexpectedAlertBehaviour' => '',
     'version' => '62.0.3202.94',
     'webStorageEnabled' => true } }
[11:28:39] D/runner - Running with spec files C:\Code\js\e2e\app.e2e-spec.ts
........ failed to connect, please retry
[11:28:52] E/launcher - Process exited with error code 1
</code>```

答:
Try to run webdriver-manager update to install a local chromedriver, then you don't need to set the chromeDriver setting in protractor config

```<code>exports.config = {
  directConnect: true,
  chromeDriver: chromeDriverPath, <--
  specs: [
    'features/*.feature'
  ],
  capabilities: {
    browserName: 'chrome',
    platform: 'ANY',
    chromeOptions: {
      args: ['--test-type']
    }
  }
}
</code>```

Body:
Using Angular 5, CLI v1.5, running e2e tests. I have run ng serve in another terminal window. When I run the test it opens the browser, logs in, then starts executing - but it always gives the error failed to connect, please retry after around 10 seconds.

We have a fake STS login page that is not Angular, so I have disabled and then re enabled Angular. This all works and it logs in and clicks around, but will error after 10 seconds.

app.e2e-spec.ts:

import { AppPage } from "./page-objects/app.po";
import { OrderPage } from "./page-objects/order.po";

describe("tslint App", () => {
    let homePage: AppPage;
    let orderPage: OrderPage;

    beforeEach(() => {
        homePage = new AppPage();
        orderPage = new OrderPage();
    });

    it("should navigate around orders", () => {
        homePage.disableAngular();
        homePage.navigateToSTS();
        homePage.selectUser();
        homePage.clickSignIn();
        homePage.enableAngular();
        expect(homePage.getParagraphText()).toEqual("First LAST");
        homePage.clickOrder();
        expect(orderPage.selectHeader()).toEqual("Orders");
        orderDashboardPage.clickCreateOrder();

        [.... etc]
    });
});

protractor.conf.js:

// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts

const { SpecReporter } = require("jasmine-spec-reporter");

exports.config = {
    allScriptsTimeout: 21000,
    specs: ["./js/e2e/**/*.e2e-spec.ts"],
    capabilities: {
        browserName: "chrome"
    },
    useAllAngular2AppRoots: true,
    directConnect: true,
    baseUrl: "http://localhost/",
    framework: "jasmine",
    jasmineNodeOpts: {
        showColors: true,
        defaultTimeoutInterval: 30000,
        print: function() {}
    },
    onPrepare() {
        require("ts-node").register({
            project: "./js/e2e/tsconfig.e2e.json"
        });
        jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
    },
    debug: true,
    nodeDebug: true,
    troubleshoot: true,
};

Terminal Output:

C:\Code\>ng e2e -s false
(node:15364) [DEP0022] DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.
[11:28:37] I/update - chromedriver: file exists C:\Code\node_modules\protractor\node_modules\webdriver-manager\selenium\chromedriver_2.33.zip
[11:28:37] I/update - chromedriver: unzipping chromedriver_2.33.zip
[11:28:37] I/update - chromedriver: chromedriver_2.33.exe up to date
[11:28:37] D/launcher - Running with --troubleshoot
[11:28:37] D/launcher - Protractor version: 5.2.0
[11:28:37] D/launcher - Your base url for tests is http://localhost/
Debugger listening on ws://127.0.0.1:9229/13448c66-b08b-448f-8838-0b1ff17c53c5
For help see https://nodejs.org/en/docs/inspector
[11:28:37] I/launcher - Running 1 instances of WebDriver
(node:18304) [DEP0068] DeprecationWarning: `node debug` is deprecated. Please use `node inspect` instead.
connecting to localhost:5858 ...[11:28:38] I/direct - Using ChromeDriver directly...

DevTools listening on ws://127.0.0.1:12608/devtools/browser/3763eefb-c5ae-4f7d-82bd-c99d98aee99c
.[11:28:39] D/runner - WebDriver session successfully started with capabilities Capabilities {
  map_:
   Map {
     'acceptSslCerts' => true,
     'applicationCacheEnabled' => false,
     'browserConnectionEnabled' => false,
     'browserName' => 'chrome',
     'chrome' => { chromedriverVersion: '2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f)',
     userDataDir: 'C:\\Users\\CONTWE~1\\AppData\\Local\\Temp\\scoped_dir20368_5804' },
     'cssSelectorsEnabled' => true,
     'databaseEnabled' => false,
     'handlesAlerts' => true,
     'hasTouchScreen' => false,
     'javascriptEnabled' => true,
     'locationContextEnabled' => true,
     'mobileEmulationEnabled' => false,
     'nativeEvents' => true,
     'networkConnectionEnabled' => false,
     'pageLoadStrategy' => 'normal',
     'platform' => 'Windows NT',
     'rotatable' => false,
     'setWindowRect' => true,
     'takesHeapSnapshot' => true,
     'takesScreenshot' => true,
     'unexpectedAlertBehaviour' => '',
     'version' => '62.0.3202.94',
     'webStorageEnabled' => true } }
[11:28:39] D/runner - Running with spec files C:\Code\js\e2e\app.e2e-spec.ts
........ failed to connect, please retry
[11:28:52] E/launcher - Process exited with error code 1

Body:
Try to run webdriver-manager update to install a local chromedriver, then you don't need to set the chromeDriver setting in protractor config

exports.config = {
  directConnect: true,
  chromeDriver: chromeDriverPath, <--
  specs: [
    'features/*.feature'
  ],
  capabilities: {
    browserName: 'chrome',
    platform: 'ANY',
    chromeOptions: {
      args: ['--test-type']
    }
  }
}


问:
Mongodb lookup and get output flat tree structure?
I have two collections points collection and users collection here i want to do aggregation based on userid.

here i am trying aggregation and everything is working fine but i need to modify result

```<code>db.points.aggregate([
     $match: {
      store: "001",
      date: {$lte: ISODate("2017-11-10T08:15:39.736Z"), $gte: ISODate("2017-11-10T08:15:39.736Z")}
    },

    {
    $lookup: {
      from: "users",
      localField: "userid",
      foreignField: "_id",
      as: "user"
    }
  },

   {

       $project:

       {

       _id:0,
       "userdata.purchasedetails.purchaseid" : 1,
       "userdata.purchasedetails.data" : 1,
       usermobinumber: { "$arrayElemAt": [ "$user.mobinumber", 0 ] }

    }}
</code>```

Data stored like this

```<code>{
    "userpoint": "2",
    "date":ISODate("2017-11-10T08:15:39.736Z"),
    "store":"001",
    "userid":[
    objectID("5a7565ug8945rt67"),
    objectID("8a35553d3446rt78")
    ],
    "userdata":{
        "profile":[],
        "purchasedetails":
        [{
                "purchaseid":"dj04944",
                "data":"awe"

        }]
    }
}
</code>```

getting result like this :

```<code>{
"usermobinumber":"9611",
"userdata":{
        "purchasedetails":
        [{
                "purchaseid":"dj04944",
                "data":"awe"

        }]
}
</code>```

my expecting result:

I dont want tree structure output i need like this

```<code>{
 "usermobinumber":"9611",
 "purchaseid":"dj04944",
 "data":"awe"
 }
</code>```

how can i do this help me out

答:
You can do something like this here,

```<code>db.points.aggregate([
    //Whatever you are doing here now (lookup and match)
    {
        $project:{
            "usermobinumber":"$usermobinumber",
            "purchaseid":"$userdata.purchasedetails.purchaseid"
        }
    }
])
</code>```

This will give you:

```<code>{
    "usermobinumber" : "9611",
    "purchaseid" : [
        "dj04944"
  ]
}
</code>```

EDIT:

```<code>db.points.aggregate([
        //Whatever you are doing here now (lookup and match)
        {
            {
             $project:{
                 "usermobinumber":"$usermobinumber",
                 "purchaseid":"$userdata.purchasedetails.purchaseid",
                 "data":"$userdata.purchasedetails.data"
               }
            }
        }
    ])
</code>```

This will give you

```<code>{
 "usermobinumber":"9611",
 "purchaseid":["dj04944"],
 "data":["awe"]
 }
</code>```

purchaseid and data are array because purchasedetails is an array.

Body:
I have two collections points collection and users collection here i want to do aggregation based on userid.

here i am trying aggregation and everything is working fine but i need to modify result

db.points.aggregate([
     $match: {
      store: "001",
      date: {$lte: ISODate("2017-11-10T08:15:39.736Z"), $gte: ISODate("2017-11-10T08:15:39.736Z")}
    },

    {
    $lookup: {
      from: "users",
      localField: "userid",
      foreignField: "_id",
      as: "user"
    }
  },

   {

       $project:

       {

       _id:0,
       "userdata.purchasedetails.purchaseid" : 1,
       "userdata.purchasedetails.data" : 1,
       usermobinumber: { "$arrayElemAt": [ "$user.mobinumber", 0 ] }

    }}

Data stored like this

{
    "userpoint": "2",
    "date":ISODate("2017-11-10T08:15:39.736Z"),
    "store":"001",
    "userid":[
    objectID("5a7565ug8945rt67"),
    objectID("8a35553d3446rt78")
    ],
    "userdata":{
        "profile":[],
        "purchasedetails":
        [{
                "purchaseid":"dj04944",
                "data":"awe"

        }]
    }
}

getting result like this :

{
"usermobinumber":"9611",
"userdata":{
        "purchasedetails":
        [{
                "purchaseid":"dj04944",
                "data":"awe"

        }]
}

my expecting result:

I dont want tree structure output i need like this

{
 "usermobinumber":"9611",
 "purchaseid":"dj04944",
 "data":"awe"
 }

how can i do this help me out

Body:
You can do something like this here,

db.points.aggregate([
    //Whatever you are doing here now (lookup and match)
    {
        $project:{
            "usermobinumber":"$usermobinumber",
            "purchaseid":"$userdata.purchasedetails.purchaseid"
        }
    }
])

This will give you:

{
    "usermobinumber" : "9611",
    "purchaseid" : [
        "dj04944"
  ]
}

EDIT:

db.points.aggregate([
        //Whatever you are doing here now (lookup and match)
        {
            {
             $project:{
                 "usermobinumber":"$usermobinumber",
                 "purchaseid":"$userdata.purchasedetails.purchaseid",
                 "data":"$userdata.purchasedetails.data"
               }
            }
        }
    ])

This will give you

{
 "usermobinumber":"9611",
 "purchaseid":["dj04944"],
 "data":["awe"]
 }

purchaseid and data are array because purchasedetails is an array.


问:
How to select foreign key value in Laravel
I've two tables one is car_category having the fields - id,type.
Another table named  vehicle having field - c_id(FK Refers car - id).
Now I want to display the FK(c_id) value which is car-type.
I've below code in models,

```<code>class Car extends Model
{
    protected $guarded = [];
    protected $table = 'car_category';

    public function vehicles()
    {
        return $this->hasMany('Vehicle');
    }
}
</code>```

vehicle model,

```<code>class Vehicle extends Model
{
    protected $guarded = [];
    protected $table = 'vehicles';
    public function cars()
    {
        return $this->belongsTo('Car');
    }
}
</code>```

What 'll be my query for this? I've tried this code, results error.

```<code>$vehicles = "SELECT cars.cartype,vehicles.model FROM cars,vehicles
             WHERE cars.id = vehicles.c_id";
</code>```

How can I achieve this? Can anybody help me?

答:
Try this

```<code>class Car extends Model
{
protected $guarded = [];
protected $table = 'car_category';

 public function vehicles()
 {
   return $this->hasMany(Vehicle::class, 'c_id');
 }
}
</code>```

The vehicle model

```<code> class Vehicle extends Model
 {
  protected $guarded = [];
  protected $table = 'vehicles';

  public function cars()
  {
    return $this->belongsTo(Car::class, 'c_id');
  }
 }
</code>```

Eloquent determines the foreign key of the relationship based on the model name. In this case, the  Car model is automatically assumed to have a car_id foreign key. If you wish to override this convention, you may pass a second argument to the method

https://laravel.com/docs/5.5/eloquent-relationships#one-to-one

To get the Car along with their Vehicle information you can do a query using Eager Loading

```<code>$result = Car::with('vehicles')->get();
</code>```

Body:
I've two tables one is car_category having the fields - id,type.
Another table named  vehicle having field - c_id(FK Refers car - id).
Now I want to display the FK(c_id) value which is car-type.
I've below code in models,

class Car extends Model
{
    protected $guarded = [];
    protected $table = 'car_category';

    public function vehicles()
    {
        return $this->hasMany('Vehicle');
    }
}

vehicle model,

class Vehicle extends Model
{
    protected $guarded = [];
    protected $table = 'vehicles';
    public function cars()
    {
        return $this->belongsTo('Car');
    }
}

What 'll be my query for this? I've tried this code, results error.

$vehicles = "SELECT cars.cartype,vehicles.model FROM cars,vehicles
             WHERE cars.id = vehicles.c_id";

How can I achieve this? Can anybody help me?

Body:
Try this

class Car extends Model
{
protected $guarded = [];
protected $table = 'car_category';

 public function vehicles()
 {
   return $this->hasMany(Vehicle::class, 'c_id');
 }
}

The vehicle model

 class Vehicle extends Model
 {
  protected $guarded = [];
  protected $table = 'vehicles';

  public function cars()
  {
    return $this->belongsTo(Car::class, 'c_id');
  }
 }

Eloquent determines the foreign key of the relationship based on the model name. In this case, the  Car model is automatically assumed to have a car_id foreign key. If you wish to override this convention, you may pass a second argument to the method

https://laravel.com/docs/5.5/eloquent-relationships#one-to-one

To get the Car along with their Vehicle information you can do a query using Eager Loading

$result = Car::with('vehicles')->get();


问:
What benefits do Java serial port libraries have over plain IO to the device?
There is a lot of talk about Java serial port libraries like RXTX and JSSC, but what do they really provide?  In both linux and windows you can simply open the serial port like a file for reading and writing, can't you?  What is the advantage of using the libraries over just reading and writing from the device with file IO?

I understand that the libraries allow you to configure the ports, which would normally need to be done by commandline calls.  But assuming the ports are already configured, is there any reason to use the libraries?

答:
Following is a quick list of why we may consider a library but largely I feel that if we are making a commercial product than ready made libraries may be good choice otherwise as a learner we can write our own.

Uniformity across various operating systems. We have to write code for all supported OS which is a task in itself.

The library authors may have more experience in that particular topic so quality might be better than us.

Time to finish project (time to market) is another factor.

Comprehensive test suite

Beyond simple read/write can be extra features especially in case of GUI driven products like hot plugging and visual indications etc.

Library might implement protocols or specifications means simple read/write may come wrapped in stream where the serial port specific things are hidden and a uniform layer is exposed to app.

Support for wider range of hardware devices esp USB-UART
Take a look at these 2 open source libraries 1st library and 2nd library

Support for both Embedded and Desktop OS


问:
How to get the location of the DLL currently executing?
I have a config file that I need to load as part of the execution of a dll I am writing.

The problem I am having is that the place I put the dll and config file is not the "current location" when the app is running.

For example, I put the dll and xml file here:

D:\Program Files\Microsoft Team Foundation Server 2010\Application Tier\Web Services\bin\Plugins

But if I try to reference the xml file (in my dll) like this:

```<code>XDocument doc = XDocument.Load(@".\AggregatorItems.xml")
</code>```

then .\AggregatorItems.xml translates to:

C:\windows\system32\inetsrv\AggregatorItems.xml

So, I need to find a way (I hope) of knowing where the dll that is currently executing is located.  Basically I am looking for this:

```<code>XDocument doc = XDocument.Load(CoolDLLClass.CurrentDirectory+@"\AggregatorItems.xml")
</code>```

答:
Reflection is your friend, as has been pointed out. But you need to use the correct method;</p>

```<code>Assembly.GetEntryAssembly()     //gives you the entrypoint assembly for the process.
Assembly.GetCallingAssembly()   // gives you the assembly from which the current method was called.
Assembly.GetExecutingAssembly() // gives you the assembly in which the currently executing code is defined
Assembly.GetAssembly( Type t )  // gives you the assembly in which the specified type is defined.
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a config file that I need to load as part of the execution of a dll I am writing.

The problem I am having is that the place I put the dll and config file is not the "current location" when the app is running.

For example, I put the dll and xml file here:

D:\Program Files\Microsoft Team Foundation Server 2010\Application Tier\Web Services\bin\Plugins

But if I try to reference the xml file (in my dll) like this:

XDocument doc = XDocument.Load(@".\AggregatorItems.xml")

then .\AggregatorItems.xml translates to:

C:\windows\system32\inetsrv\AggregatorItems.xml

So, I need to find a way (I hope) of knowing where the dll that is currently executing is located.  Basically I am looking for this:

XDocument doc = XDocument.Load(CoolDLLClass.CurrentDirectory+@"\AggregatorItems.xml")

Body:
Reflection is your friend, as has been pointed out. But you need to use the correct method;

Assembly.GetEntryAssembly()     //gives you the entrypoint assembly for the process.
Assembly.GetCallingAssembly()   // gives you the assembly from which the current method was called.
Assembly.GetExecutingAssembly() // gives you the assembly in which the currently executing code is defined
Assembly.GetAssembly( Type t )  // gives you the assembly in which the specified type is defined.


问:
Packing properties into type object and return it as result of method
I would like to create instance of type object in method, add to It two properties and return object as result of method.

```<code>public object method()
{
TypeOfClassA a;
int b;
if(method(out a, out b))
{
res = new {a=a, b=b};
}
return res;
}
</code>```

Something like this

答:
Your problem is the return statement. If you do not enter the if-body, the variable res is undeclared

```<code>public object method()
{
    TypeOfClassA a;
    int b;
    if(method(out a, out b))
    {
        res = new {a=a, b=b};
        return res;
    }

    return null;
}
</code>```

In the adjusted snippet we only return res, if it was created. Otherwise, we return null.

Body:
I would like to create instance of type object in method, add to It two properties and return object as result of method.

public object method()
{
TypeOfClassA a;
int b;
if(method(out a, out b))
{
res = new {a=a, b=b};
}
return res;
}

Something like this

Body:
Your problem is the return statement. If you do not enter the if-body, the variable res is undeclared

public object method()
{
    TypeOfClassA a;
    int b;
    if(method(out a, out b))
    {
        res = new {a=a, b=b};
        return res;
    }

    return null;
}

In the adjusted snippet we only return res, if it was created. Otherwise, we return null.


问:
Is there a browser based IDE for Python like RStudio server for R?
I am familiar with the RStudio server and it is a great tool for R statistical development in remote linux environment.

Just being curious if there is a similar server side IDE for Python development (web browser based)?

答:
Jupyterlab is due to release it's beta release in 31 Dec. 2017, it should be the most similar to RStudio server and probably the most advanced browser based IDE for Python

EDIT:
According to their Github page, it is now out of beta and ready for users.

EDIT 2:
According to their Github page, it is already stable for general use.

ContentLicense: CC BY-SA 4.0


问:
Making Tabs Swipeable in Jquery Mobile
How to make the tabs in the JQ Mobile Navbar swipeable ? Is there  any inbuilt way of adding a attribute to the  div of nav-bar or Should we write any JQuery function?.
     JSFiddle Here</p>

```<code> <div data-role="tabs" id="tabs">

        <div data-role="navbar" >

            <ul>

                <li><a href="#clothing" data-ajax="false">Men</a>
   </li>
                <li><a href="#footwear" data-ajax="false">Women</a>
  </li>
                <li><a href="#accessories" data-
   ajax="false">Kids</a></li>
            </ul>

        </div>
</code>```

答:
Try Below working Example, use it's code :</p>

```<code>    <html>
    <head>
      <title>Swipe tab</title>
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js"></script>
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mobile/1.4.5/jquery.mobile.js"></script>
      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-mobile/1.4.5/jquery.mobile.min.css">
    </head>
    <body>
    <div data-role="page" id="lessonhomepage">
      <!--content start-->
      <div data-role="content" id="tabscontent">
        <!--horizontal navigation tab start-->
        <div data-role="tabs" id="tabs">
          <div data-role="navbar" id="nav">
            <ul>
              <li><a class="ui-btn-active" href="#study" data-ajax="false">Study</a>
              </li>
              <li><a href="#quicktips" data-ajax="false">Quick Tips</a>
              </li>
              <li><a href="#quicktips3" data-ajax="false">Quick Tips</a>
              </li>
              <li><a href="#quicktips4" data-ajax="false">Quick Tips</a>
              </li>

            </ul>
          </div>
          <div id="study">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
          </div>
          <div id="quicktips">
           There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
          </div>
          <div id="quicktips3">
           There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
          </div>
          <div id="quicktips4">
           There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
          </div>
          <div id="quicktips5">
           There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
          </div>
          <div id="quicktips6">
           There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
          </div>

          <!--horizontal navigation tab end-->
          <br/>
        </div>
      </div>
    </div>
    <script type="text/javascript">
     var panel = '<div data-theme="a" data-role="panel" data-display="overlay" id="leftpanel">sdf</div>';

     $(function() {
       $("body").prepend(panel);
       $("[data-role=panel]").panel().enhanceWithin();
     });

     var nextidx = 0;

     function changeNavTab(left) {
       var $tabs = $("div[data-role=navbar] li a", $("div[data-role=page].ui-page-active"));
       var curidx = $tabs.closest("a.ui-btn-active").parent().index();

       var tabcount = $tabs.length;

       if (left) {

           if (nextidx == tabcount - 1) {
               return(false);
            }
           else {
            nextidx = (curidx == $tabs.length - 1) ? 0 : curidx + 1;

            }

       } else {
          if (nextidx ==  0) {

               return(false);
            }
           else {
               nextidx = (curidx == 0) ? $tabs.length - 1 : curidx - 1;

            }

       }
       $tabs.eq(nextidx).click();
     }

     $("div[data-role=content]").on("swipeleft", function(event) {
       changeNavTab(true);
     });
     $("div[data-role=content]").on("swiperight", function(event) {
       changeNavTab(false);
     });

     // Navigation  Drawer Swipe Listener
     $("div[data-role=header]").on("swipeleft swiperight", function(e) {
       // save swipe direction right/left
       var dir = 'prev';
       if (e.type == 'swiperight') {
         dir = 'next';
       }
       if (dir == 'prev') {
         $('#leftpanel').panel('close');

       } else {
         $('#leftpanel').panel('open');

       }
     });

    </script>
    </body>
    </html>
</code>```

Title: Making Tabs Swipeable in Jquery Mobile

Body:
How to make the tabs in the JQ Mobile Navbar swipeable ? Is there  any inbuilt way of adding a attribute to the  div of nav-bar or Should we write any JQuery function?.
     JSFiddle Here

Men

Women

Kids

Body:
Try Below working Example, use it's code :

    <html>
    <head>
      <title>Swipe tab</title>
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js"></script>
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mobile/1.4.5/jquery.mobile.js"></script>
      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-mobile/1.4.5/jquery.mobile.min.css">
    </head>
    <body>
    <div data-role="page" id="lessonhomepage">
      <!--content start-->
      <div data-role="content" id="tabscontent">
        <!--horizontal navigation tab start-->
        <div data-role="tabs" id="tabs">
          <div data-role="navbar" id="nav">
            <ul>
              <li><a class="ui-btn-active" href="#study" data-ajax="false">Study</a>
              </li>
              <li><a href="#quicktips" data-ajax="false">Quick Tips</a>
              </li>
              <li><a href="#quicktips3" data-ajax="false">Quick Tips</a>
              </li>
              <li><a href="#quicktips4" data-ajax="false">Quick Tips</a>
              </li>

            </ul>
          </div>
          <div id="study">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
          </div>
          <div id="quicktips">
           There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
          </div>
          <div id="quicktips3">
           There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
          </div>
          <div id="quicktips4">
           There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
          </div>
          <div id="quicktips5">
           There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
          </div>
          <div id="quicktips6">
           There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
          </div>

          <!--horizontal navigation tab end-->
          <br/>
        </div>
      </div>
    </div>
    <script type="text/javascript">
     var panel = '<div data-theme="a" data-role="panel" data-display="overlay" id="leftpanel">sdf</div>';

     $(function() {
       $("body").prepend(panel);
       $("[data-role=panel]").panel().enhanceWithin();
     });

     var nextidx = 0;

     function changeNavTab(left) {
       var $tabs = $("div[data-role=navbar] li a", $("div[data-role=page].ui-page-active"));
       var curidx = $tabs.closest("a.ui-btn-active").parent().index();

       var tabcount = $tabs.length;

       if (left) {

           if (nextidx == tabcount - 1) {
               return(false);
            }
           else {
            nextidx = (curidx == $tabs.length - 1) ? 0 : curidx + 1;

            }

       } else {
          if (nextidx ==  0) {

               return(false);
            }
           else {
               nextidx = (curidx == 0) ? $tabs.length - 1 : curidx - 1;

            }

       }
       $tabs.eq(nextidx).click();
     }

     $("div[data-role=content]").on("swipeleft", function(event) {
       changeNavTab(true);
     });
     $("div[data-role=content]").on("swiperight", function(event) {
       changeNavTab(false);
     });

     // Navigation  Drawer Swipe Listener
     $("div[data-role=header]").on("swipeleft swiperight", function(e) {
       // save swipe direction right/left
       var dir = 'prev';
       if (e.type == 'swiperight') {
         dir = 'next';
       }
       if (dir == 'prev') {
         $('#leftpanel').panel('close');

       } else {
         $('#leftpanel').panel('open');

       }
     });

    </script>
    </body>
    </html>


问:
How to find the average runtime of this function to be $\theta$(1)
def search(lst, x):

```<code>for item in lst:

  if item == x:

     return True

  return False
</code>```

If the allowed input is a random list of length n made up of random elements from {1,2,...10}

How do I prove that the average runtime is big-theta(1)

I've tried so many ways but I keep on getting big-theta(n)

答: If the random method be uniform, it means that The expected number of 1's in list is n/10, the expected number of 2's is n/10 and so on. Again based on uniform random you expect that find x after checking 10 elements on worst case. So the method has the expected constant time value and the Complexity is Tetha(1).</p>

Body:
def search(lst, x):

for item in lst:

  if item == x:

     return True

  return False

If the allowed input is a random list of length n made up of random elements from {1,2,...10}

How do I prove that the average runtime is big-theta(1)

I've tried so many ways but I keep on getting big-theta(n)


问:
automatic href to div when page loaded
I have html code

```<code><h1>Popup/Modal Windows without JavaScript</h1>
<div class="box">
<a class="button" href="#popup1">Let me Pop up</a>
</div>

<div id="popup1" class="overlay">
  <div class="popup">
    <h2>Here i am</h2>
    <a class="close" href="#">×</a>
    <div class="content">
        Thank to pop me out of that button, but now i'm done so you can
    </div>
  </div>
</div>
</code>```

I want popup window show when page is loaded. not waiting when i click to button. How to make with javascript or jquery? This example i found in here

答:
Try this, you would want your popup to be initially hidden. Then when the content is loaded you would want to set the display property of the popup to block

CSS

```<code>#popup1 {
    display: none;
}
</code>```

JS

```<code>window.onload = function () {
    document.getElementById("popup1").style.display = "block";
};
</code>```

Title: automatic href to div when page loaded

Body:
I have html code

Popup/Modal Windows without JavaScript

Let me Pop up

Here i am

    ×

        Thank to pop me out of that button, but now i'm done so you can

I want popup window show when page is loaded. not waiting when i click to button. How to make with javascript or jquery? This example i found in here

Body:
Try this, you would want your popup to be initially hidden. Then when the content is loaded you would want to set the display property of the popup to block

CSS

#popup1 {
    display: none;
}

JS

window.onload = function () {
    document.getElementById("popup1").style.display = "block";
};


问:
Can not run middleman server (bundle install now work)
I have problems with the launch of the server at middleman.
Please help. I ask not strictly, this is a new thing for me. I use linux mint now...
hoped that it would help me at this theme on stackoverflow But this not working for me... And bundle update && bundle install, not work to...

sudo apt-get install ruby-dev

The ruby-dev package of the newest version (1: 2.3.0 + 1) has already been installed.

commands and console output which I used:

$ bundle exec middleman server

```<code>Could not find json-1.8.1 in any of the sources
Run `bundle install` to install missing gems.
</code>```

$ sudo bundle install

```<code>[sudo] пароль для user:
Don't run Bundler as root. Bundler can ask for sudo if it is needed, and
installing your bundle as root will break this application for all non-root
users on this machine.
Fetching gem metadata from http://rubygems.org/............
Using i18n 0.6.11
Fetching json 1.8.1
Installing json 1.8.1 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory:
/var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
/usr/bin/ruby2.3 -r ./siteconf20171204-6004-665r95.rb extconf.rb
creating Makefile

current directory: /var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
make "DESTDIR=" clean

current directory: /var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
make "DESTDIR="
compiling generator.c
In file included from generator.c:1:0:
../fbuffer/fbuffer.h: In function ‘fbuffer_to_s’:
../fbuffer/fbuffer.h:175:47: error: macro "rb_str_new" requires 2 arguments, but
only 1 given
     VALUE result = rb_str_new(FBUFFER_PAIR(fb));
                                           ^
../fbuffer/fbuffer.h:175:20: warning: initialization makes integer from pointer
without a cast [-Wint-conversion]
     VALUE result = rb_str_new(FBUFFER_PAIR(fb));
                ^
Makefile:239: ошибка выполнения рецепта для цели «generator.o»
make: *** [generator.o] Ошибка 1

make failed, exit code 2

Gem files will remain installed in /var/lib/gems/2.3.0/gems/json-1.8.1 for
inspection.
Results logged to
/var/lib/gems/2.3.0/extensions/x86-linux/2.3.0/json-1.8.1/gem_make.out

An error occurred while installing json (1.8.1), and Bundler cannot
continue.
Make sure that `gem install json -v '1.8.1'` succeeds before bundling.

In Gemfile:
  middleman was resolved to 3.3.5, which depends on
    middleman-sprockets was resolved to 3.3.7, which depends on
      middleman-core was resolved to 3.3.5, which depends on
        padrino-helpers was resolved to 0.12.3, which depends on
          padrino-support was resolved to 0.12.3, which depends on
            activesupport was resolved to 4.1.5, which depends on
              json
</code>```

ok... i wrote in conlose:

$ gem install json -v '1.8.1

```<code>ERROR:  While executing gem ... (Gem::FilePermissionError)
    You don't have write permissions for the /var/lib/gems/2.3.0 directory.
</code>```

ok... no problem!

$ sudo gem install json -v '1.8.1'

```<code>Building native extensions.  This could take a while...
ERROR:  Error installing json:
    ERROR: Failed to build gem native extension.

    current directory: /var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
/usr/bin/ruby2.3 -r ./siteconf20171204-6068-15letpl.rb extconf.rb
creating Makefile

current directory: /var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
make "DESTDIR=" clean

current directory: /var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
make "DESTDIR="
compiling generator.c
In file included from generator.c:1:0:
../fbuffer/fbuffer.h: In function ‘fbuffer_to_s’:
../fbuffer/fbuffer.h:175:47: error: macro "rb_str_new" requires 2 arguments, but only 1 given
     VALUE result = rb_str_new(FBUFFER_PAIR(fb));
                                               ^
../fbuffer/fbuffer.h:175:20: warning: initialization makes integer from pointer without a cast [-Wint-conversion]
     VALUE result = rb_str_new(FBUFFER_PAIR(fb));
                    ^
Makefile:239: ошибка выполнения рецепта для цели «generator.o»
make: *** [generator.o] Ошибка 1

make failed, exit code 2

Gem files will remain installed in /var/lib/gems/2.3.0/gems/json-1.8.1 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86-linux/2.3.0/json-1.8.1/gem_make.out`enter code here`
</code>```

eahh...

if i use command

$ bundle update

i see next:

```<code>The dependency wdm (~> 0.1.0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mswin32, x86-mingw32. To add those platforms to the bundle, run `bundle lock --add-platform x86-mswin32 x86-mingw32`.
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mswin32, x86-mingw32. To add those platforms to the bundle, run `bundle lock --add-platform x86-mswin32 x86-mingw32`.
Fetching gem metadata from http://rubygems.org/............
Fetching gem metadata from http://rubygems.org/.
Resolving dependencies....
Using i18n 0.7.0 (was 0.6.11)
Using json 1.8.6 (was 1.8.1)
Using minitest 5.10.3 (was 5.4.0)
Using thread_safe 0.3.6 (was 0.3.4)
Using tzinfo 1.2.4 (was 1.2.2)
Using activesupport 4.1.16 (was 4.1.5)
Using builder 3.2.3 (was 3.2.2)
Using bundler 1.16.0
Using hitimes 1.2.6
Using timers 4.0.4 (was 1.1.0)
Using celluloid 0.16.0 (was 0.15.2)
Using chunky_png 1.3.8 (was 1.3.1)
Using coffee-script-source 1.12.2 (was 1.7.1)
Using execjs 2.7.0 (was 2.2.1)
Using coffee-script 2.4.1 (was 2.3.0)
Using multi_json 1.12.2 (was 1.10.1)
Using sass 3.4.25 (was 3.3.14)
Using compass-core 1.0.3 (was 1.0.0)
Using compass-import-once 1.0.5
Using rb-fsevent 0.10.2 (was 0.9.4)
Using ffi 1.9.18 (was 1.9.3)
Using rb-inotify 0.9.10 (was 0.9.5)
Using compass 1.0.3 (was 1.0.0)
Fetching eventmachine 1.2.5 (was 1.0.3)
Installing eventmachine 1.2.5 (was 1.0.3) with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /var/lib/gems/2.3.0/gems/eventmachine-1.2.5/ext
/usr/bin/ruby2.3 -r ./siteconf20171204-9122-1fcu0r1.rb extconf.rb
checking for main() in -lcrypto... no
checking for openssl/ssl.h... no
checking for main() in -lcrypto... no
checking for openssl/ssl.h... no
checking for main() in -lcrypto... no
checking for openssl/ssl.h... no
checking for main() in -lcrypto... no
checking for openssl/ssl.h... no
checking for rb_trap_immediate in ruby.h,rubysig.h... no
checking for rb_thread_blocking_region()... no
checking for rb_thread_call_without_gvl() in ruby/thread.h... yes
checking for rb_thread_fd_select()... yes
checking for rb_fdset_t in ruby/intern.h... yes
checking for rb_wait_for_single_fd()... yes
checking for rb_enable_interrupt()... no
checking for rb_time_new()... yes
checking for inotify_init() in sys/inotify.h... yes
checking for writev() in sys/uio.h... yes
checking for pipe2() in unistd.h... yes
checking for accept4() in sys/socket.h... yes
checking for SOCK_CLOEXEC in sys/socket.h... yes
checking for sys/event.h... no
checking for epoll_create() in sys/epoll.h... yes
checking for clock_gettime()... yes
checking for CLOCK_MONOTONIC_RAW in time.h... yes
checking for CLOCK_MONOTONIC in time.h... yes
CXXFLAGS=-g -O2 -fstack-protector-strong -Wformat -Werror=format-security
creating Makefile

To see why this extension failed to compile, please check the mkmf.log which can
be found here:

  /var/lib/gems/2.3.0/extensions/x86-linux/2.3.0/eventmachine-1.2.5/mkmf.log

current directory: /var/lib/gems/2.3.0/gems/eventmachine-1.2.5/ext
make "DESTDIR=" clean

current directory: /var/lib/gems/2.3.0/gems/eventmachine-1.2.5/ext
make "DESTDIR="
compiling binder.cpp
make: g++: Команда не найдена
Makefile:231: ошибка выполнения рецепта для цели «binder.o»
make: *** [binder.o] Ошибка 127

make failed, exit code 2

Gem files will remain installed in /var/lib/gems/2.3.0/gems/eventmachine-1.2.5
for inspection.
Results logged to
/var/lib/gems/2.3.0/extensions/x86-linux/2.3.0/eventmachine-1.2.5/gem_make.out

An error occurred while installing eventmachine (1.2.5), and Bundler
cannot continue.
Make sure that `gem install eventmachine -v '1.2.5'` succeeds before
bundling.

In Gemfile:
  middleman-livereload was resolved to 3.1.1, which depends on
    em-websocket was resolved to 0.5.1, which depends on
      eventmachine
</code>```

or

$ bundle install

```<code>Don't run Bundler as root. Bundler can ask for sudo if it is needed, and
installing your bundle as root will break this application for all non-root
users on this machine.
Fetching gem metadata from http://rubygems.org/............
Using i18n 0.6.11
Fetching json 1.8.1
Installing json 1.8.1 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory:
/var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
/usr/bin/ruby2.3 -r ./siteconf20171204-9328-qz84bl.rb extconf.rb
creating Makefile

current directory: /var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
make "DESTDIR=" clean

current directory: /var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
make "DESTDIR="
compiling generator.c
In file included from generator.c:1:0:
../fbuffer/fbuffer.h: In function ‘fbuffer_to_s’:
../fbuffer/fbuffer.h:175:47: error: macro "rb_str_new" requires 2 arguments, but
only 1 given
     VALUE result = rb_str_new(FBUFFER_PAIR(fb));
                                               ^
../fbuffer/fbuffer.h:175:20: warning: initialization makes integer from pointer
without a cast [-Wint-conversion]
     VALUE result = rb_str_new(FBUFFER_PAIR(fb));
                    ^
Makefile:239: ошибка выполнения рецепта для цели «generator.o»
make: *** [generator.o] Ошибка 1

make failed, exit code 2

Gem files will remain installed in /var/lib/gems/2.3.0/gems/json-1.8.1 for
inspection.
Results logged to
/var/lib/gems/2.3.0/extensions/x86-linux/2.3.0/json-1.8.1/gem_make.out

An error occurred while installing json (1.8.1), and Bundler cannot
continue.
Make sure that `gem install json -v '1.8.1'` succeeds before bundling.

In Gemfile:
  middleman was resolved to 3.3.5, which depends on
    middleman-sprockets was resolved to 3.3.7, which depends on
      middleman-core was resolved to 3.3.5, which depends on
        padrino-helpers was resolved to 0.12.3, which depends on
          padrino-support was resolved to 0.12.3, which depends on
            activesupport was resolved to 4.1.5, which depends on
              json
</code>```

some vicious circle

答:
the problem was very banal: g ++ not found.

the decision is simple:

on the first

$ sudo apt-get install build-essential

Secondly

$ sudo gem install eventmachine -v '1.2.5'

Thirdly

$ sudo bundle update

in the fourth

$ sudo bundle install

in fifth -
cd to u middleman project and finally

$ bundle exec middleman server

Work on Linux Mint 18.3 Sylvia (mate 32bit)

thanks to all.

Body:
I have problems with the launch of the server at middleman.
Please help. I ask not strictly, this is a new thing for me. I use linux mint now...
hoped that it would help me at this theme on stackoverflow But this not working for me... And bundle update && bundle install, not work to...

sudo apt-get install ruby-dev

The ruby-dev package of the newest version (1: 2.3.0 + 1) has already been installed.

commands and console output which I used:

$ bundle exec middleman server

Could not find json-1.8.1 in any of the sources
Run `bundle install` to install missing gems.

$ sudo bundle install

[sudo] пароль для user:
Don't run Bundler as root. Bundler can ask for sudo if it is needed, and
installing your bundle as root will break this application for all non-root
users on this machine.
Fetching gem metadata from http://rubygems.org/............
Using i18n 0.6.11
Fetching json 1.8.1
Installing json 1.8.1 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory:
/var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
/usr/bin/ruby2.3 -r ./siteconf20171204-6004-665r95.rb extconf.rb
creating Makefile

current directory: /var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
make "DESTDIR=" clean

current directory: /var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
make "DESTDIR="
compiling generator.c
In file included from generator.c:1:0:
../fbuffer/fbuffer.h: In function ‘fbuffer_to_s’:
../fbuffer/fbuffer.h:175:47: error: macro "rb_str_new" requires 2 arguments, but
only 1 given
     VALUE result = rb_str_new(FBUFFER_PAIR(fb));
                                           ^
../fbuffer/fbuffer.h:175:20: warning: initialization makes integer from pointer
without a cast [-Wint-conversion]
     VALUE result = rb_str_new(FBUFFER_PAIR(fb));
                ^
Makefile:239: ошибка выполнения рецепта для цели «generator.o»
make: *** [generator.o] Ошибка 1

make failed, exit code 2

Gem files will remain installed in /var/lib/gems/2.3.0/gems/json-1.8.1 for
inspection.
Results logged to
/var/lib/gems/2.3.0/extensions/x86-linux/2.3.0/json-1.8.1/gem_make.out

An error occurred while installing json (1.8.1), and Bundler cannot
continue.
Make sure that `gem install json -v '1.8.1'` succeeds before bundling.

In Gemfile:
  middleman was resolved to 3.3.5, which depends on
    middleman-sprockets was resolved to 3.3.7, which depends on
      middleman-core was resolved to 3.3.5, which depends on
        padrino-helpers was resolved to 0.12.3, which depends on
          padrino-support was resolved to 0.12.3, which depends on
            activesupport was resolved to 4.1.5, which depends on
              json

ok... i wrote in conlose:

$ gem install json -v '1.8.1

ERROR:  While executing gem ... (Gem::FilePermissionError)
    You don't have write permissions for the /var/lib/gems/2.3.0 directory.

ok... no problem!

$ sudo gem install json -v '1.8.1'

Building native extensions.  This could take a while...
ERROR:  Error installing json:
    ERROR: Failed to build gem native extension.

    current directory: /var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
/usr/bin/ruby2.3 -r ./siteconf20171204-6068-15letpl.rb extconf.rb
creating Makefile

current directory: /var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
make "DESTDIR=" clean

current directory: /var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
make "DESTDIR="
compiling generator.c
In file included from generator.c:1:0:
../fbuffer/fbuffer.h: In function ‘fbuffer_to_s’:
../fbuffer/fbuffer.h:175:47: error: macro "rb_str_new" requires 2 arguments, but only 1 given
     VALUE result = rb_str_new(FBUFFER_PAIR(fb));
                                               ^
../fbuffer/fbuffer.h:175:20: warning: initialization makes integer from pointer without a cast [-Wint-conversion]
     VALUE result = rb_str_new(FBUFFER_PAIR(fb));
                    ^
Makefile:239: ошибка выполнения рецепта для цели «generator.o»
make: *** [generator.o] Ошибка 1

make failed, exit code 2

Gem files will remain installed in /var/lib/gems/2.3.0/gems/json-1.8.1 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86-linux/2.3.0/json-1.8.1/gem_make.out`enter code here`

eahh...

if i use command

$ bundle update

i see next:

The dependency wdm (~> 0.1.0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mswin32, x86-mingw32. To add those platforms to the bundle, run `bundle lock --add-platform x86-mswin32 x86-mingw32`.
The dependency tzinfo-data (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for x86-mswin32, x86-mingw32. To add those platforms to the bundle, run `bundle lock --add-platform x86-mswin32 x86-mingw32`.
Fetching gem metadata from http://rubygems.org/............
Fetching gem metadata from http://rubygems.org/.
Resolving dependencies....
Using i18n 0.7.0 (was 0.6.11)
Using json 1.8.6 (was 1.8.1)
Using minitest 5.10.3 (was 5.4.0)
Using thread_safe 0.3.6 (was 0.3.4)
Using tzinfo 1.2.4 (was 1.2.2)
Using activesupport 4.1.16 (was 4.1.5)
Using builder 3.2.3 (was 3.2.2)
Using bundler 1.16.0
Using hitimes 1.2.6
Using timers 4.0.4 (was 1.1.0)
Using celluloid 0.16.0 (was 0.15.2)
Using chunky_png 1.3.8 (was 1.3.1)
Using coffee-script-source 1.12.2 (was 1.7.1)
Using execjs 2.7.0 (was 2.2.1)
Using coffee-script 2.4.1 (was 2.3.0)
Using multi_json 1.12.2 (was 1.10.1)
Using sass 3.4.25 (was 3.3.14)
Using compass-core 1.0.3 (was 1.0.0)
Using compass-import-once 1.0.5
Using rb-fsevent 0.10.2 (was 0.9.4)
Using ffi 1.9.18 (was 1.9.3)
Using rb-inotify 0.9.10 (was 0.9.5)
Using compass 1.0.3 (was 1.0.0)
Fetching eventmachine 1.2.5 (was 1.0.3)
Installing eventmachine 1.2.5 (was 1.0.3) with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /var/lib/gems/2.3.0/gems/eventmachine-1.2.5/ext
/usr/bin/ruby2.3 -r ./siteconf20171204-9122-1fcu0r1.rb extconf.rb
checking for main() in -lcrypto... no
checking for openssl/ssl.h... no
checking for main() in -lcrypto... no
checking for openssl/ssl.h... no
checking for main() in -lcrypto... no
checking for openssl/ssl.h... no
checking for main() in -lcrypto... no
checking for openssl/ssl.h... no
checking for rb_trap_immediate in ruby.h,rubysig.h... no
checking for rb_thread_blocking_region()... no
checking for rb_thread_call_without_gvl() in ruby/thread.h... yes
checking for rb_thread_fd_select()... yes
checking for rb_fdset_t in ruby/intern.h... yes
checking for rb_wait_for_single_fd()... yes
checking for rb_enable_interrupt()... no
checking for rb_time_new()... yes
checking for inotify_init() in sys/inotify.h... yes
checking for writev() in sys/uio.h... yes
checking for pipe2() in unistd.h... yes
checking for accept4() in sys/socket.h... yes
checking for SOCK_CLOEXEC in sys/socket.h... yes
checking for sys/event.h... no
checking for epoll_create() in sys/epoll.h... yes
checking for clock_gettime()... yes
checking for CLOCK_MONOTONIC_RAW in time.h... yes
checking for CLOCK_MONOTONIC in time.h... yes
CXXFLAGS=-g -O2 -fstack-protector-strong -Wformat -Werror=format-security
creating Makefile

To see why this extension failed to compile, please check the mkmf.log which can
be found here:

  /var/lib/gems/2.3.0/extensions/x86-linux/2.3.0/eventmachine-1.2.5/mkmf.log

current directory: /var/lib/gems/2.3.0/gems/eventmachine-1.2.5/ext
make "DESTDIR=" clean

current directory: /var/lib/gems/2.3.0/gems/eventmachine-1.2.5/ext
make "DESTDIR="
compiling binder.cpp
make: g++: Команда не найдена
Makefile:231: ошибка выполнения рецепта для цели «binder.o»
make: *** [binder.o] Ошибка 127

make failed, exit code 2

Gem files will remain installed in /var/lib/gems/2.3.0/gems/eventmachine-1.2.5
for inspection.
Results logged to
/var/lib/gems/2.3.0/extensions/x86-linux/2.3.0/eventmachine-1.2.5/gem_make.out

An error occurred while installing eventmachine (1.2.5), and Bundler
cannot continue.
Make sure that `gem install eventmachine -v '1.2.5'` succeeds before
bundling.

In Gemfile:
  middleman-livereload was resolved to 3.1.1, which depends on
    em-websocket was resolved to 0.5.1, which depends on
      eventmachine

or

$ bundle install

Don't run Bundler as root. Bundler can ask for sudo if it is needed, and
installing your bundle as root will break this application for all non-root
users on this machine.
Fetching gem metadata from http://rubygems.org/............
Using i18n 0.6.11
Fetching json 1.8.1
Installing json 1.8.1 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory:
/var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
/usr/bin/ruby2.3 -r ./siteconf20171204-9328-qz84bl.rb extconf.rb
creating Makefile

current directory: /var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
make "DESTDIR=" clean

current directory: /var/lib/gems/2.3.0/gems/json-1.8.1/ext/json/ext/generator
make "DESTDIR="
compiling generator.c
In file included from generator.c:1:0:
../fbuffer/fbuffer.h: In function ‘fbuffer_to_s’:
../fbuffer/fbuffer.h:175:47: error: macro "rb_str_new" requires 2 arguments, but
only 1 given
     VALUE result = rb_str_new(FBUFFER_PAIR(fb));
                                               ^
../fbuffer/fbuffer.h:175:20: warning: initialization makes integer from pointer
without a cast [-Wint-conversion]
     VALUE result = rb_str_new(FBUFFER_PAIR(fb));
                    ^
Makefile:239: ошибка выполнения рецепта для цели «generator.o»
make: *** [generator.o] Ошибка 1

make failed, exit code 2

Gem files will remain installed in /var/lib/gems/2.3.0/gems/json-1.8.1 for
inspection.
Results logged to
/var/lib/gems/2.3.0/extensions/x86-linux/2.3.0/json-1.8.1/gem_make.out

An error occurred while installing json (1.8.1), and Bundler cannot
continue.
Make sure that `gem install json -v '1.8.1'` succeeds before bundling.

In Gemfile:
  middleman was resolved to 3.3.5, which depends on
    middleman-sprockets was resolved to 3.3.7, which depends on
      middleman-core was resolved to 3.3.5, which depends on
        padrino-helpers was resolved to 0.12.3, which depends on
          padrino-support was resolved to 0.12.3, which depends on
            activesupport was resolved to 4.1.5, which depends on
              json

some vicious circle


问:
How to check if a value already exists in my database and show a validation message in ASP.NET & Entity Framework
I am doing this. I want to check if the username is already inserted in database or not.</p>

```<code>Mst_Users obj = new Mst_Users();
obj.UserName = txtUserName.Text;

obj.ContactNo = txt_ContactNo.Text.Trim();
obj.Address = txt_Address.Text;
obj.CreatedBy = LoginHandler.UserData.UserId;
obj.CreatedOn = DateTime.Now;
obj.IsActive = true;
obj.PasswordHash = Password;
obj.RoleId = Convert.ToInt32(chkRoles.SelectedValue);
obj.OtherDetails = txt_OtherDetails.Text;
objEntity.Mst_Users.Add(obj);

int result = objEntity.SaveChanges();

if (result > 0)
{
    MessageBox("Record Added Succesfully");
    txtUserName.Text = string.Empty;
    txt_ContactNo.Text = string.Empty;
    txt_Address.Text = string.Empty;
    txt_OtherDetails.Text = string.Empty;
    chkRoles.ClearSelection();
}
</code>```

答:
First you need to check if a user with this username exists, you need to do this before you use any adding/saving code.

typicaly its done somewhat like this

```<code>var user = yourDbContext.Where(u=>u.UserName == "UserNameYouWantToCheck").FirstOrDefault();

if(user!=null)
    throw new ArgumentException(); //or do whatever you want to do when an user like this exists

//code for adding your user to the application db context and for saving the data.
</code>```

As for validation method that depends, if you are doing MvC project then you can use ModelState, you can check if model is valid and access validation messages from it. but if you are doing some other project to which you just added EF from github then you could use Validator, here is an example:

```<code>public static bool IsValid(object model)
        {
            var context = new ValidationContext(model, null, null);
            var results = new List<ValidationResult>();

            if (Validator.TryValidateObject(model, context, results, true))
            {
                return true;
            }

            return false;
        }
</code>```

then you just pass your model type object you want to check as parameer to this IsValid method and you can check your validation messages in the results list

Protip. Read about linq before you start learning about EF

Body:
I am doing this. I want to check if the username is already inserted in database or not.

Mst_Users obj = new Mst_Users();
obj.UserName = txtUserName.Text;

obj.ContactNo = txt_ContactNo.Text.Trim();
obj.Address = txt_Address.Text;
obj.CreatedBy = LoginHandler.UserData.UserId;
obj.CreatedOn = DateTime.Now;
obj.IsActive = true;
obj.PasswordHash = Password;
obj.RoleId = Convert.ToInt32(chkRoles.SelectedValue);
obj.OtherDetails = txt_OtherDetails.Text;
objEntity.Mst_Users.Add(obj);

int result = objEntity.SaveChanges();

if (result > 0)
{
    MessageBox("Record Added Succesfully");
    txtUserName.Text = string.Empty;
    txt_ContactNo.Text = string.Empty;
    txt_Address.Text = string.Empty;
    txt_OtherDetails.Text = string.Empty;
    chkRoles.ClearSelection();
}

Body:
First you need to check if a user with this username exists, you need to do this before you use any adding/saving code.

typicaly its done somewhat like this

var user = yourDbContext.Where(u=>u.UserName == "UserNameYouWantToCheck").FirstOrDefault();

if(user!=null)
    throw new ArgumentException(); //or do whatever you want to do when an user like this exists

//code for adding your user to the application db context and for saving the data.

As for validation method that depends, if you are doing MvC project then you can use ModelState, you can check if model is valid and access validation messages from it. but if you are doing some other project to which you just added EF from github then you could use Validator, here is an example:

public static bool IsValid(object model)
        {
            var context = new ValidationContext(model, null, null);
            var results = new List<ValidationResult>();

            if (Validator.TryValidateObject(model, context, results, true))
            {
                return true;
            }

            return false;
        }

then you just pass your model type object you want to check as parameer to this IsValid method and you can check your validation messages in the results list

Protip. Read about linq before you start learning about EF


问:
unfinished download with curl in C
I'm using Curl library to create a simple C code with MSVC to download a file from a URL.
The problem is if the connection breaks in the middle of download my code will freeze and the unfinished file hasn't removed from the directory.
What I want is if the download failed the program must retry the connection or remove the unfinished file and then try again. I prefer to use C libraries rather than C++ libs. Here is the code I am using:

```<code>//lib for curl
#include <curl/curl.h>
#define CURL_STATICLIB

bool downloader3(string url, string file_path) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(file_path.c_str(), "wb");
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        //always cleanup
        curl_easy_cleanup(curl);
        fclose(fp);
        double val;
        res = curl_easy_getinfo(curl, CURLINFO_SPEED_DOWNLOAD, &val);
        if ((CURLE_OK == res) && (val>0))
            printf("Average download speed: %0.3f kbyte/sec.\n", val / 1024);
        if ((res == CURLE_OK)) {
            printf("Download Successful!\r\n");
            return true;
        }
        else {
            printf("Downlaod Failed!\r\n");
            remove(file_path.c_str());  //remove the temp file
            return false;
        }
    }
}
</code>```

EDIT---
Thanks to Ring Ø answer. I modifed the code but I am looking for a resume capability that can resume the download of incomplete file.

```<code>bool downloader3(string url, string file_path) {
    CURL *curl;
    FILE *fp = NULL;
    CURLcode res;

    int status;
    int maxtries = 3;
    do {
        printf("Doing try # %d\r\n", maxtries);
        curl = curl_easy_init();
        if (curl) {
            fp = fopen(file_path.c_str(), "wb");
            curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
            curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
            curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L); // 30 seconds
            res = curl_easy_perform(curl);
            //always cleanup
            curl_easy_cleanup(curl);
            fclose(fp);
            if ((res == CURLE_OK)) {
                printf("Download Successful!\r\n");
                break;
                //return true;
                }
            }
    } while (--maxtries);
    if (maxtries) { // was OK
        //curl_easy_cleanup(curl);  // clean curl / delete file?
        //fclose(fp);
        return true;
    }
    else {
        printf("Download Failed!\r\n");
        printf("file path is: %s", file_path.c_str());
        Sleep(5000);
        status = remove(file_path.c_str());  //remove the unfinished file
        if (status == 0)
            printf("%s file deleted successfully.\n", file_path);
        else
        {
            printf("Unable to delete the file\n");
        }
        return false;
    }
}
</code>```

答:
What you are looking for is the RESUME_FROM feature. To use this you must know which byte you want to start the download from. In this example it is an upload but should be same setopt technique. Here is example usage from curl website:

```<code>CURL *curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_URL, "ftp://example.com");

  /* resume upload at byte index 200 */
  curl_easy_setopt(curl, CURLOPT_RESUME_FROM, 200L);

  /* ask for upload */
  curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);

  /* set total data amount to expect */
  curl_easy_setopt(curl, CURLOPT_INFILESIZE, size_of_file);

  /* Perform the request */
  curl_easy_perform(curl);
}
</code>```

source: https://curl.haxx.se/libcurl/c/CURLOPT_RESUME_FROM.html

Title: unfinished download with curl in C

Body:
I'm using Curl library to create a simple C code with MSVC to download a file from a URL.
The problem is if the connection breaks in the middle of download my code will freeze and the unfinished file hasn't removed from the directory.
What I want is if the download failed the program must retry the connection or remove the unfinished file and then try again. I prefer to use C libraries rather than C++ libs. Here is the code I am using:

//lib for curl
#include <curl/curl.h>
#define CURL_STATICLIB

bool downloader3(string url, string file_path) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(file_path.c_str(), "wb");
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        //always cleanup
        curl_easy_cleanup(curl);
        fclose(fp);
        double val;
        res = curl_easy_getinfo(curl, CURLINFO_SPEED_DOWNLOAD, &val);
        if ((CURLE_OK == res) && (val>0))
            printf("Average download speed: %0.3f kbyte/sec.\n", val / 1024);
        if ((res == CURLE_OK)) {
            printf("Download Successful!\r\n");
            return true;
        }
        else {
            printf("Downlaod Failed!\r\n");
            remove(file_path.c_str());  //remove the temp file
            return false;
        }
    }
}

EDIT---
Thanks to Ring Ø answer. I modifed the code but I am looking for a resume capability that can resume the download of incomplete file.

bool downloader3(string url, string file_path) {
    CURL *curl;
    FILE *fp = NULL;
    CURLcode res;

    int status;
    int maxtries = 3;
    do {
        printf("Doing try # %d\r\n", maxtries);
        curl = curl_easy_init();
        if (curl) {
            fp = fopen(file_path.c_str(), "wb");
            curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
            curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
            curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L); // 30 seconds
            res = curl_easy_perform(curl);
            //always cleanup
            curl_easy_cleanup(curl);
            fclose(fp);
            if ((res == CURLE_OK)) {
                printf("Download Successful!\r\n");
                break;
                //return true;
                }
            }
    } while (--maxtries);
    if (maxtries) { // was OK
        //curl_easy_cleanup(curl);  // clean curl / delete file?
        //fclose(fp);
        return true;
    }
    else {
        printf("Download Failed!\r\n");
        printf("file path is: %s", file_path.c_str());
        Sleep(5000);
        status = remove(file_path.c_str());  //remove the unfinished file
        if (status == 0)
            printf("%s file deleted successfully.\n", file_path);
        else
        {
            printf("Unable to delete the file\n");
        }
        return false;
    }
}

Body:
What you are looking for is the RESUME_FROM feature. To use this you must know which byte you want to start the download from. In this example it is an upload but should be same setopt technique. Here is example usage from curl website:

CURL *curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_URL, "ftp://example.com");

  /* resume upload at byte index 200 */
  curl_easy_setopt(curl, CURLOPT_RESUME_FROM, 200L);

  /* ask for upload */
  curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);

  /* set total data amount to expect */
  curl_easy_setopt(curl, CURLOPT_INFILESIZE, size_of_file);

  /* Perform the request */
  curl_easy_perform(curl);
}

source: https://curl.haxx.se/libcurl/c/CURLOPT_RESUME_FROM.html


问:
std::uniform_real_distribution regenerating same random number
In running the code below, the first half of arr equals the last half.  Why?  I even tried various seeds, e.g. std::chrono::system_clock::now().time_since_epoch().count(). Thanks.

```<code>#include <algorithm>
#include <iostream>
#include <random>

template<typename DistributionType>
class Rng
{
public:
        template<typename ...Args>
        Rng(Args&&... args) : dist(args...) { }

        typename DistributionType::result_type operator()()
        {
                return dist(gen);
        }

private:
        std::default_random_engine gen;

        DistributionType dist;
};

class UniformRealRng : public Rng<std::uniform_real_distribution<double>>
{
public:
        UniformRealRng(const double a, const double b) : Rng(a, b) { }
};

int main()
{
        constexpr int sz = 6;
        constexpr int k  = sz / 2;
        double arr[sz];

        UniformRealRng rng(0.0, 1.0);
        std::generate(arr, arr + k, rng);
        std::generate(arr + k, arr + sz, rng);

        for (int i = 0; i < sz; ++i)
        {
                std::cout << arr[i];
        }
        std::cout << "\n";
}
</code>```

答:
std::generate takes its third argument by value, so rng was being copied.

For safety, one could delete copying:

```<code>Rng(Rng&)             = delete;
Rng& operator=(Rng&)  = delete;
</code>```

Body:
In running the code below, the first half of arr equals the last half.  Why?  I even tried various seeds, e.g. std::chrono::system_clock::now().time_since_epoch().count(). Thanks.

#include <algorithm>
#include <iostream>
#include <random>

template<typename DistributionType>
class Rng
{
public:
        template<typename ...Args>
        Rng(Args&&... args) : dist(args...) { }

        typename DistributionType::result_type operator()()
        {
                return dist(gen);
        }

private:
        std::default_random_engine gen;

        DistributionType dist;
};

class UniformRealRng : public Rng<std::uniform_real_distribution<double>>
{
public:
        UniformRealRng(const double a, const double b) : Rng(a, b) { }
};

int main()
{
        constexpr int sz = 6;
        constexpr int k  = sz / 2;
        double arr[sz];

        UniformRealRng rng(0.0, 1.0);
        std::generate(arr, arr + k, rng);
        std::generate(arr + k, arr + sz, rng);

        for (int i = 0; i < sz; ++i)
        {
                std::cout << arr[i];
        }
        std::cout << "\n";
}

Body:
std::generate takes its third argument by value, so rng was being copied.

For safety, one could delete copying:

Rng(Rng&)             = delete;
Rng& operator=(Rng&)  = delete;


答:
In my case (dealing with my assemblies loaded [as file] into Outlook):

```<code>typeof(OneOfMyTypes).Assembly.CodeBase
</code>```

Note the use of CodeBase (not Location) on the Assembly. Others have pointed out alternative methods of locating the assembly.

Title: How to get the location of the DLL currently executing?

Body:
In my case (dealing with my assemblies loaded [as file] into Outlook):

typeof(OneOfMyTypes).Assembly.CodeBase

Note the use of CodeBase (not Location) on the Assembly. Others have pointed out alternative methods of locating the assembly.


问:
BottomNavigationView Does not work
I am working with BottomNavigationView, but the application does directly stopped and give me an error at line

```<code>setContentView(R.layout.activity_main);
</code>```

this is my code ( I did not do anything yet )

Main.java

```<code>public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
</code>```

xml file :

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:Design="http://schemas.android.com/apk/res-auto"
tools:context="com.example.ahmad.testbottomnavigationbar.MainActivity"
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
   />
<android.support.design.widget.BottomNavigationView
    android:id="@+id/NavBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_gravity="bottom"
    Design:menu="@menu/menu_nav">
</code>```

And Menu :

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:icon="@drawable/news"
    android:title="news" />
<item
    android:icon="@drawable/sug"
    android:title="sugg" />
<item
    android:icon="@drawable/fav"
    android:title="fav" />
<item
    android:icon="@drawable/myhome"
    android:title="home" />

<item
    android:icon="@drawable/comp"
    android:title="complain" />

<item

    android:icon="@drawable/myaccount"
    android:title="account" />
</code>```

and finally dependacies :

```<code> implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:design:26.1.0'
</code>```

and the application stopped after running ,
this is the exception :

java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.ahmad.testbottomnavigationbar/com.example.ahmad.testbottomnavigationbar.MainActivity}:
  android.view.InflateException: Binary XML file line #16: Error
  inflating class android.support.design.widget.BottomNavigationView

答:
You need to just modify and remove "s" from begining of below code

```<code> <sandroid.support.design.widget.BottomNavigationView

to

  <android.support.design.widget.BottomNavigationView
</code>```

AND

check Link

Hope it's helps you.

Title: BottomNavigationView Does not work

Body:
I am working with BottomNavigationView, but the application does directly stopped and give me an error at line

setContentView(R.layout.activity_main);

this is my code ( I did not do anything yet )

Main.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

xml file :

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:Design="http://schemas.android.com/apk/res-auto"
tools:context="com.example.ahmad.testbottomnavigationbar.MainActivity"
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
   />
<android.support.design.widget.BottomNavigationView
    android:id="@+id/NavBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_gravity="bottom"
    Design:menu="@menu/menu_nav">

And Menu :

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:icon="@drawable/news"
    android:title="news" />
<item
    android:icon="@drawable/sug"
    android:title="sugg" />
<item
    android:icon="@drawable/fav"
    android:title="fav" />
<item
    android:icon="@drawable/myhome"
    android:title="home" />

<item
    android:icon="@drawable/comp"
    android:title="complain" />

<item

    android:icon="@drawable/myaccount"
    android:title="account" />

and finally dependacies :

 implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:design:26.1.0'

and the application stopped after running ,
this is the exception :

java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.ahmad.testbottomnavigationbar/com.example.ahmad.testbottomnavigationbar.MainActivity}:
  android.view.InflateException: Binary XML file line #16: Error
  inflating class android.support.design.widget.BottomNavigationView

Body:
You need to just modify and remove "s" from begining of below code

 <sandroid.support.design.widget.BottomNavigationView

to

  <android.support.design.widget.BottomNavigationView

AND

check Link

Hope it's helps you.


问:
OpenMP reduction on older version without overloading

#pragma omp parallel for    // I want reduction but overloading doesn't work on the version used
for (int i = 0; i <500; i++)
    #pragma omp critical
    for (j=i; j < 102342; j++)
    {
        Output[j] += staticConstant[i] * data[j-i];
    }
}
```

Is there a way to get reduction to work here? making local private copies doesn't speed it up.

答:
Forget about using a reduction in this case, the overhead it would incur (100000+ elements in the reduction variable) compared to the effect of the parallelization would likely kill most of the gain. Just stick to simple parallelization constructs.

Ideally, what you'd want would be to parallelize the j loop as it carries no dependencies between iterations. So you can just do it like this:

#pragma omp parallel
for ( int i = 0; i < 500; i++ ) {
    #pragma omp for
    for ( int j = i; j < 102342; j++ ) {
        Output[j] += staticConstant[i] * data[j-i];
    }
}
```

<p>For a code as simple as this one, this should be just enough.</p>

<p>Now, you might want go a step further and try to swap the <code>i</code> and <code>j</code> loops to improve the parallelization effectiveness (not sure it'll make much of a difference though). For that, you'll need to remove the dependency to <code>i</code> in the <code>j</code> loop initialization. Here is a way of doing it:</p>

<pre class="lang-c prettyprint-override"><code>// first let's do the dependent iterations in j
for ( int i = 0; i < 500; i++ ) {
    for ( int j = i; j < 500; j++ ) {
        Output[j] += staticConstant[i] * data[j-i];
    }
}
// then all the other iterations, and swap the i and j loops
// now we can parallelize no problem
#pragma omp parallel for
for ( int j = 500; j < 102342; j++ ) {
    for ( int i = 0; i < 500; i++ ) {
        Output[j] += staticConstant[i] * data[j-i];
    }
}
</code>```

Body:
#pragma omp parallel for    // I want reduction but overloading doesn't work on the version used
for (int i = 0; i <500; i++)
    #pragma omp critical
    for (j=i; j < 102342; j++)
    {
        Output[j] += staticConstant[i] * data[j-i];
    }
}

Is there a way to get reduction to work here? making local private copies doesn't speed it up.

Body:
Forget about using a reduction in this case, the overhead it would incur (100000+ elements in the reduction variable) compared to the effect of the parallelization would likely kill most of the gain. Just stick to simple parallelization constructs.

Ideally, what you'd want would be to parallelize the j loop as it carries no dependencies between iterations. So you can just do it like this:

#pragma omp parallel
for ( int i = 0; i < 500; i++ ) {
    #pragma omp for
    for ( int j = i; j < 102342; j++ ) {
        Output[j] += staticConstant[i] * data[j-i];
    }
}

For a code as simple as this one, this should be just enough.

Now, you might want go a step further and try to swap the i and j loops to improve the parallelization effectiveness (not sure it'll make much of a difference though). For that, you'll need to remove the dependency to i in the j loop initialization. Here is a way of doing it:

// first let's do the dependent iterations in j
for ( int i = 0; i < 500; i++ ) {
    for ( int j = i; j < 500; j++ ) {
        Output[j] += staticConstant[i] * data[j-i];
    }
}
// then all the other iterations, and swap the i and j loops
// now we can parallelize no problem
#pragma omp parallel for
for ( int j = 500; j < 102342; j++ ) {
    for ( int i = 0; i < 500; i++ ) {
        Output[j] += staticConstant[i] * data[j-i];
    }
}


问:
How to convert a DBNULL to double?
im getting a value from the database. it came out an error saying "Conversion from DBNULL to Double is not Valid." anyone, pls help me?

Public Function Total() As Double
        Dim Total As Double

```<code>    Dim strConn As String
    strConn = ConfigurationManager.ConnectionStrings("***").ToString
    Dim conn As New SqlConnection(strConn)

    Dim strSql As String
    strSql = "SELECT SUM (p.Price * c.Quantity) as 'Total' " & _
    "FROM CartItem sci INNER JOIN Product p ON c.ProductID=p.ProductID " & _
    "WHERE c.CartID=@CartID "

    Dim cmd As New SqlCommand(strSql, conn)

    cmd.Parameters.AddWithValue("@CartID", CartID)

    Dim da As New SqlDataAdapter(cmd)

    Dim ds As New DataSet

    conn.Open()

    da.Fill(ds, "CartItem")

    conn.Close()

    If (ds.Tables("CartItem").Rows.Count) <> 0 Then
        **Total = ds.Tables("ShopCartItem").Rows(0)("Total")**
    Else
        Total = 0.0
    End If
    Return Total
End Function
</code>```

答:
Try changing your SQL to:

```<code>SELECT SUM (ISNULL(p.Price,0) * ISNULL(c.Quantity,0) ) as 'Total' " & _
    "FROM CartItem sci INNER JOIN Product p ON c.ProductID=p.ProductID " & _
    "WHERE c.CartID=@CartID
</code>```

You could also set your database table to not allow nulls

Title: How to convert a DBNULL to double?

Body:
im getting a value from the database. it came out an error saying "Conversion from DBNULL to Double is not Valid." anyone, pls help me?

Public Function Total() As Double
        Dim Total As Double

    Dim strConn As String
    strConn = ConfigurationManager.ConnectionStrings("***").ToString
    Dim conn As New SqlConnection(strConn)

    Dim strSql As String
    strSql = "SELECT SUM (p.Price * c.Quantity) as 'Total' " & _
    "FROM CartItem sci INNER JOIN Product p ON c.ProductID=p.ProductID " & _
    "WHERE c.CartID=@CartID "

    Dim cmd As New SqlCommand(strSql, conn)

    cmd.Parameters.AddWithValue("@CartID", CartID)

    Dim da As New SqlDataAdapter(cmd)

    Dim ds As New DataSet

    conn.Open()

    da.Fill(ds, "CartItem")

    conn.Close()

    If (ds.Tables("CartItem").Rows.Count) <> 0 Then
        **Total = ds.Tables("ShopCartItem").Rows(0)("Total")**
    Else
        Total = 0.0
    End If
    Return Total
End Function

Body:
Try changing your SQL to:

SELECT SUM (ISNULL(p.Price,0) * ISNULL(c.Quantity,0) ) as 'Total' " & _
    "FROM CartItem sci INNER JOIN Product p ON c.ProductID=p.ProductID " & _
    "WHERE c.CartID=@CartID

You could also set your database table to not allow nulls