问:
Scrollview and child with flex: 1
Is it possible to have a layout which is wrapped with ScrollView:

```<code><ScrollView>
  <View>dynamic height</View>
  <View>flex with minHeight</View>
  <View>static height</View>
</ScrollView>
</code>```

and meets below prerequisites:

Height of the first View is dynamic (depends on text length). Height of the third View is static (always three buttons inside). Rest of the screen should be filled with View with map, but the minimal height is set to 250.

Now the tricky part: if there is a lot of text in first View, so that map doesn't fit, a scroll should appear. I couldn't achieve that. I was trying to give the map View flex: 1 and minHeight: 250, but it's not rendered at all.

Solution

Ok, I've found a way to fix it. In first render, I get screen height (Dimensions) and height of first and third view (onLayout). Then, I calculate the height of second view (screenHeight - view1 - view3 - naviagtionHeight) and forceUpdate() to re-render it.

答: Add contentContainerStyle={{flexGrow: 1}} prop to ScrollView and its children's flex:1 would work. So you don't need to calculate it manually.

Title: Scrollview and child with flex: 1

Body:
Is it possible to have a layout which is wrapped with ScrollView:

<ScrollView>
  <View>dynamic height</View>
  <View>flex with minHeight</View>
  <View>static height</View>
</ScrollView>

and meets below prerequisites:

Height of the first View is dynamic (depends on text length). Height of the third View is static (always three buttons inside). Rest of the screen should be filled with View with map, but the minimal height is set to 250.

Now the tricky part: if there is a lot of text in first View, so that map doesn't fit, a scroll should appear. I couldn't achieve that. I was trying to give the map View flex: 1 and minHeight: 250, but it's not rendered at all.

Solution

Ok, I've found a way to fix it. In first render, I get screen height (Dimensions) and height of first and third view (onLayout). Then, I calculate the height of second view (screenHeight - view1 - view3 - naviagtionHeight) and forceUpdate() to re-render it.


来源: stackexchange

问:
Leading zeroes not working with number data type
When I select from a view, the result with preceding zeroes coming again because

of the number data type. I need the result without leading zeroes.

```<code> -------CODE----------
create table test_number_type(c1 number);

insert into test_number_type values(100.12);

insert into test_number_type values(0.12);

commit;

create or replace view  test_data_type as
select to_number(trim(leading 0 from c1)) c_num_check from test_number_type;

desc test_data_type
</code>```

答:
Your concern is entirely misplaced.  Numbers are stored using an internal representation.  They are not stored as strings.  So, all these represent the same number (with a caveat that follows):

```<code>0.12
.12
000000.12
</code>```

The caveat is that the internal representation might differ somewhat in terms of scale and precision.

How the number gets presented is not really up to the column.  If you want to control the output, convert the value to a string.  The function to_char() allows you to control the leading zeros.

ContentLicense: CC BY-SA 3.0

Body:
When I select from a view, the result with preceding zeroes coming again because

of the number data type. I need the result without leading zeroes.

 -------CODE----------
create table test_number_type(c1 number);

insert into test_number_type values(100.12);

insert into test_number_type values(0.12);

commit;

create or replace view  test_data_type as
select to_number(trim(leading 0 from c1)) c_num_check from test_number_type;

desc test_data_type

Body:
Your concern is entirely misplaced.  Numbers are stored using an internal representation.  They are not stored as strings.  So, all these represent the same number (with a caveat that follows):

0.12
.12
000000.12

The caveat is that the internal representation might differ somewhat in terms of scale and precision.

How the number gets presented is not really up to the column.  If you want to control the output, convert the value to a string.  The function to_char() allows you to control the leading zeros.


问:
How to call only php function not whole page with ajax?
I want to return data only from the php function not whole page data.
Here is my demo.php file -

```<code>    <?
    echo "Whole Page data";

    $name = $_POST['name'];

    if ($name == "demo"){
        demo();
    }
    else{
        echo "No";
    }
    function demo(){
       echo "demo data";
}

?>
</code>```

And my ajax funtion is this -

```<code>function myAjax () {
        $.ajax( { type : 'POST',
                url  : 'demo.php',
                data : "name=demo",
                success:function(data){
                       alert (data);
               }
       });
}
</code>```

But it return whole page data with function data but I want only function data.

答:
Check like,

```<code>if (!empty($_POST)) {
    $name = $_POST['name'];

    if ($name == "demo") {
        demo();
    } else {
        echo "No";
    }
    die;
}
function demo()
{
    echo "demo data";
}
</code>```

This die; is important to halt execution process.

Give it a try, this should work.

Body:
I want to return data only from the php function not whole page data.
Here is my demo.php file -

    <?
    echo "Whole Page data";

    $name = $_POST['name'];

    if ($name == "demo"){
        demo();
    }
    else{
        echo "No";
    }
    function demo(){
       echo "demo data";
}

?>

And my ajax funtion is this -

function myAjax () {
        $.ajax( { type : 'POST',
                url  : 'demo.php',
                data : "name=demo",
                success:function(data){
                       alert (data);
               }
       });
}

But it return whole page data with function data but I want only function data.

Body:
Check like,

if (!empty($_POST)) {
    $name = $_POST['name'];

    if ($name == "demo") {
        demo();
    } else {
        echo "No";
    }
    die;
}
function demo()
{
    echo "demo data";
}

This die; is important to halt execution process.

Give it a try, this should work.


问:
Can I execute SQL with parameters from within Visual Studio?
EDIT: Judging from the comments, I have been unclear in what I am trying to achieve. I'll try from another angle.

I have been developing sprocs for a number of years. I increasingly feel that choosing between SQL embedded in C# code and sprocs are both bad choices. I know that many people will disagree and that's fine.
I didn't elaborate on this in the question to avoid having the discussion be about sprocs or not :-) .

As an experiment, I have tried embedding .sql files in my project in Visual Studio. Literally, in my project tree I have files with the .sql extension and the Build Action set to Embedded Resource.

That way I can edit the SQL query code from within VS and even run/execute it from within VS, without running the project. I love that. The actual code that I am working on right now, is akin to a "product list" with paging and multiple ordering and filtering options. The SQL query has parameters like @skip, @search, etc. This means that if I try to run/execute it from within VS (specifically by pressing CTRL + SHIFT + e or selecting "Execute" from the "SQL" menu in VS) these parameters are missing (of course), since they are meant to be provided as SqlParameter at runtime. I understand why this happens and by no way intend to imply that either VS or SSMS is bugged. I am merely looking for a way to "tell" VS that "When I execute this query from within VS, I intend for @skip to be 10". I (perhaps mistakenly) assumed that the reason that VS had IntelliSense support and Execute support for .sql files was to support a scenario akin to what I am trying).

I was just hoping someone else was doing the same and had a clever way/addon/trick to support it.

EDIT END

In an project in Visual Studio 2017, I have a number of .sql files which are embedded into the application when built.

While editing the files in VS, I can conveniently connect to a SQL server and execute the query.

However, if the query has parameters like this:

```<code>SELECT * FROM Employee WHERE ID=@ID;
</code>```

The execution, from within Visual Studio, fails with

```<code>Must declare the scalar variable "@ID".
</code>```

This can be "fixed" by adding a line at the top of the script/file, so it looks like:

```<code>DECLARE @ID int = 123;
SELECT * FROM Employee WHERE ID=@ID;
</code>```

However, now it doesn't work when called from within the code like this (using Dapper, it's not relevant to the question, but explains the syntax):

```<code>var emp = conn.Query<Employee>( sql, new { ID=123 } );
</code>```

I was hoping that either I could specify the value of ID somewhere not in the file, or specify some part of the file which VS would execute, but would be ignored later when calling from code.

EDIT: To be clear, I can craft the SQL so that it works flawlessly from within Visual Studio or at runtime, but I cannot have both. I was hoping there was some neat hack, a VS addon or just some VS feature that I was just missing. I have considered adding a simple pre-processor so I can do something like this:

```<code>--if DEBUG
DECLARE @ID int = 123;
--endif
SELECT * FROM Employee WHERE ID=@ID;
</code>```

And then I could add it to my function that loads the embedded resource.

答:
Pardon if I understood the question wrongly. Could it be you're looking for something like this? The query approach actually doesn't matter, it more looks like the issue is that you declare it like @ID when you actually have to add the replacement to the script itself</p>

```<code>con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT * FROM Employee WHERE ID=@ID;";
cmd.Parameters.Add("@ID", actualID); <--this is is why declaring doesn't work - You can declare it, but you also need to add it to the query
SqlDataReader rdr = cmd.ExecuteReader();
</code>```

Body:
EDIT: Judging from the comments, I have been unclear in what I am trying to achieve. I'll try from another angle.

I have been developing sprocs for a number of years. I increasingly feel that choosing between SQL embedded in C# code and sprocs are both bad choices. I know that many people will disagree and that's fine.
I didn't elaborate on this in the question to avoid having the discussion be about sprocs or not :-) .

As an experiment, I have tried embedding .sql files in my project in Visual Studio. Literally, in my project tree I have files with the .sql extension and the Build Action set to Embedded Resource.

That way I can edit the SQL query code from within VS and even run/execute it from within VS, without running the project. I love that. The actual code that I am working on right now, is akin to a "product list" with paging and multiple ordering and filtering options. The SQL query has parameters like @skip, @search, etc. This means that if I try to run/execute it from within VS (specifically by pressing CTRL + SHIFT + e or selecting "Execute" from the "SQL" menu in VS) these parameters are missing (of course), since they are meant to be provided as SqlParameter at runtime. I understand why this happens and by no way intend to imply that either VS or SSMS is bugged. I am merely looking for a way to "tell" VS that "When I execute this query from within VS, I intend for @skip to be 10". I (perhaps mistakenly) assumed that the reason that VS had IntelliSense support and Execute support for .sql files was to support a scenario akin to what I am trying).

I was just hoping someone else was doing the same and had a clever way/addon/trick to support it.

EDIT END

In an project in Visual Studio 2017, I have a number of .sql files which are embedded into the application when built.

While editing the files in VS, I can conveniently connect to a SQL server and execute the query.

However, if the query has parameters like this:

SELECT * FROM Employee WHERE ID=@ID;

The execution, from within Visual Studio, fails with

Must declare the scalar variable "@ID".

This can be "fixed" by adding a line at the top of the script/file, so it looks like:

DECLARE @ID int = 123;
SELECT * FROM Employee WHERE ID=@ID;

However, now it doesn't work when called from within the code like this (using Dapper, it's not relevant to the question, but explains the syntax):

var emp = conn.Query<Employee>( sql, new { ID=123 } );

I was hoping that either I could specify the value of ID somewhere not in the file, or specify some part of the file which VS would execute, but would be ignored later when calling from code.

EDIT: To be clear, I can craft the SQL so that it works flawlessly from within Visual Studio or at runtime, but I cannot have both. I was hoping there was some neat hack, a VS addon or just some VS feature that I was just missing. I have considered adding a simple pre-processor so I can do something like this:

--if DEBUG
DECLARE @ID int = 123;
--endif
SELECT * FROM Employee WHERE ID=@ID;

And then I could add it to my function that loads the embedded resource.

Body:
Pardon if I understood the question wrongly. Could it be you're looking for something like this? The query approach actually doesn't matter, it more looks like the issue is that you declare it like @ID when you actually have to add the replacement to the script itself

con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT * FROM Employee WHERE ID=@ID;";
cmd.Parameters.Add("@ID", actualID); <--this is is why declaring doesn't work - You can declare it, but you also need to add it to the query
SqlDataReader rdr = cmd.ExecuteReader();


问:
Extract a string value from code
I am trying to extract the string : "Plan B Warranty & Breakdown Recovery"

from the following block of code. I am having problems locating it via xpath and get text. I would be grateful for some pointers.

```<code><!DOCTYPE html>
<html class="ng-scope" ng-app="dan">
<head>
<body class="u-scroll-y ng-scope" ng-controller="CoreController as cc">
<div class="c-animate c-animate--show u-pos-f-t ng-hide" ng-show="global.alerts.length">
<div class="o-grid-fluid u-h-100 u-pl-0">
<div class="o-grid__row u-ml-0 u-h-100">
<div class="c-loader ng-hide" ng-show="loadingHome" style="">
<nav class="o-grid__col-xl-2 o-grid__col-lg-3 o-grid__col-xs-4 u-p-0 c-card__block u-h-100 u-shadowed u-pos-f-t ng-scope" ng-if="global.loggedIn">
<div class="u-p-0 u-h-100 o-grid__col-xl-10 o-grid__col-lg-9 o-grid__col-xs-8 u-pull-right" ng-class="{ 'o-grid__col-xl-10 o-grid__col-lg-9 o-grid__col-xs-8 u-pull-right' : global.loggedIn }">
<header class="o-layout-table__row u-bg-primary u-shadowed u-clearfix u-px ng-scope" ng-if="global.loggedIn">
<main class="o-view-container">
<div class="o-grid-fluid u-py-md">
<div class="o-grid__row">
<div class="c-animate c-animate--view-slide-in-right c-animate--view-slide-out-right ng-scope" ng-view="" style="">
<div class="o-grid__col-md-10 o-grid__col-xl-8 o-grid__col-xl-offset-2 o-grid__col-md-offset-1 ng-scope">
<div class="u-mb-lg u-text-center">
<h1 class="u-text-bold">Recommendations</h1>
</div>
<form class="ng-pristine ng-valid ng-valid-min ng-valid-max ng-valid-required" name="recommend" ng-submit="recommend.$valid">
<div class="o-media c-card c-card__block u-shadowed u-mb-lg ng-scope" ng-if="rc.WarrantyEligible && !rc.prevWarranty()">
<label class="c-form-control-label u-px u-py-sm u-w-100">Warranty Options:</label>
<div class="c-form-group u-p-0 u-mb-sm u-clearfix">
<div class="o-grid__col-md-8">
<label class="c-form-control-label u-text-normal">Product Recommendations (Years):</label>
</div>
<div class="o-grid__col-md-4">
<input class="c-form-control ng-pristine ng-untouched ng-valid ng-valid-min ng-valid-max ng-valid-required" required="" placeholder="Years" ng-model="rc.recommend.year" min="1" max="3" type="number">
</div>
</div>
<div class="c-form-group ng-scope" ng-if="!data.answer_taxi">
<label class="c-option c-option--right u-px u-py-sm u-clearfix ng-scope" ng-if="!rc.planA && !rc.prestige" ng-click="cc.utils.audit('recommendation_warranty_plan_b')">
<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.warrantyPlan" value="planB" name="warrantyPlan" type="radio">
<i class="c-option__radio"></i>
Plan B Warranty & Breakdown Recovery
</label>
</div>
</div>
<div class="o-media c-card c-card__block u-shadowed u-mb-lg u-text-body u-bg-success" ng-if="!rc.prevVap() && rc.VapEligible ">
<div class="c-form-group">
<label class="c-form-control-label u-px u-py-sm u-w-100">Vehicle Asset Protection Options:</label>
<label class="c-option c-option--right u-px u-py-sm u-clearfix" ng-click="cc.utils.audit('recommend_vap')">
<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.vapPlan.plan" value="standard" name="vapPlan" type="radio">
<i class="c-option__radio"></i>
Vehicle Asset Protection - Standard Cover
</label>
<label class="c-option c-option--right u-px u-py-sm u-clearfix" ng-click="cc.utils.audit('vap_key_facts_checked')">
<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.vapCheck" name="vapCheck" type="checkbox">
<i class="c-option__checkbox"></i>
You confirm that you have received the VAP key facts leaflet?
</label>
</div>
</div>
</form>
<div class="c-form-group">
<input class="c-btn c-btn--primary c-btn--block u-pull-right" value="Complete and Preview" ng-click="rc.complete(recommend.$valid); cc.utils.audit('recommend_complete')" ng-disabled="recommend.$invalid" type="submit">
</div>
</div>
</div>
</div>
</div>
</main>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js">
<script src="./build/app.js?v=2.13" defer="">
<script src="/build/standalone/jspdf.js" defer="">
<script src="/build/standalone/sigWebTablet.js" defer="">
</body>
</html>
</code>```

ignore this ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

答:
To extract the string "Plan B Warranty & Breakdown Recovery" you can use the following code block :

```<code>System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label[@class='c-option c-option--right u-px u-py-sm u-clearfix ng-scope' and not(@class='ng-pristine ng-untouched ng-valid ng-valid-required') and not (@class='c-option__radio')]"))).getAttribute("innerHTML"));
</code>```

As an alternative, you can try this code block as well :

```<code>WebDriverWait wait20 = new WebDriverWait(driver, 20);
WebElement ele = wait20.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label[@class='c-option c-option--right u-px u-py-sm u-clearfix ng-scope' and not(@class='ng-pristine ng-untouched ng-valid ng-valid-required') and not (@class='c-option__radio')]")));
System.out.println(ele.getAttribute("innerHTML"));
</code>```

Title: Extract a string value from code

Body:
I am trying to extract the string : "Plan B Warranty & Breakdown Recovery"

from the following block of code. I am having problems locating it via xpath and get text. I would be grateful for some pointers.

<!DOCTYPE html>

Recommendations

<form class="ng-pristine ng-valid ng-valid-min ng-valid-max ng-valid-required" name="recommend" ng-submit="recommend.$valid">

Warranty Options:

Product Recommendations (Years):

<input class="c-form-control ng-pristine ng-untouched ng-valid ng-valid-min ng-valid-max ng-valid-required" required="" placeholder="Years" ng-model="rc.recommend.year" min="1" max="3" type="number">

<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.warrantyPlan" value="planB" name="warrantyPlan" type="radio">

Plan B Warranty & Breakdown Recovery

Vehicle Asset Protection Options:

<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.vapPlan.plan" value="standard" name="vapPlan" type="radio">

Vehicle Asset Protection - Standard Cover

<input class="ng-pristine ng-untouched ng-valid ng-valid-required" required="" ng-model="rc.recommend.vapCheck" name="vapCheck" type="checkbox">

You confirm that you have received the VAP key facts leaflet?

</form>

<input class="c-btn c-btn--primary c-btn--block u-pull-right" value="Complete and Preview" ng-click="rc.complete(recommend.$valid); cc.utils.audit('recommend_complete')" ng-disabled="recommend.$invalid" type="submit">

Body:
To extract the string "Plan B Warranty & Breakdown Recovery" you can use the following code block :

System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label[@class='c-option c-option--right u-px u-py-sm u-clearfix ng-scope' and not(@class='ng-pristine ng-untouched ng-valid ng-valid-required') and not (@class='c-option__radio')]"))).getAttribute("innerHTML"));

As an alternative, you can try this code block as well :

WebDriverWait wait20 = new WebDriverWait(driver, 20);
WebElement ele = wait20.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label[@class='c-option c-option--right u-px u-py-sm u-clearfix ng-scope' and not(@class='ng-pristine ng-untouched ng-valid ng-valid-required') and not (@class='c-option__radio')]")));
System.out.println(ele.getAttribute("innerHTML"));


问:
Adding leading and trailing spaces to uitableview of child class inherited from parent class programmatically using swift
I am trying to add leading and trailing spaces to tableview embedded in view programmatically. This tableview has constraints been declared in parent class i am trying to override them in child class. I am doing in the following way

```<code>class TestTableView: BaseTableViewController{

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.lpBaseTableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.lpBaseTableView.contentSize.height)
    self.lpBaseTableView.center = self.view.center
    self.lpBaseTableView.translatesAutoresizingMaskIntoConstraints = false
    self.lpBaseTableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 16).isActive = true
    self.lpBaseTableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 16).isActive = true

 }
}
</code>```

After researching few links from stack overflow i am using the above code but there is no change in the table view position as shown below in the image. Please help me out. I am new to swift and iOS

答:
Adding a leading and trailing constraints are simple, just give proper constants with respect to the superview and also give top and bottom constraints. Frame and centre is not needed since you're using autolayout here.</p>

```<code>    lpBaseTableView = UITableView()
    lpBaseTableView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(lpBaseTableView)

    NSLayoutConstraint.activate([
        lpBaseTableView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
        lpBaseTableView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
        lpBaseTableView.topAnchor.constraint(equalTo: view.topAnchor),
        lpBaseTableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
    ])
</code>```

Body:
I am trying to add leading and trailing spaces to tableview embedded in view programmatically. This tableview has constraints been declared in parent class i am trying to override them in child class. I am doing in the following way

class TestTableView: BaseTableViewController{

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.lpBaseTableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.lpBaseTableView.contentSize.height)
    self.lpBaseTableView.center = self.view.center
    self.lpBaseTableView.translatesAutoresizingMaskIntoConstraints = false
    self.lpBaseTableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 16).isActive = true
    self.lpBaseTableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 16).isActive = true

 }
}

After researching few links from stack overflow i am using the above code but there is no change in the table view position as shown below in the image. Please help me out. I am new to swift and iOS

Body:
Adding a leading and trailing constraints are simple, just give proper constants with respect to the superview and also give top and bottom constraints. Frame and centre is not needed since you're using autolayout here.

    lpBaseTableView = UITableView()
    lpBaseTableView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(lpBaseTableView)

    NSLayoutConstraint.activate([
        lpBaseTableView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),
        lpBaseTableView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16),
        lpBaseTableView.topAnchor.constraint(equalTo: view.topAnchor),
        lpBaseTableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
    ])


问:
Use of getter-setter within class
Should one use under any circumstances getters-setters of a class within the class?</p>

答:
You're supposed to use the getters and setter almost everywhere, including inside the class. If you don't, then you are potentially breaking encapsulation, and even worse, you could invalidate your invariants.

As a simple example in C++:

```<code>class BankAccount
{
public:
    void withdraw(int amount)
    {
        m_balance -= amount;
        m_withdrawals++;
    }

    void transfer(BankAcount& other, int amount)
    {
        m_balance -= amount;
        other.m_balance += amount;
    }

private:
    int m_balance;
    int m_withdrawals;
};
</code>```

See the bug? transfer withdraws money, but it doesn't increment m_withdrawals. This could have been avoided if it simply called withdraw rather than manually decrementing the balance.

The same applies to getters and setters. For example, its quite common to have getters that lazily initialise their values. If another member function tries to access the uninitialised member directly then you're going to get a null pointer dereference.

Essentially, you should always try to use the getters and setters whenever they provide the functionality they want. The more low level things you do, the more low level bugs you are going to have. There's no point writing getters and setters if you aren't going to use them.

ContentLicense: CC BY-SA 2.5

Title: Use of getter-setter within class

Body:
You're supposed to use the getters and setter almost everywhere, including inside the class. If you don't, then you are potentially breaking encapsulation, and even worse, you could invalidate your invariants.

As a simple example in C++:

class BankAccount
{
public:
    void withdraw(int amount)
    {
        m_balance -= amount;
        m_withdrawals++;
    }

    void transfer(BankAcount& other, int amount)
    {
        m_balance -= amount;
        other.m_balance += amount;
    }

private:
    int m_balance;
    int m_withdrawals;
};

See the bug? transfer withdraws money, but it doesn't increment m_withdrawals. This could have been avoided if it simply called withdraw rather than manually decrementing the balance.

The same applies to getters and setters. For example, its quite common to have getters that lazily initialise their values. If another member function tries to access the uninitialised member directly then you're going to get a null pointer dereference.

Essentially, you should always try to use the getters and setters whenever they provide the functionality they want. The more low level things you do, the more low level bugs you are going to have. There's no point writing getters and setters if you aren't going to use them.


问:
Hover button to make image change to grayscale 100% css
I'm trying to make my image into grayscale 100% while hovering the button. The problem is it does not become greyscale image while hovering the Button. I have tried to use :active,:hover but it doesn't solve my issue.

#image1:hover {
   filter: grayscale(100%);
}
.button1 {
  position: absolute;
  width: 500px;
  left:0;
  top: 180px;
  text-align: center;
  opacity: 0;
  transition: opacity .35s ease;
}
.button1 a {
  width: 200px;
  padding: 12px 48px;
  text-align: center;
  color: #ff991e;
  border: 1px solid #ff991e;
  z-index: 1;
  text-decoration: none;
  font-weight: bolder;
}

.image-1:hover .button1 {
  opacity: 1;
}

div.button1:hover > #image1 {
  filter: grayscale(100%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-6 image-1">
  <img src="http://servesphere.com.ph/moto/wp-content/uploads/2017/12/Left-image.png" class="" id="image1" style="width: auto; height: 320px;">
  <div class="centered">
    <p class="title1">BRAND NEW</p>
    <div class="button1"> ENTER </div>
  </div>
</div></code>```

答:
.button-div a {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  width: 100px;
  padding: 12px 48px;
  color: #ff991e;
  border: 1px solid #ff991e;
  z-index: 1;
  text-decoration: none;
  font-weight: bolder;
  opacity: 0;
  text-align: center;
  transition: opacity .35s ease;
}

.button-div img {
  width: auto;
  height: 320px;
  position: relative;
}

.button-div:hover a.button {
  opacity: 1;
}

.button-div a:hover + #image1 {
  filter: grayscale(100%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-6 image-1">
    <div class="button-div">
       ENTER
      <img src="http://servesphere.com.ph/moto/wp-content/uploads/2017/12/Left-image.png" class="" id="image1" style="">
    </div>

  <div class="centered">
   <p class="title1">BRAND NEW</p>
  </div>
 </div></code>```

Check this out.

Body:
I'm trying to make my image into grayscale 100% while hovering the button. The problem is it does not become greyscale image while hovering the Button. I have tried to use :active,:hover but it doesn't solve my issue.

#image1:hover {
   filter: grayscale(100%);
}
.button1 {
  position: absolute;
  width: 500px;
  left:0;
  top: 180px;
  text-align: center;
  opacity: 0;
  transition: opacity .35s ease;
}
.button1 a {
  width: 200px;
  padding: 12px 48px;
  text-align: center;
  color: #ff991e;
  border: 1px solid #ff991e;
  z-index: 1;
  text-decoration: none;
  font-weight: bolder;
}

.image-1:hover .button1 {
  opacity: 1;
}

div.button1:hover > #image1 {
  filter: grayscale(100%);
}

BRAND NEW

 ENTER

Body:
.button-div a {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  width: 100px;
  padding: 12px 48px;
  color: #ff991e;
  border: 1px solid #ff991e;
  z-index: 1;
  text-decoration: none;
  font-weight: bolder;
  opacity: 0;
  text-align: center;
  transition: opacity .35s ease;
}

.button-div img {
  width: auto;
  height: 320px;
  position: relative;
}

.button-div:hover a.button {
  opacity: 1;
}

.button-div a:hover + #image1 {
  filter: grayscale(100%);
}

<div class="col-md-6 image-1">
    <div class="button-div">
      <a class="button" href="#"> ENTER </a>
      <img src="http://servesphere.com.ph/moto/wp-content/uploads/2017/12/Left-image.png" class="" id="image1" style="">
    </div>

  <div class="centered">
   <p class="title1">BRAND NEW</p>
  </div>
 </div>

Check this out.


答:
Your elements have a given size, as described by your size column. So basically what this tells you is:

Version starts at offset 0x00 (aka, position 0) and has a size of 1, so its the first element: 0xCB

Timestamp starts at offset 0x01 (aka, position 1) and has a size of 15, so its the combined elements: [0xF8, 0xFA, 0xFB, 0xCA, 0xAC, 0x24, 0x53, 0x64, 0x4F, 0x1E, 0xA2, 0xF9, 0x78, 0xCA, 0x63]

Info1 starts at offset 0x10 (aka, position 16) and has a size of 8, so its the combined elements: [0xB8, 0x7F, 0xFC, 0xFB, 0xD8, 0xFA, 0xFB, 0x8F]

Info2 starts at offset 0x18 (aka, position 24) and has a size of 2, so its the combined elements: [0x67, 0xC1]

And so it goes...

One thing that you seem to be getting wrong in your analysis, as others have pointed out is that the offsets are in base 16 (hexadecimal). So 0x10 is 1 * 16 + 0 = 16.

How to interpret each byte sequence as a proper type is up to you.

Does this make sense?

Title: calculate hexadecimal offset within array

Body:
I know in general what  offsets are, but I have a question regarding offsets on the following array. Let's say I have a uint8 array:

   const myArray uint8[]=
   {
   0xCB, 0xF8, 0xFA, 0xFB, 0xCA, 0xAC, 0x24, 0x53, 0x64, 0x4F, 0x1E, 0xA2,
   0xF9, 0x78, 0xCA, 0x63, 0xB8, 0x7F, 0xFC, 0xFB, 0xD8, 0xFA, 0xFB, 0x8F,
   0x67, 0xC1, 0xFD, 0xF8, 0xC2, 0xF8, 0xFF, 0xF9, 0xFA, 0xE4, 0xFA, 0xF9,
   0xFB, 0xFE, 0xE4, 0xFA, 0xCA, 0xCF, 0x94, 0xD5, 0xD6, 0xCA, 0xA2, 0xA2,
   ....
   ....
   ....
   ....
}

Now I have description which says:

--------------------------------------------------
| Offset in myArray | meaning     |  size (Byte) |
--------------------------------------------------
|    0x00           |  Version     |  1          |
-------------------------------------------------
|    0x01           |  Timestamp  |  15         |
 ------------------------------------------------
|    0x10           |  Info1      |   8         |
 ------------------------------------------------
|    0x18           |  Info2      |   2         |
 ------------------------------------------------

Does this in myArray mean:

For offset 0x00: It's the element with index 0 of myArray, so 0xCB

For offset 0x01: It's the element with index 1..9,so 0xF8, 0xFA, 0xFB, 0xCA, 0xAC, 0x24, 0x53, 0x64, 0x4F

etc.

Or do I interpret it wrong?


答:
It should be obvious how to populate your parent table:

```<code>INSERT INTO parent_table (name, details)
SELECT p_name name, p_details details FROM staging_table;
</code>```

The child table you can create the same way, but doing unions of the three pairs of columns

```<code>INSERT INTO child_table (pid, name, details)
SELECT p.id pid, child_1 name, child_details_1 details
  FROM staging_table s
  JOIN parent_table p ON s.p_name = p.name AND s.p_details = p.details
 WHERE child_1 IS NOT NULL
   AND child_details_1 IS NOT NULL

 UNION ALL

SELECT p.id pid, child_2 name, child_details_2 details
  FROM staging_table s
  JOIN parent_table p ON s.p_name = p.name AND s.p_details = p.details
 WHERE child_2 IS NOT NULL
   AND child_details_2 IS NOT NULL

 UNION ALL

SELECT p.id pid, child_3 name, child_details_3 details
  FROM staging_table s
  JOIN parent_table p ON s.p_name = p.name AND s.p_details = p.details
 WHERE child_3 IS NOT NULL
   AND child_details_3 IS NOT NULL;
</code>```

See the three repeating parts of the query?  That's how you handle your denormalized input table.

See the JOIN ... ON .. clauses? That's how you handle getting your pid values into your child_table.

I haven't debugged this.

Title: How to insert data from staging to multiple table with mapping

Body:
What i want is to insert data in mysql table but i unable to find the way to make relationship from one row

i have a staging table which has data like :

            staging_table
+-----------+-------------------+-----------+-------------------+-----------+-------------------+-----------+-------------------+
|  p_name   |      p_details    |  child_1  |  child_details_1  |  child_2  |  child_details_2  |  child_3  |  child_details_3  |
+-----------+-------------------+-----------+-------------------+-----------+-------------------+-----------+-------------------+
|  parent_1 |  parent_details_1 | child_1.1 | child_details_1.1 | child_1.2 | child_details_1.2 |           |                   |
|  parent_2 |  parent_details_2 | child_2.1 | child_details_2.1 |           |                   |           |                   |
|  parent_3 |  parent_details_3 | child_3.1 | child_details_3.1 | child_3.2 | child_details_3.2 | child_3.3 | child_details_3.3 |
+-----------+-------------------+-----------+-------------------+-----------+-------------------+-----------+-------------------+

what i want to achive is to insert data in two table like

            parent_table
+---+-----------+-------------------+
|id |   name    |      details      |
+---+-----------+-------------------+
| 1 |  parent_1 |  parent_details_1 |
| 2 |  parent_2 |  parent_details_2 |
| 3 |  parent_3 |  parent_details_3 |
+---+-----------+-------------------+

              child_table
+---+-----+-----------+-------------------+
|id | pid |   name    |      details      |
+---+-----+-----------+-------------------+
| 1 |  1  | child_1.1 | child_details_1.1 |
| 2 |  1  | child_1.2 | child_details_1.2 |
| 3 |  2  | child_2.1 | child_details_2.1 |
| 4 |  3  | child_3.1 | child_details_3.1 |
| 5 |  3  | child_3.2 | child_details_3.2 |
| 6 |  3  | child_3.3 | child_details_3.3 |
+---+-----+-----------+-------------------+

first two columns is for parent and after that two-two columns belongs to child. so i have to insert child data in child table but if it only insert data if columns has value not on null.

i have tried. if statement for this but unable to make relationship

but what do i do next i have no idea.

Body:
It should be obvious how to populate your parent table:

INSERT INTO parent_table (name, details)
SELECT p_name name, p_details details FROM staging_table;

The child table you can create the same way, but doing unions of the three pairs of columns

INSERT INTO child_table (pid, name, details)
SELECT p.id pid, child_1 name, child_details_1 details
  FROM staging_table s
  JOIN parent_table p ON s.p_name = p.name AND s.p_details = p.details
 WHERE child_1 IS NOT NULL
   AND child_details_1 IS NOT NULL

 UNION ALL

SELECT p.id pid, child_2 name, child_details_2 details
  FROM staging_table s
  JOIN parent_table p ON s.p_name = p.name AND s.p_details = p.details
 WHERE child_2 IS NOT NULL
   AND child_details_2 IS NOT NULL

 UNION ALL

SELECT p.id pid, child_3 name, child_details_3 details
  FROM staging_table s
  JOIN parent_table p ON s.p_name = p.name AND s.p_details = p.details
 WHERE child_3 IS NOT NULL
   AND child_details_3 IS NOT NULL;

See the three repeating parts of the query?  That's how you handle your denormalized input table.

See the JOIN ... ON .. clauses? That's how you handle getting your pid values into your child_table.

I haven't debugged this.


问:
Passing variadic args in Swift 4 for os_log
I am trying to write a convenience wrapper for os_log in Swift 4 / iOS 11, but I've run into an uphill battle with passing the variadic arguments.

Basically, I want to write a function that looks like the following.

```<code>static let logger = OSLog(subsystem: "com.example.foo", category: "foobar")
func logError(_ message: StaticString, _ args: Any...) {
    os_log(message, log: logger, type: .error, args)
}
</code>```

Unfortunately, I can't seem to figure out the magic syntax to get the arguments passed along and have gotten a bit lost in the quagmire of CVarArg discussions.

(... this makes me miss Python's splatting syntax)

答:
I also haven't found solution yet so made this silly hack:</p>

```<code>switch args.count {
case 0:
    os_log(message, log: log!, type: type)
case 1:
    os_log(message, log: log!, type: type, args[0])
case 2:
    os_log(message, log: log!, type: type, args[0], args[1])
case 3:
    os_log(message, log: log!, type: type, args[0], args[1], args[2])
default:
    os_log(message, log: log!, type: type, args)
}
</code>```

Body:
I am trying to write a convenience wrapper for os_log in Swift 4 / iOS 11, but I've run into an uphill battle with passing the variadic arguments.

Basically, I want to write a function that looks like the following.

static let logger = OSLog(subsystem: "com.example.foo", category: "foobar")
func logError(_ message: StaticString, _ args: Any...) {
    os_log(message, log: logger, type: .error, args)
}

Unfortunately, I can't seem to figure out the magic syntax to get the arguments passed along and have gotten a bit lost in the quagmire of CVarArg discussions.

(... this makes me miss Python's splatting syntax)

Body:
I also haven't found solution yet so made this silly hack:

switch args.count {
case 0:
    os_log(message, log: log!, type: type)
case 1:
    os_log(message, log: log!, type: type, args[0])
case 2:
    os_log(message, log: log!, type: type, args[0], args[1])
case 3:
    os_log(message, log: log!, type: type, args[0], args[1], args[2])
default:
    os_log(message, log: log!, type: type, args)
}


问:
C#: Cannot get 100% score for "Path" www.testdome.com/questions/c-sharp/path/12280?visibility=1
Practice on the C# question on the testdome https://www.testdome.com/questions/c-sharp/path/12280?visibility=1. I only get 75% score. Could someone help me to get 100% score? Code attached below</p>

```<code>using System.Collections.Generic;
public class Path {
    public string CurrentPath { get; private set; }

    public Path(string path) {
        this.CurrentPath = path;
    }

    public void Cd(string newPath) {
        //absolute path
        if (newPath.StartsWith("/")) {
            CurrentPath = newPath;
        } else if (newPath.Contains("../")) {
            var pathList = new LinkedList<string>(CurrentPath.Split('/'));
            var newPathList = newPath.Split('/');
            foreach (var item in newPathList) {
                if (item == "..") {
                    if (pathList.Count > 0)
                        pathList.RemoveLast();
                } else {
                    pathList.AddLast(item);
                }
            }
            CurrentPath = string.Join("/", pathList);
            if (!CurrentPath.StartsWith("/"))
                CurrentPath = "/" + CurrentPath;
         } else {
            CurrentPath += "/" + newPath;
        }
    }
}
</code>```

答:
Your code misses test cases when .. appears at the end of the path, e.g.

```<code>some-dir/dir/..
</code>```

Your code prepends / and returns the path without further processing, because the string does not contain "../" search string. Removing forward slash from that string fixes this problem.

Body:
Practice on the C# question on the testdome https://www.testdome.com/questions/c-sharp/path/12280?visibility=1. I only get 75% score. Could someone help me to get 100% score? Code attached below

using System.Collections.Generic;
public class Path {
    public string CurrentPath { get; private set; }

    public Path(string path) {
        this.CurrentPath = path;
    }

    public void Cd(string newPath) {
        //absolute path
        if (newPath.StartsWith("/")) {
            CurrentPath = newPath;
        } else if (newPath.Contains("../")) {
            var pathList = new LinkedList<string>(CurrentPath.Split('/'));
            var newPathList = newPath.Split('/');
            foreach (var item in newPathList) {
                if (item == "..") {
                    if (pathList.Count > 0)
                        pathList.RemoveLast();
                } else {
                    pathList.AddLast(item);
                }
            }
            CurrentPath = string.Join("/", pathList);
            if (!CurrentPath.StartsWith("/"))
                CurrentPath = "/" + CurrentPath;
         } else {
            CurrentPath += "/" + newPath;
        }
    }
}

Body:
Your code misses test cases when .. appears at the end of the path, e.g.

some-dir/dir/..

Your code prepends / and returns the path without further processing, because the string does not contain "../" search string. Removing forward slash from that string fixes this problem.


问:
pthread mutex with a global variable: correct usage?
I understand the purpose of mutex in pthreads, but I often here that it is considered a bad practice to use mutex with a global variable as a shared resource (for example, like in the answer to this question: Mutex lock threads).

So, the questions:

Is it really that bad to put the shared resource as a global variable?

If you have only 1 shared variable, like in the example, would it be considered ok to use a global variable, or still no?

What is the better way to share the variables between the processes?

答:
Is it really that bad to put the shared resource as a global variable?

It depends , It is up to the developer to decide . But in general we need to be cautious about using the shared variable as a global one . For example if the program is so simple , then it is easy to manage global variables , if the program is complex and large enough with its own other complexities , it is somewhat not easy to maintain .

If you have only 1 shared variable, like in the example, would it be considered ok to use a global variable, or still no?

Above answer answers this question as well.

What is the better way to share the variables between the processes?

You can go ahead with some kind of serialization method which suits for you .


问:
run python script from google home
I am trying to figure out if it is possible to trigger a python script to be run using google home? I would like to do something like saying "Hey Google run my python script." And from the Google home would execute running my python script. Anyone know if that is possible? </p>

答:
I had to do this for my assistant as well. Here's what I did:

First I made a PHP script which wraps my Python script.
The code goes like this:

```<code><?php
$resolved_query = $_POST['resolved_query'];
$keywords=shell_exec('/usr/bin/python <YOUR PYTHON FILE NAME>.py "'.$resolved_query.'"');
echo $keywords;
?>
</code>```

Next I changed my Default Fallback Intent in dialogflow so that it uses webhook. You can see this option at the bottom of the page in Default Fallback Intent.

Now, in order for you to return the result from Python script, just print the result in your Python script. Like:

```<code>print result
</code>```

Now, if your Python file executes successfully, the result will be stored in $keywords. Just print that out and your response will be back at dialogflow.

This is basically how you can get your Python script to be run by dialogflow.

Title: run python script from google home

Body:
I had to do this for my assistant as well. Here's what I did:

First I made a PHP script which wraps my Python script.
The code goes like this:

<?php
$resolved_query = $_POST['resolved_query'];
$keywords=shell_exec('/usr/bin/python <YOUR PYTHON FILE NAME>.py "'.$resolved_query.'"');
echo $keywords;
?>

Next I changed my Default Fallback Intent in dialogflow so that it uses webhook. You can see this option at the bottom of the page in Default Fallback Intent.

Now, in order for you to return the result from Python script, just print the result in your Python script. Like:

print result

Now, if your Python file executes successfully, the result will be stored in $keywords. Just print that out and your response will be back at dialogflow.

This is basically how you can get your Python script to be run by dialogflow.


问:
open excel file python so it is visible
I'm trying to open a excel so it is displayed visibly.

I am using:

```<code>import subprocess
subprocess.check_call(['open', '-a', 'C:\\1\\2\\22.xlsx'])
</code>```

https://ibb.co/eOhY4b

Sorry if this is obvious but I keep getting this error message.  AS far as I can tell the file is located there.

```<code>FileNotFoundError: [WinError 2] The system cannot find the file specified
</code>```

答:
Not sure why

```<code>import os
os.path.join('C:', '1', '2', '22.xlsx')
</code>```

Did not work.  I think it worked but there was no visible excel.

Anyway, this works

```<code>xl=win32com.client.Dispatch("Excel.Application")
xl.Visible = True

xl.Workbooks.Open("C:\\1\\2\\22.xlsx")
</code>```

Title: open excel file python so it is visible

Body:
I'm trying to open a excel so it is displayed visibly.

I am using:

import subprocess
subprocess.check_call(['open', '-a', 'C:\\1\\2\\22.xlsx'])

https://ibb.co/eOhY4b

Sorry if this is obvious but I keep getting this error message.  AS far as I can tell the file is located there.

FileNotFoundError: [WinError 2] The system cannot find the file specified

Body:
Not sure why

import os
os.path.join('C:', '1', '2', '22.xlsx')

Did not work.  I think it worked but there was no visible excel.

Anyway, this works

xl=win32com.client.Dispatch("Excel.Application")
xl.Visible = True

xl.Workbooks.Open("C:\\1\\2\\22.xlsx")


问:
Sqoop import error: Access denied for user 'root'@'localhost' , even if rights are OK
I found a lot of people with the similar error but no tips are working for my problem.

My command line:

```<code>sqoop import --connect jdbc:mysql://localhost/databaseY --username=root -P --table tableX --target-dir /user/ec2-user/databaseY/tableX --as-textfile --fields-terminated-by "\t"
</code>```

The error

```<code>16/08/19 11:25:51 INFO mapreduce.Job: Job job_1471608424445_0028 running in uber mode : false
16/08/19 11:25:51 INFO mapreduce.Job:  map 0% reduce 0%
16/08/19 11:25:58 INFO mapreduce.Job:  map 25% reduce 0%
16/08/19 11:26:04 INFO mapreduce.Job:  map 50% reduce 0%
16/08/19 11:26:06 INFO mapreduce.Job: Task Id :     attempt_1471608424445_0028_m_000000_0, Status : FAILED
Error: java.lang.RuntimeException: java.lang.RuntimeException: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
</code>```

How it is possible that the map start and stop after due to this error?

It looks like I have all the right needed as this two command line are working:

```<code>sqoop list-databases --connect jdbc:mysql://localhost --username root -P
</code>```

And

On mysql with root account I can do

```<code>select * from databaseY.tableX
</code>```

---EDIT---

This command line is working:

```<code>sqoop import --connect jdbc:mysql://localhost/databaseY --username root --password PASSWORD --query "select * from databaseY.tableX where number = 1474 AND \$CONDITIONS" --target-dir /tmp/ok --as-textfile --direct --split-by number
</code>```

but this one no:

```<code>sqoop import --connect jdbc:mysql://localhost/databaseY --username root --password PASSWORD --query "select * from databaseY.tableX where 1 = 1 AND \$CONDITIONS" --target-dir /tmp/ok --as-textfile --direct --split-by number
</code>```

Then, I realized that if I use -m 1 my sqoop import is working. Only with -m 1

Does it mean I have a bad cluster configuration? Why my job is working only with one map task?

----- SOLUTION -----

It was simply a problem of the IP address. I changed localhost by the IP address and it is working fine now.

答:
Late but not least, I think I am going to give the answer part here in this thread

similar issue I were facing with sqoop in importing the table data from host windows machine to virtual box guest ubuntu os, just because of my windows host machine installed mysql server username doesn't have sufficient privileges for granting connection and schema over remote request.

So, now not talking much on issue I am illustrating the issue I were facing -

```<code>vm4learning@vm4learning:~/Installations/sqoop-1.4.4$ bin/sqoop import --connect jdbc:mysql://192.168.56.1/india --table india_most_populated_cities --target-dir /user/vm4learning/remotedir/ --username root --password password -m 1
no main manifest attribute, in /home/vm4learning/Installations/hbase-0.94.14/lib/coprocessor.jar
find: paths must precede expression: sqoop-test-1.4.4.jar
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
Warning: $HADOOP_HOME is deprecated.

17/12/06 11:01:10 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead.
17/12/06 11:01:11 INFO manager.MySQLManager: Preparing to use a MySQL streaming resultset.
17/12/06 11:01:11 INFO tool.CodeGenTool: Beginning code generation
17/12/06 11:01:13 ERROR manager.SqlManager: Error executing statement: java.sql.SQLException: Access denied for user 'root'@'Administrator' (using password: YES)
java.sql.SQLException: Access denied for user 'root'@'Administrator' (using password: YES)
</code>```

Then, I came to my windows host machine, run ipconfig from cmd and first get the ipaddress of the host machine and in linux(ubuntu) it is "ifconfig":

```<code>Ethernet adapter VirtualBox Host-Only Network:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::54d4:4f16:4bdb:885%18
   IPv4 Address. . . . . . . . . . . : 192.168.56.1
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :
</code>```

So here my ip address is 192.168.56.1 in windows host machine and then I login into mysql through command in windows host and run below said scripts for granting the privilege -

mysql -u root -p
Enter password: ********

mysql> GRANT ALL ON . TO root@'192.168.56.1' IDENTIFIED BY 'password';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> exit

that's it, and then I go the guest ubuntu machine inside virtual box (by doing this my windows were connected with wifi internet) and re-run the same above said sqoop command and that imports my desired table data to the cluster.

I would like to share the lines I got after successfully script run -

```<code>vm4learning@vm4learning:~/Installations/sqoop-1.4.4$ bin/sqoop import --connect jdbc:mysql://192.168.56.1/india --table india_most_populated_cities --target-dir /user/vm4learning/remotedir/ --username root --password password -m 1
no main manifest attribute, in /home/vm4learning/Installations/hbase-0.94.14/lib/coprocessor.jar
find: paths must precede expression: sqoop-test-1.4.4.jar
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
Warning: $HADOOP_HOME is deprecated.

17/12/06 17:00:55 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead.
17/12/06 17:00:55 INFO manager.MySQLManager: Preparing to use a MySQL streaming resultset.
17/12/06 17:00:55 INFO tool.CodeGenTool: Beginning code generation
17/12/06 17:00:58 INFO manager.SqlManager: Executing SQL statement: SELECT t.* FROM `india_most_populated_cities` AS t LIMIT 1
17/12/06 17:00:58 INFO manager.SqlManager: Executing SQL statement: SELECT t.* FROM `india_most_populated_cities` AS t LIMIT 1
17/12/06 17:00:58 INFO orm.CompilationManager: HADOOP_MAPRED_HOME is /home/vm4learning/Installations/hadoop-1.2.1
Note: /tmp/sqoop-vm4learning/compile/fc8e526de8f7a74171941455a22f573f/india_most_populated_cities.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
17/12/06 17:01:02 INFO orm.CompilationManager: Writing jar file: /tmp/sqoop-vm4learning/compile/fc8e526de8f7a74171941455a22f573f/india_most_populated_cities.jar
17/12/06 17:01:02 WARN manager.MySQLManager: It looks like you are importing from mysql.
17/12/06 17:01:02 WARN manager.MySQLManager: This transfer can be faster! Use the --direct
17/12/06 17:01:02 WARN manager.MySQLManager: option to exercise a MySQL-specific fast path.
17/12/06 17:01:02 INFO manager.MySQLManager: Setting zero DATETIME behavior to convertToNull (mysql)
17/12/06 17:01:02 INFO mapreduce.ImportJobBase: Beginning import of india_most_populated_cities
17/12/06 17:01:06 INFO mapred.JobClient: Running job: job_201712061003_0002
17/12/06 17:01:07 INFO mapred.JobClient:  map 0% reduce 0%
17/12/06 17:01:29 INFO mapred.JobClient:  map 100% reduce 0%
17/12/06 17:01:36 INFO mapred.JobClient: Job complete: job_201712061003_0002
17/12/06 17:01:37 INFO mapred.JobClient: Counters: 18
17/12/06 17:01:37 INFO mapred.JobClient:   Job Counters
17/12/06 17:01:37 INFO mapred.JobClient:     SLOTS_MILLIS_MAPS=24525
17/12/06 17:01:37 INFO mapred.JobClient:     Total time spent by all reduces waiting after reserving slots (ms)=0
17/12/06 17:01:37 INFO mapred.JobClient:     Total time spent by all maps waiting after reserving slots (ms)=0
17/12/06 17:01:37 INFO mapred.JobClient:     Launched map tasks=1
17/12/06 17:01:37 INFO mapred.JobClient:     SLOTS_MILLIS_REDUCES=0
17/12/06 17:01:37 INFO mapred.JobClient:   File Output Format Counters
17/12/06 17:01:37 INFO mapred.JobClient:     Bytes Written=10406
17/12/06 17:01:37 INFO mapred.JobClient:   FileSystemCounters
17/12/06 17:01:37 INFO mapred.JobClient:     HDFS_BYTES_READ=87
17/12/06 17:01:37 INFO mapred.JobClient:     FILE_BYTES_WRITTEN=80423
17/12/06 17:01:37 INFO mapred.JobClient:     HDFS_BYTES_WRITTEN=10406
17/12/06 17:01:37 INFO mapred.JobClient:   File Input Format Counters
17/12/06 17:01:37 INFO mapred.JobClient:     Bytes Read=0
17/12/06 17:01:37 INFO mapred.JobClient:   Map-Reduce Framework
17/12/06 17:01:37 INFO mapred.JobClient:     Map input records=271
17/12/06 17:01:37 INFO mapred.JobClient:     Physical memory (bytes) snapshot=81043456
17/12/06 17:01:37 INFO mapred.JobClient:     Spilled Records=0
17/12/06 17:01:37 INFO mapred.JobClient:     CPU time spent (ms)=2530
17/12/06 17:01:37 INFO mapred.JobClient:     Total committed heap usage (bytes)=49807360
17/12/06 17:01:37 INFO mapred.JobClient:     Virtual memory (bytes) snapshot=973082624
17/12/06 17:01:37 INFO mapred.JobClient:     Map output records=271
17/12/06 17:01:37 INFO mapred.JobClient:     SPLIT_RAW_BYTES=87
17/12/06 17:01:37 INFO mapreduce.ImportJobBase: Transferred 10.1621 KB in 33.9572 seconds (306.4444 bytes/sec)
17/12/06 17:01:37 INFO mapreduce.ImportJobBase: Retrieved 271 records.
</code>```

Hope it will help you and also bring my post the answer of this thread, thanks.

Body:
I found a lot of people with the similar error but no tips are working for my problem.

My command line:

sqoop import --connect jdbc:mysql://localhost/databaseY --username=root -P --table tableX --target-dir /user/ec2-user/databaseY/tableX --as-textfile --fields-terminated-by "\t"

The error

16/08/19 11:25:51 INFO mapreduce.Job: Job job_1471608424445_0028 running in uber mode : false
16/08/19 11:25:51 INFO mapreduce.Job:  map 0% reduce 0%
16/08/19 11:25:58 INFO mapreduce.Job:  map 25% reduce 0%
16/08/19 11:26:04 INFO mapreduce.Job:  map 50% reduce 0%
16/08/19 11:26:06 INFO mapreduce.Job: Task Id :     attempt_1471608424445_0028_m_000000_0, Status : FAILED
Error: java.lang.RuntimeException: java.lang.RuntimeException: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

How it is possible that the map start and stop after due to this error?

It looks like I have all the right needed as this two command line are working:

sqoop list-databases --connect jdbc:mysql://localhost --username root -P

And

On mysql with root account I can do

select * from databaseY.tableX

---EDIT---

This command line is working:

sqoop import --connect jdbc:mysql://localhost/databaseY --username root --password PASSWORD --query "select * from databaseY.tableX where number = 1474 AND \$CONDITIONS" --target-dir /tmp/ok --as-textfile --direct --split-by number

but this one no:

sqoop import --connect jdbc:mysql://localhost/databaseY --username root --password PASSWORD --query "select * from databaseY.tableX where 1 = 1 AND \$CONDITIONS" --target-dir /tmp/ok --as-textfile --direct --split-by number

Then, I realized that if I use -m 1 my sqoop import is working. Only with -m 1

Does it mean I have a bad cluster configuration? Why my job is working only with one map task?

----- SOLUTION -----

It was simply a problem of the IP address. I changed localhost by the IP address and it is working fine now.

Body:
Late but not least, I think I am going to give the answer part here in this thread

similar issue I were facing with sqoop in importing the table data from host windows machine to virtual box guest ubuntu os, just because of my windows host machine installed mysql server username doesn't have sufficient privileges for granting connection and schema over remote request.

So, now not talking much on issue I am illustrating the issue I were facing -

vm4learning@vm4learning:~/Installations/sqoop-1.4.4$ bin/sqoop import --connect jdbc:mysql://192.168.56.1/india --table india_most_populated_cities --target-dir /user/vm4learning/remotedir/ --username root --password password -m 1
no main manifest attribute, in /home/vm4learning/Installations/hbase-0.94.14/lib/coprocessor.jar
find: paths must precede expression: sqoop-test-1.4.4.jar
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
Warning: $HADOOP_HOME is deprecated.

17/12/06 11:01:10 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead.
17/12/06 11:01:11 INFO manager.MySQLManager: Preparing to use a MySQL streaming resultset.
17/12/06 11:01:11 INFO tool.CodeGenTool: Beginning code generation
17/12/06 11:01:13 ERROR manager.SqlManager: Error executing statement: java.sql.SQLException: Access denied for user 'root'@'Administrator' (using password: YES)
java.sql.SQLException: Access denied for user 'root'@'Administrator' (using password: YES)

Then, I came to my windows host machine, run ipconfig from cmd and first get the ipaddress of the host machine and in linux(ubuntu) it is "ifconfig":

Ethernet adapter VirtualBox Host-Only Network:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::54d4:4f16:4bdb:885%18
   IPv4 Address. . . . . . . . . . . : 192.168.56.1
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :

So here my ip address is 192.168.56.1 in windows host machine and then I login into mysql through command in windows host and run below said scripts for granting the privilege -

mysql -u root -p
Enter password: ********

mysql> GRANT ALL ON . TO root@'192.168.56.1' IDENTIFIED BY 'password';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> exit

that's it, and then I go the guest ubuntu machine inside virtual box (by doing this my windows were connected with wifi internet) and re-run the same above said sqoop command and that imports my desired table data to the cluster.

I would like to share the lines I got after successfully script run -

vm4learning@vm4learning:~/Installations/sqoop-1.4.4$ bin/sqoop import --connect jdbc:mysql://192.168.56.1/india --table india_most_populated_cities --target-dir /user/vm4learning/remotedir/ --username root --password password -m 1
no main manifest attribute, in /home/vm4learning/Installations/hbase-0.94.14/lib/coprocessor.jar
find: paths must precede expression: sqoop-test-1.4.4.jar
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
Warning: $HADOOP_HOME is deprecated.

17/12/06 17:00:55 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead.
17/12/06 17:00:55 INFO manager.MySQLManager: Preparing to use a MySQL streaming resultset.
17/12/06 17:00:55 INFO tool.CodeGenTool: Beginning code generation
17/12/06 17:00:58 INFO manager.SqlManager: Executing SQL statement: SELECT t.* FROM `india_most_populated_cities` AS t LIMIT 1
17/12/06 17:00:58 INFO manager.SqlManager: Executing SQL statement: SELECT t.* FROM `india_most_populated_cities` AS t LIMIT 1
17/12/06 17:00:58 INFO orm.CompilationManager: HADOOP_MAPRED_HOME is /home/vm4learning/Installations/hadoop-1.2.1
Note: /tmp/sqoop-vm4learning/compile/fc8e526de8f7a74171941455a22f573f/india_most_populated_cities.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
17/12/06 17:01:02 INFO orm.CompilationManager: Writing jar file: /tmp/sqoop-vm4learning/compile/fc8e526de8f7a74171941455a22f573f/india_most_populated_cities.jar
17/12/06 17:01:02 WARN manager.MySQLManager: It looks like you are importing from mysql.
17/12/06 17:01:02 WARN manager.MySQLManager: This transfer can be faster! Use the --direct
17/12/06 17:01:02 WARN manager.MySQLManager: option to exercise a MySQL-specific fast path.
17/12/06 17:01:02 INFO manager.MySQLManager: Setting zero DATETIME behavior to convertToNull (mysql)
17/12/06 17:01:02 INFO mapreduce.ImportJobBase: Beginning import of india_most_populated_cities
17/12/06 17:01:06 INFO mapred.JobClient: Running job: job_201712061003_0002
17/12/06 17:01:07 INFO mapred.JobClient:  map 0% reduce 0%
17/12/06 17:01:29 INFO mapred.JobClient:  map 100% reduce 0%
17/12/06 17:01:36 INFO mapred.JobClient: Job complete: job_201712061003_0002
17/12/06 17:01:37 INFO mapred.JobClient: Counters: 18
17/12/06 17:01:37 INFO mapred.JobClient:   Job Counters
17/12/06 17:01:37 INFO mapred.JobClient:     SLOTS_MILLIS_MAPS=24525
17/12/06 17:01:37 INFO mapred.JobClient:     Total time spent by all reduces waiting after reserving slots (ms)=0
17/12/06 17:01:37 INFO mapred.JobClient:     Total time spent by all maps waiting after reserving slots (ms)=0
17/12/06 17:01:37 INFO mapred.JobClient:     Launched map tasks=1
17/12/06 17:01:37 INFO mapred.JobClient:     SLOTS_MILLIS_REDUCES=0
17/12/06 17:01:37 INFO mapred.JobClient:   File Output Format Counters
17/12/06 17:01:37 INFO mapred.JobClient:     Bytes Written=10406
17/12/06 17:01:37 INFO mapred.JobClient:   FileSystemCounters
17/12/06 17:01:37 INFO mapred.JobClient:     HDFS_BYTES_READ=87
17/12/06 17:01:37 INFO mapred.JobClient:     FILE_BYTES_WRITTEN=80423
17/12/06 17:01:37 INFO mapred.JobClient:     HDFS_BYTES_WRITTEN=10406
17/12/06 17:01:37 INFO mapred.JobClient:   File Input Format Counters
17/12/06 17:01:37 INFO mapred.JobClient:     Bytes Read=0
17/12/06 17:01:37 INFO mapred.JobClient:   Map-Reduce Framework
17/12/06 17:01:37 INFO mapred.JobClient:     Map input records=271
17/12/06 17:01:37 INFO mapred.JobClient:     Physical memory (bytes) snapshot=81043456
17/12/06 17:01:37 INFO mapred.JobClient:     Spilled Records=0
17/12/06 17:01:37 INFO mapred.JobClient:     CPU time spent (ms)=2530
17/12/06 17:01:37 INFO mapred.JobClient:     Total committed heap usage (bytes)=49807360
17/12/06 17:01:37 INFO mapred.JobClient:     Virtual memory (bytes) snapshot=973082624
17/12/06 17:01:37 INFO mapred.JobClient:     Map output records=271
17/12/06 17:01:37 INFO mapred.JobClient:     SPLIT_RAW_BYTES=87
17/12/06 17:01:37 INFO mapreduce.ImportJobBase: Transferred 10.1621 KB in 33.9572 seconds (306.4444 bytes/sec)
17/12/06 17:01:37 INFO mapreduce.ImportJobBase: Retrieved 271 records.

Hope it will help you and also bring my post the answer of this thread, thanks.


问:
Drag a div smoothly
I want to create a draggable div. I wonder how I could improve the regarding browser rendering and a smooth result.

jsfiddle

reactJS

```<code> mouseDown() {
this.setState({
  thumbActive: true,
});
},

mouseUp() {
this.setState({
  thumbActive: false,
});
},

mouseMove(e) {
  if(!this.state.thumbActive) {
  return;
  }

  const y = e.nativeEvent.offsetY;
  this.setState({
  topPosition: y,
  });
},
</code>```

HTML

```<code>  <div
      className='scroll'
      onMouseMove={this.mouseMove}
    >
      <div className={this.state.thumbActive ? 'thumb pointer-events-none' : 'thumb'}
        onMouseDown={this.mouseDown}
        onMouseUp={this.mouseUp}
        style={{top: this.state.topPosition}}
      />
    </div>
</code>```

答:
try with drag and drop plugins, which saves lots of time.

plugin - react-dnd

Title: Drag a div smoothly

Body:
I want to create a draggable div. I wonder how I could improve the regarding browser rendering and a smooth result.

jsfiddle

reactJS

 mouseDown() {
this.setState({
  thumbActive: true,
});
},

mouseUp() {
this.setState({
  thumbActive: false,
});
},

mouseMove(e) {
  if(!this.state.thumbActive) {
  return;
  }

  const y = e.nativeEvent.offsetY;
  this.setState({
  topPosition: y,
  });
},

HTML


问:
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?

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

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

In controller,

```<code>    $vehicles = Vehicle::all();
    return view('vehicles.vehicle',['vehicles'=>$vehicles]);
</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:
In Model,
 class Vehicle extends Model
 {
protected $guarded = [];
protected $table = 'vehicles';

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

In controller,

    $vehicles = Vehicle::all();
    return view('vehicles.vehicle',['vehicles'=>$vehicles]);


问:
Rails ActiveRecord summary statement
How to translate this simple query to ruby on rails ActiveRecord

select sum(current*progress) from features;

i have tried

```<code> @feature = Feature.where(project_detail_id: @project_detail.id )
 @current_progress =  @feature.current * @feature.progress
 @total_current_progress =  @feature.sum(@current_progress)
</code>```

but nothing works
i cannot get @total_current_progress result

thanks in advance

答:
Try this:</p>

```<code>@total_current_progress = Feature.where(project_detail_id: @project_detail.id).sum("current*progress")
</code>```

Title: Rails ActiveRecord summary statement

Body:
How to translate this simple query to ruby on rails ActiveRecord

select sum(current*progress) from features;

i have tried

 @feature = Feature.where(project_detail_id: @project_detail.id )
 @current_progress =  @feature.current * @feature.progress
 @total_current_progress =  @feature.sum(@current_progress)

but nothing works
i cannot get @total_current_progress result

thanks in advance

Body:
Try this:

@total_current_progress = Feature.where(project_detail_id: @project_detail.id).sum("current*progress")


问:
Google App Engine Task Deadline
is there a way to handle any soft deadline while executing a task ?
The DeadlineExceededError is thrown after 10 minutes of execution and I am given few seconds after that to do some stuff.
I want to clean up somethings before the task dies and create a new task. This may take few seconds. Is there a way to do this by capturing any exception like around 9 mins.
I know I can manually throw an exception after 9 mins. But can this be done automatically by GAE ?

```<code>class FillMtxHandler():

def post(self,index,user,seqlen):

    try :
        FillMtx(index,user,seqlen)

    except DeadlineExceededError:

        deferred.defer(self.post,index,user,seqlen)
</code>```

The above is my code. index is a list and starts from 0. It will be incremented inside FillMtx. Once a deadline exceeded error is thrown, i want to continue from where index was incremented last. I get the following error

```<code>   The API call taskqueue.BulkAdd() was explicitly cancelled.
Traceback (most recent call last):
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 517, in __call__
    handler.post(*groups)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/deferred/deferred.py", line 258, in post
    run(self.request.body)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/deferred/deferred.py", line 124, in run
    return func(*args, **kwds)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/deferred/deferred.py", line 166, in invoke_member
    return getattr(obj, membername)(*args, **kwargs)
  File "/base/data/home/apps/0xxopdp/3.347813391084738922/fillmtx.py", line 204, in post
    deferred.defer(self.post,index,user,seqlen)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/deferred/deferred.py", line 241, in defer
    return task.add(queue, transactional=transactional)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/taskqueue/taskqueue.py", line 688, in add
    return Queue(queue_name).add(self, transactional=transactional)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/taskqueue/taskqueue.py", line 744, in add
    self.__AddTasks(tasks, transactional)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/taskqueue/taskqueue.py", line 770, in __AddTasks
    apiproxy_stub_map.MakeSyncCall('taskqueue', 'BulkAdd', request, response)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 86, in MakeSyncCall
    return stubmap.MakeSyncCall(service, call, request, response)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 286, in MakeSyncCall
    rpc.CheckSuccess()
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/apiproxy_rpc.py", line 126, in CheckSuccess
    raise self.exception
CancelledError: The API call taskqueue.BulkAdd() was explicitly cancelled.
</code>```

I find that a new task has been created and queued up. But why does GAE throw this error still?

答:
You don't have to raise an exception after 9 minutes; when the soft deadline exception raises, you have enough time to add a clean-up task to the Task Queue via deferred.

```<code>from google.appengine.ext import deferred
...
try:
  # Do your stuff
except DeadlineExceededError:
  deferred.defer(do_your_cleanup, ..)
</code>```

In this way you have 10 minutes to do any clean-up stuff you need in your app.

Title: Google App Engine Task Deadline

Body:
is there a way to handle any soft deadline while executing a task ?
The DeadlineExceededError is thrown after 10 minutes of execution and I am given few seconds after that to do some stuff.
I want to clean up somethings before the task dies and create a new task. This may take few seconds. Is there a way to do this by capturing any exception like around 9 mins.
I know I can manually throw an exception after 9 mins. But can this be done automatically by GAE ?

class FillMtxHandler():

def post(self,index,user,seqlen):

    try :
        FillMtx(index,user,seqlen)

    except DeadlineExceededError:

        deferred.defer(self.post,index,user,seqlen)

The above is my code. index is a list and starts from 0. It will be incremented inside FillMtx. Once a deadline exceeded error is thrown, i want to continue from where index was incremented last. I get the following error

   The API call taskqueue.BulkAdd() was explicitly cancelled.
Traceback (most recent call last):
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 517, in __call__
    handler.post(*groups)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/deferred/deferred.py", line 258, in post
    run(self.request.body)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/deferred/deferred.py", line 124, in run
    return func(*args, **kwds)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/deferred/deferred.py", line 166, in invoke_member
    return getattr(obj, membername)(*args, **kwargs)
  File "/base/data/home/apps/0xxopdp/3.347813391084738922/fillmtx.py", line 204, in post
    deferred.defer(self.post,index,user,seqlen)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/deferred/deferred.py", line 241, in defer
    return task.add(queue, transactional=transactional)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/taskqueue/taskqueue.py", line 688, in add
    return Queue(queue_name).add(self, transactional=transactional)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/taskqueue/taskqueue.py", line 744, in add
    self.__AddTasks(tasks, transactional)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/taskqueue/taskqueue.py", line 770, in __AddTasks
    apiproxy_stub_map.MakeSyncCall('taskqueue', 'BulkAdd', request, response)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 86, in MakeSyncCall
    return stubmap.MakeSyncCall(service, call, request, response)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 286, in MakeSyncCall
    rpc.CheckSuccess()
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/apiproxy_rpc.py", line 126, in CheckSuccess
    raise self.exception
CancelledError: The API call taskqueue.BulkAdd() was explicitly cancelled.

I find that a new task has been created and queued up. But why does GAE throw this error still?

Body:
You don't have to raise an exception after 9 minutes; when the soft deadline exception raises, you have enough time to add a clean-up task to the Task Queue via deferred.

from google.appengine.ext import deferred
...
try:
  # Do your stuff
except DeadlineExceededError:
  deferred.defer(do_your_cleanup, ..)

In this way you have 10 minutes to do any clean-up stuff you need in your app.


问:
Why applied Font is removed upon font.dispose() in swt?
I have created an SWT Table and added columns to it. I want to apply bold font to header row alone. So my code looks like below

```<code> Table table= new Table(top, tableStyle);
 Font font = new Font(null, StringUtils.EMPTY, 9, SWT.BOLD);
 for (int i = 0; i < titles.length; i++)
 {
        new TableColumn(table, SWT.NONE);
        header.setFont(i, font);
        header.setText(i, titles[i]);
 }
 font.dispose();
</code>```

In the above code, I have disposed as it is a good practice to do. But this is removing the font style from the header. If I remove the last line, font remains applied.

Is there any mistake over here? Or is this the expected behavior?

答:
You need to wait and only dispose() the Font when you no longer need it. You could tie the disposal to the dispose event of the table so you don't have to manually dispose it:

```<code>public static void main(String[] args)
{
    final Display d = new Display();
    Shell s = new Shell(d);
    s.setLayout(new FillLayout());

    Table table = new Table(s, SWT.NONE);
    Font font = new Font(null, "", 12, SWT.BOLD);
    for (int i = 0; i < 3; i++)
    {
        TableItem item = new TableItem(table, SWT.NONE);
        item.setFont(font);
        item.setText("" + i);
    }

    table.addListener(SWT.Dispose, e -> font.dispose());

    s.pack();
    s.open();

    while (!s.isDisposed())
    {
        if (!d.readAndDispatch())
            d.sleep();
    }
    d.dispose();
}
</code>```

Body:
I have created an SWT Table and added columns to it. I want to apply bold font to header row alone. So my code looks like below

 Table table= new Table(top, tableStyle);
 Font font = new Font(null, StringUtils.EMPTY, 9, SWT.BOLD);
 for (int i = 0; i < titles.length; i++)
 {
        new TableColumn(table, SWT.NONE);
        header.setFont(i, font);
        header.setText(i, titles[i]);
 }
 font.dispose();

In the above code, I have disposed as it is a good practice to do. But this is removing the font style from the header. If I remove the last line, font remains applied.

Is there any mistake over here? Or is this the expected behavior?

Body:
You need to wait and only dispose() the Font when you no longer need it. You could tie the disposal to the dispose event of the table so you don't have to manually dispose it:

public static void main(String[] args)
{
    final Display d = new Display();
    Shell s = new Shell(d);
    s.setLayout(new FillLayout());

    Table table = new Table(s, SWT.NONE);
    Font font = new Font(null, "", 12, SWT.BOLD);
    for (int i = 0; i < 3; i++)
    {
        TableItem item = new TableItem(table, SWT.NONE);
        item.setFont(font);
        item.setText("" + i);
    }

    table.addListener(SWT.Dispose, e -> font.dispose());

    s.pack();
    s.open();

    while (!s.isDisposed())
    {
        if (!d.readAndDispatch())
            d.sleep();
    }
    d.dispose();
}


问:
How to define 'phi' so I don't get an error for trying to multiply a non-int by a complex number in the exponential
Using:

```<code>arr2 = np.array([np.arange(0,20)]*20,dtype=np.complex_)

for a in range(arr2.shape[0]):
 for b in range(arr2.shape[1]):
    if a-b:
        arr2[a,b] =1-(1j/np.sqrt(3))
    else:
        arr2[a,b] = np.e**(1j*phi*abs(a-b))
</code>```

to produce a matrix of size N * N which I have defined as a * b above gives the error 'TypeError: can't multiply sequence by non-int of type 'complex''.

I need to define \phi however I do not want python to solve it numerically.
I want my output to be of the form (this is just an example of the first 3 terms of the first 3 lines of the matrix where i is an imaginary number):

```<code>( 1-(i/sqrt(3)) ,    e^(i{\phi})    ,    e^(2i{\phi})  ,  ... )
( e^(i{\phi})   ,  1-(i/sqrt(3))    ,    e^(i{\phi})   ,  ... )
( e^(2i{\phi})  ,    e^(i{\phi})    ,  1-(i/sqrt(3))   ,  ... )
(     ...       ,       ...         ,      ...         ,  ... )
</code>```

instead of trying to numerically solve this matrix, is there a way to express the matrix in the general form I have displayed above? Would a simple

```<code>arr2inv = inv(np.matrix(arr2))
</code>```

return the inverse of the general form I want or produce an error?

So to summarise:

How do I define phi to remove the complex-non-int error?

How do I get python to produce the general form shown above?

Will it invert without an error?

答:
The simplest and faster way to do that numerically is :

```<code>i=np.arange(20)
phi = (1 + np.sqrt(5))/2                       # for example  :)
a_b = np.abs(np.subtract.outer(i,i))           # make all the differences in a matrix
arr2 = np.exp(1j*phi*a_b)                      # compute the exp
np.fill_diagonal(arr2, 1-1j/np.sqrt(3))        # set the diag
</code>```

For symbolic approach python have the sympy module which can manage that ;
 it will probably difficultly simplify inv(arr2) with rank = 20. but numpy is good to quickly check a mathematical assumption.

Body:
Using:

arr2 = np.array([np.arange(0,20)]*20,dtype=np.complex_)

for a in range(arr2.shape[0]):
 for b in range(arr2.shape[1]):
    if a-b:
        arr2[a,b] =1-(1j/np.sqrt(3))
    else:
        arr2[a,b] = np.e**(1j*phi*abs(a-b))

to produce a matrix of size N * N which I have defined as a * b above gives the error 'TypeError: can't multiply sequence by non-int of type 'complex''.

I need to define \phi however I do not want python to solve it numerically.
I want my output to be of the form (this is just an example of the first 3 terms of the first 3 lines of the matrix where i is an imaginary number):

( 1-(i/sqrt(3)) ,    e^(i{\phi})    ,    e^(2i{\phi})  ,  ... )
( e^(i{\phi})   ,  1-(i/sqrt(3))    ,    e^(i{\phi})   ,  ... )
( e^(2i{\phi})  ,    e^(i{\phi})    ,  1-(i/sqrt(3))   ,  ... )
(     ...       ,       ...         ,      ...         ,  ... )

instead of trying to numerically solve this matrix, is there a way to express the matrix in the general form I have displayed above? Would a simple

arr2inv = inv(np.matrix(arr2))

return the inverse of the general form I want or produce an error?

So to summarise:

How do I define phi to remove the complex-non-int error?

How do I get python to produce the general form shown above?

Will it invert without an error?

Body:
The simplest and faster way to do that numerically is :

i=np.arange(20)
phi = (1 + np.sqrt(5))/2                       # for example  :)
a_b = np.abs(np.subtract.outer(i,i))           # make all the differences in a matrix
arr2 = np.exp(1j*phi*a_b)                      # compute the exp
np.fill_diagonal(arr2, 1-1j/np.sqrt(3))        # set the diag

For symbolic approach python have the sympy module which can manage that ;
 it will probably difficultly simplify inv(arr2) with rank = 20. but numpy is good to quickly check a mathematical assumption.


问:
Parent child relation in C# classes
I have the following case:

```<code>public class ParentObject
{
public int id {get;set;}
public string parent_object_name {get;set;}
public List<ChildObject> child_objects {get;set;}
}

public class ChildObject
{
public int id {get;set;}
public string child_object_name {get;set;}
}

ParentObject parent_object = new ParentObject()
{
  id = 1,
  parent_object_name = "test name",
  child_objects = new List<ChildObject>(){ new ChildObject(){ id = 1, child_object_name = "test name"};
}
</code>```

I am aware that it is perfectly valid to reference parent_object.child_objects, but I am not sure how can I code my classes to have a reference such as child_objects.First().parent_object ie. similar to navigational properties in Entity Framework.

答:
By adding a ParentObject in ChildObject, you can use the parent from the child:

Try it online

```<code>public class ParentObject
{
    public int id {get;set;}
    public string parent_object_name {get;set;}
    public List<ChildObject> child_objects {get;set;}
}

public class ChildObject
{
    public int id {get;set;}
    public string child_object_name {get;set;}

    // add a parent
    public ParentObject parent_object {get;set;}
}

public static void Main()
{
    var parent_object = new ParentObject
    {
        id = 1,
        parent_object_name = "test name"
    };
    parent_object.child_objects = new List<ChildObject>
    {
        new ChildObject {id = 1, child_object_name = "test name", parent_object = parent_object}
    };
    Console.WriteLine(parent_object.child_objects.First().parent_object.parent_object_name);
}
</code>```

Title: Parent child relation in C# classes

Body:
I have the following case:

public class ParentObject
{
public int id {get;set;}
public string parent_object_name {get;set;}
public List<ChildObject> child_objects {get;set;}
}

public class ChildObject
{
public int id {get;set;}
public string child_object_name {get;set;}
}

ParentObject parent_object = new ParentObject()
{
  id = 1,
  parent_object_name = "test name",
  child_objects = new List<ChildObject>(){ new ChildObject(){ id = 1, child_object_name = "test name"};
}

I am aware that it is perfectly valid to reference parent_object.child_objects, but I am not sure how can I code my classes to have a reference such as child_objects.First().parent_object ie. similar to navigational properties in Entity Framework.

Body:
By adding a ParentObject in ChildObject, you can use the parent from the child:

Try it online

public class ParentObject
{
    public int id {get;set;}
    public string parent_object_name {get;set;}
    public List<ChildObject> child_objects {get;set;}
}

public class ChildObject
{
    public int id {get;set;}
    public string child_object_name {get;set;}

    // add a parent
    public ParentObject parent_object {get;set;}
}

public static void Main()
{
    var parent_object = new ParentObject
    {
        id = 1,
        parent_object_name = "test name"
    };
    parent_object.child_objects = new List<ChildObject>
    {
        new ChildObject {id = 1, child_object_name = "test name", parent_object = parent_object}
    };
    Console.WriteLine(parent_object.child_objects.First().parent_object.parent_object_name);
}


问:
Show data on top of bar chart in Chart.js v 2.7.1
I am trying to show actual data value on top of bar in Chart.js (v 2.7.1) but it is not working.
Here is my JSFIDDLE

So far, I am adding this bit of code to make it work.

```<code>showTooltips: false,
onAnimationComplete: function () {

    var ctx = this.chart.ctx;
    ctx.font = this.scale.font;
    ctx.fillStyle = this.scale.textColor
    ctx.textAlign = "center";
    ctx.textBaseline = "bottom";

    this.datasets.forEach(function (dataset) {
        dataset.bars.forEach(function (bar) {
            ctx.fillText(bar.value, bar.x, bar.y - 5);
        });
    })
}
</code>```

What am I doing wrong? Feel free to fork the fiddle.

答:
You have to add the below code:

```<code>Chart.plugins.register({
        afterDatasetsDraw: function(chart, easing) {
            // To only draw at the end of animation, check for easing === 1
            var ctx = chart.ctx;

            chart.data.datasets.forEach(function (dataset, i) {
                var meta = chart.getDatasetMeta(i);
                if (!meta.hidden) {
                    meta.data.forEach(function(element, index) {
                        // Draw the text in black, with the specified font
                        ctx.fillStyle = 'rgb(0, 0, 0)';

                        var fontSize = 16;
                        var fontStyle = 'normal';
                        var fontFamily = 'Helvetica Neue';
                        ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);

                        // Just naively convert to string for now
                        var dataString = dataset.data[index].toString();

                        // Make sure alignment settings are correct
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'middle';

                        var padding = 5;
                        var position = element.tooltipPosition();
                        ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
                    });
                }
            });
        }
    });
</code>```

Look at the updated Fiddle https://jsfiddle.net/ca7unnu4/

Body:
I am trying to show actual data value on top of bar in Chart.js (v 2.7.1) but it is not working.
Here is my JSFIDDLE

So far, I am adding this bit of code to make it work.

showTooltips: false,
onAnimationComplete: function () {

    var ctx = this.chart.ctx;
    ctx.font = this.scale.font;
    ctx.fillStyle = this.scale.textColor
    ctx.textAlign = "center";
    ctx.textBaseline = "bottom";

    this.datasets.forEach(function (dataset) {
        dataset.bars.forEach(function (bar) {
            ctx.fillText(bar.value, bar.x, bar.y - 5);
        });
    })
}

What am I doing wrong? Feel free to fork the fiddle.

Body:
You have to add the below code:

Chart.plugins.register({
        afterDatasetsDraw: function(chart, easing) {
            // To only draw at the end of animation, check for easing === 1
            var ctx = chart.ctx;

            chart.data.datasets.forEach(function (dataset, i) {
                var meta = chart.getDatasetMeta(i);
                if (!meta.hidden) {
                    meta.data.forEach(function(element, index) {
                        // Draw the text in black, with the specified font
                        ctx.fillStyle = 'rgb(0, 0, 0)';

                        var fontSize = 16;
                        var fontStyle = 'normal';
                        var fontFamily = 'Helvetica Neue';
                        ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);

                        // Just naively convert to string for now
                        var dataString = dataset.data[index].toString();

                        // Make sure alignment settings are correct
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'middle';

                        var padding = 5;
                        var position = element.tooltipPosition();
                        ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
                    });
                }
            });
        }
    });

Look at the updated Fiddle https://jsfiddle.net/ca7unnu4/


问:
JanusGraph function cyclicPath()
```<code>g.V().has('name', 'alice').both().both().cyclicPath().path().by('name')
</code>```

Why we need 2 both()s to get the cyclicPath()?

答:
It's not completely clear as to what you are asking but your traversal is simply translating to:

```<code>g.V().has('name', 'alice'). // (1)
  both().                   // (2)
  both().                   // (3)
  cyclicPath().             // (4)
  path().by('name')         // (5)
</code>```

Find the vertex with the "name" of "alice"

Traverse away from "alice" on both incoming and outgoing edges to adjacent vertices

For all of those vertices traverse away again on both incoming and outgoing edges to adjacent vertices. It is worth noting that some of those paths will go back to "alice"

Examine the path that the traverser took in getting this far and filter out any paths that do not return to their start (i.e. do not return to "alice"). The alternative to this step is simplePath() which would filter out paths that cycle (i.e. go back to start).

Display the paths followed and extract the "name" property into the path for each vertex in the path.

Title: JanusGraph function cyclicPath()

Body:
g.V().has('name', 'alice').both().both().cyclicPath().path().by('name')

Why we need 2 both()s to get the cyclicPath()?

Body:
It's not completely clear as to what you are asking but your traversal is simply translating to:

g.V().has('name', 'alice'). // (1)
  both().                   // (2)
  both().                   // (3)
  cyclicPath().             // (4)
  path().by('name')         // (5)

Find the vertex with the "name" of "alice"

Traverse away from "alice" on both incoming and outgoing edges to adjacent vertices

For all of those vertices traverse away again on both incoming and outgoing edges to adjacent vertices. It is worth noting that some of those paths will go back to "alice"

Examine the path that the traverser took in getting this far and filter out any paths that do not return to their start (i.e. do not return to "alice"). The alternative to this step is simplePath() which would filter out paths that cycle (i.e. go back to start).

Display the paths followed and extract the "name" property into the path for each vertex in the path.


问:
Change culture on Finnish Windows Server 2008 R2 for Powershell Script
I am making a script that gets a bunch of tags and outputting it to a CSV file. The database in question only allows for a specific date input ("dd-mmm-yyyy hh:mm:ss") when requesting the tags. However the server I am running the script on is in finland and using finnish culture for powershell. So when I type:

```<code>Get-Date
</code>```

I get everything in finnish:

```<code>6. joulukuuta 2017 13:37:47
</code>```

I really want 06-dec-2017 13:37:47

I am unable to use the "Set-Location" because this command does not work in Windows Server 2008 R2.

So I need help. When I type:

```<code>(get-date).ToString("dd-mmm-yyyy hh:mm:ss")
</code>```

I want it to output 06-dec-2017 12.41.23

答:
You could use the -Format paramter of Get-Date

```<code>Get-Date -Format "dd-MMM-yyy HH:mm:ss"
</code>```

This will return the hour in 24 hour format, use hh instead of HH for the 12 hour format.

Body:
I am making a script that gets a bunch of tags and outputting it to a CSV file. The database in question only allows for a specific date input ("dd-mmm-yyyy hh:mm:ss") when requesting the tags. However the server I am running the script on is in finland and using finnish culture for powershell. So when I type:

Get-Date

I get everything in finnish:

6. joulukuuta 2017 13:37:47

I really want 06-dec-2017 13:37:47

I am unable to use the "Set-Location" because this command does not work in Windows Server 2008 R2.

So I need help. When I type:

(get-date).ToString("dd-mmm-yyyy hh:mm:ss")

I want it to output 06-dec-2017 12.41.23

Body:
You could use the -Format paramter of Get-Date

Get-Date -Format "dd-MMM-yyy HH:mm:ss"

This will return the hour in 24 hour format, use hh instead of HH for the 12 hour format.


问:
Route to URL helper default parameters
I am using the code found here https://laracasts.com/discuss/channels/laravel/how-to-prefixing-in-routes-for-localization to prefix my routes with a locale.

```<code>Route::prefix('{lang?}')->middleware('locale')->group(function() {

    Route::get('/', function () {
        return view('index');
    })->name('index');
});
</code>```

This locale is optional, but then my question is how am I supposed to reinject the locale when calling the route helper.

```<code>route('index');
</code>```

to generate: /it/ or /, or another, depending on the current locale.

If have tried this with no success :

```<code>Route::resourceParameters(['lang' => 'en']);
</code>```

答:
This should should be,

```<code>route('index', ['lang' => 'fr']);
</code>```

And change route helper with

```<code>/**
     * Generate a URL to a named route.
     *
     * @param  string  $name
     * @param  array   $parameters
     * @param  bool    $absolute
     * @param  \Illuminate\Routing\Route  $route
     * @return string
     */
    function route($name, $parameters = [], $absolute = true, $route = null)
   {
    if (!isset($parameters['lang'])) $parameters['lang'] = App::getLocale();

        return app('url')->route($name, $parameters, $absolute, $route);
    }
</code>```

Refer link for more details.

Title: Route to URL helper default parameters

Body:
I am using the code found here https://laracasts.com/discuss/channels/laravel/how-to-prefixing-in-routes-for-localization to prefix my routes with a locale.

Route::prefix('{lang?}')->middleware('locale')->group(function() {

    Route::get('/', function () {
        return view('index');
    })->name('index');
});

This locale is optional, but then my question is how am I supposed to reinject the locale when calling the route helper.

route('index');

to generate: /it/ or /, or another, depending on the current locale.

If have tried this with no success :

Route::resourceParameters(['lang' => 'en']);

Body:
This should should be,

route('index', ['lang' => 'fr']);

And change route helper with

/**
     * Generate a URL to a named route.
     *
     * @param  string  $name
     * @param  array   $parameters
     * @param  bool    $absolute
     * @param  \Illuminate\Routing\Route  $route
     * @return string
     */
    function route($name, $parameters = [], $absolute = true, $route = null)
   {
    if (!isset($parameters['lang'])) $parameters['lang'] = App::getLocale();

        return app('url')->route($name, $parameters, $absolute, $route);
    }

Refer link for more details.