问:
How to call a method in dropdown?
I want to call  graph based on selected drop down value, the method is graph($p), in that I will pass parameter based on $p graph will change.How to call that method inside option tag.

```<code><?php
//connect  database
include("C:\wamp64\www\DashBoard\Config2.php");
$pro_name=array();

        $sql = "select project_name from project_table";
        $result = mysqli_query($db,$sql);

        $pro="select  count(project_name)from project_table;";
        $res=mysqli_query($db,$pro);
        $row=mysqli_fetch_array($res);
        $cntp=$row['count(project_name)'];

   echo "<select name='project_name'>";
      while ($row = mysqli_fetch_array($result)) {

        $pro_name[]=$row['project_name'];

        }
  for($p=0;$p<$cntp;$p++){

      echo '<option >'.$pro_name[$p].'</option>';

   }

echo "</select>";
?>
</code>```

Can Any one help me. and the written graph method is php method.

答:
Once you click the drop down link you can pass the parameters in the URL to the subsequent pages as GET parameter and can access the parameters over there and do the modifications.

The following snippet shows you one of the ways to achieve it.

NOTE : There are other ways to achieve. But I am showing you the easiest one. Please make sure to check for the securities best pracites as I wont incorporate here.

in HTML

```<code>echo '<option > <a  href="link.php?par1=$par1&par2=$par2">'.$pro_name[$p].'</option>';
</code>```

In link.php file.

```<code><?php

    $par1 = $_GET['par1'];

    $par2 = $_GET['par2'];

    /* Your code */
</code>```

Second way

```<code>echo '<option>'. someFunction($par1, $par2) .'</option>';
</code>```

Title: How to call a method in dropdown?

Body:
I want to call  graph based on selected drop down value, the method is graph($p), in that I will pass parameter based on $p graph will change.How to call that method inside option tag.

<?php
//connect  database
include("C:\wamp64\www\DashBoard\Config2.php");
$pro_name=array();

        $sql = "select project_name from project_table";
        $result = mysqli_query($db,$sql);

        $pro="select  count(project_name)from project_table;";
        $res=mysqli_query($db,$pro);
        $row=mysqli_fetch_array($res);
        $cntp=$row['count(project_name)'];

   echo "<select name='project_name'>";
      while ($row = mysqli_fetch_array($result)) {

        $pro_name[]=$row['project_name'];

        }
  for($p=0;$p<$cntp;$p++){

      echo '<option >'.$pro_name[$p].'</option>';

   }

echo "</select>";
?>

Can Any one help me. and the written graph method is php method.

Body:
Once you click the drop down link you can pass the parameters in the URL to the subsequent pages as GET parameter and can access the parameters over there and do the modifications.

The following snippet shows you one of the ways to achieve it.

NOTE : There are other ways to achieve. But I am showing you the easiest one. Please make sure to check for the securities best pracites as I wont incorporate here.

in HTML

echo '<option > <a  href="link.php?par1=$par1&par2=$par2">'.$pro_name[$p].'</option>';

In link.php file.

<?php

    $par1 = $_GET['par1'];

    $par2 = $_GET['par2'];

    /* Your code */

Second way

echo '<option>'. someFunction($par1, $par2) .'</option>';


来源: stackexchange

问:
Text overflow ellipsis on two lines
I know you can use a combination of CSS rules to make text end with ellipsis (...) when it's time to overflow (get out of parent's bounds).

Is it possible (feel free to just say, no) to achieve the same effect, but let the text wrap on more than one line?

Here's a demo.

```<code>div {
  width: 300px;
  height: 42px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</code>```

As you can see, the text ends with ellipsis when it goes wider than the div's width. However, there is still enough space for the text to wrap on a second line and go on. This is interrupted by white-space: nowrap, which is required for the ellipsis to work.

Any ideas?

P.S.: No JS solutions, pure CSS if possible.

答:
Css below should do the trick.

After the second line the, text will contain ...

```<code>line-height: 1em;
max-height: 2em;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Text overflow ellipsis on two lines

Body:
I know you can use a combination of CSS rules to make text end with ellipsis (...) when it's time to overflow (get out of parent's bounds).

Is it possible (feel free to just say, no) to achieve the same effect, but let the text wrap on more than one line?

Here's a demo.

div {
  width: 300px;
  height: 42px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

As you can see, the text ends with ellipsis when it goes wider than the div's width. However, there is still enough space for the text to wrap on a second line and go on. This is interrupted by white-space: nowrap, which is required for the ellipsis to work.

Any ideas?

P.S.: No JS solutions, pure CSS if possible.

Body:
Css below should do the trick.

After the second line the, text will contain ...

line-height: 1em;
max-height: 2em;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;

ContentLicense: CC BY-SA 4.0


问:
If `ModelState.IsValid==false`, we should return `View()` or `View(movie)`?
If ModelState.IsValid==false, we should return View() or View(movie)?

```<code>    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            context.Movies.Add(movie);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View();
        }
    }
</code>```

or

```<code>    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            context.Movies.Add(movie);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View(movie);
        }
    }
</code>```

?

答: Always return the same model when validation fails (return View(movie); )</p>

ContentLicense: CC BY-SA 2.5

Body:
If ModelState.IsValid==false, we should return View() or View(movie)?

    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            context.Movies.Add(movie);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View();
        }
    }

or

    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Movie movie)
    {
        if (ModelState.IsValid)
        {
            context.Movies.Add(movie);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            return View(movie);
        }
    }

?


问:
Update an existing column in mysql
I have a column pass VARCHAR(50). I need to change it to VARCHAR(255):

```<code>ALTER TABLE college
ALTER column pass varchar (255) NOT NULL

ALTER TABLE college
CHANGE COLUMN pass VARCHAR (255) NOT NULL;

ALTER TABLE college
SET COLUMN pass VARCHAR (255) NOT NULL;
</code>```

I tried the above commands, but nothing is working.

答:
Have you try this then ?

```<code>ALTER TABLE college MODIFY pass VARCHAR(255);
</code>```

Title: Update an existing column in mysql

Body:
I have a column pass VARCHAR(50). I need to change it to VARCHAR(255):

ALTER TABLE college
ALTER column pass varchar (255) NOT NULL

ALTER TABLE college
CHANGE COLUMN pass VARCHAR (255) NOT NULL;

ALTER TABLE college
SET COLUMN pass VARCHAR (255) NOT NULL;

I tried the above commands, but nothing is working.

Body:
Have you try this then ?

ALTER TABLE college MODIFY pass VARCHAR(255);


问:
Postgres: use function that returns a string in another function
I've a PostgreSQL function that returns a string. I want to use this function into another one but I obtain an error.

These are the sample functions, with get_some_string that returns text, and use_the_string where I want to call the previous one and store the result in a variable:

```<code>CREATE OR REPLACE FUNCTION public.get_some_string()

RETURNS text AS
$func$
DECLARE

BEGIN

  return 'mystring';

END
$func$ LANGUAGE plpgsql VOLATILE;

CREATE OR REPLACE FUNCTION public.use_the_string()

RETURNS boolean AS
$func$
DECLARE

  mytext text;

BEGIN

  mytext := select public.get_some_string();

END
$func$ LANGUAGE plpgsql VOLATILE;
</code>```

If I run this query I obtain the error:

```<code>ERROR:  syntax error at or near "select"
LINE 24:   mytext := select public.get_some_string();
</code>```

What I'm doing wrong? How can I use the return value of the first function into the second one?

答:
You don't need a select:</p>

```<code>CREATE OR REPLACE FUNCTION public.use_the_string()

RETURNS boolean AS
$func$
DECLARE

  mytext text;

BEGIN

  mytext := public.get_some_string();

END
$func$ LANGUAGE plpgsql VOLATILE;
</code>```

Body:
I've a PostgreSQL function that returns a string. I want to use this function into another one but I obtain an error.

These are the sample functions, with get_some_string that returns text, and use_the_string where I want to call the previous one and store the result in a variable:

CREATE OR REPLACE FUNCTION public.get_some_string()

RETURNS text AS
$func$
DECLARE

BEGIN

  return 'mystring';

END
$func$ LANGUAGE plpgsql VOLATILE;

CREATE OR REPLACE FUNCTION public.use_the_string()

RETURNS boolean AS
$func$
DECLARE

  mytext text;

BEGIN

  mytext := select public.get_some_string();

END
$func$ LANGUAGE plpgsql VOLATILE;

If I run this query I obtain the error:

ERROR:  syntax error at or near "select"
LINE 24:   mytext := select public.get_some_string();

What I'm doing wrong? How can I use the return value of the first function into the second one?

Body:
You don't need a select:

CREATE OR REPLACE FUNCTION public.use_the_string()

RETURNS boolean AS
$func$
DECLARE

  mytext text;

BEGIN

  mytext := public.get_some_string();

END
$func$ LANGUAGE plpgsql VOLATILE;


问:
WTForms validation error not working
I am trying to create a login form wherein if the username is blank, it throws an error.

```<code>from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import InputRequired, Email, length, ValidationError

app = Flask(__name__)
app.config['SECRET_KEY'] = 'This is a secret'
class LoginForm(FlaskForm):
  username = StringField('username', validators=[InputRequired()])
  password = PasswordField('password')

@app.route('/form', methods=['GET','POST'])
def form():
  form=LoginForm()
  return render_template('form.html', form=form)

if __name__== '__main__':
  app.run(debug=True)
</code>```

The html code is as below:

```<code><html>
<title> MY FORM </title>
<body>
<form method="POST" action="{{ url_for('form') }}">
  {{form.csrf_token}}
  {{ form.username.label }}
  {{ form.username }}
  <ul>
  {% for error in form.username.errors %}
    <li style="color: red;">{{ error }} </li>

  {% endfor %}
  </ul>
  {{ form.password }}
  {{ form.password.label }}
  <input type="submit" value="Submit">

</form>
</body>
</html>
</code>```

Apparently, the for loop is skipped and nothing happens on clicking the submit button while the user field is null

答:
Assuming that your form will be sent with POST method you have to validate the form data if they have been submitted. With flask-wtf it is really simple:

```<code>@app.route('/form', methods=['GET','POST'])
def check_form():
    form = LoginForm()
    if form.validate_on_submit():
        # do something
        return # something
    return render_template('form.html', form=form)
</code>```

I invite you to read more about flask-wtf

Title: WTForms validation error not working

Body:
I am trying to create a login form wherein if the username is blank, it throws an error.

from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import InputRequired, Email, length, ValidationError

app = Flask(__name__)
app.config['SECRET_KEY'] = 'This is a secret'
class LoginForm(FlaskForm):
  username = StringField('username', validators=[InputRequired()])
  password = PasswordField('password')

@app.route('/form', methods=['GET','POST'])
def form():
  form=LoginForm()
  return render_template('form.html', form=form)

if __name__== '__main__':
  app.run(debug=True)

The html code is as below:

<title> MY FORM </title>

<form method="POST" action="{{ url_for('form') }}">
  {{form.csrf_token}}
  {{ form.username.label }}
  {{ form.username }}

  {% for error in form.username.errors %}

{{ error }}

  {% endfor %}

  {{ form.password }}
  {{ form.password.label }}
  <input type="submit" value="Submit">

</form>

Apparently, the for loop is skipped and nothing happens on clicking the submit button while the user field is null

Body:
Assuming that your form will be sent with POST method you have to validate the form data if they have been submitted. With flask-wtf it is really simple:

@app.route('/form', methods=['GET','POST'])
def check_form():
    form = LoginForm()
    if form.validate_on_submit():
        # do something
        return # something
    return render_template('form.html', form=form)

I invite you to read more about flask-wtf


问:
How to get logs of app from android without using android studio?
I have given App to my friend but its not working.I want to know the issue  so that I want log file of my App.Is there anyway to get logs from android without using android studio or any debugger tool.I want only log file to get solve issue.So What is the way to get log file from android device.
Thanks in advance.</p>

答:
Use Fabric io Crashlytics for reports and errors

for more information  visit: https://fabric.io/kits/android/crashlytics


问:
Auto change font size for different iPhone devices
Is it possible to set different UILabels' font sizes based on the different iPhone device size for an entire application?

答:
I am using custom class of each control for this purpose

```<code>    class Label: UILabel {

    @IBInspectable var iPhoneFontSize:CGFloat = 0 {
        didSet {
            overrideFontSize(fontSize: iPhoneFontSize)
        }
    }

    @IBInspectable
    public var cornerRadius: CGFloat = 2.0 {
        didSet {
            self.layer.cornerRadius = self.cornerRadius
        }
    }

    @IBInspectable
    public var borderWidth: CGFloat = 0 {
        didSet {
            self.layer.borderWidth = self.borderWidth
        }
    }

    @IBInspectable
    public var borderColor: UIColor = .clear {
        didSet {
            self.layer.borderColor = self.borderColor.cgColor
        }
    }

   private func overrideFontSize(fontSize:CGFloat){
        let currentFontName = self.font.fontName
        var calculatedFont: UIFont?
        let bounds = UIScreen.main.bounds
        let height = bounds.size.height
        switch height {
        case 480.0: //Iphone 3,4,SE => 3.5 inch
            calculatedFont = UIFont(name: currentFontName, size: fontSize * 0.7)
            self.font = calculatedFont
            break
        case 568.0: //iphone 5, 5s => 4 inch
            calculatedFont = UIFont(name: currentFontName, size: fontSize * 0.8)
            self.font = calculatedFont
            break
        case 667.0: //iphone 6, 6s, 7, 7s => 4.7 inch
            calculatedFont = UIFont(name: currentFontName, size: fontSize * 0.9)
            self.font = calculatedFont
            break
        case 736.0: //iphone 6+, 6s+, 7+, 7s+ => 5.5 inch
            calculatedFont = UIFont(name: currentFontName, size: fontSize)
            self.font = calculatedFont
            break
        default: // New devices
            calculatedFont = UIFont(name: currentFontName, size: fontSize)
            self.font = calculatedFont
            break
        }

    }
}
</code>```

Then in  Storyboard set iPhoneFontSize property value for highest resolution as seen in screenshot below.

Body:
I am using custom class of each control for this purpose

    class Label: UILabel {

    @IBInspectable var iPhoneFontSize:CGFloat = 0 {
        didSet {
            overrideFontSize(fontSize: iPhoneFontSize)
        }
    }

    @IBInspectable
    public var cornerRadius: CGFloat = 2.0 {
        didSet {
            self.layer.cornerRadius = self.cornerRadius
        }
    }

    @IBInspectable
    public var borderWidth: CGFloat = 0 {
        didSet {
            self.layer.borderWidth = self.borderWidth
        }
    }

    @IBInspectable
    public var borderColor: UIColor = .clear {
        didSet {
            self.layer.borderColor = self.borderColor.cgColor
        }
    }

   private func overrideFontSize(fontSize:CGFloat){
        let currentFontName = self.font.fontName
        var calculatedFont: UIFont?
        let bounds = UIScreen.main.bounds
        let height = bounds.size.height
        switch height {
        case 480.0: //Iphone 3,4,SE => 3.5 inch
            calculatedFont = UIFont(name: currentFontName, size: fontSize * 0.7)
            self.font = calculatedFont
            break
        case 568.0: //iphone 5, 5s => 4 inch
            calculatedFont = UIFont(name: currentFontName, size: fontSize * 0.8)
            self.font = calculatedFont
            break
        case 667.0: //iphone 6, 6s, 7, 7s => 4.7 inch
            calculatedFont = UIFont(name: currentFontName, size: fontSize * 0.9)
            self.font = calculatedFont
            break
        case 736.0: //iphone 6+, 6s+, 7+, 7s+ => 5.5 inch
            calculatedFont = UIFont(name: currentFontName, size: fontSize)
            self.font = calculatedFont
            break
        default: // New devices
            calculatedFont = UIFont(name: currentFontName, size: fontSize)
            self.font = calculatedFont
            break
        }

    }
}

Then in  Storyboard set iPhoneFontSize property value for highest resolution as seen in screenshot below.


问:
Angular4 Change field B when field A has changed
I have created a form containing two fields, Country Code and Dialing Code.

The form is used to fill a JSON file with key-value pairs, where countryCode is the key and the Dialing Code is the value.

I want to implement a UI where the Dialing Code is automatically filled in when an existing Country Code is entered.

How can I implement this in Angular 4?

Here is my Form View:

```<code><label class="k-form-field">
    <span>Country Code <span class="k-required">*</span></span>
        <kendo-dropdownlist id="countryCode"
            formControlName="countryCode"
            [data]="countryCodeList"
            [textField]="key"
            [valueField]="value"
            class="width100">
        </kendo-dropdownlist>
        <span *ngIf="countryCode.touched && countryCode.invalid" class="help-block">
        <span *ngIf="countryCode.errors.required">Country Code is required.</span>
    </span>
</label>

<label class="k-form-field">
    <span>Dial Code <span class="k-required">*</span></span>
    <input id="dialCode"
        name="dialCode"
        formControlName="dialCode"
        [value] ="syncCountryCode"
        class="k-textbox width100" />
    <span *ngIf="dialCode.touched && dialCode.invalid" class="help-block">
        <span *ngIf="dialCode.errors.required">Dial Code is required.</span>
    </span>
</label>
</code>```

Here is my Component:

```<code>public countryCodeList: Array<string>;
public syncCountryCode: string = "";

ngOnInit(): void {
    this.utilService.getCodes()
    .then((res: Array<PhoneCode>) => {
        this.countryCodeList = Object.keys(res); //--> Object.values(res);
    })
    .catch(res => { });
}
</code>```

答:
https://angular.io/guide/template-syntax#binding-syntax-an-overview

More specifically you likely want two way data binding on an input using NgModel ngModel=[(someProperty)]

https://angular.io/api/forms/NgModel

Body:
I have created a form containing two fields, Country Code and Dialing Code.

The form is used to fill a JSON file with key-value pairs, where countryCode is the key and the Dialing Code is the value.

I want to implement a UI where the Dialing Code is automatically filled in when an existing Country Code is entered.

How can I implement this in Angular 4?

Here is my Form View:

    Country Code *
        <kendo-dropdownlist id="countryCode"
            formControlName="countryCode"
            [data]="countryCodeList"
            [textField]="key"
            [valueField]="value"
            class="width100">
        </kendo-dropdownlist>

        Country Code is required.

    Dial Code *
    <input id="dialCode"
        name="dialCode"
        formControlName="dialCode"
        [value] ="syncCountryCode"
        class="k-textbox width100" />

        Dial Code is required.

Here is my Component:

public countryCodeList: Array<string>;
public syncCountryCode: string = "";

ngOnInit(): void {
    this.utilService.getCodes()
    .then((res: Array<PhoneCode>) => {
        this.countryCodeList = Object.keys(res); //--> Object.values(res);
    })
    .catch(res => { });
}


问:
How do I make my wxpython top frame show in the middle of my desktop?
I want to make my GUI program top frame both vertically and horizontally aligned.

```<code>wx.Frame.__init__(self, parent=None, id= -1, title="Test Frame", pos=(-1, -1), size=(1280, 770), style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX)
</code>```

What should I do(except do the calculation to find the absolute position) to pos=(-1, -1) to make it show in the middle(no matter 800 * 600 or 1280 * 800 etc.), or some other attributes setting also needed?

答:
```<code>w = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X)
h = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)

pos=(w/2, h/2)
</code>```

This gives you the centre of the screen.

Now, assuming you have an 800x600 sized application:

```<code>APPWIDTH = 800
APPHEIGHT = 600

w = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X)
h = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)

# Centre of the screen
x = w / 2
y = h / 2

# Minus application offset
x -= (APPWIDTH / 2)
y -= (APPHEIGHT / 2)

pos=(x, y)
</code>```

Body:
I want to make my GUI program top frame both vertically and horizontally aligned.

wx.Frame.__init__(self, parent=None, id= -1, title="Test Frame", pos=(-1, -1), size=(1280, 770), style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX)

What should I do(except do the calculation to find the absolute position) to pos=(-1, -1) to make it show in the middle(no matter 800 * 600 or 1280 * 800 etc.), or some other attributes setting also needed?

Body:
w = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X)
h = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)

pos=(w/2, h/2)

This gives you the centre of the screen.

Now, assuming you have an 800x600 sized application:

APPWIDTH = 800
APPHEIGHT = 600

w = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X)
h = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)

# Centre of the screen
x = w / 2
y = h / 2

# Minus application offset
x -= (APPWIDTH / 2)
y -= (APPHEIGHT / 2)

pos=(x, y)


问:
how can I uninstall last firefox update
I was happy with the last version of Firefox and wish I never allowed auto updates because I am unhappy with the new browser and want to go back to it.  So how can I return the last version of Firefox and not have to use the new one?</p>

答: After a day of searching for browser add-on's to replace those I lost in the Firefox 57.0 update it became clear that my only option was to re-install version 56.0.2.  The newest version was a bit quicker and have several features that would be useful to some I found the older vision and the Legacy add-on's was the one I would stay with for now. This link will set you back to the 56.0.2 version.</p>

Title: how can I uninstall last firefox update


问:
i want to hide fragment layout when click any place in screen
Here is one frame layout added in bottom view. i want to hide if user click on any place on the screen

i have tried to get parent layout and on that touch listener set visiblity GONE but on touch listner is not working. here my code is.
View rootView = getWindow().getDecorView().getRootView();

```<code>    rootView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_DOWN) {

                // show-hide view here

                contentSubTableList.setVisibility(View.GONE);

                AppUtility.showToast(PhoneBaseActivity.this, "On touch listner");

                return true;
            }

            contentSubTableList.setVisibility(View.GONE);

            AppUtility.showToast(PhoneBaseActivity.this, "On touch listner");
            return true;
        }
    });

    rootView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

    llParentView = (LinearLayout) findViewById(R.id.llParentView);
    llParentView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_DOWN) {

                // show-hide view here

                contentSubTableList.setVisibility(View.GONE);

                AppUtility.showToast(PhoneBaseActivity.this, "On touch listner");

                return true;
            }

            contentSubTableList.setVisibility(View.GONE);

            AppUtility.showToast(PhoneBaseActivity.this, "On touch listner");

            return true;
        }
    });
</code>```

please any one help me in that.

答:
you can use this method for hide and show fragment</p>

```<code>public void showHideFragment(final Fragment fragment){

    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.setCustomAnimations(android.R.animator.fade_in,
                    android.R.animator.fade_out);

    if (fragment.isHidden()) {
        ft.show(fragment);
        Log.d("hidden","Show");
    } else {
        ft.hide(fragment);
        Log.d("Shown","Hide");
    }

    ft.commit();
}
</code>```

Body:
Here is one frame layout added in bottom view. i want to hide if user click on any place on the screen

i have tried to get parent layout and on that touch listener set visiblity GONE but on touch listner is not working. here my code is.
View rootView = getWindow().getDecorView().getRootView();

    rootView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_DOWN) {

                // show-hide view here

                contentSubTableList.setVisibility(View.GONE);

                AppUtility.showToast(PhoneBaseActivity.this, "On touch listner");

                return true;
            }

            contentSubTableList.setVisibility(View.GONE);

            AppUtility.showToast(PhoneBaseActivity.this, "On touch listner");
            return true;
        }
    });

    rootView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

    llParentView = (LinearLayout) findViewById(R.id.llParentView);
    llParentView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_DOWN) {

                // show-hide view here

                contentSubTableList.setVisibility(View.GONE);

                AppUtility.showToast(PhoneBaseActivity.this, "On touch listner");

                return true;
            }

            contentSubTableList.setVisibility(View.GONE);

            AppUtility.showToast(PhoneBaseActivity.this, "On touch listner");

            return true;
        }
    });

please any one help me in that.

Body:
you can use this method for hide and show fragment

public void showHideFragment(final Fragment fragment){

    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.setCustomAnimations(android.R.animator.fade_in,
                    android.R.animator.fade_out);

    if (fragment.isHidden()) {
        ft.show(fragment);
        Log.d("hidden","Show");
    } else {
        ft.hide(fragment);
        Log.d("Shown","Hide");
    }

    ft.commit();
}


答:
You can use below statement to update your column

```<code>ALTER TABLE college MODIFY pass varchar(255);
</code>```

Reference: https://www.roseindia.net/sql/sql-alter-column-size.shtml

Title: Update an existing column in mysql

Body:
You can use below statement to update your column

ALTER TABLE college MODIFY pass varchar(255);

Reference: https://www.roseindia.net/sql/sql-alter-column-size.shtml


问:
Remove file extension in apache 2.4
I want to refer to a page without the .php extension and not to use the .htaccess file, as a documentation says:

You should avoid using .htaccess files completely if you have access
  to httpd main server config file. Using .htaccess files slows down your Apache http server.

答:
I see no reason not using .htaccess for this

Use .htaccess to remove php extension:

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
</code>```

That's it, you can now link your pages without needing to add the php extension. E.g :

Home

Title: Remove file extension in apache 2.4

Body:
I see no reason not using .htaccess for this

Use .htaccess to remove php extension:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

That's it, you can now link your pages without needing to add the php extension. E.g :

<a href="http://example.com/index">Home</a>


问:
Format of JSON payload in Azure Logic App HTTP Request trigger
I have been trying to create a very simple Logic App in Azure but I keep failing because it does not seem to be accepting my JSON.

Using my payload

```<code>{
  "userPrincipalName": "notmy@ddress.com",
  "computerName": "MyComputername"
}
</code>```

I created the trigger

I then use the values of my payload in my response:

Save it and then I POST using Hurl.it to the HTTP POST URL in the request.

So why the heck is the value not used? I'm not able to use any of the values I'm sending.

答:
Okay..  that was dumb..

I had to add the Content-Type header to the POST:

Body:
I have been trying to create a very simple Logic App in Azure but I keep failing because it does not seem to be accepting my JSON.

Using my payload

{
  "userPrincipalName": "notmy@ddress.com",
  "computerName": "MyComputername"
}

I created the trigger

I then use the values of my payload in my response:

Save it and then I POST using Hurl.it to the HTTP POST URL in the request.

So why the heck is the value not used? I'm not able to use any of the values I'm sending.


问:
HTML & CSS - Links doesn't work
I have made a very simple website using HTML and CSS, I have added a few links as well but only one of the links actually work. There are 4 links in total and only the one at the bottom of the code will work. Please help. This is my HTML code:

html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video {  margin: 0;  padding: 0;  border: 0;  font-size: 100%;  font: inherit;  vertical-align: baseline;}

/* HTML5 display-role reset for older browsers */

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

body {
  line-height: 1;
  font: 25px 'Open Sans', Arial, Helvetica, sans-serif;
}

ol,ul {
  list-style: none;
}

blockquote,q {
  quotes: none;
}

blockquote:before,blockquote:after,q:before,q:after {
  content: '';
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

.nav {
  float: left;
}

.home {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 1200px;
}

.faq {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 900px;
}

.shop {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 580px;
}

.contact {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 200px;
}

html {
  box-sizing: border-box;
}

*,
*:before,*:after {
  box-sizing: inherit;
}

a {
  text-decoration: none;
}

.header {
  text-align: center;
}

.hemsidan {
  background: #ffffff url(../images/hemsidan.png)no-repeat 50% 50%;
  height: 1389px;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="header">
  <div class="container">
    <div class="hemsidan"><img src="images/hemsidan.png" height="1389" width="1366" alt=""></div>
    <div class="centered">Centered</div>
    <nav>
      <ul class="nav">
        <li class="home">Home</li>
        <li class="faq">FAQ</li>
        <li class="shop">Shop</li>
        <li class="contact">Contact us</li>
      </ul>
    </nav>
  </div>
</header></code>```

I am very new to HTML and CSS so forgive me for the horrible coding, I just want the links to work.

答:
This is the sanitized code (As mentioned you were using position: absolute; for links which was leading to a click to other place but not on link)

ol,
ul {
  list-style: none;
}

li {
  display: inline-block;
  margin: 10px;
}

a {
  text-decoration: none;
}

.container {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="hemsidan"><img src="images/hemsidan.png" height="1389" width="1366" alt=""></div>

  <nav>
    <ul class="nav">
      <li class="home">Home</li>
      <li class="faq">FAQ</li>
      <li class="shop">Shop</li>
      <li class="contact">Contact us</li>

    </ul>
  </nav>
</div></code>```

Title: HTML & CSS - Links doesn't work

Body:
I have made a very simple website using HTML and CSS, I have added a few links as well but only one of the links actually work. There are 4 links in total and only the one at the bottom of the code will work. Please help. This is my HTML code:

html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video {  margin: 0;  padding: 0;  border: 0;  font-size: 100%;  font: inherit;  vertical-align: baseline;}

/* HTML5 display-role reset for older browsers */

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

body {
  line-height: 1;
  font: 25px 'Open Sans', Arial, Helvetica, sans-serif;
}

ol,ul {
  list-style: none;
}

blockquote,q {
  quotes: none;
}

blockquote:before,blockquote:after,q:before,q:after {
  content: '';
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

.nav {
  float: left;
}

.home {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 1200px;
}

.faq {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 900px;
}

.shop {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 580px;
}

.contact {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 200px;
}

html {
  box-sizing: border-box;
}

*,
*:before,*:after {
  box-sizing: inherit;
}

a {
  text-decoration: none;
}

.header {
  text-align: center;
}

.hemsidan {
  background: #ffffff url(../images/hemsidan.png)no-repeat 50% 50%;
  height: 1389px;
  width: 100%;
}

Centered

Home

FAQ

Shop

Contact us

I am very new to HTML and CSS so forgive me for the horrible coding, I just want the links to work.

Body:
This is the sanitized code (As mentioned you were using position: absolute; for links which was leading to a click to other place but not on link)

ol,
ul {
  list-style: none;
}

li {
  display: inline-block;
  margin: 10px;
}

a {
  text-decoration: none;
}

.container {
  text-align: center;
}

<div class="container">
  <div class="hemsidan"><img src="images/hemsidan.png" height="1389" width="1366" alt=""></div>

  <nav>
    <ul class="nav">
      <li class="home"><a href="#">Home</a></li>
      <li class="faq"><a href="http://pages.ebay.com/seller-center/faq/index.html">FAQ</a></li>
      <li class="shop"><a href="https://www.blocket.se/">Shop</a></li>
      <li class="contact"><a href="https://twitter.com/realdonaldtrump">Contact us</a></li>

    </ul>
  </nav>
</div>


问:
Sort By in Left Bar Magento
I need to show Sort by instead of a selectbox to clickable text Newest, Highest Price, Lowest Price in on left toolbar in Category page, if there any way we can do it?</p>

答:
edit toolbar template

app/design/frontend/[theme]/template/catalog/product/list/toolbar.phtml

```<code><div class="sort-by">
    <?php foreach($this->getAvailableOrders() as $_key=>$_order): ?>
            <?php if($_key=='price'):?>
            <a href="<?php echo $this->getOrderUrl($_key, 'asc') ?>">
                <?php echo $this->__($_order) . ' ' . $this->__('asc') ?>
            </a>
            <a href="<?php echo $this->getOrderUrl($_key, 'desc') ?>">
                <?php echo $this->__($_order) . ' ' . $this->__('desc') ?>
            </a>
        <?php else:?>
            <a href="<?php echo $this->getOrderUrl($_key, 'desc') ?>">
                <?php echo $this->__($_order) ?>
            </a>
        <?php endif;?>
    <?php endforeach; ?>
</div>
</code>```

Title: Sort By in Left Bar Magento

Body:
edit toolbar template

app/design/frontend/[theme]/template/catalog/product/list/toolbar.phtml

<div class="sort-by">
    <?php foreach($this->getAvailableOrders() as $_key=>$_order): ?>
            <?php if($_key=='price'):?>
            <a href="<?php echo $this->getOrderUrl($_key, 'asc') ?>">
                <?php echo $this->__($_order) . ' ' . $this->__('asc') ?>
            </a>
            <a href="<?php echo $this->getOrderUrl($_key, 'desc') ?>">
                <?php echo $this->__($_order) . ' ' . $this->__('desc') ?>
            </a>
        <?php else:?>
            <a href="<?php echo $this->getOrderUrl($_key, 'desc') ?>">
                <?php echo $this->__($_order) ?>
            </a>
        <?php endif;?>
    <?php endforeach; ?>
</div>


问:
Is it possible to combine SharePoint with .net 4 code
We are designing a system.

We would like to use SharePoint webparts which are .net framework 3.5 as the UI. We also have some access to the database which we would like to use EF4 which is framework 4.

Is this possible? Or do we need to put as web service hop in between?

答: This website shows what you have to do to integrate SharePoint – The MOSS</p>


问:
Getting results from Ref Cursor Oracle using ProcedureCall hibernate to createStoredProcedureCall
I'm using ProcedureCall to create stored procedure:

```<code>    ProcedureCall procedure=getCurrentSession().createStoredProcedureCall("getContractServiceForContract");
    procedure.registerParameter(1, ResultSet.class , ParameterMode.REF_CURSOR);
    procedure.registerParameter(2, Integer.class, ParameterMode.IN);
    procedure.registerParameter(3, Integer.class, ParameterMode.IN);
    procedure.registerParameter(4, Integer.class, ParameterMode.IN);

    procedure.getParameterRegistration(2).bindValue(contractId);
    procedure.getParameterRegistration(3).bindValue(month);
    procedure.getParameterRegistration(4).bindValue(year);
</code>```

After this i have:

```<code>    ResultSetOutput rso=(ResultSetOutput) procedure.getOutputs().getCurrent();
</code>```

But

getCurrent();

Throws exception:

```<code> java.lang.UnsupportedOperationException: org.hibernate.dialect.Oracle10gDialect does not support resultsets via stored procedures
</code>```

I was trying to use expression:

```<code> ResultSetOutput rso=(ResultSetOutput)procedure.getOutputs().getOutputParameterValue(1);
</code>```

But again i got exception:

```<code> org.hibernate.procedure.ParameterMisuseException: REF_CURSOR parameters should be accessed via results
</code>```

Any ideas how to make this work? My procedure starts with:

```<code>PROCEDURE getContractServiceForContract
(
  pResultValue OUT PROCTYPES.ref_cursor,
  pContractID IN INT,
  pMonth IN INT,
  pYear IN INT,
  pIsLoadByAccountingPeriod IN INT default 0
) AS
yearMin int;
yearMax int;
monthMin int;
monthMax int;
vContractIDs t_num_ids_tab;       --holds event id's
vContractServIDs t_num_ids_tab;       --holds event id's
BEGIN   ...
</code>```

答:
It's work. I get List of objects array.</p>

```<code>StoredProcedureQuery query = em.createStoredProcedureQuery(GET_GOODS_PROCEDURE)
                .registerStoredProcedureParameter(1, GoodTest.class, ParameterMode.REF_CURSOR)
                .registerStoredProcedureParameter(2, String.class, ParameterMode.OUT)
                .registerStoredProcedureParameter(3, Integer.class, ParameterMode.OUT);

        query.execute();
        List<Object[]> goods = query.getResultList();

        for (Object[] good : goods) {
            System.out.println(Arrays.toString(good));
        }
</code>```

Body:
I'm using ProcedureCall to create stored procedure:

    ProcedureCall procedure=getCurrentSession().createStoredProcedureCall("getContractServiceForContract");
    procedure.registerParameter(1, ResultSet.class , ParameterMode.REF_CURSOR);
    procedure.registerParameter(2, Integer.class, ParameterMode.IN);
    procedure.registerParameter(3, Integer.class, ParameterMode.IN);
    procedure.registerParameter(4, Integer.class, ParameterMode.IN);

    procedure.getParameterRegistration(2).bindValue(contractId);
    procedure.getParameterRegistration(3).bindValue(month);
    procedure.getParameterRegistration(4).bindValue(year);

After this i have:

    ResultSetOutput rso=(ResultSetOutput) procedure.getOutputs().getCurrent();

But

getCurrent();

Throws exception:

 java.lang.UnsupportedOperationException: org.hibernate.dialect.Oracle10gDialect does not support resultsets via stored procedures

I was trying to use expression:

 ResultSetOutput rso=(ResultSetOutput)procedure.getOutputs().getOutputParameterValue(1);

But again i got exception:

 org.hibernate.procedure.ParameterMisuseException: REF_CURSOR parameters should be accessed via results

Any ideas how to make this work? My procedure starts with:

PROCEDURE getContractServiceForContract
(
  pResultValue OUT PROCTYPES.ref_cursor,
  pContractID IN INT,
  pMonth IN INT,
  pYear IN INT,
  pIsLoadByAccountingPeriod IN INT default 0
) AS
yearMin int;
yearMax int;
monthMin int;
monthMax int;
vContractIDs t_num_ids_tab;       --holds event id's
vContractServIDs t_num_ids_tab;       --holds event id's
BEGIN   ...

Body:
It's work. I get List of objects array.

StoredProcedureQuery query = em.createStoredProcedureQuery(GET_GOODS_PROCEDURE)
                .registerStoredProcedureParameter(1, GoodTest.class, ParameterMode.REF_CURSOR)
                .registerStoredProcedureParameter(2, String.class, ParameterMode.OUT)
                .registerStoredProcedureParameter(3, Integer.class, ParameterMode.OUT);

        query.execute();
        List<Object[]> goods = query.getResultList();

        for (Object[] good : goods) {
            System.out.println(Arrays.toString(good));
        }


问:
Is there any way to increase the number limit of double type in Swift?
I'm try to filter my array and sum the amount. It works but when the number is above 999.99, it will getting nil. Is there any way to increase the number limit of double type? Is it possible?

largest number: 100,000,000.00

```<code>incomeFilter = record.filter { $0.recordtype!.contains("收入") && $0.createdAt! == recordItem.createdAt!}
let incomeSum = incomeFilter.map{Double($0.amount!.dropFirst()) ?? 0.00}.reduce(0, +)
//[9.99, nil]
</code>```

Other than that, I'm also trying to convert it to Number.

But I found that I can't use the .dropFirst() function. I got this error Cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String' after I delete it, It show another error Cannot invoke 'reduce' with an argument list of type '(Int, _)'

How to fix it?

```<code>let fmt = NumberFormatter()
fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
fmt.maximumFractionDigits = 4
fmt.minimumFractionDigits = 4
let incomeSum = incomeFilter.map{fmt.number(from: $0.amount!) ?? 0.00}.reduce(0, +)
</code>```

答:
Are you trying to sum up the first element of each array (which is a string?). If so this Playground shows how:

```<code>import UIKit

let records: [[String]] = [(100..<103).map{"\($0)"},
                           (200..<203).map{"\($0)"},
                           (300..<303).map{"\($0)"}]
print(records)
let sum = records.flatMap {$0.first}.flatMap{Double($0)}.reduce(0, +)
print(sum)
</code>```

The first flat map makes an array of strings containing the first element from all of the arrays, if a first element exists.

The second flat map converts the strings to double if they can be converted.

The reduce then adds everything up.

Body:
I'm try to filter my array and sum the amount. It works but when the number is above 999.99, it will getting nil. Is there any way to increase the number limit of double type? Is it possible?

largest number: 100,000,000.00

incomeFilter = record.filter { $0.recordtype!.contains("收入") && $0.createdAt! == recordItem.createdAt!}
let incomeSum = incomeFilter.map{Double($0.amount!.dropFirst()) ?? 0.00}.reduce(0, +)
//[9.99, nil]

Other than that, I'm also trying to convert it to Number.

But I found that I can't use the .dropFirst() function. I got this error Cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String' after I delete it, It show another error Cannot invoke 'reduce' with an argument list of type '(Int, _)'

How to fix it?

let fmt = NumberFormatter()
fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
fmt.maximumFractionDigits = 4
fmt.minimumFractionDigits = 4
let incomeSum = incomeFilter.map{fmt.number(from: $0.amount!) ?? 0.00}.reduce(0, +)

Body:
Are you trying to sum up the first element of each array (which is a string?). If so this Playground shows how:

import UIKit

let records: [[String]] = [(100..<103).map{"\($0)"},
                           (200..<203).map{"\($0)"},
                           (300..<303).map{"\($0)"}]
print(records)
let sum = records.flatMap {$0.first}.flatMap{Double($0)}.reduce(0, +)
print(sum)

The first flat map makes an array of strings containing the first element from all of the arrays, if a first element exists.

The second flat map converts the strings to double if they can be converted.

The reduce then adds everything up.


问:
Detect if the device is iPhone X
My iOS app uses a custom height for the UINavigationBar which leads to some problems on the new iPhone X.

Does someone already know how to reliable detect programmatically (in Objective-C) if an app is running on iPhone X?

EDIT:

Of course checking the size of the screen is possible, however, I wonder if there is some "build in" method like TARGET_OS_IPHONE to detect iOS...

```<code>if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
    CGSize screenSize = [[UIScreen mainScreen] bounds].size;
    if (screenSize.height == 812)
        NSLog(@"iPhone X");
}
</code>```

EDIT 2:

I do not think, that my question is a duplicate of the linked question. Of course, there are methods to "measure" different properties of the current device and to use the results to decide which device is used. However, this was not the actual point of my question as I tried to emphasize in my first edit.

The actual question is: "Is it possible to directly detect if the current device is an iPhone X (e.g. by some SDK feature) or do I have to use indirect measurements"?

By the answers given so far, I assume that the answer is "No, there is no direct methods. Measurements are the way to go".

答:
Usually, the Programmer needs it for constraining to top or bottom, so these methods can help

```<code>static func extraTop() -> CGFloat {

    var top: CGFloat = 0

    if #available(iOS 11.0, *) {

        if let t = UIApplication.shared.keyWindow?.safeAreaInsets.top {
            top = t
        }
    }
    return top
}

static func extraBottom() -> CGFloat {

    var bottom: CGFloat = 0

    if #available(iOS 11.0, *) {

        if let b = UIApplication.shared.keyWindow?.safeAreaInsets.bottom {
            bottom = b
        }
    }
    return bottom
}
</code>```

For before iPhone X these methods return: 0

For iPhone X: 44 and 34 accordingly

Then just add these extras to top or bottom constraints

Title: Detect if the device is iPhone X

Body:
My iOS app uses a custom height for the UINavigationBar which leads to some problems on the new iPhone X.

Does someone already know how to reliable detect programmatically (in Objective-C) if an app is running on iPhone X?

EDIT:

Of course checking the size of the screen is possible, however, I wonder if there is some "build in" method like TARGET_OS_IPHONE to detect iOS...

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
    CGSize screenSize = [[UIScreen mainScreen] bounds].size;
    if (screenSize.height == 812)
        NSLog(@"iPhone X");
}

EDIT 2:

I do not think, that my question is a duplicate of the linked question. Of course, there are methods to "measure" different properties of the current device and to use the results to decide which device is used. However, this was not the actual point of my question as I tried to emphasize in my first edit.

The actual question is: "Is it possible to directly detect if the current device is an iPhone X (e.g. by some SDK feature) or do I have to use indirect measurements"?

By the answers given so far, I assume that the answer is "No, there is no direct methods. Measurements are the way to go".

Body:
Usually, the Programmer needs it for constraining to top or bottom, so these methods can help

static func extraTop() -> CGFloat {

    var top: CGFloat = 0

    if #available(iOS 11.0, *) {

        if let t = UIApplication.shared.keyWindow?.safeAreaInsets.top {
            top = t
        }
    }
    return top
}

static func extraBottom() -> CGFloat {

    var bottom: CGFloat = 0

    if #available(iOS 11.0, *) {

        if let b = UIApplication.shared.keyWindow?.safeAreaInsets.bottom {
            bottom = b
        }
    }
    return bottom
}

For before iPhone X these methods return: 0

For iPhone X: 44 and 34 accordingly

Then just add these extras to top or bottom constraints


问:
How to fix the iOS 11 input element in fixed modals bug
A bug in HTML inputs in the newly released iOS 11 is creating problems for websites that have input elements in fixed containers. Here is exactly what is happening and some possible workarounds.

If you have an  in an fixed container and it is close enough to the bottom of the screen forcing the browser to scroll to make room for the keyboard, the cursor is put outside of the text input.
This was a critical problem for us since one of our core functionalities relies on the user input through a fixed modal dialog.

This was a critical problem for us since one of our core functionalities relies on the user input through a fixed modal dialog.

答:
I had this iOS bugg with a login form inside a fixed header/banner element. There is a button inside the header to open the modal window with the login form.
The actual modal window is absolute positioned, but the header/banner element is fixed.

I solved it quite easy with just a few rows of code. So what I am doing is that I am changing the fixed container to absolute, but only when the login form is open, it makes the magic with the input marker.

jQuery:

```<code>$('.ios #mob-login').on('click', function(){
  $('body').toggleClass('login-open');
});
</code>```

CSS:

```<code>.ios body.login-open #banner-wrapper {
  position: absolute;
}
</code>```

So now the fixed header becomes absolute. If it is iOS and only when the login box is open.

This might solve your problem if you have a similar problems.

Ps. You need a script to detect and write the class name ios/ios11 to  or similar, but I am not going into that in this post. You can find many solutions for that out there.

Body:
I had this iOS bugg with a login form inside a fixed header/banner element. There is a button inside the header to open the modal window with the login form.
The actual modal window is absolute positioned, but the header/banner element is fixed.

I solved it quite easy with just a few rows of code. So what I am doing is that I am changing the fixed container to absolute, but only when the login form is open, it makes the magic with the input marker.

jQuery:

$('.ios #mob-login').on('click', function(){
  $('body').toggleClass('login-open');
});

CSS:

.ios body.login-open #banner-wrapper {
  position: absolute;
}

So now the fixed header becomes absolute. If it is iOS and only when the login box is open.

This might solve your problem if you have a similar problems.

Ps. You need a script to detect and write the class name ios/ios11 to <html> or similar, but I am not going into that in this post. You can find many solutions for that out there.


问:
Flex Builder 3: syntax coloring, add keyword
I wish to know where I can add Keywords for the syntax coloring in Flex Builder - i need to extend it a little for my own sanity.</p>

答:
I don't think you can.  I haven't been able to find anywhere in the settings or in the files installed with the app where you can change the list of keywords.

As the other poster said, try FlashDevelop.  I like it a lot more than FlexBuilder.

OwnerDisplayName: Kasper

OwnerDisplayName: Herms


问:
Automating Chrome
I've seen some wild things happen when I paste some urlencoded Javascript into a URL on Firefox and Chrome. Is it possible to use this technique to tell Chrome to visit a URL and then save it as a file? I'm trying to automate Chrome, and Selenium looked extremely daunting.

EDIT: Unfortunately, I forgot to be more clear here. Let me explain. Things like wget, curl, etc. won't work because I have to get through logins in some of these scripts. And I've looked at iMacros, but found that I can't get them to run from command line except on Windows, unless I pay for the $499 package. Some other advantages of GCEs are that the dev platform is free and open to some degree, and they are cross-platform. (I use Linux.)

EDIT: At this point, I'm learning about Google Chrome Extensions. It appears they are easy to build and will let me (I think) tell the browser to open a new tab, go to a page, manipulate the DOM on that page (such as populating some fields and logging in), and then manipulate the DOM on the response page. GCEs don't let you do File I/O, so they are not like Firefox Extensions with XPCOM, but you can get around that by using AJAX to send data to a backend script (like a PHP script on a LAMP server) to save that data.

EDIT: By the way, and this is slightly off-topic (but I add to clarify) those "wild things" in Javascript that I mentioned were when you manipulate the DOM creating a URL that looks like so:

```<code>javascript:(function(){...your URL-encoded Javascript here...})();
</code>```

答:
You can use Python to automate web tasks using pywebkitgtk. It is a Python binding for WebKitGtk, which uses the WebKit engine, the same engine as chrome.

Thanks to this blog post, pywebkitgtk - Execute JavaScript from Python, I made a subclass of webkit.WebView to make these tasks easier.

```<code>import gtk
import webkit
import json

class WebView(webkit.WebView):
    def eval_script(self, script):
        self.execute_script('oldtitle=document.title;document.title="!!!!";document.title=JSON.stringify(eval(' + json.dumps(script) + '));')
        result = json.loads(self.get_main_frame().get_title())
        self.execute_script('document.title=oldtitle;')
        return result
    def wait_for_load(self):
        handle = None
        def load_status_cb(view, frame):
            if frame == view.get_main_frame():
                self.disconnect(handle)
                gtk.main_quit()
        handle = self.connect('load-finished', load_status_cb)
        gtk.main()
</code>```

I added the function called eval_script which is like execute_script, but you could get the results of the function as Python objects. You just need to make sure that what you are evaluating is JSON-serializable.

Also, I added a wait_for_load function which is pretty self-explanatory.

To set up a UI, you first have to create a window, a scrolled window, and a web view.

```<code># window
window = gtk.Window()
window.set_default_size(800, 600)

# scroll view
scroll_view = gtk.ScrolledWindow()
scroll_view.props.hscrollbar_policy = gtk.POLICY_AUTOMATIC
scroll_view.props.vscrollbar_policy = gtk.POLICY_AUTOMATIC

# web view
web_view = WebView()

# events
window.connect('delete-event', lambda window, event: gtk.main_quit())

# show
scroll_view.add(web_view)
window.add(scroll_view)
window.show_all()
</code>```

Then you can start automating things! For example, this code loads StackOverflow's login page, click the Facebook login button, fills in the username and password (in this case "test"). Finally, it shows the login button text.

```<code># the script is here
web_view.open('http://www.stackoverflow.com/users/login')
web_view.wait_for_load()

web_view.execute_script('openid.signin("facebook")')
web_view.wait_for_load()

web_view.execute_script('document.querySelector("#email").value = "test"')
web_view.execute_script('document.querySelector("#pass").value = "test"')

print "Login's button text is:", web_view.eval_script('document.querySelector("#buttons input[type=\\"submit\\"]").value')
</code>```

In my case, the Facebook's interface was in Thai language, and I could see the login's button text.

Login's button text is: เข้าสู่ระบบ

You can also have it actually click the submit button, just by calling click() on that element. (Note: click() works for button elements, not on links)

```<code>web_view.execute_script('document.querySelector("#buttons input[type=\\"submit\\"]").click()')
web_view.wait_for_load()
</code>```

You will notice that after all the scripts are finished, the application closes itself without waiting.

If you want to keep the application running after it finish all the scripts in there, you need to add the last line:

```<code>gtk.main()
</code>```

Also, if you remove the window.show_all() line and the last gtk.main() line. Then your app will work without a GUI. (Note: You still need a display server.)

Right now, we don't have good pywebkitgtk docs yet, so you have to look at WebKitGtk's documentation instead. Good luck.

Title: Automating Chrome

Body:
I've seen some wild things happen when I paste some urlencoded Javascript into a URL on Firefox and Chrome. Is it possible to use this technique to tell Chrome to visit a URL and then save it as a file? I'm trying to automate Chrome, and Selenium looked extremely daunting.

EDIT: Unfortunately, I forgot to be more clear here. Let me explain. Things like wget, curl, etc. won't work because I have to get through logins in some of these scripts. And I've looked at iMacros, but found that I can't get them to run from command line except on Windows, unless I pay for the $499 package. Some other advantages of GCEs are that the dev platform is free and open to some degree, and they are cross-platform. (I use Linux.)

EDIT: At this point, I'm learning about Google Chrome Extensions. It appears they are easy to build and will let me (I think) tell the browser to open a new tab, go to a page, manipulate the DOM on that page (such as populating some fields and logging in), and then manipulate the DOM on the response page. GCEs don't let you do File I/O, so they are not like Firefox Extensions with XPCOM, but you can get around that by using AJAX to send data to a backend script (like a PHP script on a LAMP server) to save that data.

EDIT: By the way, and this is slightly off-topic (but I add to clarify) those "wild things" in Javascript that I mentioned were when you manipulate the DOM creating a URL that looks like so:

javascript:(function(){...your URL-encoded Javascript here...})();

Body:
You can use Python to automate web tasks using pywebkitgtk. It is a Python binding for WebKitGtk, which uses the WebKit engine, the same engine as chrome.

Thanks to this blog post, pywebkitgtk - Execute JavaScript from Python, I made a subclass of webkit.WebView to make these tasks easier.

import gtk
import webkit
import json

class WebView(webkit.WebView):
    def eval_script(self, script):
        self.execute_script('oldtitle=document.title;document.title="!!!!";document.title=JSON.stringify(eval(' + json.dumps(script) + '));')
        result = json.loads(self.get_main_frame().get_title())
        self.execute_script('document.title=oldtitle;')
        return result
    def wait_for_load(self):
        handle = None
        def load_status_cb(view, frame):
            if frame == view.get_main_frame():
                self.disconnect(handle)
                gtk.main_quit()
        handle = self.connect('load-finished', load_status_cb)
        gtk.main()

I added the function called eval_script which is like execute_script, but you could get the results of the function as Python objects. You just need to make sure that what you are evaluating is JSON-serializable.

Also, I added a wait_for_load function which is pretty self-explanatory.

To set up a UI, you first have to create a window, a scrolled window, and a web view.

# window
window = gtk.Window()
window.set_default_size(800, 600)

# scroll view
scroll_view = gtk.ScrolledWindow()
scroll_view.props.hscrollbar_policy = gtk.POLICY_AUTOMATIC
scroll_view.props.vscrollbar_policy = gtk.POLICY_AUTOMATIC

# web view
web_view = WebView()

# events
window.connect('delete-event', lambda window, event: gtk.main_quit())

# show
scroll_view.add(web_view)
window.add(scroll_view)
window.show_all()

Then you can start automating things! For example, this code loads StackOverflow's login page, click the Facebook login button, fills in the username and password (in this case "test"). Finally, it shows the login button text.

# the script is here
web_view.open('http://www.stackoverflow.com/users/login')
web_view.wait_for_load()

web_view.execute_script('openid.signin("facebook")')
web_view.wait_for_load()

web_view.execute_script('document.querySelector("#email").value = "test"')
web_view.execute_script('document.querySelector("#pass").value = "test"')

print "Login's button text is:", web_view.eval_script('document.querySelector("#buttons input[type=\\"submit\\"]").value')

In my case, the Facebook's interface was in Thai language, and I could see the login's button text.

Login's button text is: เข้าสู่ระบบ

You can also have it actually click the submit button, just by calling click() on that element. (Note: click() works for button elements, not on links)

web_view.execute_script('document.querySelector("#buttons input[type=\\"submit\\"]").click()')
web_view.wait_for_load()

You will notice that after all the scripts are finished, the application closes itself without waiting.

If you want to keep the application running after it finish all the scripts in there, you need to add the last line:

gtk.main()

Also, if you remove the window.show_all() line and the last gtk.main() line. Then your app will work without a GUI. (Note: You still need a display server.)

Right now, we don't have good pywebkitgtk docs yet, so you have to look at WebKitGtk's documentation instead. Good luck.


问:
What's the best way to get device locale in react native (iOS)?
Something similar to [NSLocale currentLocale] in Objective-C.</p>

答:
Personally I prefer use react-native-i18n.
then you can use like this inside the documentation..

```<code>import { getLanguages } from 'react-native-i18n'

getLanguages().then(languages => {
  console.log(languages) // ['en-US', 'en']
})
</code>```

link: https://github.com/AlexanderZaytsev/react-native-i18n

Body:
Personally I prefer use react-native-i18n.
then you can use like this inside the documentation..

import { getLanguages } from 'react-native-i18n'

getLanguages().then(languages => {
  console.log(languages) // ['en-US', 'en']
})

link: https://github.com/AlexanderZaytsev/react-native-i18n


问:
How to prevent Google Chrome suppressing dialogs?
How can I prevent Chrome console giving the following error when I try to use the prompt() command?

A window.prompt() dialog generated by this page was suppressed because
  this page is not the active tab of the front window. Please make sure
  your dialogs are triggered by user interactions to avoid this
  situation. https://www.chromestatus.com/feature/5637107137642496

Up until 2-3 days ago the prompt() command worked fine and would open a dialog where I could input data, now it always gives me this error even if I am definitely on the active tab. I have checked chrome content settings and allow popups is checked.

Thanks!

答:
You have to dock the developer window in the same window.
Don't undock into a separate window.
This helped me.
EDIT: Screenshot
In Undocked mode
That is no active window attached.
And when
It is docked to left || right || down the window
It works Properly


问:
extract timestamp from EPOCH cloumn from postgresql DB table
I am trying to execute below-mentioned PostgreSQL query and in which checkin_ts in epoch format and want to write a query which is humanly understandable(putting timestamp in human readable format).

```<code>select * from users where to_timestamp(checkin_ts) >= '2017-11-11 00:00:00'
LIMIT 100;
</code>```

when I tried to execute the above query then I get the following error

```<code>ERROR:  execute cannot be used while an asynchronous query is underway
</code>```

答:
You need to give us the description of your table, to know checkin_ts format.

But to_timestamp need to text paramaters like this :

```<code>SELECT *
  FROM users
 WHERE to_timestamp(checkin_ts::text, 'YYYY-MM-DD HH24:MI:SS') >= '2017-11-11 00:00:00' LIMIT 100;
</code>```

And what is your environment to execute this query ?
The error seems to be that you are trying to execute two queries on the same connection using two different cursors.

Body:
I am trying to execute below-mentioned PostgreSQL query and in which checkin_ts in epoch format and want to write a query which is humanly understandable(putting timestamp in human readable format).

select * from users where to_timestamp(checkin_ts) >= '2017-11-11 00:00:00'
LIMIT 100;

when I tried to execute the above query then I get the following error

ERROR:  execute cannot be used while an asynchronous query is underway

Body:
You need to give us the description of your table, to know checkin_ts format.

But to_timestamp need to text paramaters like this :

SELECT *
  FROM users
 WHERE to_timestamp(checkin_ts::text, 'YYYY-MM-DD HH24:MI:SS') >= '2017-11-11 00:00:00' LIMIT 100;

And what is your environment to execute this query ?
The error seems to be that you are trying to execute two queries on the same connection using two different cursors.


问:
How to use Rcpp in Code::Blocks IDE
I am trying to use Rcpp package in Code::Blocks IDE but when I try to compile a script with #include<Rcpp.h> I get an error saying that the file or repository does not exists.

I have the library Rcpp installed, so in RStudio I can run .cpp files.

The thing is I want to use Rcpp classes in a c++ script in Code::Blocks IDE.

How can I do this?

答:
After a long search on the internet and ask for help from the c ++ programmers of the company where I am a fellow, I managed to find a viable solution to my problem, I will explain it next in case it is useful to somebody:

The solution is pretty simple, instead of trying to compile and execute an independent script, the key is to make a project in Code::Blocks and declare the script inside. After that just declare the Rcpp and R libraries inside the project, in file dependences, as also the dynamic libraries. This makes it possible to run #include<Rcpp.h> and so work with all the adventages it provides to R programmers.

Title: How to use Rcpp in Code::Blocks IDE


问:
How can I make my animation transition smoothly?
I am trying to make an animation of a panel attached with two string though a nail swing from left to right like a pendulum. Here is the animation code and transition function. For the demo, you can check the snippet below:

.headline {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
  margin-top: 150px;
}

.headline .box {
  position: relative;
  top: 10px;
  left: -70px;
}

.headline .box:after {
  content: "";
  width: 45px;
  height: 45px;
  background: black;
  position: absolute;
  border-radius: 50%;
  top: -85px;
  left: 105px;
  z-index: 10;
}

.headline .panel {
  background: white;
  color: #ff004f;
  font-size: 46px;
  font-family: "Quicksand", sans-serif;
  padding: 10px;
  font-weight: 700;
  max-width: 250px;
  display: block;
  line-height: 46px;
  position: relative;
}

.headline .panel:hover {
  animation-timing-function: cubic-bezier(0.120, 0.485, 0.950, 0.475);
  animation: pendulum 2s infinite;
}

.headline .panel:before {
  content: "";
  width: 155px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(8px) rotate(148deg);
  position: absolute;
  top: -40px;
  left: -16px;
  border-radius: 5px;
}

.headline .panel:after {
  content: "";
  width: 150px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(-10px) rotate(-148deg);
  position: absolute;
  top: -40px;
  right: -18px;
}

@keyframes pendulum {
  0%,
  50%,
  100% {
    transform: rotate(0deg);
    transform-origin: 50% -50%;
  }
  25% {
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
  75% {
    transform: rotate(25deg);
    transform-origin: 50% -50%;
  }
}

body {
  background-color: #EEE;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="headline">
  <div class="box">
    <span class="panel">Test Panel</span>
  </div>
</div></code>```

It worked somehow but the animation is robotic and not very smooth and natural. Could you please point out how to improve this animation.

I also can use jQuery for this case if you need to use JS.

答:
.headline {
        display: flex;
        justify-content: center;
        margin-bottom: 40px;
        margin-top: 150px;
    }

    .headline .box {
        position: relative;
        top: 10px;
        left: -70px;
    }

    .headline .box:after {
        content: "";
        width: 45px;
        height: 45px;
        background: black;
        position: absolute;
        border-radius: 50%;
        top: -85px;
        left: 105px;
        z-index: 10;
    }

    .headline .panel {
        background: white;
        color: #ff004f;
        font-size: 46px;
        font-family: "Quicksand", sans-serif;
        padding: 10px;
        font-weight: 700;
        max-width: 250px;
        display: block;
        line-height: 46px;
        position: relative;
    }

    .headline .panel:hover {
        animation-timing-function: cubic-bezier(0.97, 0.96, 0.01, 0.01);
        animation: pendulum 3s infinite;
        -webkit-transition: 15s;
    }

    .headline .panel:before {
        content: "";
        width: 155px;
        height: 10px;
        background: white;
        display: block;
        transform: translateX(8px) rotate(148deg);
        position: absolute;
        top: -40px;
        left: -16px;
        border-radius: 5px;
    }

    .headline .panel:after {
        content: "";
        width: 150px;
        height: 10px;
        background: white;
        display: block;
        transform: translateX(-10px) rotate(-148deg);
        position: absolute;
        top: -40px;
        right: -18px;
    }

    @keyframes pendulum {
        0%{
            transform: rotate(-25deg);
            transform-origin: 50% -50%;
        }
        50%{
            transform: rotate(25deg);
            transform-origin: 50% -50%;
        }
        100%{
            transform: rotate(-25deg);
            transform-origin: 50% -50%;
        }
    }

    body {
        background-color: #EEE;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="headline">
    <div class="box">
        <span class="panel">Test Panel</span>
    </div>
</div></code>```

Body:
I am trying to make an animation of a panel attached with two string though a nail swing from left to right like a pendulum. Here is the animation code and transition function. For the demo, you can check the snippet below:

.headline {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
  margin-top: 150px;
}

.headline .box {
  position: relative;
  top: 10px;
  left: -70px;
}

.headline .box:after {
  content: "";
  width: 45px;
  height: 45px;
  background: black;
  position: absolute;
  border-radius: 50%;
  top: -85px;
  left: 105px;
  z-index: 10;
}

.headline .panel {
  background: white;
  color: #ff004f;
  font-size: 46px;
  font-family: "Quicksand", sans-serif;
  padding: 10px;
  font-weight: 700;
  max-width: 250px;
  display: block;
  line-height: 46px;
  position: relative;
}

.headline .panel:hover {
  animation-timing-function: cubic-bezier(0.120, 0.485, 0.950, 0.475);
  animation: pendulum 2s infinite;
}

.headline .panel:before {
  content: "";
  width: 155px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(8px) rotate(148deg);
  position: absolute;
  top: -40px;
  left: -16px;
  border-radius: 5px;
}

.headline .panel:after {
  content: "";
  width: 150px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(-10px) rotate(-148deg);
  position: absolute;
  top: -40px;
  right: -18px;
}

@keyframes pendulum {
  0%,
  50%,
  100% {
    transform: rotate(0deg);
    transform-origin: 50% -50%;
  }
  25% {
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
  75% {
    transform: rotate(25deg);
    transform-origin: 50% -50%;
  }
}

body {
  background-color: #EEE;
}

    Test Panel

It worked somehow but the animation is robotic and not very smooth and natural. Could you please point out how to improve this animation.

I also can use jQuery for this case if you need to use JS.

Body:
.headline {
        display: flex;
        justify-content: center;
        margin-bottom: 40px;
        margin-top: 150px;
    }

    .headline .box {
        position: relative;
        top: 10px;
        left: -70px;
    }

    .headline .box:after {
        content: "";
        width: 45px;
        height: 45px;
        background: black;
        position: absolute;
        border-radius: 50%;
        top: -85px;
        left: 105px;
        z-index: 10;
    }

    .headline .panel {
        background: white;
        color: #ff004f;
        font-size: 46px;
        font-family: "Quicksand", sans-serif;
        padding: 10px;
        font-weight: 700;
        max-width: 250px;
        display: block;
        line-height: 46px;
        position: relative;
    }

    .headline .panel:hover {
        animation-timing-function: cubic-bezier(0.97, 0.96, 0.01, 0.01);
        animation: pendulum 3s infinite;
        -webkit-transition: 15s;
    }

    .headline .panel:before {
        content: "";
        width: 155px;
        height: 10px;
        background: white;
        display: block;
        transform: translateX(8px) rotate(148deg);
        position: absolute;
        top: -40px;
        left: -16px;
        border-radius: 5px;
    }

    .headline .panel:after {
        content: "";
        width: 150px;
        height: 10px;
        background: white;
        display: block;
        transform: translateX(-10px) rotate(-148deg);
        position: absolute;
        top: -40px;
        right: -18px;
    }

    @keyframes pendulum {
        0%{
            transform: rotate(-25deg);
            transform-origin: 50% -50%;
        }
        50%{
            transform: rotate(25deg);
            transform-origin: 50% -50%;
        }
        100%{
            transform: rotate(-25deg);
            transform-origin: 50% -50%;
        }
    }

    body {
        background-color: #EEE;
    }

<div class="headline">
    <div class="box">
        <span class="panel">Test Panel</span>
    </div>
</div>


问:
Case statement to add extra column with custom data
Need some help with building a case statement. My information brought back is telemetry based and need to adjust where a solution name is "Excel" I need it to rename it to "Microsoft Excel" (just an example). The coloumn with the data is called "Solution name".

Something in the line of Where solution name is "excel" then "MS excel"

Any help will be useful, thanks

Code below

```<code>let
    Source = Sql.Database("xx.xxx.xx.xx\Telemetry", "TELEMETRY"),
    dbo_Lookup_solutions = Source{[Schema="dbo",Item="Lookup_solutions"]}[Data]
in
    dbo_Lookup_solutions
</code>```

答: Case when solution like ‘%excel%’ then ‘msexcel’ else solution end

Body:
Need some help with building a case statement. My information brought back is telemetry based and need to adjust where a solution name is "Excel" I need it to rename it to "Microsoft Excel" (just an example). The coloumn with the data is called "Solution name".

Something in the line of Where solution name is "excel" then "MS excel"

Any help will be useful, thanks

Code below

let
    Source = Sql.Database("xx.xxx.xx.xx\Telemetry", "TELEMETRY"),
    dbo_Lookup_solutions = Source{[Schema="dbo",Item="Lookup_solutions"]}[Data]
in
    dbo_Lookup_solutions


问:
Remove selected attribute if another select is changed, with Bootstrap Select
I want to remove the selected attribute from a select if its sibling select changes its option. With ordinary jQuery, this code is working as usual. See this fiddle: https://jsfiddle.net/hv0x43em/1/

However, I'm also using Bootstrap Select.

With Bootstrap Select, the selected attribute doesn't seem to get removed. Here is my fiddle and code: https://jsfiddle.net/L71xtwx3/2/

$(document).ready(function() {
  $(".charts-city").on('change', function(e) {
    var dataOptions = $(this).closest(".form-group").next().find(".charts-data option");
    $(dataOptions).prop("selected", false);
    e.preventDefault();
  });
});
```

Any idea how to work on it?

答:
According to your jsfiddle  demo code you are taking wrong class charts-provinsi instead of charts-city.

here is the working code

```<code>$(document).ready(function() {
    $(".charts-city").on('change', function(e) {
        $(".charts-data").val('0');
        $(".charts-data").selectpicker("refresh");
    });
});
</code>```

here is the referral link
https://silviomoreto.github.io/bootstrap-select/methods/#selectpickerrefresh

here is the working demo  https://jsfiddle.net/L71xtwx3/6/

Body:
I want to remove the selected attribute from a select if its sibling select changes its option. With ordinary jQuery, this code is working as usual. See this fiddle: https://jsfiddle.net/hv0x43em/1/

However, I'm also using Bootstrap Select.

With Bootstrap Select, the selected attribute doesn't seem to get removed. Here is my fiddle and code: https://jsfiddle.net/L71xtwx3/2/

$(document).ready(function() {
  $(".charts-city").on('change', function(e) {
    var dataOptions = $(this).closest(".form-group").next().find(".charts-data option");
    $(dataOptions).prop("selected", false);
    e.preventDefault();
  });
});

Any idea how to work on it?

Body:
According to your jsfiddle  demo code you are taking wrong class charts-provinsi instead of charts-city.

here is the working code

$(document).ready(function() {
    $(".charts-city").on('change', function(e) {
        $(".charts-data").val('0');
        $(".charts-data").selectpicker("refresh");
    });
});

here is the referral link
https://silviomoreto.github.io/bootstrap-select/methods/#selectpickerrefresh

here is the working demo  https://jsfiddle.net/L71xtwx3/6/


问:
How to get user id of logged in user in .NET Core 2.0?
I have created a angular 2 application using .NET Core and MVC.
I want to know the login id of user. How to get logged in id of a user in .net core?

This is my first angular application. I used following link to start
https://blogs.msdn.microsoft.com/webdev/2017/02/14/building-single-page-applications-on-asp-net-core-with-javascriptservices/

I want to use windows authentication, to get login id in a controller.

答:
Try this one:

var user = await userManager.GetUserAsync(HttpContext.User);
var ID = user.Id;
```


问:
Error removing column Rails
In my Rails app, I have a model called Rutinas. After some time, I needed to add some columns to the table so I generated a migration 20171116094810_add_votos_y_veces_asignada_to_rutinas.rb:

```<code>class AddVotosYVecesAsignadaToRutinas < ActiveRecord::Migration[5.1]
  def change
    add_column :rutinas, :votos_pos, :integer, :default => 0
    add_column :rutinas, :votos_neg, :integer, :default => 0
    add_column :rutinas, :veces_asig, :integer, :default => 0
  end
end
</code>```

After some other migrations, I needed to delete two columns that I don't need anymore votos_pos and votos_neg so I generated another migration 20171117092026_remove_votos_from_rutinas.rb:

```<code>class RemoveVotosFromRutinas < ActiveRecord::Migration[5.1]
  def change
    remove_column :rutinas, :votos_pos, :integer
    remove_column :rutinas, :votos_neg, :integer
  end
end
</code>```

The problem is that when I run rails db:migrate to migrate this last migration, it throws some weird error:

```<code>== 20171117092026 RemoveVotosFromRutinas: migrating ===========================
-- remove_column(:rutinas, :votos_pos)
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::ConstraintException: FOREIGN KEY constraint failed: DROP TABLE "rutinas"
C:/Users/pepe/Dropbox/pepe/KeepMeFit/KeepMeFit-git/db/migrate/20171117092026_remove_votos_from_rutinas.rb:3:in `change'
bin/rails:4:in `require'
bin/rails:4:in `<main>'

Caused by:
ActiveRecord::InvalidForeignKey: SQLite3::ConstraintException: FOREIGN KEY constraint failed: DROP TABLE "rutinas"
C:/Users/pepe/Dropbox/pepe/KeepMeFit/KeepMeFit-git/db/migrate/20171117092026_remove_votos_from_rutinas.rb:3:in `change'
bin/rails:4:in `require'
bin/rails:4:in `<main>'

Caused by:
SQLite3::ConstraintException: FOREIGN KEY constraint failed
C:/Users/pepe/Dropbox/pepe/KeepMeFit/KeepMeFit-git/db/migrate/20171117092026_remove_votos_from_rutinas.rb:3:in `change'
bin/rails:4:in `require'
bin/rails:4:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
</code>```

My Rutinas model is the following:

```<code>class Rutina < ActiveRecord::Base
  validates_presence_of :nombre

  belongs_to :user
  has_many :repeticions
  has_many :entrenos, dependent: :destroy
  has_many :votos

  has_many :days, dependent: :destroy

  def get_array_dias
    (1..self.repeticions.last.dia).to_a
  end

  def get_number_of_days
    days.count
  end

end
</code>```

User, repeticion, entreno, voto and day are other tables which are non-related to the columns that I'm trying to delete. That is to say, these columns are not a foreign key and any foreign key references these columns.

答:
It seems like the problem is the limitation of SQLite. If you check the documentation you'll see, that it only allows adding a column, but not removing one: https://sqlite.org/lang_altertable.html

It is possible, that the migration actually drops the whole table and recreates it, when a column is removed. This would explain the DROP TABLE "rutinas" message. Of course if the while table is dropped, it would make sense that certain foreign key constraints fail.

Title: Error removing column Rails

Body:
In my Rails app, I have a model called Rutinas. After some time, I needed to add some columns to the table so I generated a migration 20171116094810_add_votos_y_veces_asignada_to_rutinas.rb:

class AddVotosYVecesAsignadaToRutinas < ActiveRecord::Migration[5.1]
  def change
    add_column :rutinas, :votos_pos, :integer, :default => 0
    add_column :rutinas, :votos_neg, :integer, :default => 0
    add_column :rutinas, :veces_asig, :integer, :default => 0
  end
end

After some other migrations, I needed to delete two columns that I don't need anymore votos_pos and votos_neg so I generated another migration 20171117092026_remove_votos_from_rutinas.rb:

class RemoveVotosFromRutinas < ActiveRecord::Migration[5.1]
  def change
    remove_column :rutinas, :votos_pos, :integer
    remove_column :rutinas, :votos_neg, :integer
  end
end

The problem is that when I run rails db:migrate to migrate this last migration, it throws some weird error:

== 20171117092026 RemoveVotosFromRutinas: migrating ===========================
-- remove_column(:rutinas, :votos_pos)
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::ConstraintException: FOREIGN KEY constraint failed: DROP TABLE "rutinas"
C:/Users/pepe/Dropbox/pepe/KeepMeFit/KeepMeFit-git/db/migrate/20171117092026_remove_votos_from_rutinas.rb:3:in `change'
bin/rails:4:in `require'
bin/rails:4:in `'

Caused by:
ActiveRecord::InvalidForeignKey: SQLite3::ConstraintException: FOREIGN KEY constraint failed: DROP TABLE "rutinas"
C:/Users/pepe/Dropbox/pepe/KeepMeFit/KeepMeFit-git/db/migrate/20171117092026_remove_votos_from_rutinas.rb:3:in `change'
bin/rails:4:in `require'
bin/rails:4:in `'

Caused by:
SQLite3::ConstraintException: FOREIGN KEY constraint failed
C:/Users/pepe/Dropbox/pepe/KeepMeFit/KeepMeFit-git/db/migrate/20171117092026_remove_votos_from_rutinas.rb:3:in `change'
bin/rails:4:in `require'
bin/rails:4:in `'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

My Rutinas model is the following:

class Rutina < ActiveRecord::Base
  validates_presence_of :nombre

  belongs_to :user
  has_many :repeticions
  has_many :entrenos, dependent: :destroy
  has_many :votos

  has_many :days, dependent: :destroy

  def get_array_dias
    (1..self.repeticions.last.dia).to_a
  end

  def get_number_of_days
    days.count
  end

end

User, repeticion, entreno, voto and day are other tables which are non-related to the columns that I'm trying to delete. That is to say, these columns are not a foreign key and any foreign key references these columns.


问:
How to change the attributes of the
```

<p>How can i change the value of <code>data-amount="100"</code> to my desired value</p>

<p>I tried like</p>

```document.getElementById("paymentWidget").attr("data-amount") = total
```

<p>But it is showing error like </p>

```document.getElementById(...).attr is not a function
```

How can i fix this and set values dynamically ?

答:
Right function is setAttribute, check its syntax bellow:</p>

```<code>document.getElementById("paymentWidget").setAttribute('data-amount', total)
</code>```

Title: How to change the attributes of the <script> tag

Body:
Here is my script tag

How can i change the value of data-amount="100" to my desired value

I tried like

document.getElementById("paymentWidget").attr("data-amount") = total

But it is showing error like

document.getElementById(...).attr is not a function

How can i fix this and set values dynamically ?

Body:
Right function is setAttribute, check its syntax bellow:

document.getElementById("paymentWidget").setAttribute('data-amount', total)


问:
In Java how can I validate a thrown exception with JUnit?
When writing unit tests for a Java API there may be circumstances where you want to perform more detailed validation of an exception. I.e. more than is offered by the @test annotation offered by JUnit.

For example, consider an class that should catch an exception from some other Interface, wrap that exception and throw the wrapped exception. You may want to verify:

The exact method call that throws the wrapped exception.

That the wrapper exception has the original exception as its cause.

The message of the wrapper exception.

The main point here is that you want to be perf additional validation of an exception in a unit test (not a debate about whether you should verify things like the exception message).

What's a good approach for this?

答:
For JUnit 5 it is much easier:

```<code>    @Test
    void testAppleIsSweetAndRed() throws Exception {

        IllegalArgumentException ex = assertThrows(
                IllegalArgumentException.class,
                () -> testClass.appleIsSweetAndRed("orange", "red", "sweet"));

        assertEquals("this is the exception message", ex.getMessage());
        assertEquals(NullPointerException.class, ex.getCause().getClass());
    }
</code>```

By returning the exception object itself, assertThrows() allows you to test every aspect regarding your thrown exceptions.

Body:
For JUnit 5 it is much easier:

    @Test
    void testAppleIsSweetAndRed() throws Exception {

        IllegalArgumentException ex = assertThrows(
                IllegalArgumentException.class,
                () -> testClass.appleIsSweetAndRed("orange", "red", "sweet"));

        assertEquals("this is the exception message", ex.getMessage());
        assertEquals(NullPointerException.class, ex.getCause().getClass());
    }

By returning the exception object itself, assertThrows() allows you to test every aspect regarding your thrown exceptions.


问:
Draw line between two given points (OpenCV, Python)
I am struggling with this problem for an hour by now...

I have an image with a rectangle inside:

This is the code I wrote to find the points for the corners:

```<code>import cv2
import numpy as np

img = cv2.imread('rect.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)

points = cv2.goodFeaturesToTrack(gray, 100, 0.01, 10)
points = np.int0(points)

for point in points:
    x, y = point.ravel()
    cv2.circle(img, (x, y), 3, (0, 255, 0), -1)

print(points[0])
print(points[1])
print(points[2])
print(points[3])

cv2.imshow('img', img)
cv2.waitKey(0)
cv2.imwrite('rect.png', img)
</code>```

This is the result:

As you can see, it works perfect. What I want is to draw a line along the upper/lower points (x1,x2 - x3,x4).

What I produced since now is this...

```<code>cv2.line(img, (points[0]), (points[1]), (0, 255, 0), thickness=3, lineType=8)

cv2.imshow('img', img)
cv2.waitKey(0)
</code>```

But it doesn't work.

Any idea ?

The result should be like this:

The two lines must pass along the coordinates of the points. print(points[0]) above give the next output, as example:

```<code>[[561 168]]
[[155 168]]
[[561  53]]
[[155  53]]
</code>```

Thanks

答:
```<code>points = cv2.goodFeaturesToTrack(gray, 100, 0.01, 10)
points = np.int0(points).reshape(-1,2)

for point in points:
    x, y = point.ravel()
    cv2.circle(img, (x, y), 3, (0, 255, 0), -1)

y1 = min(points[:,1])
y2 = max(points[:,1])

## small and big enough
cv2.line(img, (0, y1), (1000, y1), (0, 255, 0), thickness=3, lineType=8)
cv2.line(img, (0, y2), (1000, y2), (0, 255, 0), thickness=3, lineType=8)
</code>```

Body:
I am struggling with this problem for an hour by now...

I have an image with a rectangle inside:

This is the code I wrote to find the points for the corners:

import cv2
import numpy as np

img = cv2.imread('rect.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)

points = cv2.goodFeaturesToTrack(gray, 100, 0.01, 10)
points = np.int0(points)

for point in points:
    x, y = point.ravel()
    cv2.circle(img, (x, y), 3, (0, 255, 0), -1)

print(points[0])
print(points[1])
print(points[2])
print(points[3])

cv2.imshow('img', img)
cv2.waitKey(0)
cv2.imwrite('rect.png', img)

This is the result:

As you can see, it works perfect. What I want is to draw a line along the upper/lower points (x1,x2 - x3,x4).

What I produced since now is this...

cv2.line(img, (points[0]), (points[1]), (0, 255, 0), thickness=3, lineType=8)

cv2.imshow('img', img)
cv2.waitKey(0)

But it doesn't work.

Any idea ?

The result should be like this:

The two lines must pass along the coordinates of the points. print(points[0]) above give the next output, as example:

[[561 168]]
[[155 168]]
[[561  53]]
[[155  53]]

Thanks


问:
Display the result column name from COALESCE result using SQL SERVER 2008?
Can someone help me with the below query update the RESULTANT COLUMN NAME EG:A OR B OR C after using the COALESCE function?

Example:

Table:

```<code>A - null,
B - null,
C - 5

select COALESCE(A,B,C) As [COL1], [COL2]
from TABLE
</code>```

In this case [Col2] should display the column name as 'C'

Result:

```<code>[COl1] = 5
[Col2] = C   (Displays the Column Name)
</code>```

Thanks,
Kavin

答:
One method uses case:

```<code>select coalesce(A, B, C) As [COL1],
       (case when A is not null then 'A'
             when B is not null then 'B'
             when C is not null then 'C'
        end) as [COL2]
from TABLE;
</code>```

If you wanted to be fancy, you could use APPLY:

```<code>select v.val, v.col
from t outer apply
     (select top (1) v.*
      from (values (t.A, 'A', 1), (t.B, 'B', 2), (t.C, 'C', 3)
           ) v(val, col, ord)
      where val is not null
      order by ord
     ) tt;
</code>```

Body:
Can someone help me with the below query update the RESULTANT COLUMN NAME EG:A OR B OR C after using the COALESCE function?

Example:

Table:

A - null,
B - null,
C - 5

select COALESCE(A,B,C) As [COL1], [COL2]
from TABLE

In this case [Col2] should display the column name as 'C'

Result:

[COl1] = 5
[Col2] = C   (Displays the Column Name)

Thanks,
Kavin

Body:
One method uses case:

select coalesce(A, B, C) As [COL1],
       (case when A is not null then 'A'
             when B is not null then 'B'
             when C is not null then 'C'
        end) as [COL2]
from TABLE;

If you wanted to be fancy, you could use APPLY:

select v.val, v.col
from t outer apply
     (select top (1) v.*
      from (values (t.A, 'A', 1), (t.B, 'B', 2), (t.C, 'C', 3)
           ) v(val, col, ord)
      where val is not null
      order by ord
     ) tt;


问:
How to get logs of app from android without using android studio?
I have given App to my friend but its not working.I want to know the issue  so that I want log file of my App.Is there anyway to get logs from android without using android studio or any debugger tool.I want only log file to get solve issue.So What is the way to get log file from android device.
Thanks in advance.</p>

答: You can use firebase log events.</p>

Body: You can use firebase log events.


答:
If you simply split the (stripped) string using

```<code>[,\n]\s*
</code>```

you'll end up with an array of phone numbers.

It matches all commas or newlines, and any following whitespace.

See it here at ideone.

Title: Need a little twitch in my regex to get all the numbers

Body:
How to fix the pattern to get the all listed numbers. Currently what I'm getting with the way I've tried is given below:

import re

content='''
(555) 567-4523, 555 567 4523, (555) 567 4523, 555-567-4623
+91-8071805024, +91-11-2352280
'''
print(re.findall(r"\+?.\d+.-?\(?\d+.\)?-?\s?\w*.-?\s?\w*.",content))

Result I'm getting:

['(555) 567-4523,', ' 555 567 4523, (', ' 567 4523, 555-567-', '+91-8071805024, +91-', '11-2352280']

Result I'm after:

(555) 567-4523, 555 567 4523, (555) 567 4523, 555-567-4623
+91-8071805024, +91-11-2352280

Body:
If you simply split the (stripped) string using

[,\n]\s*

you'll end up with an array of phone numbers.

It matches all commas or newlines, and any following whitespace.

See it here at ideone.


答:
Your question is tagged with Jquery, but you're using plain JavaScript to get and element from the DOM

Try changing it to use a Jquery selector and setting the attribute correctly

```<code>$('#paymentWidget').attr('data-amount', total)
</code>```

The reason your code isn't working is because you're trying to use the Jquery method .attr on something which isn't a Jquery object.

Alternatively you could use .data

```<code>$('#paymentWidget').data('amount', total)
</code>```

The major difference is that .data will not change the DOM

Body:
Your question is tagged with Jquery, but you're using plain JavaScript to get and element from the DOM

Try changing it to use a Jquery selector and setting the attribute correctly

$('#paymentWidget').attr('data-amount', total)

The reason your code isn't working is because you're trying to use the Jquery method .attr on something which isn't a Jquery object.

Alternatively you could use .data

$('#paymentWidget').data('amount', total)

The major difference is that .data will not change the DOM