问:
C# 'LBImqP.Form1' does not contain a definition for 'Form1_Load'
Please someone help me, i stuck at this error and i dont now how to fix it.

Error code: 'LBImqP.Form1' does not contain a definition for 'Form1_Load' and no extension method 'Form1_Load' accepting a first argument of type 'LBImqP.Form1' could be found (are you missing a using directive or an assembly reference?)

Here my code:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace LBImqP
{
    public partial class Form1 : Form
    {
        MySqlConnection con = new MySqlConnection(@"Data Source=localhost;port=3306;Initial Catalog=lbimqp;User ID=root;password='server1234'");
        int i;
        public Form1()
        {
            InitializeComponent();
        }

        private void login_Click(object sender, EventArgs e)
        {
            i = 0;
            con.Open();
            MySqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select * from login where username='"+user.Text+"' and password='"+pass.Text+"'";
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            da.Fill(dt);
            i = Convert.ToInt32(dt.Rows.Count.ToString());

            if (i == 0)
            {
                wrong.Text = "Benutzername oder Passwort ist falsch!";
            }
            else
            {
                this.Hide();
                mainscreen ms = new mainscreen();
                ms.Show();
            }
            con.Close();
        }
        private void pass_TextChanged(object sender, EventArgs e)
        {
            pass.PasswordChar = '*';
        }

        private void exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
</code>```

I'm getting this error at button1_Click, and Form1_Load

it would be greatful when someone can help me please.

答:
It looks like you are attaching an event inside the Form1 designer with event handler Form1_Load, and the event handler is not defined in Form1 class.

Or the namespaces of the designer class and form class are not identical.

Body:
Please someone help me, i stuck at this error and i dont now how to fix it.

Error code: 'LBImqP.Form1' does not contain a definition for 'Form1_Load' and no extension method 'Form1_Load' accepting a first argument of type 'LBImqP.Form1' could be found (are you missing a using directive or an assembly reference?)

Here my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace LBImqP
{
    public partial class Form1 : Form
    {
        MySqlConnection con = new MySqlConnection(@"Data Source=localhost;port=3306;Initial Catalog=lbimqp;User ID=root;password='server1234'");
        int i;
        public Form1()
        {
            InitializeComponent();
        }

        private void login_Click(object sender, EventArgs e)
        {
            i = 0;
            con.Open();
            MySqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select * from login where username='"+user.Text+"' and password='"+pass.Text+"'";
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            da.Fill(dt);
            i = Convert.ToInt32(dt.Rows.Count.ToString());

            if (i == 0)
            {
                wrong.Text = "Benutzername oder Passwort ist falsch!";
            }
            else
            {
                this.Hide();
                mainscreen ms = new mainscreen();
                ms.Show();
            }
            con.Close();
        }
        private void pass_TextChanged(object sender, EventArgs e)
        {
            pass.PasswordChar = '*';
        }

        private void exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

I'm getting this error at button1_Click, and Form1_Load

it would be greatful when someone can help me please.


来源: stackexchange

问:
How to see if running under service fabric
I sometimes run projects locally out of visual studio is there a better way to detect if I'm hosted by SF rather than the exception. I can see possibly the path or entry assembly but there must be a better way. </p>

```<code>try
{
    ServiceRuntime.RegisterServiceAsync("FisConfigUIType",
        context = > new WebHost < Startup > (context, loggerFactory, "ServiceEndpoint", Startup.serviceName)).GetAwaiter().GetResult();
    Thread.Sleep(Timeout.Infinite);
}
catch (FabricException sfEx)
{
    RunLocal(args, loggerFactory);
}
</code>```

答:
Check Service Fabric Environment Variables:

var sfAppName = Environment.GetEnvironmentVariable("Fabric_ApplicationName");
var isSf = sfAppName != null;
```

Source: from @mkosieradzki GitHub Issue

ContentLicense: CC BY-SA 3.0

Body:
I sometimes run projects locally out of visual studio is there a better way to detect if I'm hosted by SF rather than the exception. I can see possibly the path or entry assembly but there must be a better way.

try
{
    ServiceRuntime.RegisterServiceAsync("FisConfigUIType",
        context = > new WebHost < Startup > (context, loggerFactory, "ServiceEndpoint", Startup.serviceName)).GetAwaiter().GetResult();
    Thread.Sleep(Timeout.Infinite);
}
catch (FabricException sfEx)
{
    RunLocal(args, loggerFactory);
}

Body:
Check Service Fabric Environment Variables:

var sfAppName = Environment.GetEnvironmentVariable("Fabric_ApplicationName");
var isSf = sfAppName != null;

Source: from @mkosieradzki GitHub Issue


问:
Resource not found in ResourceDictionary for external control
PROBLEM

I would like to style control that is defined in Project B, but used on page in Project A using styles from Project A. I decided to do it by defining Merged Dictionary with styles dictionary that contains keys used in MyCtrl.xaml.

I thought that MyCtrl that is used in MainPage will go up the XAML tree to find the right style if it didn't find it in own xaml (broader scope), but I get exceptions that name/key was not found. Am I doing something wrong, or this idea is incorrect and I should find another solution?

Here is the structure:

I have a 2 projects:

Project A - main application with MainPage page and all styles/resources.

Project B - contains user controls

Project A references Project B.

(Project A) MainPage.xaml

```<code><Page
   xmlns:ext="using:ProjB.Ctrls">
  <Page.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
         <ResourceDictionary Source="ms-appx:///SomeDir/MyCtrlStyles.xaml" />
         <ResourceDictionary Source="ms-appx:///SomeDir/MainPageStyles.xaml" />
      </ResourceDictionary.MergedDictionaries>
  </Page.Resources>
  …
  <ext: MyCtrl x:Id="myCtrlA" />
  …
</Page>
</code>```

(Project A) MainPageStyles.xaml

```<code><ResourceDictionary>
  <Style x:Key="StyleAAA" />
</ResourceDictionary>
</code>```

(Project A) MainPageStyles.xaml

```<code><ResourceDictionary>
  <Style x:Key="StyleBBB" BasedOn="{StaticResource BodyTextBlockStyle}" TargetType="TextBlock">
    <Setter Property="Margin" Value="24 13 12 0" />
  </Style>
</ResourceDictionary>
</code>```

(Project B) MyCtrl.xaml

```<code><UserControl>
  <TextBlock x:Name="txtA" Style="{StaticResource StyleBBB}" Text="Text A" />
</ UserControl>
</code>```

答:
```<code><ext: MyCtrl x:Id="myCtrlA" />
</code>```

is just an instance of your custom control, in a different project with no knowledge of the styles you are trying to use.

Since the xaml for your custom control must be loaded before it can be instantiated, it will try to find the resource StyleBBB at that time. The resource cannot be found because the resource is not in any dictionary available to it, or the app.xaml merged dictionaries.

Some options, in the order I would recommend trying them.

Option 1

You should try using DynamicResource.

This will allow the binding to revevaluate when the control is placed into the page, so it can properly look it up at runtime.

DynamicResource is moderately more performance demanding, so if this is a control you plan on creating thousands of instances of all the time, this could be too much of a tradeoff.

Option 2

Place the merged dictionaries into your app.xaml file.

This application wide resource dictionary can be considered a fallback lookup when a resource cannot be found elsewhere.

The downside is that it's available to everything in your application, and it only works for one resource of any given key, so you can't just override it in a sub-control like you normally can.

Option 3

Add a reference to Project A into Project B. Merge the dictionary you need into the resources of your control.

This adds a dependency you didn't have before, and it's circular, so try not to do this.

Body:
PROBLEM

I would like to style control that is defined in Project B, but used on page in Project A using styles from Project A. I decided to do it by defining Merged Dictionary with styles dictionary that contains keys used in MyCtrl.xaml.

I thought that MyCtrl that is used in MainPage will go up the XAML tree to find the right style if it didn't find it in own xaml (broader scope), but I get exceptions that name/key was not found. Am I doing something wrong, or this idea is incorrect and I should find another solution?

Here is the structure:

I have a 2 projects:

Project A - main application with MainPage page and all styles/resources.

Project B - contains user controls

Project A references Project B.

(Project A) MainPage.xaml

<Page
   xmlns:ext="using:ProjB.Ctrls">
  <Page.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
         <ResourceDictionary Source="ms-appx:///SomeDir/MyCtrlStyles.xaml" />
         <ResourceDictionary Source="ms-appx:///SomeDir/MainPageStyles.xaml" />
      </ResourceDictionary.MergedDictionaries>
  </Page.Resources>
  …
  <ext: MyCtrl x:Id="myCtrlA" />
  …
</Page>

(Project A) MainPageStyles.xaml

<ResourceDictionary>

</ResourceDictionary>

(Project B) MyCtrl.xaml

<UserControl>
  <TextBlock x:Name="txtA" Style="{StaticResource StyleBBB}" Text="Text A" />
</ UserControl>

Body:
<ext: MyCtrl x:Id="myCtrlA" />

is just an instance of your custom control, in a different project with no knowledge of the styles you are trying to use.

Since the xaml for your custom control must be loaded before it can be instantiated, it will try to find the resource StyleBBB at that time. The resource cannot be found because the resource is not in any dictionary available to it, or the app.xaml merged dictionaries.

Some options, in the order I would recommend trying them.

Option 1

You should try using DynamicResource.

This will allow the binding to revevaluate when the control is placed into the page, so it can properly look it up at runtime.

DynamicResource is moderately more performance demanding, so if this is a control you plan on creating thousands of instances of all the time, this could be too much of a tradeoff.

Option 2

Place the merged dictionaries into your app.xaml file.

This application wide resource dictionary can be considered a fallback lookup when a resource cannot be found elsewhere.

The downside is that it's available to everything in your application, and it only works for one resource of any given key, so you can't just override it in a sub-control like you normally can.

Option 3

Add a reference to Project A into Project B. Merge the dictionary you need into the resources of your control.

This adds a dependency you didn't have before, and it's circular, so try not to do this.


问:
setting default tab in tabBarController
I have tried this:

```<code>class MainVC: UITabBarController {

    override func viewDidAppear(_ animated: Bool) {

       self.selectedIndex = 3

    }

}
</code>```

But all it does it takes me to a blank view.  The tab bar is highlighted at the bottom.

I am trying to set the default tab when the app starts.

答:
From the Apple documentation here:

https://developer.apple.com/documentation/uikit/uitabbarcontroller

The order in which you specify the view controllers determines the order in which they appear in the tab bar. When setting this property, you should also assign a value to the selectedViewController property to indicate which view controller is selected initially.

Title: setting default tab in tabBarController

Body:
I have tried this:

class MainVC: UITabBarController {

    override func viewDidAppear(_ animated: Bool) {

       self.selectedIndex = 3

    }

}

But all it does it takes me to a blank view.  The tab bar is highlighted at the bottom.

I am trying to set the default tab when the app starts.


问:
Html textbox without model in Yii2
I just moved to Yii2. How to make text box like this:

```<code><?= $form->field($model, 'xxx') ?>
</code>```

but without using any model?

答:
I would add a label and the form-control Bootstrap class:

```<code><?= Html::label('Person', 'xxx') ?>
<?= Html::textInput('xxx', value, ['class' => 'form-control']) ?>
</code>```

Title: Html textbox without model in Yii2

Body:
I just moved to Yii2. How to make text box like this:

<?= $form->field($model, 'xxx') ?>

but without using any model?

Body:
I would add a label and the form-control Bootstrap class:

<?= Html::label('Person', 'xxx') ?>
<?= Html::textInput('xxx', value, ['class' => 'form-control']) ?>


问:
In javascript, when to use object literal and when to use array?
Here's a sample. My concern is both seem to do the job. which of them to prefer?

```<code>var fooArr = [{ "bar": {"blah": 9 } }];

for(var i in fooArr) {
    var value = fooArr[i].bar.blah;
console.log(value); //checking in firebug console
}

var fooObj = { "bar": {"blah": 9 } };
for(var i in fooObj) {
    var value = fooObj[i].blah;
console.log(value); //checking in firebug console
}
</code>```

Also, the following seems to be not valid, Any way of avoiding array notation.

```<code>var fooObj1 = {
    { "bar": { "blah": 9 } },
    { "bar": { "blah": 4 } },
    { "bar": { "blah":12} }
};
</code>```

So I had to modify the above code to something like below which works. Is it too too bad to be too much sticky with Object literals

```<code>var fooObj1 = {
    1:{ "bar": { "blah": 9 } },
    2:{ "bar": { "blah": 4 } },
    3:{ "bar": { "blah":12} }
};
</code>```

Thanks again and in advance to those who help me with the query.

答:
Use an array when you know you'll have more than one objects. A one item array isn't needed when only one object will be used.

As you can see, the syntax is also a bit more complex (you have [...] and bar when using arrays -> more characters are used), so don't use it if you don't need to.

ContentLicense: CC BY-SA 2.5

Body:
Here's a sample. My concern is both seem to do the job. which of them to prefer?

var fooArr = [{ "bar": {"blah": 9 } }];

for(var i in fooArr) {
    var value = fooArr[i].bar.blah;
console.log(value); //checking in firebug console
}

var fooObj = { "bar": {"blah": 9 } };
for(var i in fooObj) {
    var value = fooObj[i].blah;
console.log(value); //checking in firebug console
}

Also, the following seems to be not valid, Any way of avoiding array notation.

var fooObj1 = {
    { "bar": { "blah": 9 } },
    { "bar": { "blah": 4 } },
    { "bar": { "blah":12} }
};

So I had to modify the above code to something like below which works. Is it too too bad to be too much sticky with Object literals

var fooObj1 = {
    1:{ "bar": { "blah": 9 } },
    2:{ "bar": { "blah": 4 } },
    3:{ "bar": { "blah":12} }
};

Thanks again and in advance to those who help me with the query.


问:
Accessing the JavaScript Control for a Kendo UI MVC RadioButtonFor Helper
I am using KendoUI for MVC.  I created some RadioButtons using the RadioButtonFor helper.  All KendoUI have a javascript controller that manages client-side aspects for each control that you can access.

FOR EXAMPLE: MVC GRID HELPER

```<code>// MVC HELPER
@(Html.Kendo().Grid<SomeDataItem>().Name("SomeGrid") ...other stuff... )

// Grid
var control = $('#SomeGrid')).data('kendoGrid')

...now I can use "control" to set events or do othjer things for the Grid.
</code>```

I NEED TO:

I need to setup some events and other things for the RadioButton control client-side.

```<code>// MVC HELPER
@(Html.Kendo().RadioButtonFor(model => model.Entity.Meter.FlowTypeId)
              .Label("Initial")
              .Value(1))
@(Html.Kendo().RadioButtonFor(model => model.Entity.Meter.FlowTypeId)
              .Label("Reconnect/Resumed")
              .Value(2))
</code>```

QUESTION:

How do I access the "Kendo UI Control" for these radio buttons?

Normal means do not work:  $('#Entity_Meter_FlowTypeId_1').data() //<-- empty

...this would usually give you a list of DATA contents.

答:
Kendo does not have a client-side API for radio buttons.

This is because it is just a radio button with a label, so there are no custom events you can bind to, outside of the vanilla javascript ones. You can bind to these using javascript/jquery, so there is no real point adding these same events to a kendo object.

Setting properties is also limited (text/checked/?), and these can again be easily handled with vanilla JS.

The only other thing you can do is style the radio button, which is described on the Telerik site.

Body:
I am using KendoUI for MVC.  I created some RadioButtons using the RadioButtonFor helper.  All KendoUI have a javascript controller that manages client-side aspects for each control that you can access.

FOR EXAMPLE: MVC GRID HELPER

// MVC HELPER
@(Html.Kendo().Grid<SomeDataItem>().Name("SomeGrid") ...other stuff... )

// Grid
var control = $('#SomeGrid')).data('kendoGrid')

...now I can use "control" to set events or do othjer things for the Grid.

I NEED TO:

I need to setup some events and other things for the RadioButton control client-side.

// MVC HELPER
@(Html.Kendo().RadioButtonFor(model => model.Entity.Meter.FlowTypeId)
              .Label("Initial")
              .Value(1))
@(Html.Kendo().RadioButtonFor(model => model.Entity.Meter.FlowTypeId)
              .Label("Reconnect/Resumed")
              .Value(2))

QUESTION:

How do I access the "Kendo UI Control" for these radio buttons?

Normal means do not work:  $('#Entity_Meter_FlowTypeId_1').data() //<-- empty

...this would usually give you a list of DATA contents.


问:
TSQL Conditional Where or Group By?
I have a table like the following:

```<code>id | type        | duedate
-------------------------
 1 | original    | 01/01/2017
 1 | revised     | 02/01/2017
 2 | original    | 03/01/2017
 3 | original    | 10/01/2017
 3 | revised     | 09/01/2017
</code>```

Where there may be either one or two rows for each id.  If there are two rows with same id, there would be one with type='original' and one with type='revised'.  If there is one row for the id, type will always be 'original'.

What I want as a result are all the rows where type='revised', but if there is only one row for a particular id (thus type='original') then I want to include that row too.  So desired output for the above would be:

```<code>id | type        | duedate
 1 | revised     | 02/01/2017
 2 | original    | 03/01/2017
 3 | revised     | 09/01/2017
</code>```

I do not know how to construct a WHERE clause that conditionally checks whether there are 1 or 2 rows for a given id, nor am I sure how to use GROUP BY because the revised date could be greater than or less than than the original date so use of aggregate functions MAX or MIN don't work.  I thought about using CASE somehow, but also do not know how to construct a conditional that chooses between two different rows of data (if there are two rows) and display one of them rather than the other.

Any suggested approaches would be appreciated.

Thanks!

答:
Is something like this sufficient?</p>

```<code>SELECT *
FROM mytable m1
WHERE type='revised'
 or 1=(SELECT COUNT(*) FROM mytable m2 WHERE m2.id=m1.id)
</code>```

Title: TSQL Conditional Where or Group By?

Body:
I have a table like the following:

id | type        | duedate
-------------------------
 1 | original    | 01/01/2017
 1 | revised     | 02/01/2017
 2 | original    | 03/01/2017
 3 | original    | 10/01/2017
 3 | revised     | 09/01/2017

Where there may be either one or two rows for each id.  If there are two rows with same id, there would be one with type='original' and one with type='revised'.  If there is one row for the id, type will always be 'original'.

What I want as a result are all the rows where type='revised', but if there is only one row for a particular id (thus type='original') then I want to include that row too.  So desired output for the above would be:

id | type        | duedate
 1 | revised     | 02/01/2017
 2 | original    | 03/01/2017
 3 | revised     | 09/01/2017

I do not know how to construct a WHERE clause that conditionally checks whether there are 1 or 2 rows for a given id, nor am I sure how to use GROUP BY because the revised date could be greater than or less than than the original date so use of aggregate functions MAX or MIN don't work.  I thought about using CASE somehow, but also do not know how to construct a conditional that chooses between two different rows of data (if there are two rows) and display one of them rather than the other.

Any suggested approaches would be appreciated.

Thanks!

Body:
Is something like this sufficient?

SELECT *
FROM mytable m1
WHERE type='revised'
 or 1=(SELECT COUNT(*) FROM mytable m2 WHERE m2.id=m1.id)


答:
you can use row number for this.</p>

```<code>WITH T AS
(
SELECT *,
       ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Type DESC) AS RN
FROM YourTable
)
SELECT *
FROM T
WHERE RN = 1
</code>```

Title: TSQL Conditional Where or Group By?

Body:
you can use row number for this.

WITH T AS
(
SELECT *,
       ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Type DESC) AS RN
FROM YourTable
)
SELECT *
FROM T
WHERE RN = 1


问:
After updating to Fedora 27, Files application looks horrible. Details in the description below
I have just updated my system to Fedora 27 from Fedora 26. After updating I noticed that the Files application is not showing the folders or files properly. Here is a screenshot,
https://imgur.com/a/THKYY

This was not happening in Fedora 26.

Does any one know how to fix it?

答:
Pango package issue. See here-
https://forums.fedoraforum.org/showthread.php?316160-Issue-with-viewing-icons-in-thunar

Bug has been filed.


问:
Coq HoTT - How to correctly put a definition inside a theorem?
I have completed a proof in coq (shown below) for Theorem 2.8.1 from HoTT's book. It works, however I get this warning

```<code>Toplevel input, characters 0-4:
<warning>
Warning: Nested proofs are deprecated and will stop working in a future Coq
version [deprecated-nested-proofs,deprecated]</warning>
</code>```

I know it's because of the definitions inside the theorem because when I put them out, the warning disappeared. But the only definition I want to be global is J.

How can I remove the warnings while keeping the definitions inside the theorem?

```<code>Require Export HoTT.

Definition J (A:Type) (P : forall (x y:A), x = y -> Type)
           (h : forall x:A, P x x idpath) :
  forall (x y:A) (p:x=y), P x y p
  :=
    fun x y p => match p with idpath => h x end.

Theorem th_2_8_1 :
  forall (x y:Unit), Unit <~> x=y.
Proof.

  Definition g (x y:Unit)(p:x=y) : Unit :=
    match p with idpath => tt end.

  Definition f (x y:Unit)(s:Unit) : x=y :=
    match x,y,s with tt,tt,tt => idpath end.

  Definition alpha1 (x y:Unit)(s:Unit) : ((g x y) o (f x y))s = s
    :=
      match x,y,s with tt,tt,tt => idpath end.

  Definition P (f : forall (x y:Unit)(s:Unit), x=y)
               (g : forall (x y:Unit)(p:x=y), Unit)
               (x y:Unit) (p:x=y) : Type
    :=
      ((f x y) o (g x y)) p = p.

  Definition h (x:Unit) : P f g x x idpath
    :=
      match x with tt => idpath idpath end.

  Definition alpha2 (x y:Unit)(p:x=y): ((f x y) o (g x y)) p = p :=
    (J Unit (P f g) h) x y p.

  intros x y.
  exists (f x y).
  apply(BuildIsEquiv Unit (x=y) (f x y) (g x y) (alpha2 x y) (alpha1 x y)).

  induction x0.
  rewrite <- (f x y).
  induction x.
  simpl.
  apply(idpath idpath).
  apply(tt).
Defined
</code>```

答:
Using pose for defining the terms should work: (although there may be another way)

```<code>Require Export HoTT.

Theorem th_2_8_1 :
  forall (x y:Unit), Unit <~> x=y.
Proof.

  pose(g:=fun (x y:Unit)(p:x=y) => match p with idpath => tt end).

  pose(f := fun (x y:Unit)(s:Unit) =>
              match x,y,s return (x=y) with tt,tt,tt => idpath end).

  pose( alpha1 := fun (x y:Unit)(s:Unit) =>
      match x,y,s return ((g x y) o (f x y))s = s
      with tt,tt,tt => idpath end).

  pose(P := fun
             (f : forall (x y:Unit)(s:Unit), x=y)
             (g : forall (x y:Unit)(p:x=y), Unit)
             (x y:Unit)
             (p:x=y)
    =>
      ((f x y) o (g x y)) p = p).

  pose(h := fun (x:Unit) =>
       match x return P f g x x idpath
       with tt => idpath idpath end).

  pose(alpha2 := fun (x y:Unit)(p:x=y) => (J Unit (P f g) h) x y p).

  intros x y.
  exists (f x y).
  apply(BuildIsEquiv Unit (x=y) (f x y) (g x y) (alpha2 x y) (alpha1 x y)).

  induction x0.
  rewrite <- (f x y).
  induction x.
  simpl.
  apply(idpath idpath).
  apply(tt).
Defined.
</code>```

Body:
I have completed a proof in coq (shown below) for Theorem 2.8.1 from HoTT's book. It works, however I get this warning

Toplevel input, characters 0-4:
<warning>
Warning: Nested proofs are deprecated and will stop working in a future Coq
version [deprecated-nested-proofs,deprecated]</warning>

I know it's because of the definitions inside the theorem because when I put them out, the warning disappeared. But the only definition I want to be global is J.

How can I remove the warnings while keeping the definitions inside the theorem?

Require Export HoTT.

Definition J (A:Type) (P : forall (x y:A), x = y -> Type)
           (h : forall x:A, P x x idpath) :
  forall (x y:A) (p:x=y), P x y p
  :=
    fun x y p => match p with idpath => h x end.

Theorem th_2_8_1 :
  forall (x y:Unit), Unit <~> x=y.
Proof.

  Definition g (x y:Unit)(p:x=y) : Unit :=
    match p with idpath => tt end.

  Definition f (x y:Unit)(s:Unit) : x=y :=
    match x,y,s with tt,tt,tt => idpath end.

  Definition alpha1 (x y:Unit)(s:Unit) : ((g x y) o (f x y))s = s
    :=
      match x,y,s with tt,tt,tt => idpath end.

  Definition P (f : forall (x y:Unit)(s:Unit), x=y)
               (g : forall (x y:Unit)(p:x=y), Unit)
               (x y:Unit) (p:x=y) : Type
    :=
      ((f x y) o (g x y)) p = p.

  Definition h (x:Unit) : P f g x x idpath
    :=
      match x with tt => idpath idpath end.

  Definition alpha2 (x y:Unit)(p:x=y): ((f x y) o (g x y)) p = p :=
    (J Unit (P f g) h) x y p.

  intros x y.
  exists (f x y).
  apply(BuildIsEquiv Unit (x=y) (f x y) (g x y) (alpha2 x y) (alpha1 x y)).

  induction x0.
  rewrite <- (f x y).
  induction x.
  simpl.
  apply(idpath idpath).
  apply(tt).
Defined

Body:
Using pose for defining the terms should work: (although there may be another way)

Require Export HoTT.

Theorem th_2_8_1 :
  forall (x y:Unit), Unit <~> x=y.
Proof.

  pose(g:=fun (x y:Unit)(p:x=y) => match p with idpath => tt end).

  pose(f := fun (x y:Unit)(s:Unit) =>
              match x,y,s return (x=y) with tt,tt,tt => idpath end).

  pose( alpha1 := fun (x y:Unit)(s:Unit) =>
      match x,y,s return ((g x y) o (f x y))s = s
      with tt,tt,tt => idpath end).

  pose(P := fun
             (f : forall (x y:Unit)(s:Unit), x=y)
             (g : forall (x y:Unit)(p:x=y), Unit)
             (x y:Unit)
             (p:x=y)
    =>
      ((f x y) o (g x y)) p = p).

  pose(h := fun (x:Unit) =>
       match x return P f g x x idpath
       with tt => idpath idpath end).

  pose(alpha2 := fun (x y:Unit)(p:x=y) => (J Unit (P f g) h) x y p).

  intros x y.
  exists (f x y).
  apply(BuildIsEquiv Unit (x=y) (f x y) (g x y) (alpha2 x y) (alpha1 x y)).

  induction x0.
  rewrite <- (f x y).
  induction x.
  simpl.
  apply(idpath idpath).
  apply(tt).
Defined.


问:
Iterate with files in Openvms DCL
I have this file input.text with say 20 lines. (Although I would like to be able to use any number of lines)

So I want to open the said file and use each string as though it was a parameter for another command.

This other command would take each parameter perform it's function and then write the output to another file itself.

How can I accomplish the intended?

答:
Here is an example DCL command file that reads INPUT.TXT and uses the lines found as parameters to a DIR command that outputs to a file called DIROUT.TXT:

```<code>$! Read file using results as DIR command parameters...
$ file1="INPUT.TXT"
$ file2="DIROUT.TXT"
$ open/read chnl1 'file1'
$ on control_y then goto done_loop
$ on error then goto done_loop
$read_loop:
$ read/end_of_file=done_loop chnl1 opt1
$ write sys$output ">>> Sending DIR ",opt1," output to ''file2'..."
$ dir/out='file2' 'opt1'
$ goto read_loop
$done_loop:
$ close chnl1
$ write sys$output "Finished..."
$ EXIT
</code>```

You should be able to adapt this to your requirements.

Title: Iterate with files in Openvms DCL

Body:
Here is an example DCL command file that reads INPUT.TXT and uses the lines found as parameters to a DIR command that outputs to a file called DIROUT.TXT:

$! Read file using results as DIR command parameters...
$ file1="INPUT.TXT"
$ file2="DIROUT.TXT"
$ open/read chnl1 'file1'
$ on control_y then goto done_loop
$ on error then goto done_loop
$read_loop:
$ read/end_of_file=done_loop chnl1 opt1
$ write sys$output ">>> Sending DIR ",opt1," output to ''file2'..."
$ dir/out='file2' 'opt1'
$ goto read_loop
$done_loop:
$ close chnl1
$ write sys$output "Finished..."
$ EXIT

You should be able to adapt this to your requirements.


问:
dompdf form submit didn't send data codeigniter
i am trying to create an PDF using Dompdf, in my program i have model query with a dynamic parameter based on the input in the form, but when i click on my button to send the value from the select button to the controller, the data not been send properly, any idea why? below are my code

```<code><form class="form" method="get" action="<?=site_url()?>/laporan/pdfdownload" id="myID" name="myName">
    <select id="sel1" class="form-control">
         <option disabled selected="selected">Pilih</option>
                  <?php foreach ($kerja as $rows){?>
                  <option value="<?php echo $rows->id_project?>"><?php echo $rows->id_project.' - '.$rows->nama_project ?></option>
                  <?php }?>
    </select>
    <select id="sel2" class="form-control">
         <option disabled selected="selected">Pilih</option>
                  <?php foreach ($item as $rows){?>
                  <option value="<?php echo $rows->id_project?>"><?php echo $rows->id_project.' - '.$rows->nama_project ?></option>
                  <?php }?>
    </select>
   <button id="filter_button" style="margin-top: 26px;margin-left: 28px;width: auto" name="filter_button" type="submit" class="form btn btn-danger"><i class="fa fa-search"></i>&nbspSearch</button>
</form>
</code>```

and here is my controller

```<code>public function pdfdownload(){
                                      //If i click submit then all of the post didnt get sended
    $one = $this->input->post('sel1');//no value at all, anyone know why?
    $two = $this->input->post('sel2');//no value at all, anyone know why?

    $data['real'] = $this->report_m($one,$two)->row();

    htmlcontent = $this->load->view('laporan/download/laporan3.php',$data,true);
    include(APPPATH."third_party/dompdf/autoload.inc.php");
    // require_once APPPATH . 'third_party/dompdf/autoload.inc.php';
    $dompdf = new Dompdf\Dompdf();
    $dompdf->load_html($htmlcontent);
    $dompdf->set_paper("f4");
    $dompdf->render();
    $dompdf->stream("cobadlu.pdf",array("Attachment" => false));
    exit(0);
}

enter code here
</code>```

答:
In your HTML form, you need to use name attribute, and not only ID :</p>

```<code><select id="sel2" name="sel2" class="form-control">
</code>```

Body:
i am trying to create an PDF using Dompdf, in my program i have model query with a dynamic parameter based on the input in the form, but when i click on my button to send the value from the select button to the controller, the data not been send properly, any idea why? below are my code

<form class="form" method="get" action="<?=site_url()?>/laporan/pdfdownload" id="myID" name="myName">
    <select id="sel1" class="form-control">
         <option disabled selected="selected">Pilih</option>
                  <?php foreach ($kerja as $rows){?>
                  <option value="<?php echo $rows->id_project?>"><?php echo $rows->id_project.' - '.$rows->nama_project ?></option>
                  <?php }?>
    </select>
    <select id="sel2" class="form-control">
         <option disabled selected="selected">Pilih</option>
                  <?php foreach ($item as $rows){?>
                  <option value="<?php echo $rows->id_project?>"><?php echo $rows->id_project.' - '.$rows->nama_project ?></option>
                  <?php }?>
    </select>
   <button id="filter_button" style="margin-top: 26px;margin-left: 28px;width: auto" name="filter_button" type="submit" class="form btn btn-danger">&nbspSearch</button>
</form>

and here is my controller

public function pdfdownload(){
                                      //If i click submit then all of the post didnt get sended
    $one = $this->input->post('sel1');//no value at all, anyone know why?
    $two = $this->input->post('sel2');//no value at all, anyone know why?

    $data['real'] = $this->report_m($one,$two)->row();

    htmlcontent = $this->load->view('laporan/download/laporan3.php',$data,true);
    include(APPPATH."third_party/dompdf/autoload.inc.php");
    // require_once APPPATH . 'third_party/dompdf/autoload.inc.php';
    $dompdf = new Dompdf\Dompdf();
    $dompdf->load_html($htmlcontent);
    $dompdf->set_paper("f4");
    $dompdf->render();
    $dompdf->stream("cobadlu.pdf",array("Attachment" => false));
    exit(0);
}

enter code here

Body:
In your HTML form, you need to use name attribute, and not only ID :

<select id="sel2" name="sel2" class="form-control">


问:
Redis: Database Size to Memory Ratio?
What is Redis's database size to memory ratio?

For instance, if I have an 80MB database, how much RAM will Redis use (when used with a normal web app)?

答:
Redis will use a bit more RAM than disk. The dumpfile format is probably a bit more densely packed. This is some numbers from a real production system (a 64 bit EC2 large instance running Redis 2.0.4 on Ubuntu 10.04):

```<code>$ redis-cli info | grep used_memory_human
used_memory_human:1.36G

$ du -sh /mnt/data/redis/dump.rdb
950M /mnt/data/redis/dump.rdb
</code>```

As you can see, the dumpfile is a few hundred megs smaller than the memory usage.

In the end it depends on what you store in the database. I have mainly hashes in mine, with only a few (perhaps less than 1%) sets. None of the keys contain very large objects, the average object size is 889 bytes.

Title: Redis: Database Size to Memory Ratio?

Body:
Redis will use a bit more RAM than disk. The dumpfile format is probably a bit more densely packed. This is some numbers from a real production system (a 64 bit EC2 large instance running Redis 2.0.4 on Ubuntu 10.04):

$ redis-cli info | grep used_memory_human
used_memory_human:1.36G

$ du -sh /mnt/data/redis/dump.rdb
950M /mnt/data/redis/dump.rdb

As you can see, the dumpfile is a few hundred megs smaller than the memory usage.

In the end it depends on what you store in the database. I have mainly hashes in mine, with only a few (perhaps less than 1%) sets. None of the keys contain very large objects, the average object size is 889 bytes.


问:
How to get date of all updates to particular table in oracle?
Is there a way to get all modification dates of a particular table in Oracle?

Query below:

```<code>select * from sys.dba_tab_modifications
</code>```

could include number of inserts and updates however not particular dates of each.

答:
You may be able to use Oracle Flashback Query if you have sufficient privs, and sufficient redo logs exist for the time period in question:</p>

```<code>select versions_operation
     , versions_starttime
     , versions_endtime
     , <TableAlias>.*
from <TableName> versions between timestamp systimestamp - numtodsinterval(1,'day')
                                        and systimestamp <TableAlias>
</code>```

Body:
Is there a way to get all modification dates of a particular table in Oracle?

Query below:

select * from sys.dba_tab_modifications

could include number of inserts and updates however not particular dates of each.

Body:
You may be able to use Oracle Flashback Query if you have sufficient privs, and sufficient redo logs exist for the time period in question:

select versions_operation
     , versions_starttime
     , versions_endtime
     , <TableAlias>.*
from <TableName> versions between timestamp systimestamp - numtodsinterval(1,'day')
                                        and systimestamp <TableAlias>


问:
Cron and Crouton (Chromebox)
I can't get cron jobs to run properly on my ASUS Chromebox, which is running Crouton. I have followed these instructions.

I've edited /etc/rc.local

I've added the cron job to /etc/crontab

When I run crontab -l as root, I see the cron job

The script works when I run it from the terminal

The cron job is this: 30 2 * * * /home/name/daily.py

答: Can't be certain with the info provided, but this could be as simple as the PATH not being set correctly for cron. Keep in mind, cron doesn't source dotfiles like .bashrc, so it won't have all the settings that your shell has. Just set the PATH in /etc/crontab before defining the individual cronjob.

Title: Cron and Crouton (Chromebox)


问:
Pandas store a nested object using mongodb
I want to store a dataframe in mongodb. I am able to do that normally, but I need to add another column with values to be stored as an object in mongodb as

```<code>Column C:
 1.   {
    "test1": "Unknown",
    "test2": "Unknown"
    }
 2.   {
    "test1": "Unknown",
    "test2": "Unknown"
    }
</code>```

I am trying to do this by:

```<code>df['C'] = {
    "test1": "Unknown",
    "test2": "Unknown"
    }
</code>```

This is giving me an error as

```<code>ValueError: Length of values does not match length of index
</code>```

I will be storing this in mongodb later using

```<code>records = json.loads(df.T.to_json()).values()

db.users.insert(records)
</code>```

Any ideas how to accomplish this?

答:
I assume your dataframe isn't one row long, so you can't assign a single value to df['C'].

You could make a list of the same length as the dataframe:

```<code>import pandas as pd
df = pd.DataFrame(data=list(range(5)), columns=["Sample"])
df['C'] = [{"test":"value"}]* df.shape[0]
df

    Sample  C
0   0   {'test': 'value'}
1   1   {'test': 'value'}
2   2   {'test': 'value'}
3   3   {'test': 'value'}
4   4   {'test': 'value'}
</code>```

or use apply to run some function which populates the column:

```<code>df['C'] = df['Sample'].apply(lambda x: {'test{}'.format(x):'Unknown'})
df

    Sample  C
0   0   {'test0': 'Unknown'}
1   1   {'test1': 'Unknown'}
2   2   {'test2': 'Unknown'}
3   3   {'test3': 'Unknown'}
4   4   {'test4': 'Unknown'}
</code>```

Using apply has the advantage of being able to easily drop existing data from the dataframe into the new column. For example here the number for test is being passed in from the "Sample" field.

Body:
I want to store a dataframe in mongodb. I am able to do that normally, but I need to add another column with values to be stored as an object in mongodb as

Column C:
 1.   {
    "test1": "Unknown",
    "test2": "Unknown"
    }
 2.   {
    "test1": "Unknown",
    "test2": "Unknown"
    }

I am trying to do this by:

df['C'] = {
    "test1": "Unknown",
    "test2": "Unknown"
    }

This is giving me an error as

ValueError: Length of values does not match length of index

I will be storing this in mongodb later using

records = json.loads(df.T.to_json()).values()

db.users.insert(records)

Any ideas how to accomplish this?

Body:
I assume your dataframe isn't one row long, so you can't assign a single value to df['C'].

You could make a list of the same length as the dataframe:

import pandas as pd
df = pd.DataFrame(data=list(range(5)), columns=["Sample"])
df['C'] = [{"test":"value"}]* df.shape[0]
df

    Sample  C
0   0   {'test': 'value'}
1   1   {'test': 'value'}
2   2   {'test': 'value'}
3   3   {'test': 'value'}
4   4   {'test': 'value'}

or use apply to run some function which populates the column:

df['C'] = df['Sample'].apply(lambda x: {'test{}'.format(x):'Unknown'})
df

    Sample  C
0   0   {'test0': 'Unknown'}
1   1   {'test1': 'Unknown'}
2   2   {'test2': 'Unknown'}
3   3   {'test3': 'Unknown'}
4   4   {'test4': 'Unknown'}

Using apply has the advantage of being able to easily drop existing data from the dataframe into the new column. For example here the number for test is being passed in from the "Sample" field.


问:
Android elements overlapping when dynamically inserting fragment
My project consists of a main activity which loads different fragments into view when tabs are pressed on the bottom navigation bar. Blue depicts the activity controls, orange what should be included from one of the fragments. In this case, it is a MapBox MapView with FABs in the corners.

My problem is that I can't seem to get the fragment container height correct; either the top or bottom button (sometimes both) is always cut off vertically underneath the status bar or bottom navigation bar.

My current layout (irrelevant attributes removed for brevity):

activity_main.xml:

```<code><ConstraintLayout
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/nav_bottom">
        <FrameLayout
            android:id="@+id/fragment_container"
            android:layout_height="wrap_content">
        </FrameLayout>
    </RelativeLayout>

    <BottomNavigationView
        android:id="@+id/nav_bottom"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:menu="@menu/nav_bottom">
    </BottomNavigationView>

</ConstraintLayout>
</code>```

fragment_map.xml:

```<code><ConstraintLayout
    android:layout_height="wrap_content">

    <MapView
        android:id="@+id/map_view"
        android:layout_height="match_parent"
        mapbox:layout_constraintTop_toTopOf="parent"
        mapbox:layout_constraintBottom_toBottomOf="parent">
    </MapView>

    <FloatingActionButton
        android:id="@+id/button_top"
        android:layout_height="wrap_content"
        mapbox:layout_constraintTop_toTopOf="@id/map_view"
        mapbox:layout_constraintRight_toRightOf="@id/map_view" />

    <FloatingActionButton
        android:id="@+id/button_bottom"
        android:layout_height="wrap_content"
        mapbox:layout_constraintBottom_toBottomOf="@id/map_view"
        mapbox:layout_constraintRight_toRightOf="@id/map_view" />

</ConstraintLayout>
</code>```

I am adding the fragment to the activity like this:

```<code>getSupportFragmentManager()
        .beginTransaction()
        .replace(R.id.fragment_container, fragment, "myFrag")
        .commit();
</code>```

答:
Change your layout style activity_main.xml:

```<code><LinearLayout
    android:layout_height="match_parent"
    orientation = vertical>

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_height="0dp"
        weight = "1">

    </FrameLayout>

    <BottomNavigationView
        android:id="@+id/nav_bottom"
        android:layout_height="wrap_content"
        app:menu="@menu/nav_bottom">

    </BottomNavigationView>

</LinearLayout>
</code>```

and your fragment_map.xml:

```<code><RelaytiveLayout
    android:layout_height="match_parent">

    <MapView
        android:id="@+id/map_view"
        android:layout_height="match_parent">

    </MapView>

    <FloatingActionButton
        android:id="@+id/button_top"
        android:layout_height="wrap_content"
        alignParentRight = true />

    <FloatingActionButton
        android:id="@+id/button_bottom"
        android:layout_height="wrap_content"
        alignParentRight = true
        alignParentBottom = true />

</RelaytiveLayout>
</code>```

edited your fragment_map.xml see the changes

Body:
My project consists of a main activity which loads different fragments into view when tabs are pressed on the bottom navigation bar. Blue depicts the activity controls, orange what should be included from one of the fragments. In this case, it is a MapBox MapView with FABs in the corners.

My problem is that I can't seem to get the fragment container height correct; either the top or bottom button (sometimes both) is always cut off vertically underneath the status bar or bottom navigation bar.

My current layout (irrelevant attributes removed for brevity):

activity_main.xml:

<ConstraintLayout
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/nav_bottom">
        <FrameLayout
            android:id="@+id/fragment_container"
            android:layout_height="wrap_content">
        </FrameLayout>
    </RelativeLayout>

    <BottomNavigationView
        android:id="@+id/nav_bottom"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:menu="@menu/nav_bottom">
    </BottomNavigationView>

</ConstraintLayout>

fragment_map.xml:

<ConstraintLayout
    android:layout_height="wrap_content">

    <MapView
        android:id="@+id/map_view"
        android:layout_height="match_parent"
        mapbox:layout_constraintTop_toTopOf="parent"
        mapbox:layout_constraintBottom_toBottomOf="parent">
    </MapView>

    <FloatingActionButton
        android:id="@+id/button_top"
        android:layout_height="wrap_content"
        mapbox:layout_constraintTop_toTopOf="@id/map_view"
        mapbox:layout_constraintRight_toRightOf="@id/map_view" />

    <FloatingActionButton
        android:id="@+id/button_bottom"
        android:layout_height="wrap_content"
        mapbox:layout_constraintBottom_toBottomOf="@id/map_view"
        mapbox:layout_constraintRight_toRightOf="@id/map_view" />

</ConstraintLayout>

I am adding the fragment to the activity like this:

getSupportFragmentManager()
        .beginTransaction()
        .replace(R.id.fragment_container, fragment, "myFrag")
        .commit();

Body:
Change your layout style activity_main.xml:

<LinearLayout
    android:layout_height="match_parent"
    orientation = vertical>

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_height="0dp"
        weight = "1">

    </FrameLayout>

    <BottomNavigationView
        android:id="@+id/nav_bottom"
        android:layout_height="wrap_content"
        app:menu="@menu/nav_bottom">

    </BottomNavigationView>

</LinearLayout>

and your fragment_map.xml:

<RelaytiveLayout
    android:layout_height="match_parent">

    <MapView
        android:id="@+id/map_view"
        android:layout_height="match_parent">

    </MapView>

    <FloatingActionButton
        android:id="@+id/button_top"
        android:layout_height="wrap_content"
        alignParentRight = true />

    <FloatingActionButton
        android:id="@+id/button_bottom"
        android:layout_height="wrap_content"
        alignParentRight = true
        alignParentBottom = true />

</RelaytiveLayout>

edited your fragment_map.xml see the changes


问:
Reveal background image from the center
I'm working on rounded avatar with hover effects, by default there is a semi-transparent overlay on top of the background image, and it reveals the image on hover.

The question is, would it be possible to have the overlay to disappear from the center of the box on hover? Right now it's the opposite.

jsFiddle

.avatar {
  position: relative;
  background: url("https://i.stack.imgur.com/zBjxW.jpg") center / cover no-repeat;
  border-radius: 50%;
  width: 200px;
  height: 200px;
}

.avatar:before {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border-radius: 50%;
  background-color: rgba(0, 0, 255, .5);
  transition: width .5s, height .5s;
}

.avatar:hover:before {
  width: 0;
  height: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="avatar"></div></code>```

答:
Yes, You could use an inset shadow for this kind of effect:

.avatar {
  position: relative;
  background: url("https://i.stack.imgur.com/zBjxW.jpg") center / cover no-repeat;
  border-radius: 50%;
  width: 200px;
  height: 200px;
  box-shadow:inset 0 0 0 105px rgba(0, 0, 255, .5);
  transition:0.25s
}

.avatar:hover {

  box-shadow:inset 0 0 0 0 rgba(0, 0, 255, .5);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="avatar"></div></code>```

Title: Reveal background image from the center

Body:
Yes, You could use an inset shadow for this kind of effect:

.avatar {
  position: relative;
  background: url("https://i.stack.imgur.com/zBjxW.jpg") center / cover no-repeat;
  border-radius: 50%;
  width: 200px;
  height: 200px;
  box-shadow:inset 0 0 0 105px rgba(0, 0, 255, .5);
  transition:0.25s
}

.avatar:hover {

  box-shadow:inset 0 0 0 0 rgba(0, 0, 255, .5);
}

<div class="avatar"></div>


问:
Ionic3 ion-img do not show images with ng-for
I am trying to show the dynamic images with loop using ion-img but it is not working.

```<code><ion-item no-lines no-padding *ngFor="let company of shortedDistanceArray">
    <div>
        <ion-img style="width: 15vh;height: 12vh;" src={{company.images}}"></ion-img>
    </div>
</ion-item>
</code>```

答:
Here you need to use property binding as shown below. Always try to avoid string interpolation.

```<code><ion-item no-lines no-padding *ngFor="let company of shortedDistanceArray">
    <div>
        <img style="width: 15vh;height: 12vh;" [src]="company.images"></img>
    </div>
</ion-item>
</code>```

Body:
I am trying to show the dynamic images with loop using ion-img but it is not working.

<ion-item no-lines no-padding *ngFor="let company of shortedDistanceArray">

        <ion-img style="width: 15vh;height: 12vh;" src={{company.images}}"></ion-img>

</ion-item>

Body:
Here you need to use property binding as shown below. Always try to avoid string interpolation.

<ion-item no-lines no-padding *ngFor="let company of shortedDistanceArray">
    <div>
        <img style="width: 15vh;height: 12vh;" [src]="company.images"></img>
    </div>
</ion-item>


问:
Saving PreviewImage has a green tint - Android
There's a green tint after saving the image.  The preview image on the surface holder look normal.  What can I do to remove this?</p>

```<code>mCamera.setPreviewCallback(new Camera.PreviewCallback() {
    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {

        try {

            if (saveImg) {
                int width = parameters.getPreviewSize().width;
                int height = parameters.getPreviewSize().height;

                YuvImage yuv = new YuvImage(data, parameters.getPreviewFormat(), width, height, null);

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                yuv.compressToJpeg(new Rect(0, 0, width, height), 100, out);

                byte[] bytes = out.toByteArray();
                final Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                File file = new File(Environment.getExternalStorageDirectory() + "/newimage.png");
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
                byte[] blobArray = os.toByteArray();

                FileOutputStream fos = new FileOutputStream(file);
                fos.write(blobArray);
                fos.close();
</code>```

答:
I ended up setting this value for the white-balance to remove the green tint:</p>

```<code>parameters.set("whitebalance", WHITE_BALANCE_FLUORESCENT);
mCamera.setParameters(parameters);
</code>```

Body:
There's a green tint after saving the image.  The preview image on the surface holder look normal.  What can I do to remove this?

mCamera.setPreviewCallback(new Camera.PreviewCallback() {
    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {

        try {

            if (saveImg) {
                int width = parameters.getPreviewSize().width;
                int height = parameters.getPreviewSize().height;

                YuvImage yuv = new YuvImage(data, parameters.getPreviewFormat(), width, height, null);

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                yuv.compressToJpeg(new Rect(0, 0, width, height), 100, out);

                byte[] bytes = out.toByteArray();
                final Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                File file = new File(Environment.getExternalStorageDirectory() + "/newimage.png");
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
                byte[] blobArray = os.toByteArray();

                FileOutputStream fos = new FileOutputStream(file);
                fos.write(blobArray);
                fos.close();

Body:
I ended up setting this value for the white-balance to remove the green tint:

parameters.set("whitebalance", WHITE_BALANCE_FLUORESCENT);
mCamera.setParameters(parameters);


问:
What's wrong with this simple method to sample from multinomial in C#?
I wanted to implement a simple method to sample from a multinomial distribution in C# (the first argument is an array of integers we want to sample and the second one is the probabilities of selecting each of those integers).

When I do this with numpy in python, the results make sense.

```<code>np.random.choice(np.array([1,2,3,4,5,6]),p=np.array([.624,.23,.08,.04, .02, .006]),size=len(b))
</code>```

I get a lot of 1's (probability 62%), a bunch of 2's, some 3's etc.

However, when I try the implementation below in C# (pretty straightforward inverse transform sampling for multinomial, only relies on a uniform random variable), I get really weird results. For all 1000 samples, I'll often find all 1's. Sometimes, I'll find all 3's (!!??). The results never look like what you would expect (and what you get from the python function - try running it yourself a few times). This is really scary since we rely on these primitives. Does anyone have insight into what might be wrong with the C# version?

```<code>    static void Main(string[] args)
    {
        int[] iis = new int[7];
        int[] itms = new int[] { 1, 2, 3, 4, 5, 6 };
        double[] probs = new double[] { .624, .23, .08, .04, .02, .006 };
        for (int i = 0; i < 1000; i++)
        {
            iis[MultinomialSample(itms, probs)] += 1;
        }

        foreach (var ii in iis)
        {
            Console.Write(ii + ",");
        }

        Console.Read();
    }

     private static int MultinomialSample(int[] s, double[] ps)
    {
        double[] cumProbs = new double[ps.Length];
        cumProbs[0] = ps[0];

        for (int i = 1; i < ps.Length; i++)
        {
            cumProbs[i] = cumProbs[i - 1] + ps[i];
        }

        Random random = new Random();
        double u = random.NextDouble();

        for (int i = 0; i < cumProbs.Length - 1; i++)
        {
            if (u < cumProbs[i])
            {
                return s[i];
            }
        }

        return s[s.Length - 1];
    }
</code>```

答:
You're initializing Random each time you call MultinomialSample. If these calls are very close together, Random will be initialized with the same seed (based on the system clock). Try either making Random a private class field: private static Random random = new Random(); or pass it into the method as an argument from Main, where it would be initialized only once:

```<code>private static Random random = new Random();

private static int MultinomialSample(IReadOnlyList<int> sample,
    IReadOnlyList<double> probabilities)
{
    var cumProbs = new double[probabilities.Count];
    cumProbs[0] = probabilities[0];

    for (var i = 1; i < probabilities.Count; i++)
    {
        cumProbs[i] = cumProbs[i - 1] + probabilities[i];
    }

    for (var i = 0; i < cumProbs.Length - 1; i++)
    {
        if (random.NextDouble() < cumProbs[i])
        {
            return sample[i];
        }
    }

    return sample[sample.Count - 1];
}

private static void Main()
{
    var iis = new int[7];
    var items = new[] {1, 2, 3, 4, 5, 6};
    var probabilities = new[] {.624, .23, .08, .04, .02, .006};

    for (int i = 0; i < 1000; i++)
    {
        iis[MultinomialSample(items, probabilities)] ++;
    }

    Console.WriteLine(string.Join(", ", iis));

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}
</code>```

Body:
I wanted to implement a simple method to sample from a multinomial distribution in C# (the first argument is an array of integers we want to sample and the second one is the probabilities of selecting each of those integers).

When I do this with numpy in python, the results make sense.

np.random.choice(np.array([1,2,3,4,5,6]),p=np.array([.624,.23,.08,.04, .02, .006]),size=len(b))

I get a lot of 1's (probability 62%), a bunch of 2's, some 3's etc.

However, when I try the implementation below in C# (pretty straightforward inverse transform sampling for multinomial, only relies on a uniform random variable), I get really weird results. For all 1000 samples, I'll often find all 1's. Sometimes, I'll find all 3's (!!??). The results never look like what you would expect (and what you get from the python function - try running it yourself a few times). This is really scary since we rely on these primitives. Does anyone have insight into what might be wrong with the C# version?

    static void Main(string[] args)
    {
        int[] iis = new int[7];
        int[] itms = new int[] { 1, 2, 3, 4, 5, 6 };
        double[] probs = new double[] { .624, .23, .08, .04, .02, .006 };
        for (int i = 0; i < 1000; i++)
        {
            iis[MultinomialSample(itms, probs)] += 1;
        }

        foreach (var ii in iis)
        {
            Console.Write(ii + ",");
        }

        Console.Read();
    }

     private static int MultinomialSample(int[] s, double[] ps)
    {
        double[] cumProbs = new double[ps.Length];
        cumProbs[0] = ps[0];

        for (int i = 1; i < ps.Length; i++)
        {
            cumProbs[i] = cumProbs[i - 1] + ps[i];
        }

        Random random = new Random();
        double u = random.NextDouble();

        for (int i = 0; i < cumProbs.Length - 1; i++)
        {
            if (u < cumProbs[i])
            {
                return s[i];
            }
        }

        return s[s.Length - 1];
    }

Body:
You're initializing Random each time you call MultinomialSample. If these calls are very close together, Random will be initialized with the same seed (based on the system clock). Try either making Random a private class field: private static Random random = new Random(); or pass it into the method as an argument from Main, where it would be initialized only once:

private static Random random = new Random();

private static int MultinomialSample(IReadOnlyList<int> sample,
    IReadOnlyList<double> probabilities)
{
    var cumProbs = new double[probabilities.Count];
    cumProbs[0] = probabilities[0];

    for (var i = 1; i < probabilities.Count; i++)
    {
        cumProbs[i] = cumProbs[i - 1] + probabilities[i];
    }

    for (var i = 0; i < cumProbs.Length - 1; i++)
    {
        if (random.NextDouble() < cumProbs[i])
        {
            return sample[i];
        }
    }

    return sample[sample.Count - 1];
}

private static void Main()
{
    var iis = new int[7];
    var items = new[] {1, 2, 3, 4, 5, 6};
    var probabilities = new[] {.624, .23, .08, .04, .02, .006};

    for (int i = 0; i < 1000; i++)
    {
        iis[MultinomialSample(items, probabilities)] ++;
    }

    Console.WriteLine(string.Join(", ", iis));

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}


问:
azure mobile app authentication external redirect url
I have created Azure Mobile App and I am following official docs for this. During Authentication part of the docs following is stated

In the Allowed External Redirect URLs, enter url_scheme_of_your_app://easyauth.callback. The url_scheme_of_your_app in this string is the URL Scheme for your mobile application. It should follow normal URL specification for a protocol (use letters and numbers only, and start with a letter). You should make a note of the string that you choose as you will need to adjust your mobile application code with the URL Scheme in several places.

My Question is that they havent provided any valid example for redirect url so I pasted url_scheme_of_your_app://easyauth.callback in my redirect url in the portal and it gives error because it isnt a valid format, so can anyone please give me a valid example for this url?

Thanks in advance

答:
To anyone still struggling to figure out what exactly is the "MobileAppUrl", "url_scheme_of_your_app" and "redirectUriScheme" in Azure, here is an example: Assuming that your Azure Mobile App is called myapp, you will have the following:

Mobile App URL: https://myapp.azurewebsites.net

url_scheme_of_your_app: myapp

redirectUriScheme: myapp://easyauth.callback

It is also useful to know that an "Allowed External Redirect URL" for your Authentication settings in Azure Portal, would be:

myapp://easyauth.callback


问:
Is it correct to access the DAO layer from the Controller layer?
In my applications I usually access the DAO layer in order to obtain/save or update objects to it's repository, and I use a Service layer to perform more complex operations.

So my question is this: Is it correct (according to best practices and design/architecture patterns) to access the DAO layer from the Controller layer, or should I bypass it through the Service layer? Thanks!

答:
I guess I'm the iconoclast here.  I agree with the answers given thus far that say bypassing the service layer is fine in principle, but in my humble opinion, it's not in practice.

The main reason is that it is hard to anticipate when business logic may some day be introduced.   For example, I consider "logging" to be business logic.  If I want to INTRODUCE logging or journaling or restrict access, I don't  want to do that in the DAO layer.     But if I have code that bypasses the DAO layer, now ALL that code needs to be refactored.

There's another advantage to the DAO layer that I have often found useful.   There are operations I may want to expose to a service layer, but not to any layer above it.

As an example, I can imagine a DAO layer that returns encrypted passwords, but a service layer that only allows you to tell whether an encrypted password you pass in matches the one in the database.   I don't want a controller layer being able to fetch valid encrypted passwords - I see that unnecessary exposure.

Thus while I might agree that if you KNOW for damned sure you never ever will need to introduce business logic (such as I've described), and if you have ZERO need to hide some data access operations while exposing others... then by all means expose the DAO layer to higher layers.

My point is that in practice, you can't "know" that, nor should you assume that.


问:
Set UILabel's number of lines depending by the text contained - Objective C and/or Swift
I'm trying to display some random text into a UILabel and of course I have nothing but its width. Is there a way to set my UILabel's height and/or number of lines depending by the text contained in it?

Thanks ;)

答:
For Swift 4.0

```<code>func getStringHeight(mytext: String, fontSize: CGFloat, width: CGFloat)->CGFloat {

    let font = UIFont.systemFont(ofSize: fontSize)
    let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineBreakMode = .byWordWrapping;
    let attributes = [NSAttributedStringKey.font:font,
                      NSAttributedStringKey.paragraphStyle:paragraphStyle.copy()]

    let text = mytext as NSString
    let rect = text.boundingRect(with: size,
                                options:.usesLineFragmentOrigin,
                                attributes: attributes,
                                context:nil)
    return rect.size.height
}
</code>```

Body:
For Swift 4.0

func getStringHeight(mytext: String, fontSize: CGFloat, width: CGFloat)->CGFloat {

    let font = UIFont.systemFont(ofSize: fontSize)
    let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineBreakMode = .byWordWrapping;
    let attributes = [NSAttributedStringKey.font:font,
                      NSAttributedStringKey.paragraphStyle:paragraphStyle.copy()]

    let text = mytext as NSString
    let rect = text.boundingRect(with: size,
                                options:.usesLineFragmentOrigin,
                                attributes: attributes,
                                context:nil)
    return rect.size.height
}


问:
How to create a sequence of clicks in ActionScript?
I am creating a puzzle in which the player have to click on the buttons on the right order or sequence to go to the next level (Scene 2 for example). I don't know how to do it. If any one have any idea to how to achieve this in Action Script.

Thank you

Scene 1:

enter image description here

each number is a button. Now the player has to click in the right order or sequence (1 2 3 4 5 6 7 8) to open the next level (Scene 2)

```<code>var checkString:String = "";

//Create event listeners and their functions.
btn1.addEventListener(Mouse.CLICK, oneClick);
btn2.addEventListener(Mouse.CLICK, twoClick);
btn3.addEventListener(Mouse.CLICK, threeClick);
btn4.addEventListener(Mouse.CLICK, fourClick);
btn5.addEventListener(Mouse.CLICK, fiveClick);
btn6.addEventListener(Mouse.CLICK, sixClick);
btn7.addEventListener(Mouse.CLICK, sevenClick);
btn8.addEventListener(Mouse.CLICK, eightClick);

function oneClick(evt:Event):void
{
   //In each event listener function, add a letter or
   //string to the checkString variable.
   checkString += "on";

   //Then, see if the string matches or not.
   check();
}

function twoClick(evt:Event):void
{
   checkString += "tw";
   check();
}

function threeClick(evt:Event):void
{
   checkString += "th";
   check();
}

function fourClick(evt:Event):void
{
   checkString += "fo";
   check();
}

function fiveClick(evt:Event):void
{
   checkString += "fi";
   check();
}

function sixClick(evt:Event):void
{
   checkString += "si";
   check();
}

function sevenClick(evt:Event):void
{
   checkString += "se";
   check();
}

function eightClick(evt:Event):void
{
   checkString += "ei";
   check();
}

//If the proper sequence is one, two, three, four, five, six, seven, eight the string would read "ontwthfofisiseei".
function check():void
{
   if(checkString == "ontwthfofisiseei")
   {
      //Clear the checkString for convenience before going on.
      clearString();
      //CODE TO GO TO NEW FRAME

gotoAndPlay(1, "Scene 3");
   }

}

function clearString():void
{
   //You will want to have a function for clearing the string.
   //This is especially useful if you have a button for "start over."
   checkString = "";
}
</code>```

this the code i used before but it show error in the listener and it doesn't. work

答:
To answer your updated question:

Your error is likely that Mouse.CLICK should be MouseEvent.CLICK.

Your other error is telling you that there is no scene called "Scene 3"

Let's assume you have 8 MovieClips (or buttons) that are on a timeline in Flash/Animate.

One (of many) ways to accomplish this would be the following:

Give each of those buttons an instance name.   To make for less code, lets give them the name btn + their respective correct order number - so btn1, btn2, btn3 etc.

You'll need to add a click listener to each button, so they can have something happen when they are clicked.

You could do this 8 times (one for each button):  btn1.addEventListener(MouseEvent.CLICK, buttonClick); but to make things simpler, you can just iterate through all the objects on the timeline and add the listener to each object whose name starts with "btn":

```<code>var totalBtns:int = 0; //create a var to store how many buttons there are
//loop through each child of the current timeline
var i:int = numChildren;
while(i--){
    //if the child's name starts with 'btn'
    if(getChildAt(i).name.indexOf("btn") == 0){
        //add the click listener
        getChildAt(i).addEventListener(MouseEvent.CLICK, buttonClick,false,0,true);
        totalBtns++; //increase the total buttons variable by 1
    }
}
</code>```

This also means less work later if you add/remove buttons

You need a way to track when a button was clicked.  To accomplish this, we'll use an array.

```<code>var clickArray:Array = []; //this creates a new array
//When a button is clicked, you add it to this array
</code>```

lets create the function that is called when a button is clicked:

```<code>function buttonClick(e:Event):void {
    //add the item that was just clicked (represented by the event's currentTarget property) to the array
    //so if btn1 was just clicked, btn1 would be e.currentTarget
    clickArray.push(e.currentTarget);

    //now disable the button so it can't be clicked anymore
    SimpleButton(e.currentTarget).enabled = false;

    //check if all button have been clicked
    if(clickArray.length == totalBtns){

       //lets go through every item in the array, and see if it's in the right order
       var ctr:int = 0; //a counter to keep track of the expected next number         var i:int = 0; //iterator for the for loops
       for(i=0;i<clickArray.length;i++){
           //lets convert everything after the 3rd character of the name to a number - so for btn1, that would be 1
           if(parseInt(clickArray[i].name.substring(3)) == ctr + 1){
              ctr++; //increment the counter to the next expected number
           }else{
              break; //leave the for loop early since a click was out of place
           }
       }

       //if the correct order was achieved
       if(ctr == totalBtns){
           nextScene(); //or however you continue
       }else{
           //the correct order was NOT acheived

           //make all the buttons clickable again
           for(i=0;i<clickArray.length;i++){
               SimpleButton(clickArray[i]).enabled = true;
           }

           //reset the array
           clickArray = [];

           //probably want to tell the user to try again
       }
    }
}
</code>```

Body:
I am creating a puzzle in which the player have to click on the buttons on the right order or sequence to go to the next level (Scene 2 for example). I don't know how to do it. If any one have any idea to how to achieve this in Action Script.

Thank you

Scene 1:

enter image description here

each number is a button. Now the player has to click in the right order or sequence (1 2 3 4 5 6 7 8) to open the next level (Scene 2)

var checkString:String = "";

//Create event listeners and their functions.
btn1.addEventListener(Mouse.CLICK, oneClick);
btn2.addEventListener(Mouse.CLICK, twoClick);
btn3.addEventListener(Mouse.CLICK, threeClick);
btn4.addEventListener(Mouse.CLICK, fourClick);
btn5.addEventListener(Mouse.CLICK, fiveClick);
btn6.addEventListener(Mouse.CLICK, sixClick);
btn7.addEventListener(Mouse.CLICK, sevenClick);
btn8.addEventListener(Mouse.CLICK, eightClick);

function oneClick(evt:Event):void
{
   //In each event listener function, add a letter or
   //string to the checkString variable.
   checkString += "on";

   //Then, see if the string matches or not.
   check();
}

function twoClick(evt:Event):void
{
   checkString += "tw";
   check();
}

function threeClick(evt:Event):void
{
   checkString += "th";
   check();
}

function fourClick(evt:Event):void
{
   checkString += "fo";
   check();
}

function fiveClick(evt:Event):void
{
   checkString += "fi";
   check();
}

function sixClick(evt:Event):void
{
   checkString += "si";
   check();
}

function sevenClick(evt:Event):void
{
   checkString += "se";
   check();
}

function eightClick(evt:Event):void
{
   checkString += "ei";
   check();
}

//If the proper sequence is one, two, three, four, five, six, seven, eight the string would read "ontwthfofisiseei".
function check():void
{
   if(checkString == "ontwthfofisiseei")
   {
      //Clear the checkString for convenience before going on.
      clearString();
      //CODE TO GO TO NEW FRAME

gotoAndPlay(1, "Scene 3");
   }

}

function clearString():void
{
   //You will want to have a function for clearing the string.
   //This is especially useful if you have a button for "start over."
   checkString = "";
}

this the code i used before but it show error in the listener and it doesn't. work

Body:
To answer your updated question:

Your error is likely that Mouse.CLICK should be MouseEvent.CLICK.

Your other error is telling you that there is no scene called "Scene 3"

Let's assume you have 8 MovieClips (or buttons) that are on a timeline in Flash/Animate.

One (of many) ways to accomplish this would be the following:

Give each of those buttons an instance name.   To make for less code, lets give them the name btn + their respective correct order number - so btn1, btn2, btn3 etc.

You'll need to add a click listener to each button, so they can have something happen when they are clicked.

You could do this 8 times (one for each button):  btn1.addEventListener(MouseEvent.CLICK, buttonClick); but to make things simpler, you can just iterate through all the objects on the timeline and add the listener to each object whose name starts with "btn":

var totalBtns:int = 0; //create a var to store how many buttons there are
//loop through each child of the current timeline
var i:int = numChildren;
while(i--){
    //if the child's name starts with 'btn'
    if(getChildAt(i).name.indexOf("btn") == 0){
        //add the click listener
        getChildAt(i).addEventListener(MouseEvent.CLICK, buttonClick,false,0,true);
        totalBtns++; //increase the total buttons variable by 1
    }
}

This also means less work later if you add/remove buttons

You need a way to track when a button was clicked.  To accomplish this, we'll use an array.

var clickArray:Array = []; //this creates a new array
//When a button is clicked, you add it to this array

lets create the function that is called when a button is clicked:

function buttonClick(e:Event):void {
    //add the item that was just clicked (represented by the event's currentTarget property) to the array
    //so if btn1 was just clicked, btn1 would be e.currentTarget
    clickArray.push(e.currentTarget);

    //now disable the button so it can't be clicked anymore
    SimpleButton(e.currentTarget).enabled = false;

    //check if all button have been clicked
    if(clickArray.length == totalBtns){

       //lets go through every item in the array, and see if it's in the right order
       var ctr:int = 0; //a counter to keep track of the expected next number         var i:int = 0; //iterator for the for loops
       for(i=0;i<clickArray.length;i++){
           //lets convert everything after the 3rd character of the name to a number - so for btn1, that would be 1
           if(parseInt(clickArray[i].name.substring(3)) == ctr + 1){
              ctr++; //increment the counter to the next expected number
           }else{
              break; //leave the for loop early since a click was out of place
           }
       }

       //if the correct order was achieved
       if(ctr == totalBtns){
           nextScene(); //or however you continue
       }else{
           //the correct order was NOT acheived

           //make all the buttons clickable again
           for(i=0;i<clickArray.length;i++){
               SimpleButton(clickArray[i]).enabled = true;
           }

           //reset the array
           clickArray = [];

           //probably want to tell the user to try again
       }
    }
}


问:
CloudKit Dashboard shows push log, but it is not received, why?
I am struggling since a couple of weeks with the implementation of a silent push notification  of database changes from iCloud. I have read everything about that, but I couldn't find out what I am missing to finally receive the push notification. Now I watched the loggings on CloudKit Dashboard and I surprisingly found, that there is a "push" logging (see image below).

But my real devices (iPhone and iPad) are never receiving the push notification via "application didReceive...." in the AppDelegate? What could be the reason. YES, I registered successfully for push notification in "application didFinishLaunching" and the apps capabilities are set properly. Does the logging prove a push from APNS ?

答: At the end the solution was to activate a "reset" on the CloudKit Dashboards development environment. No more problems after that. What a relief, it is "pushing" nicely and completely as expected.


问:
Access multiple elements by dynamic id and class inside a loop (multidimensional array?)
Sorry for the confusing title.

I'm working on this code: https://jsfiddle.net/8ers54s9/13/

It creates a simple text area and compares it to a predefined array for common words in a string. If any match, it changes the button color and shows some rows of a table. Try inputting "cat" and/or "blue".

That code is fully functional, however I will need to create up to 20 new arrays / buttons to check (there are two now - colors and animals - and I will add forms, emotions, names, cities, etc). As the code is very poorly optimized, I would need to actually copy-paste all the code for each new array type. I would like to know if there is a way to create most of the work inside for loops.

I thought about creating a multidimensional array that works as a "settings" base, like:

```<code>var mainSettings = [
  ["Color", "colorArray", "colorGroup", "colorbutton"],
  ["Animal", "animalArray", "animalGroup", "animalbutton"]
];
</code>```

And just call it by mainSettings[i][0], mainSettings[i][1] etc...

However I can't implement this idea (multiple undefined errors) or think about any other. What would be the best approach?

This part would be the most important one to avoid replicating:

```<code>if (manual.Color == true) {
    $('#colorbutton').removeClass().addClass('button blue');
    $('.colorGroup').show();
    $('#header').show();
}
if (manual.Color == false) {
    if (test.Color == true) {
        $('#colorbutton').removeClass().addClass('button green');
        $('.colorGroup').show();
        $('#header').show();
    }
    if (test.Color == false) $('#colorbutton').removeClass().addClass('button black');
}

if (manual.Animal == true) {
    $('#animalbutton').removeClass().addClass('button blue');
    $('.animalGroup').show();
    $('#header').show();
}
if (manual.Animal == false) {
    if (test.Animal == true) {
        $('#animalbutton').removeClass().addClass('button green');
        $('.animalGroup').show();
        $('#header').show();
    }
    if (test.Animal == false) $('#animalbutton').removeClass().addClass('button black');
}
</code>```

You can see it's just repeating code.

答:
I thought it would be a good exercise, here is a really simple prototype I made:

try inputting 'green' or 'cat'

/**
  @typedef KeywordButton
  @type {object}
  @property {string} id - the button ID, must be unique
  @property {string[]} keywords - a string array of keywords
  @property {string} title - The button title
  @property {string} color - The button border color
 */

function KeywordWidget(inputSelector, buttonsSelector) {
  this.$input = $(inputSelector);
  this.$buttons = $(buttonsSelector);
  var _keywordButtons = [];
  var widget = this;

  // register input event
  this.$input.on('input', function() {
    var text = widget.$input.val();
    _keywordButtons.forEach(function(keywordButton) {
      var keywords = keywordButton.keywords;
      var button = widget.$buttons.find('#' + keywordButton.id);
      var keywordExixts = keywords.some(function(v) {
        return text.indexOf(v) > -1;
      });
      if (keywordExixts) button.css('border-color', keywordButton.color);
      else button.css('border-color', 'black');
    });
  });

  /**
   * function to add new button
   * @param {KeywordButton} keywordButton - a keyword button config object
   */
  this.add = function(keywordButton) {
    if (_idExists(keywordButton.id)) throw new Error("id: " + keywordButton.id + " already exists");
    _keywordButtons.push(keywordButton);
    var $button = $('<button type="button" class="button">' + keywordButton.title + '</button>');
    $button.attr("id", keywordButton.id);
    this.$buttons.append($button);
  }

  // helper to check if id exists
  function _idExists(id) {
    return _keywordButtons.some(function(button) {
      button.id === id
    });
  }
}

var w = new KeywordWidget("#input", "#buttons");
// add color button
w.add({
  id: "color",
  title: "Color",
  keywords: ["green", "blue"],
  color: "red"
});
// add animal button
w.add({
  id: "animal",
  title: "Animal",
  keywords: ["dog", "cat"],
  color: "blue"
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.button {
  background-color: white;
  color: black;
  border-radius: 4px;
  border: 2px solid black;
}</code>```

  <textarea id="input" placeholder="Test one" rows="4" cols="50"></textarea>

```

Body:
Sorry for the confusing title.

I'm working on this code: https://jsfiddle.net/8ers54s9/13/

It creates a simple text area and compares it to a predefined array for common words in a string. If any match, it changes the button color and shows some rows of a table. Try inputting "cat" and/or "blue".

That code is fully functional, however I will need to create up to 20 new arrays / buttons to check (there are two now - colors and animals - and I will add forms, emotions, names, cities, etc). As the code is very poorly optimized, I would need to actually copy-paste all the code for each new array type. I would like to know if there is a way to create most of the work inside for loops.

I thought about creating a multidimensional array that works as a "settings" base, like:

var mainSettings = [
  ["Color", "colorArray", "colorGroup", "colorbutton"],
  ["Animal", "animalArray", "animalGroup", "animalbutton"]
];

And just call it by mainSettings[i][0], mainSettings[i][1] etc...

However I can't implement this idea (multiple undefined errors) or think about any other. What would be the best approach?

This part would be the most important one to avoid replicating:

if (manual.Color == true) {
    $('#colorbutton').removeClass().addClass('button blue');
    $('.colorGroup').show();
    $('#header').show();
}
if (manual.Color == false) {
    if (test.Color == true) {
        $('#colorbutton').removeClass().addClass('button green');
        $('.colorGroup').show();
        $('#header').show();
    }
    if (test.Color == false) $('#colorbutton').removeClass().addClass('button black');
}

if (manual.Animal == true) {
    $('#animalbutton').removeClass().addClass('button blue');
    $('.animalGroup').show();
    $('#header').show();
}
if (manual.Animal == false) {
    if (test.Animal == true) {
        $('#animalbutton').removeClass().addClass('button green');
        $('.animalGroup').show();
        $('#header').show();
    }
    if (test.Animal == false) $('#animalbutton').removeClass().addClass('button black');
}

You can see it's just repeating code.

Body:
I thought it would be a good exercise, here is a really simple prototype I made:

try inputting 'green' or 'cat'

/**
  @typedef KeywordButton
  @type {object}
  @property {string} id - the button ID, must be unique
  @property {string[]} keywords - a string array of keywords
  @property {string} title - The button title
  @property {string} color - The button border color
 */

function KeywordWidget(inputSelector, buttonsSelector) {
  this.$input = $(inputSelector);
  this.$buttons = $(buttonsSelector);
  var _keywordButtons = [];
  var widget = this;

  // register input event
  this.$input.on('input', function() {
    var text = widget.$input.val();
    _keywordButtons.forEach(function(keywordButton) {
      var keywords = keywordButton.keywords;
      var button = widget.$buttons.find('#' + keywordButton.id);
      var keywordExixts = keywords.some(function(v) {
        return text.indexOf(v) > -1;
      });
      if (keywordExixts) button.css('border-color', keywordButton.color);
      else button.css('border-color', 'black');
    });
  });

  /**
   * function to add new button
   * @param {KeywordButton} keywordButton - a keyword button config object
   */
  this.add = function(keywordButton) {
    if (_idExists(keywordButton.id)) throw new Error("id: " + keywordButton.id + " already exists");
    _keywordButtons.push(keywordButton);
    var $button = $('<button type="button" class="button">' + keywordButton.title + '</button>');
    $button.attr("id", keywordButton.id);
    this.$buttons.append($button);
  }

  // helper to check if id exists
  function _idExists(id) {
    return _keywordButtons.some(function(button) {
      button.id === id
    });
  }
}

var w = new KeywordWidget("#input", "#buttons");
// add color button
w.add({
  id: "color",
  title: "Color",
  keywords: ["green", "blue"],
  color: "red"
});
// add animal button
w.add({
  id: "animal",
  title: "Animal",
  keywords: ["dog", "cat"],
  color: "blue"
});

.button {
  background-color: white;
  color: black;
  border-radius: 4px;
  border: 2px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <textarea id="input" placeholder="Test one" rows="4" cols="50"></textarea>
</div>
<div id="buttons">


问:
In Java, can a method/constructor declaration appear inside another method/constructor declaration?
In Java, can a method/constructor declaration appear inside another method/constructor declaration? Example:

```<code>void A() {
    int B() { }
}
</code>```

I think not, but I'd love to be reassured.

答: No. it is not compilable.

Body:
In Java, can a method/constructor declaration appear inside another method/constructor declaration? Example:

void A() {
    int B() { }
}

I think not, but I'd love to be reassured.

Body: No. it is not compilable.


问:
Post data into custom Google Analytics metric from javascript
I've created custom dimension streamIdMismatch and custom metric
with same name streamIdMismatch

Also, I've created custom report which is based on my dimension and metric:

And now I want to post some data into my report, I use this javascript code:

```<code>var metricValue = '123';
ga('set', 'metric1', metricValue);
</code>```

But in the report I see nothing...

答:
The custom metric must be a positive integer (reference).

I would try the following code instead:

```<code>var metricValue = 123;
ga('set', 'metric1', metricValue);
</code>```

Body:
I've created custom dimension streamIdMismatch and custom metric
with same name streamIdMismatch

Also, I've created custom report which is based on my dimension and metric:

And now I want to post some data into my report, I use this javascript code:

var metricValue = '123';
ga('set', 'metric1', metricValue);

But in the report I see nothing...

Body:
The custom metric must be a positive integer (reference).

I would try the following code instead:

var metricValue = 123;
ga('set', 'metric1', metricValue);


问:
TODO reminder constexpr
I saw a guy creating something like a static_assert that uses DATE to create a reminder of a TODO code section, I liked the idea so I tried to implement it, the problem cames when my compiler doesn't like my aproximation, it says:

Too complex constexpr function

Expression should have constant value

Im using Visual studio 2017 with c++17 features enabled, the keyword CONSTEXPR is a macro that subtitudes with constexpr if the compiler supports it

Code:

```<code>namespace private_TODO
{
CONSTEXPR bool is_digit(char c)
{
    return c <= '9' && c >= '0';
}

CONSTEXPR unsigned stoi_impl(const char* str, int rec = 0, int value = 0)
{
    return rec != 0 ?
        is_digit(*str) ?
        stoi_impl(str + 1, rec--, (*str - '0') + value * 10)
        : throw "Compile-time-error: not a digit"
        : value;
}

CONSTEXPR unsigned stoi(const char* str, int maxIter)
{
    return stoi_impl(str, maxIter);
}

CONSTEXPR unsigned year(const char* str)
{
    return stoi(str, 4);
}

CONSTEXPR bool str_cmp(const char* str, const char* str2, unsigned sz)
{
    return sz != 0 ?
        *str == *str2 ? str_cmp(str + 1, str2 + 1, --sz)
            : false
        : true;
}

CONSTEXPR unsigned month(const char* str)
{
    return str_cmp(str, "Jan", 3) ? 1 :
        str_cmp(str, "Feb", 3) ? 2 :
        str_cmp(str, "Mar", 3) ? 3 :
        str_cmp(str, "Apr", 3) ? 4 :
        str_cmp(str, "May", 3) ? 5 :
        str_cmp(str, "Jun", 3) ? 6 :
        str_cmp(str, "Jul", 3) ? 7 :
        str_cmp(str, "Aug", 3) ? 8 :
        str_cmp(str, "Set", 3) ? 9 :
        str_cmp(str, "Oct", 3) ? 10 :
        str_cmp(str, "Nov", 3) ? 11 :
        str_cmp(str, "Dec", 3) ? 12 :
        throw "Compile-time error: Not a month!";
}

CONSTEXPR unsigned day(const char* str)
{
    return stoi(str, 2);
}

CONSTEXPR unsigned str_size(const char* str, unsigned value = 0)
{
    return *str != 0 ?
        str_size(str++, value++)
        : value;
}

CONSTEXPR unsigned total(const char* str)
{
    return (str_size(str) == 11 && str[3] == ' ' && str[6] == ' ') ?
        year(str + 7) * 512 + month(str) * 32 + day(str + 4)
        : throw "invalid string";
}
}

#define TODO(DATE, MESSAGE)\
static_assert(::private_TODO::total(__DATE__) < ::private_TODO::total(DATE), MESSAGE)
void test()
{
    TODO("NOV 16 2017", "THIS SHOULD THROW"); //11/16/17 is when I tested
}
</code>```

I don't understand why says Expression should have constant value, cause everything I think is constant, and yes they are complex functions, I wish if someone could help me to reduce de complexity of this functions

EDIT: One of the errors came from str_size it says that cannot evaluate it as constant

I finally made it using string_view class

```<code>using namespace std::string_literals;
using namespace std::string_view_literals;
/* TODO reminders */
namespace private_TODO
{
CONSTEXPR bool is_digit(char c)
{
    return c <= '9' && c >= '0';
}

CONSTEXPR unsigned stoi_impl(const std::string_view& str, int value = 0)
{
    return str.size() != 0 ?
        is_digit(str[0]) ?
        stoi_impl(str.substr(1, str.size() - 1), (str[0] - '0') + value * 10)
        : throw "Compile-time-error: not a digit"
        : value;
}

CONSTEXPR unsigned stoi(const std::string_view& str)
{
    return stoi_impl(str);
}

CONSTEXPR bool str_cmp(const std::string_view& str, const std::string_view& str2, unsigned sz = 0)
{
    return sz != str.size() ?
        str[sz] == str2[sz] ?
        str_cmp(str, str2, ++sz)
        : false
        : true;
}

CONSTEXPR unsigned month(const std::string_view& str)
{
    return
        str_cmp(str, "Jan"sv) ? 1 :
        str_cmp(str, "Feb"sv) ? 2 :
        str_cmp(str, "Mar"sv) ? 3 :
        str_cmp(str, "Apr"sv) ? 4 :
        str_cmp(str, "May"sv) ? 5 :
        str_cmp(str, "Jun"sv) ? 6 :
        str_cmp(str, "Jul"sv) ? 7 :
        str_cmp(str, "Aug"sv) ? 8 :
        str_cmp(str, "Set"sv) ? 9 :
        str_cmp(str, "Oct"sv) ? 10 :
        str_cmp(str, "Nov"sv) ? 11 :
        str_cmp(str, "Dec"sv) ? 12 :
        throw "Compile-time error: Not a month!";
}

CONSTEXPR unsigned total(const std::string_view& str)
{
    return (str.size() == 11 && str[3] == ' ' && str[6] == ' ') ?
        stoi(str.substr(7, 4)) * 512 + month(str.substr(0, 3)) * 32 + stoi(str.substr(4, 2))
        : throw "invalid string";
}
}
#define TODO(DATE, MESSAGE)\
static_assert(::private_TODO::total(std::string_view(__DATE__, 11)) < ::private_TODO::total(DATE ## sv), MESSAGE)
</code>```

答:
A constexpr must evaluate after a finite number of recursions. Your functions

```<code>constexpr bool str_cmp(const char* str, const char* str2, unsigned sz)
{
    return sz != 0 ?
        *str == *str2 ? str_cmp(str + 1, str2 + 1, sz--)
            : false
        : true;
}

constexpr unsigned str_size(const char* str, unsigned value = 0)
{
    return *str != 0 ?
        str_size(str++, value++)
        : value;
}
</code>```

don't. Rather they constitute infinite recursion and out-of-bounds access. The point is that the return values, i.e. the values passed to the recursion, of

```<code>sz--
str++
value++
</code>```

are the same as the input. Correct is

```<code>constexpr bool str_cmp(const char* str1, const char* str2, unsigned size)
{
  return size==0 || (*str1 == *str2 && str_cmp(++str1,++str2,--size));
}

constexpr unsigned str_size(const char* str, unsigned value = 0)
{
  return *str? str_size(++str,++value) : value;
}
</code>```

This may not be the only error in your code, though.

Title: TODO reminder constexpr

Body:
I saw a guy creating something like a static_assert that uses DATE to create a reminder of a TODO code section, I liked the idea so I tried to implement it, the problem cames when my compiler doesn't like my aproximation, it says:

Too complex constexpr function

Expression should have constant value

Im using Visual studio 2017 with c++17 features enabled, the keyword CONSTEXPR is a macro that subtitudes with constexpr if the compiler supports it

Code:

namespace private_TODO
{
CONSTEXPR bool is_digit(char c)
{
    return c <= '9' && c >= '0';
}

CONSTEXPR unsigned stoi_impl(const char* str, int rec = 0, int value = 0)
{
    return rec != 0 ?
        is_digit(*str) ?
        stoi_impl(str + 1, rec--, (*str - '0') + value * 10)
        : throw "Compile-time-error: not a digit"
        : value;
}

CONSTEXPR unsigned stoi(const char* str, int maxIter)
{
    return stoi_impl(str, maxIter);
}

CONSTEXPR unsigned year(const char* str)
{
    return stoi(str, 4);
}

CONSTEXPR bool str_cmp(const char* str, const char* str2, unsigned sz)
{
    return sz != 0 ?
        *str == *str2 ? str_cmp(str + 1, str2 + 1, --sz)
            : false
        : true;
}

CONSTEXPR unsigned month(const char* str)
{
    return str_cmp(str, "Jan", 3) ? 1 :
        str_cmp(str, "Feb", 3) ? 2 :
        str_cmp(str, "Mar", 3) ? 3 :
        str_cmp(str, "Apr", 3) ? 4 :
        str_cmp(str, "May", 3) ? 5 :
        str_cmp(str, "Jun", 3) ? 6 :
        str_cmp(str, "Jul", 3) ? 7 :
        str_cmp(str, "Aug", 3) ? 8 :
        str_cmp(str, "Set", 3) ? 9 :
        str_cmp(str, "Oct", 3) ? 10 :
        str_cmp(str, "Nov", 3) ? 11 :
        str_cmp(str, "Dec", 3) ? 12 :
        throw "Compile-time error: Not a month!";
}

CONSTEXPR unsigned day(const char* str)
{
    return stoi(str, 2);
}

CONSTEXPR unsigned str_size(const char* str, unsigned value = 0)
{
    return *str != 0 ?
        str_size(str++, value++)
        : value;
}

CONSTEXPR unsigned total(const char* str)
{
    return (str_size(str) == 11 && str[3] == ' ' && str[6] == ' ') ?
        year(str + 7) * 512 + month(str) * 32 + day(str + 4)
        : throw "invalid string";
}
}

#define TODO(DATE, MESSAGE)\
static_assert(::private_TODO::total(__DATE__) < ::private_TODO::total(DATE), MESSAGE)
void test()
{
    TODO("NOV 16 2017", "THIS SHOULD THROW"); //11/16/17 is when I tested
}

I don't understand why says Expression should have constant value, cause everything I think is constant, and yes they are complex functions, I wish if someone could help me to reduce de complexity of this functions

EDIT: One of the errors came from str_size it says that cannot evaluate it as constant

I finally made it using string_view class

using namespace std::string_literals;
using namespace std::string_view_literals;
/* TODO reminders */
namespace private_TODO
{
CONSTEXPR bool is_digit(char c)
{
    return c <= '9' && c >= '0';
}

CONSTEXPR unsigned stoi_impl(const std::string_view& str, int value = 0)
{
    return str.size() != 0 ?
        is_digit(str[0]) ?
        stoi_impl(str.substr(1, str.size() - 1), (str[0] - '0') + value * 10)
        : throw "Compile-time-error: not a digit"
        : value;
}

CONSTEXPR unsigned stoi(const std::string_view& str)
{
    return stoi_impl(str);
}

CONSTEXPR bool str_cmp(const std::string_view& str, const std::string_view& str2, unsigned sz = 0)
{
    return sz != str.size() ?
        str[sz] == str2[sz] ?
        str_cmp(str, str2, ++sz)
        : false
        : true;
}

CONSTEXPR unsigned month(const std::string_view& str)
{
    return
        str_cmp(str, "Jan"sv) ? 1 :
        str_cmp(str, "Feb"sv) ? 2 :
        str_cmp(str, "Mar"sv) ? 3 :
        str_cmp(str, "Apr"sv) ? 4 :
        str_cmp(str, "May"sv) ? 5 :
        str_cmp(str, "Jun"sv) ? 6 :
        str_cmp(str, "Jul"sv) ? 7 :
        str_cmp(str, "Aug"sv) ? 8 :
        str_cmp(str, "Set"sv) ? 9 :
        str_cmp(str, "Oct"sv) ? 10 :
        str_cmp(str, "Nov"sv) ? 11 :
        str_cmp(str, "Dec"sv) ? 12 :
        throw "Compile-time error: Not a month!";
}

CONSTEXPR unsigned total(const std::string_view& str)
{
    return (str.size() == 11 && str[3] == ' ' && str[6] == ' ') ?
        stoi(str.substr(7, 4)) * 512 + month(str.substr(0, 3)) * 32 + stoi(str.substr(4, 2))
        : throw "invalid string";
}
}
#define TODO(DATE, MESSAGE)\
static_assert(::private_TODO::total(std::string_view(__DATE__, 11)) < ::private_TODO::total(DATE ## sv), MESSAGE)

Body:
A constexpr must evaluate after a finite number of recursions. Your functions

constexpr bool str_cmp(const char* str, const char* str2, unsigned sz)
{
    return sz != 0 ?
        *str == *str2 ? str_cmp(str + 1, str2 + 1, sz--)
            : false
        : true;
}

constexpr unsigned str_size(const char* str, unsigned value = 0)
{
    return *str != 0 ?
        str_size(str++, value++)
        : value;
}

don't. Rather they constitute infinite recursion and out-of-bounds access. The point is that the return values, i.e. the values passed to the recursion, of

sz--
str++
value++

are the same as the input. Correct is

constexpr bool str_cmp(const char* str1, const char* str2, unsigned size)
{
  return size==0 || (*str1 == *str2 && str_cmp(++str1,++str2,--size));
}

constexpr unsigned str_size(const char* str, unsigned value = 0)
{
  return *str? str_size(++str,++value) : value;
}

This may not be the only error in your code, though.