问:
php artisan migrate - SQLSTATE[HY000] [1045] Access denied for user 'laravel'@'localhost'
I want to set up and learn Laravel following this course

When I try to use the command php artisan migrate I get this error:

```<code>[Illuminate\Database\QueryException]
  SQLSTATE[HY000] [1045] Access denied for user 'laravel'@'localhost' (using password: NO) (SQL: select * from information_schema.tables whe
  re table_schema = laravel and table_name = migrations)

[PDOException]
  SQLSTATE[HY000] [1045] Access denied for user 'laravel'@'localhost' (using password: NO)
</code>```

I have looked for answers. I figured I may have to make some changes in the .env file, but I don't know what, and nothing I have tried so far has worked.

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=
</code>```

I'm using Ubuntu 16.04, not a Mac OS X as in the video, so I wonder what should I do differently? Is there some MySQL setting I did not set correctly?

答:
You don't have a user named 'laravel'.
You should change the DB_USERNAME to the one you're actually using to access your DB.
Mostly it's root by default so the changes in .env should be </p>

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
</code>```

Body:
I want to set up and learn Laravel following this course

When I try to use the command php artisan migrate I get this error:

[Illuminate\Database\QueryException]
  SQLSTATE[HY000] [1045] Access denied for user 'laravel'@'localhost' (using password: NO) (SQL: select * from information_schema.tables whe
  re table_schema = laravel and table_name = migrations)

[PDOException]
  SQLSTATE[HY000] [1045] Access denied for user 'laravel'@'localhost' (using password: NO)

I have looked for answers. I figured I may have to make some changes in the .env file, but I don't know what, and nothing I have tried so far has worked.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=laravel
DB_PASSWORD=

I'm using Ubuntu 16.04, not a Mac OS X as in the video, so I wonder what should I do differently? Is there some MySQL setting I did not set correctly?

Body:
You don't have a user named 'laravel'.
You should change the DB_USERNAME to the one you're actually using to access your DB.
Mostly it's root by default so the changes in .env should be

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=


来源: stackexchange

问:
how i can get xml data from url using php?
i want to get data from remotely XML URL with less memory, i'm using simplexml_load_string() but i'm not sure about my code and the xml feed contain around 980 records so what is the best way to get this big data and transform to array.

my code :

```<code>$xmlURL = 'http://www.ironitekstil.com/store/xmlfeed/productsxml.aspx?xslt=picksel.xsl';
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $xmlURL);
$contents = curl_exec($c);
curl_close($c);

if ($contents) {
  $xmlString = $contents;
  $xml = simplexml_load_string($xmlString);
  echo '```';
  print_r($xml);
  //echo count($xml); // 980 records
  echo '```';
}else {
  return FALSE;
}
</code>```

答:
SimpleXML will load the whole data into memory (It is a DOM abstraction layer). Try XMLReader. It can open URLs an read the XML tag by tag. The current node (and its descendants can be expanded into DOM. This allows you to iterate the outer nodes (list) and load the inner part (record).

You can use the PHP Streamwrappers to open the URL directly or use CURL to fetch and store it into a local file.

ContentLicense: CC BY-SA 3.0

Body:
i want to get data from remotely XML URL with less memory, i'm using simplexml_load_string() but i'm not sure about my code and the xml feed contain around 980 records so what is the best way to get this big data and transform to array.

my code :

$xmlURL = 'http://www.ironitekstil.com/store/xmlfeed/productsxml.aspx?xslt=picksel.xsl';
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $xmlURL);
$contents = curl_exec($c);
curl_close($c);

if ($contents) {
  $xmlString = $contents;
  $xml = simplexml_load_string($xmlString);
  echo '
';
  print_r($xml);
  //echo count($xml); // 980 records
  echo '
';
}else {
  return FALSE;
}


问:
About intellij-idea, how can I back to the previous code after I changed it?
I'm starting to use intellij-idea in few days , not like visual studio , when I changed the code , I can still go back if i'm not content with it , does intellij-idea have this function ? How can I find it ?</p>

答: You can use any version control for that. If you don't have any VCS enabled for the project, use Local History.</p>


问:
How to call only one button click function when user press enter from Textbox in Jquery?

I already made my code. But when user enter the EnterKey, it is calling 2 button event on server side. I want to call only one event.

I have three Asp.net buttons,

```<code><asp:Button ID="btnSearch" class="btn btn-info" runat="server" Text="SEARCH" Width="100" OnClick="btnSearch_Click" />
<asp:Button ID="btnSaveFile" runat="server" Text="SaveFile" OnClick="btnSaveFile_Click"/>
<asp:Button ID="btnLoadData" CssClass="btn btn-info"  runat="server" Text="Ok" OnClick="btnLoadData_Click" />
</code>```

Those 3 buttons will perform 3 different things. I have a textbox, once user enter the data and when they press the enter I want to call the btnSaveFile click event.

This is that text box

```<code><asp:TextBox ID="txtFileName" CssClass="form-control" runat="server"></asp:TextBox>
</code>```

Note

I already define the click function for btnSaveFile here is the code

```<code>$('#btnSaveFile').click(function () {
    var fileNames = $('#txtFileName').val();
    var flag = 'returnTrue';
    $.ajax({
        url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
        method: 'post',
        async: false,
        contentType: 'application/json',
        data: '{fileName:"' + fileNames + '",reportName:"TotalSales"}',
        dataType: 'json',
        success: function (data) {
            if (data.d === 'dataExist') {
                flag = 'returnFalse';
                $('#lblSaveErrorMsg').text('This filename already exist. Please change the name');
            }
            else {
                //alert('else');
                $(".FilterTable > tbody > tr").each(function () {
                    $("#hiddenTableRecord").val($("#hiddenTableRecord").val() + $(this).find(".FieldNameID").html() + "$$$" + $(this).find(".OperatorID").html() + "$$$");
                });
                $("#hiddenTableRecord").val('');
                return true;
            }
        },
        error: function (error) {
            alert('Please Call Administrator');
        }
    });
    //alert('faisal'+flag);
    if (flag === 'returnFalse') {
        return false;
    }

});
</code>```

The below code is for to call the above function.

```<code>$('#txtFileName').keydown(function (e) {
    //enter key
    var key = e.which;
    if (key == 13) {
        $('#btnSaveFile').click();
        return false;
    }
})
</code>```

Problem

keydown function is working fine. But at the same time when I press the enter key it is calling btnSearch server side code also. It should not call btnSearch. It should call btnSaveFile on server side

Doubt

Totally I have 3 server side button, But it is calling only 2 why? (Just want to know the reason). Target: want to call only one button

Thanks

答:
however i would suggest put your button and textbox into update panel and then set default button on update panel.
like below: </p>

```<code><asp:Panel ID="Panel1" runat="server" DefaultButton="btnSearch">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <input runat="server" id="txtSearch" class="form-control" type="text" placeholder="Search the Store..." />
        <asp:Button ID="btnSearch" class="btn btn-info" runat="server" Text="SEARCH" Width="100" OnClick="btnSearch_Click" />
    </ContentTemplate></asp:UpdatePanel>
</asp:Panel>
</code>```

Body:
I already made my code. But when user enter the EnterKey, it is calling 2 button event on server side. I want to call only one event.

I have three Asp.net buttons,

<asp:Button ID="btnSearch" class="btn btn-info" runat="server" Text="SEARCH" Width="100" OnClick="btnSearch_Click" />
<asp:Button ID="btnSaveFile" runat="server" Text="SaveFile" OnClick="btnSaveFile_Click"/>
<asp:Button ID="btnLoadData" CssClass="btn btn-info"  runat="server" Text="Ok" OnClick="btnLoadData_Click" />

Those 3 buttons will perform 3 different things. I have a textbox, once user enter the data and when they press the enter I want to call the btnSaveFile click event.

This is that text box

<asp:TextBox ID="txtFileName" CssClass="form-control" runat="server"></asp:TextBox>

Note

I already define the click function for btnSaveFile here is the code

$('#btnSaveFile').click(function () {
    var fileNames = $('#txtFileName').val();
    var flag = 'returnTrue';
    $.ajax({
        url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
        method: 'post',
        async: false,
        contentType: 'application/json',
        data: '{fileName:"' + fileNames + '",reportName:"TotalSales"}',
        dataType: 'json',
        success: function (data) {
            if (data.d === 'dataExist') {
                flag = 'returnFalse';
                $('#lblSaveErrorMsg').text('This filename already exist. Please change the name');
            }
            else {
                //alert('else');
                $(".FilterTable > tbody > tr").each(function () {
                    $("#hiddenTableRecord").val($("#hiddenTableRecord").val() + $(this).find(".FieldNameID").html() + "$$$" + $(this).find(".OperatorID").html() + "$$$");
                });
                $("#hiddenTableRecord").val('');
                return true;
            }
        },
        error: function (error) {
            alert('Please Call Administrator');
        }
    });
    //alert('faisal'+flag);
    if (flag === 'returnFalse') {
        return false;
    }

});

The below code is for to call the above function.

$('#txtFileName').keydown(function (e) {
    //enter key
    var key = e.which;
    if (key == 13) {
        $('#btnSaveFile').click();
        return false;
    }
})

Problem

keydown function is working fine. But at the same time when I press the enter key it is calling btnSearch server side code also. It should not call btnSearch. It should call btnSaveFile on server side

Doubt

Totally I have 3 server side button, But it is calling only 2 why? (Just want to know the reason). Target: want to call only one button

Thanks

Body:
however i would suggest put your button and textbox into update panel and then set default button on update panel.
like below:

<asp:Panel ID="Panel1" runat="server" DefaultButton="btnSearch">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <input runat="server" id="txtSearch" class="form-control" type="text" placeholder="Search the Store..." />
        <asp:Button ID="btnSearch" class="btn btn-info" runat="server" Text="SEARCH" Width="100" OnClick="btnSearch_Click" />
    </ContentTemplate></asp:UpdatePanel>
</asp:Panel>


问:
XSLT: rename XML attributes
I've got the following XML

```<code><message code="100" description="checkSnr">
 <string name="id" />
 <string name="serialNr" />
</message>
</code>```

Now I basically want to rename

```<code><string name="serialNr" />
</code>```

into

```<code><string name1="serialNr" />
</code>```

I read all the other questions about this topic but none work for me.

The idea behind this is easy: The single strings are supposed to be different to each other. Example:

```<code><xsl:value-of select="message/string/@name"  />
</code>```

will be "id".

```<code><xsl:value-of select="message/string/@name1"  />
</code>```

will be "serialNr".

I want them to be listed in a CSV like "id;serialNr" my actual output without renaming the attributes is "id;id". If you've got any other ideas how to solve this problem, your solutions are appreciated aswell!

Thanks in advance.

答:
Something like this should work:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" />

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="string/@name">
    <xsl:attribute name="name1">
      <xsl:value-of select="."/>
    </xsl:attribute>
  </xsl:template>
</xsl:stylesheet>
</code>```

Title: XSLT: rename XML attributes

Body:
I've got the following XML

<message code="100" description="checkSnr">
 <string name="id" />
 <string name="serialNr" />
</message>

Now I basically want to rename

<string name="serialNr" />

into

<string name1="serialNr" />

I read all the other questions about this topic but none work for me.

The idea behind this is easy: The single strings are supposed to be different to each other. Example:

<xsl:value-of select="message/string/@name"  />

will be "id".

<xsl:value-of select="message/string/@name1"  />

will be "serialNr".

I want them to be listed in a CSV like "id;serialNr" my actual output without renaming the attributes is "id;id". If you've got any other ideas how to solve this problem, your solutions are appreciated aswell!

Thanks in advance.

Body:
Something like this should work:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" />

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="string/@name">
    <xsl:attribute name="name1">
      <xsl:value-of select="."/>
    </xsl:attribute>
  </xsl:template>
</xsl:stylesheet>


问:
Closure Compiler JsDoc annotations to replace tests in source code?
Are the JSDoc annotations sufficient to test parameters validity?

Example: in the following "add" method, the parameter (Point object) is defined as Non-nullable Point type. In this method and using Closure Compiler, can I then skip the code required to test the value of this parameter:

if (!point) {...

if (!(point instanceof Point)) {...

Thanks

```<code>class Point{
  /**
   * Add x/y values to the Point object
   *
   * @param {!Point} point The x/y values to add.
   *
   */
  add(point) {
    this.x += point.x;
    this.y += point.y;
  }
}
</code>```

答:
Yes, provided any code calling that method is being compiled.

If you have  code calling that method which is not being compiled, then the compiler cannot guarantee the type being passed.  For example if you make a library to be called by non-compiled code. In that case you are probably exporting the add method to make it
accessible to outside non-compiled code.

If you are not exporting the add method then only compiled code can access it.

See the section Checks Provided by the Compiler on page 408 in Closure The Definitive Guide by Michael Bolin.  You need to specify certain flags to the compiler such as:

```<code>--jscomp_error=checkTypes
--warning_level=VERBOSE
</code>```

Body:
Are the JSDoc annotations sufficient to test parameters validity?

Example: in the following "add" method, the parameter (Point object) is defined as Non-nullable Point type. In this method and using Closure Compiler, can I then skip the code required to test the value of this parameter:

if (!point) {...

if (!(point instanceof Point)) {...

Thanks

class Point{
  /**
   * Add x/y values to the Point object
   *
   * @param {!Point} point The x/y values to add.
   *
   */
  add(point) {
    this.x += point.x;
    this.y += point.y;
  }
}

Body:
Yes, provided any code calling that method is being compiled.

If you have  code calling that method which is not being compiled, then the compiler cannot guarantee the type being passed.  For example if you make a library to be called by non-compiled code. In that case you are probably exporting the add method to make it
accessible to outside non-compiled code.

If you are not exporting the add method then only compiled code can access it.

See the section Checks Provided by the Compiler on page 408 in Closure The Definitive Guide by Michael Bolin.  You need to specify certain flags to the compiler such as:

--jscomp_error=checkTypes
--warning_level=VERBOSE


问:
How to disable the Timepicker in Android
I have a TimePicker in my layout.
I need to disable the TimePicker (user cannot change hours or minutes) by clicking on buttons or events.

How can I disable it?

The below snippet did not work

```<code>TimePicker tp = (...)findViewById(...);

  for(int i = 0; i< tp.getChildCount(); i++)
        ((View)tp.getChildAt(i)).setEnabled(false);
</code>```

答:
```<code>    sButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (sButton.isChecked()) {

                timePicker.setEnabled(true);
                timePicker.setIs24HourView(true);
                displayTime.setText(currentTime());
                changeTime.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        displayTime.setText(currentTime());
                    }
                });

            } else {
                timePicker.setEnabled(false);

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

Body:
I have a TimePicker in my layout.
I need to disable the TimePicker (user cannot change hours or minutes) by clicking on buttons or events.

How can I disable it?

The below snippet did not work

TimePicker tp = (...)findViewById(...);

  for(int i = 0; i< tp.getChildCount(); i++)
        ((View)tp.getChildAt(i)).setEnabled(false);


问:
Multiple dex files define Lcom/google/android/gms/common/api/zza
I'm trying to integrate firebase database into my project but i'm getting this error after adding this line to my app gradle file :

```<code>compile 'com.google.firebase:firebase-database:9.8.0'
</code>```

error :

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/common/api/zza;

答:
for me, removing
apply plugin: 'com.google.gms.google-services'

worked. Helps this helps someone else

Body:
I'm trying to integrate firebase database into my project but i'm getting this error after adding this line to my app gradle file :

compile 'com.google.firebase:firebase-database:9.8.0'

error :

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/common/api/zza;


问:
Mysql Query to Merge Two Condition Into One Row
I just get confused. Already tried to search this whole site or google but didn't find the 'nearest' solution.

Ok let's say I have this table structure.

```<code>id date       finger_id finger_time is_enter
1  2017-03-30  2          09:00       1
2  2017-03-30  2          17:13       0
3  2017-03-31  4          09:10       1
4  2017-03-31  3          09:01       1
5. 2017-03-31  3          17:00       0
</code>```

I want to make the table to be like below.

```<code>date       finger_id  enter_time  exit_time
2017-03-30   2        09:00       17:13
2017-03-30   4        09:10
2017-03-31   3        09:10       17:00
</code>```

I have made sql statement but it turns like this.

```<code>date       finger_id  enter_time   exit_time
2017-03-30  2         09:00
2017-03-30  2                       17:13
2017-03-31  4         09:10
2017-03-31  3         09:01
2017-03-31  3                       17:00
</code>```

I just want to know how to merge the is_enter 1 with is_enter 0 on the same date by the finger_id column.

Here's my sql query for the reference.

```<code>SELECT *
FROM `tbl_fingerprint`
    LEFT JOIN `tbl_employee` ON `tbl_employee`.`fingerprint_id`=`tbl_fingerprint`.`fingerprint_id`
    LEFT JOIN `tbl_position` ON `tbl_position`.`position_id`=`tbl_employee`.`position_id`
WHERE `fingerprint_date` >= '2017-03-01'
AND `fingerprint_date` <= '2017-04-01'
GROUP BY `tbl_fingerprint`.`fingerprint_id`,
         `tbl_fingerprint`.`fingerprint_date`,
         `tbl_fingerprint`.`is_enter`
ORDER BY `fingerprint_date` ASC LIMIT 30
</code>```

Thanks for your help guys.

答:
Try This (This will work if finger_time is of time type):-

```<code>SELECT date, finger_id, min(finger_time) enter_time, if (min(finger_time) = max(finger_time), null, max(finger_time)) exit_time FROM xyz group by finger_id, date
</code>```

Body:
I just get confused. Already tried to search this whole site or google but didn't find the 'nearest' solution.

Ok let's say I have this table structure.

id date       finger_id finger_time is_enter
1  2017-03-30  2          09:00       1
2  2017-03-30  2          17:13       0
3  2017-03-31  4          09:10       1
4  2017-03-31  3          09:01       1
5. 2017-03-31  3          17:00       0

I want to make the table to be like below.

date       finger_id  enter_time  exit_time
2017-03-30   2        09:00       17:13
2017-03-30   4        09:10
2017-03-31   3        09:10       17:00

I have made sql statement but it turns like this.

date       finger_id  enter_time   exit_time
2017-03-30  2         09:00
2017-03-30  2                       17:13
2017-03-31  4         09:10
2017-03-31  3         09:01
2017-03-31  3                       17:00

I just want to know how to merge the is_enter 1 with is_enter 0 on the same date by the finger_id column.

Here's my sql query for the reference.

SELECT *
FROM `tbl_fingerprint`
    LEFT JOIN `tbl_employee` ON `tbl_employee`.`fingerprint_id`=`tbl_fingerprint`.`fingerprint_id`
    LEFT JOIN `tbl_position` ON `tbl_position`.`position_id`=`tbl_employee`.`position_id`
WHERE `fingerprint_date` >= '2017-03-01'
AND `fingerprint_date` <= '2017-04-01'
GROUP BY `tbl_fingerprint`.`fingerprint_id`,
         `tbl_fingerprint`.`fingerprint_date`,
         `tbl_fingerprint`.`is_enter`
ORDER BY `fingerprint_date` ASC LIMIT 30

Thanks for your help guys.

Body:
Try This (This will work if finger_time is of time type):-

SELECT date, finger_id, min(finger_time) enter_time, if (min(finger_time) = max(finger_time), null, max(finger_time)) exit_time FROM xyz group by finger_id, date


问:
Autoscroll to the bottom of a multiline textbox
I have started to make a master-server program for a small project involving rebuilding a game on a newer engine.
The master server program currently looks like this:

The large textbox with the 'Found 4 installed processor(s)' is a 'console' which outputs raw event messages sent to and from clients/gameservers using the master-server. It cannot be inputted into and the administrator (the only person who has access to this interface of the master-server program) can only copy from the textbox; they cannot delete/add anything.

The issue is that because it's supposed to be a 'console', it should automatically scroll down to the last line of the multiline textbox.

There are many questions on Stack Overflow which cover this (this one for example), but I haven't been able to get it working (the textbox doesn't scroll down) when placing the code within the console_TextChanged subroutine.
I have tried this:

```<code>Private Sub console_TextChanged(sender As Object, e As EventArgs) Handles console.TextChanged
    console.AppendText(Text)
    console.Select(console.TextLength, 0)
    console.ScrollToCaret()
End Sub
</code>```

It doesn't work, but it does however cause a bug in the program where each line is appended with the program's title quite a few times:

```<code>[net 11:32:22.243] System Started.Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5
</code>```

Some C# solutions have also worked for me in Visual Basic .Net in the past, and so I have tried some of the ones on Stack Overflow but I haven't been able to get these working either.

Is this really the correct way to autoscroll a multilined textbox, and if so, why is it not working for me?

The complete (relevant) code:

```<code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    console.Text = GetNetTime() + "System Started."
    WriteToConsole("Working Area: " + CStr(My.Computer.Screen.WorkingArea().Width) + "*" + CStr(My.Computer.Screen.WorkingArea().Height))
    WriteToConsole("Found " + CStr(Environment.ProcessorCount) + " installed processor(s)")
    Dim i As Integer = 0
    While (i < Environment.ProcessorCount)
        WriteToConsole("Processor " + CStr(i) + ": " + My.Computer.Registry.LocalMachine.OpenSubKey("Hardware\Description\System\CentralProcessor\" + CStr(i)).GetValue("ProcessorNameString"))
        WriteToConsole("            Family: " + My.Computer.Registry.LocalMachine.OpenSubKey("Hardware\Description\System\CentralProcessor\" + CStr(i)).GetValue("Identifier"))
        WriteToConsole("            Manufacturer: " + My.Computer.Registry.LocalMachine.OpenSubKey("Hardware\Description\System\CentralProcessor\" + CStr(i)).GetValue("VendorIdentifier"))
        i += 1
    End While
    WriteToConsole("Starting networking services")
End Sub
Private Sub console_TextChanged(sender As Object, e As EventArgs) Handles console.TextChanged
    console.AppendText(Text)
    console.Select(console.TextLength, 0)
    console.ScrollToCaret()
End Sub
Function GetNetTime()
    Return "[net " + CStr(DateTime.UtcNow.Hour) + ":" + CStr(DateTime.UtcNow.Minute) + ":" + CStr(DateTime.UtcNow.Second) + "." + CStr(DateTime.UtcNow.Millisecond) + "] "
End Function
Function WriteToConsole(ByVal input As String)
    console.AppendText(Environment.NewLine & GetNetTime() + input)
    Return -1
End Function
</code>```

答:
One more useful solution:

```<code>textBox1.SelectionStart = textBox1.Text.Length
textBox1.ScrollToCaret()
</code>```

It just put cursor at the end of text in textbox and scroll to current cursor position. Worked for me perfectly!

Body:
I have started to make a master-server program for a small project involving rebuilding a game on a newer engine.
The master server program currently looks like this:

The large textbox with the 'Found 4 installed processor(s)' is a 'console' which outputs raw event messages sent to and from clients/gameservers using the master-server. It cannot be inputted into and the administrator (the only person who has access to this interface of the master-server program) can only copy from the textbox; they cannot delete/add anything.

The issue is that because it's supposed to be a 'console', it should automatically scroll down to the last line of the multiline textbox.

There are many questions on Stack Overflow which cover this (this one for example), but I haven't been able to get it working (the textbox doesn't scroll down) when placing the code within the console_TextChanged subroutine.
I have tried this:

Private Sub console_TextChanged(sender As Object, e As EventArgs) Handles console.TextChanged
    console.AppendText(Text)
    console.Select(console.TextLength, 0)
    console.ScrollToCaret()
End Sub

It doesn't work, but it does however cause a bug in the program where each line is appended with the program's title quite a few times:

[net 11:32:22.243] System Started.Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5Server Network | Crysis Wars 1.5

Some C# solutions have also worked for me in Visual Basic .Net in the past, and so I have tried some of the ones on Stack Overflow but I haven't been able to get these working either.

Is this really the correct way to autoscroll a multilined textbox, and if so, why is it not working for me?

The complete (relevant) code:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    console.Text = GetNetTime() + "System Started."
    WriteToConsole("Working Area: " + CStr(My.Computer.Screen.WorkingArea().Width) + "*" + CStr(My.Computer.Screen.WorkingArea().Height))
    WriteToConsole("Found " + CStr(Environment.ProcessorCount) + " installed processor(s)")
    Dim i As Integer = 0
    While (i < Environment.ProcessorCount)
        WriteToConsole("Processor " + CStr(i) + ": " + My.Computer.Registry.LocalMachine.OpenSubKey("Hardware\Description\System\CentralProcessor\" + CStr(i)).GetValue("ProcessorNameString"))
        WriteToConsole("            Family: " + My.Computer.Registry.LocalMachine.OpenSubKey("Hardware\Description\System\CentralProcessor\" + CStr(i)).GetValue("Identifier"))
        WriteToConsole("            Manufacturer: " + My.Computer.Registry.LocalMachine.OpenSubKey("Hardware\Description\System\CentralProcessor\" + CStr(i)).GetValue("VendorIdentifier"))
        i += 1
    End While
    WriteToConsole("Starting networking services")
End Sub
Private Sub console_TextChanged(sender As Object, e As EventArgs) Handles console.TextChanged
    console.AppendText(Text)
    console.Select(console.TextLength, 0)
    console.ScrollToCaret()
End Sub
Function GetNetTime()
    Return "[net " + CStr(DateTime.UtcNow.Hour) + ":" + CStr(DateTime.UtcNow.Minute) + ":" + CStr(DateTime.UtcNow.Second) + "." + CStr(DateTime.UtcNow.Millisecond) + "] "
End Function
Function WriteToConsole(ByVal input As String)
    console.AppendText(Environment.NewLine & GetNetTime() + input)
    Return -1
End Function

Body:
One more useful solution:

textBox1.SelectionStart = textBox1.Text.Length
textBox1.ScrollToCaret()

It just put cursor at the end of text in textbox and scroll to current cursor position. Worked for me perfectly!


问:
Delete all lines until a specific line in Notepad++
I have to edit a lot of source codes similar to each other.

```<code>random blah
 random blah
blah
<table style="width: 232px; font-size: small;" cellpadding="0" cellspacing="0">....
</code>```

What I want to do is to delete lines until table tag. I think I can do it with Regex search but I couldnt write the regex pattern.
Thank you

答:
You have to go through multiple steps to do what you stated above:

Go to the replace window, select the "extended" mode, and in the "find what" field type in "\r\n" and replace them with: "LINEBREAK" (theres a space after 'LINEBREAK'). Click on replace all.

Go to the replace window again, select the "regular expression" mode, and in the "find what" field type in "(.*)(.*)(
)(.*)(.*)" and in the replace with field, type in "\2\3\4\5". Click on replace all.

Now go to replace window again, select elect the "extended" mode, and in the "find what" field type in "LINEBREAK" (theres a space after 'LINEBREAK') and replace them with: "\r\n". Click on replace all.

Notepad++ doesn't support multi line regex, which makes it hard to do what you wanted to do without going through the steps given above.

ContentLicense: CC BY-SA 2.5

Body:
I have to edit a lot of source codes similar to each other.

random blah
 random blah
blah

....

What I want to do is to delete lines until table tag. I think I can do it with Regex search but I couldnt write the regex pattern.
Thank you

Body:
You have to go through multiple steps to do what you stated above:

Go to the replace window, select the "extended" mode, and in the "find what" field type in "\r\n" and replace them with: "LINEBREAK" (theres a space after 'LINEBREAK'). Click on replace all.

Go to the replace window again, select the "regular expression" mode, and in the "find what" field type in "(.*)(.*)(<table)(.*)(>)(.*)(.*)" and in the replace with field, type in "\2\3\4\5". Click on replace all.

Now go to replace window again, select elect the "extended" mode, and in the "find what" field type in "LINEBREAK" (theres a space after 'LINEBREAK') and replace them with: "\r\n". Click on replace all.

Notepad++ doesn't support multi line regex, which makes it hard to do what you wanted to do without going through the steps given above.


问:
Mapping users to all of their files(URLs) in a mysql database.
What I want is that when I have looked up a user in a table, I want to list all the file urls that the user have access to. My first thought was to have a field in the table with a list of file URLs. However, I have now understood that there are no such field type.

I was then thinking that maybe ForeignKeys might work, but I am having trouble getting my head around it.

Another solution maybe is to have one table for each user, with each row representing each file.

What would you say is best practice in this case?
I am also going to expand into having shared files, but thought that I'd address this issue first.

答: Suggest you explore the JSON Data Type</p>

Body: Suggest you explore the JSON Data Type


问:
How to load 2 controllers one by one or at a time in angularjs?
Is it possible to load multiple controllers one by one or at a time. If yes  then Can anyone tell me how to load two different controllers at the time of loading page in AngularJs. I'm using routing.

Thank you.

答:
The way you are trying to solve this issue is wrong you can't control these things in a controller every time. Rather than calling both controllers you can use a service that will be doing this for you and you can call this service anytime you want in any controllers.

For your problem add this relogin to a service and call it whenever the controller loads in that way it will more feasible.


问:
Position of WHERE statement in left outer join
In the following query I am trying to first, filter all subscriptions that have a network_id = 24, and then join the column payment_plans.plan_type to subscriptions where the ids are the same.

I think there is a problem in the positioning of the WHERE statement but I am not sure where it is - the error shows that the there is a syntax error near the join statement

Any suggestions as to where the error might be?

```<code>SELECT DISTINCT subscriptions.user_id, subscriptions.payment_plan_id, payment_plans.plan_type
FROM subscriptions WHERE network_id = 24
LEFT OUTER JOIN payment_plans ON subscription.payment_plan_id = payment_plans.id

ERROR:  syntax error at or near "LEFT"
LINE 3: LEFT OUTER JOIN payment_plans ON subscription.payment_plan_i...
        ^
</code>```

答:
Your query should be:

```<code>SELECT DISTINCT subscriptions.user_id, subscriptions.payment_plan_id, payment_plans.plan_type
FROM subscriptions
LEFT OUTER JOIN payment_plans ON subscription.payment_plan_id = payment_plans.id
WHERE network_id = 24
</code>```

You can check out the documentation for the SELECT statement, in particular this section.

Body:
In the following query I am trying to first, filter all subscriptions that have a network_id = 24, and then join the column payment_plans.plan_type to subscriptions where the ids are the same.

I think there is a problem in the positioning of the WHERE statement but I am not sure where it is - the error shows that the there is a syntax error near the join statement

Any suggestions as to where the error might be?

SELECT DISTINCT subscriptions.user_id, subscriptions.payment_plan_id, payment_plans.plan_type
FROM subscriptions WHERE network_id = 24
LEFT OUTER JOIN payment_plans ON subscription.payment_plan_id = payment_plans.id

ERROR:  syntax error at or near "LEFT"
LINE 3: LEFT OUTER JOIN payment_plans ON subscription.payment_plan_i...
        ^

Body:
Your query should be:

SELECT DISTINCT subscriptions.user_id, subscriptions.payment_plan_id, payment_plans.plan_type
FROM subscriptions
LEFT OUTER JOIN payment_plans ON subscription.payment_plan_id = payment_plans.id
WHERE network_id = 24

You can check out the documentation for the SELECT statement, in particular this section.


问:
Design Help! java generics in a enum factory transformer!
I am wondering if I could get some input on a good way to design this.  I will put my approach but I think that there is a better solution (hence the question :) ).

I want to create an enum (to make clear the options and to avoid a singleton architecture) that has accessors for creating one object from another.  But what those objects are is pretty flexible.

Think of it as a way to limit the number of options for this transformation.

Let me go into a little of the hierarchy. If I am going from a diverse set of objects to something like this:

```<code>class Base {...}
class ValueA extends Base {...}
class ValueB extends Base {...}
</code>```

I was thinking of doing something like this:

```<code>public enum ValueTransformer{
  VALUE_A{

    @Override
    public <T> T createVo (Class<T> expectedRtn, Object obj) {
      ValueA retObj = null;

      if (expectedRtn == getReturnType ()) {
        if (obj != null && CanBeTranslatedToA.class == obj.getClass ()) {
          retObj = new ValueA ();
          /*...*/
        }
      }

      return retObj;
    }

    @Override
    public Class<ValueA> getReturnType () { return ValueA.class; }

  },
  VALUE_B {
    @Override
    public Class<ValueB> getReturnType () { return ValueB.class; }

    @Override
    public <T> T createVo (Class<T> expectedRtn, Object obj) {
      ValueB retObj = null;

      if (expectedRtn == getReturnType ()) {
        if (obj != null && CanBeTranslatedToB.class == obj.getClass ()) {
          retObj = new ValueB ();
          /*...*/
        }  else if (obj != null && AnotherClassForB.class = obj.getClass ()){
          retObj = new ValueB();
          /* ... */
        }
      }

      return retObj;
    }
  };

  public abstract <T> Class<T> getReturnType ();
  public abstract <T> T createVo (Class<T> expectedRtn, Object obj);
}
</code>```

Is this a decent design?  This enum will probably grow, and what ValueA and ValueB can be created from might change (as the sys grows).  I could return a 'Base' in all those cases, but it would require a cast and a check.  I'd prefer to not have that.

Is it necessary for me to have the expectedRtn parameter?  Should I be using Generics at all?  I am fairly new to Java so I am not always sure the best way to handle this case.

Thanks for any tips!!!!

答:
This isn't a very good design and I really can't even tell what this enum is trying to accomplish. To start with, you're using generic methods that each enum value implements, which means the caller of the method gets to decide what type they want T to be... but that's not what you want, because the methods are in fact opinionated about what types of objects they'll return.

```<code>Class<String> foo = ValueTransformer.VALUE_B.getReturnType();
String string = ValueTransformer.VALUE_A.createVo(String.class, "");
</code>```

The above is totally legal given your code, but your code does not actually handle this. Generic methods don't do what you seem to think they do.

I feel like what you actually want is just a simple way to transform objects of specific types to objects of type ValueA or ValueB. The simplest way to do this is just to have each class that can be transformed in this way provide a method that does that on each such class:

```<code>public class CanBeTranslatedToB {
  ...

  public ValueB toValueB() {
    ValueB result = new ValueB();
    ...
    return result;
  }
}
</code>```

Then, if you have an instance of CanBeTranslatedToB, rather than doing:

```<code> CanBeTranslatedToB foo = ...
 ValueB b = ValueTransformer.VALUE_B.createVo(ValueB.class, foo);
</code>```

you'd just do:

```<code>CanBeTranslatedToB foo = ...
ValueB b = foo.toValueB();
</code>```

That's much clearer and not error-prone like the enum version.

If necessary, you can do various things to make this easier such as making an interfaces that define the toValueA() and toValueB() methods and making helper classes to provide any common behavior that all implementations need to use. I don't see any use for an enum like you describe.

Edit:

If you can't change the code for the classes that need to be transformed to ValueB etc., you have several options. The simplest (and probably best, in my opinion) way to handle that would be to add factory methods to ValueA and ValueB such as:

```<code>// "from" would be another good name
public static ValueB valueOf(CanBeTranslatedToB source) {
  ...
}

public static ValueB valueOf(AnotherClassForB source) {
  ...
}
</code>```

Then you can just write:

```<code>CanBeTranslatedToB foo = ...
ValueB b = ValueB.valueOf(foo);
</code>```

If you don't want those methods on ValueB, you could have them in another class with method names like newValueB(CanBeTranslatedToB).

Finally, another option would be to use Guava and create a Function for each conversion. This is the closest to your original design, but it is type safe and works well with all the Function-accepting utilities Guava provides. You could collect these Function implementations in classes as you see fit. Here's an example of a singleton implementing a conversion from Foo to ValueB:

```<code>public static Function<Foo, ValueB> fooToValueB() {
  return FooToValueB.INSTANCE;
}

private enum FooToValueB implements Function<Foo, ValueB> {
  INSTANCE;

  @Override public ValueB apply(Foo input) {
    ...
  }
}
</code>```

However, I wouldn't use this as the only way to do the conversion... it would be better to have the static valueOf methods I mentioned above and provide such Functions only as a convenience if your application needs to transform whole collections of objects at once a lot.

Body:
I am wondering if I could get some input on a good way to design this.  I will put my approach but I think that there is a better solution (hence the question :) ).

I want to create an enum (to make clear the options and to avoid a singleton architecture) that has accessors for creating one object from another.  But what those objects are is pretty flexible.

Think of it as a way to limit the number of options for this transformation.

Let me go into a little of the hierarchy. If I am going from a diverse set of objects to something like this:

class Base {...}
class ValueA extends Base {...}
class ValueB extends Base {...}

I was thinking of doing something like this:

public enum ValueTransformer{
  VALUE_A{

    @Override
    public <T> T createVo (Class<T> expectedRtn, Object obj) {
      ValueA retObj = null;

      if (expectedRtn == getReturnType ()) {
        if (obj != null && CanBeTranslatedToA.class == obj.getClass ()) {
          retObj = new ValueA ();
          /*...*/
        }
      }

      return retObj;
    }

    @Override
    public Class<ValueA> getReturnType () { return ValueA.class; }

  },
  VALUE_B {
    @Override
    public Class<ValueB> getReturnType () { return ValueB.class; }

    @Override
    public <T> T createVo (Class<T> expectedRtn, Object obj) {
      ValueB retObj = null;

      if (expectedRtn == getReturnType ()) {
        if (obj != null && CanBeTranslatedToB.class == obj.getClass ()) {
          retObj = new ValueB ();
          /*...*/
        }  else if (obj != null && AnotherClassForB.class = obj.getClass ()){
          retObj = new ValueB();
          /* ... */
        }
      }

      return retObj;
    }
  };

  public abstract <T> Class<T> getReturnType ();
  public abstract <T> T createVo (Class<T> expectedRtn, Object obj);
}

Is this a decent design?  This enum will probably grow, and what ValueA and ValueB can be created from might change (as the sys grows).  I could return a 'Base' in all those cases, but it would require a cast and a check.  I'd prefer to not have that.

Is it necessary for me to have the expectedRtn parameter?  Should I be using Generics at all?  I am fairly new to Java so I am not always sure the best way to handle this case.

Thanks for any tips!!!!

Body:
This isn't a very good design and I really can't even tell what this enum is trying to accomplish. To start with, you're using generic methods that each enum value implements, which means the caller of the method gets to decide what type they want T to be... but that's not what you want, because the methods are in fact opinionated about what types of objects they'll return.

Class<String> foo = ValueTransformer.VALUE_B.getReturnType();
String string = ValueTransformer.VALUE_A.createVo(String.class, "");

The above is totally legal given your code, but your code does not actually handle this. Generic methods don't do what you seem to think they do.

I feel like what you actually want is just a simple way to transform objects of specific types to objects of type ValueA or ValueB. The simplest way to do this is just to have each class that can be transformed in this way provide a method that does that on each such class:

public class CanBeTranslatedToB {
  ...

  public ValueB toValueB() {
    ValueB result = new ValueB();
    ...
    return result;
  }
}

Then, if you have an instance of CanBeTranslatedToB, rather than doing:

 CanBeTranslatedToB foo = ...
 ValueB b = ValueTransformer.VALUE_B.createVo(ValueB.class, foo);

you'd just do:

CanBeTranslatedToB foo = ...
ValueB b = foo.toValueB();

That's much clearer and not error-prone like the enum version.

If necessary, you can do various things to make this easier such as making an interfaces that define the toValueA() and toValueB() methods and making helper classes to provide any common behavior that all implementations need to use. I don't see any use for an enum like you describe.

Edit:

If you can't change the code for the classes that need to be transformed to ValueB etc., you have several options. The simplest (and probably best, in my opinion) way to handle that would be to add factory methods to ValueA and ValueB such as:

// "from" would be another good name
public static ValueB valueOf(CanBeTranslatedToB source) {
  ...
}

public static ValueB valueOf(AnotherClassForB source) {
  ...
}

Then you can just write:

CanBeTranslatedToB foo = ...
ValueB b = ValueB.valueOf(foo);

If you don't want those methods on ValueB, you could have them in another class with method names like newValueB(CanBeTranslatedToB).

Finally, another option would be to use Guava and create a Function for each conversion. This is the closest to your original design, but it is type safe and works well with all the Function-accepting utilities Guava provides. You could collect these Function implementations in classes as you see fit. Here's an example of a singleton implementing a conversion from Foo to ValueB:

public static Function<Foo, ValueB> fooToValueB() {
  return FooToValueB.INSTANCE;
}

private enum FooToValueB implements Function<Foo, ValueB> {
  INSTANCE;

  @Override public ValueB apply(Foo input) {
    ...
  }
}

However, I wouldn't use this as the only way to do the conversion... it would be better to have the static valueOf methods I mentioned above and provide such Functions only as a convenience if your application needs to transform whole collections of objects at once a lot.


问:
javascript moment the mouse is held down
How do I get the coordinates from my mouse with JavaScript? How can I hold only the coordinates of the moment the mouse is held down?</p>

答:
The mousedown event is your friend. Just click and hold on the gray area:

var x = document.querySelector('#x')
var y = document.querySelector('#y')

document.querySelector('div').addEventListener('mousedown', function(e) {
  x.innerText = e.clientX
  y.innerText = e.clientY
}, false)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#target {
  width: 200px;
  height: 200px;
  background: gray;
  border: 1px solid black;
}</code>```

X:

Y:

```

Body:
The mousedown event is your friend. Just click and hold on the gray area:

var x = document.querySelector('#x')
var y = document.querySelector('#y')

document.querySelector('div').addEventListener('mousedown', function(e) {
  x.innerText = e.clientX
  y.innerText = e.clientY
}, false)

#target {
  width: 200px;
  height: 200px;
  background: gray;
  border: 1px solid black;
}

X: <span id="x"></span><br>
Y: <span id="y"></span>

<div id="target"></div>


问:
Is it risky to use a submitted but not approved PhoneGap plugin?
In my next Mobile Application , I am planning to use "cordova-plugin-customurlscheme 4.2.0",

in the description section , it was clearly mentioned that this plugin is "Submitted and waiting for approval at PhoneGap Build" .

My question about the submitted but not approved phonegap plugins, is it risky to use them ?

答:
Phonegap Build plugins are deprecated, so don't worry about it not being approved. Just use the npm version of the plugin:

```<code><gap:plugin name="cordova-plugin-customurlscheme" source="npm">
  <param name="URL_SCHEME" value="mycoolapp" />
</gap:plugin>
</code>```

Just replace mycoolapp with your own url scheme you want to use

Body:
Phonegap Build plugins are deprecated, so don't worry about it not being approved. Just use the npm version of the plugin:

<gap:plugin name="cordova-plugin-customurlscheme" source="npm">
  <param name="URL_SCHEME" value="mycoolapp" />
</gap:plugin>

Just replace mycoolapp with your own url scheme you want to use


问:
Swift delegate value is nil
Please help configure the delegate in my code. For the moment, I get the value nil.

Here is the first class:

```<code>    @IBOutlet weak var loginField: UITextField!
    @IBOutlet weak var passField: UITextField!

    extension LoginViewController: LoginDelegate {

    func checkFields() -> [String:String] {

        var result = [String:String]()
        if loginField.text == "" && passField.text == "" {
            CRNotifications.showNotification(type: .info, title: "Введите логин и пароль", message: "Укажите логин и пароль для авторизации в системе", dismissDelay: 4)
        } else if loginField.text == "" {
            CRNotifications.showNotification(type: .info, title: "Введите логин", message: "Укажите логин для авторизации в системе", dismissDelay: 4)
        } else if passField.text == "" {
            CRNotifications.showNotification(type: .info, title: "Введите пароль", message: "Укажите пароль для авторизации в системе", dismissDelay: 4)
        } else {
            result["login"] = loginField.text
            result["password"] = passField.text
        }
        return result
    }
}
</code>```

Here's the second:

```<code>    protocol LoginDelegate {
    func checkFields() -> [String:String]
}

class SettingsRepositoryImpl: NSObject, SettingsService {

    // MARK: Authorization
    var delegate:LoginDelegate?

    func authorization() -> AnyPromise {

        let loginAndPassword = delegate?.checkFields()

        delegate? = LoginViewController()

        let login = loginAndPassword?["login"]
        let password = loginAndPassword?["password"]

        print(login)
        print(password)

        let url = "http://gps-tracker.com.ua/login.php"
        let parameters: Parameters = [
            "login": login,
            "password": password
        ]

        let promise = Promise<Bool> { fulfill, reject in

            if Reachability.isConnectedToNetwork() == true
            {
                Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default).responseJSON { response in
                    switch response.result {
                    case .success:
                        fulfill(true)
                    case .failure:
                        CRNotifications.showNotification(type: .error, title: "Ошибка авторизации", message: "Неправильный логин или пароль", dismissDelay: 4)
                        fulfill(false)
                    }
                }
            }
            else
            {
                CRNotifications.showNotification(type: .error, title: "Ошибка связи", message: "Проблема с интернет соединением", dismissDelay: 4)
            }
        }
        return AnyPromise(promise)
    }

}
</code>```

What should I add that checkFields() has no nil value? I'm completely confused. I hope very much for your help.

答:
you are creating new instance of LoginViewController inside your authorization function, but what you should do it to create an instance of SettingsRepositoryImpl inside your LoginViewController like

```<code>fileprivate let settingsAPI = SettingsRepositoryImpl()
</code>```

and then inside LoginViewController

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    self.settingsAPI.delegate = self
}
</code>```

also you should change your delegate to be

```<code>weak var delegate: LoginDelegate?
</code>```

and then delete this inside your function

```<code>delegate? = LoginViewController()
</code>```

you can call authorization inside LoginViewController like

```<code>self.settingsAPI.authorization()
</code>```

Title: Swift delegate value is nil

Body:
Please help configure the delegate in my code. For the moment, I get the value nil.

Here is the first class:

    @IBOutlet weak var loginField: UITextField!
    @IBOutlet weak var passField: UITextField!

    extension LoginViewController: LoginDelegate {

    func checkFields() -> [String:String] {

        var result = [String:String]()
        if loginField.text == "" && passField.text == "" {
            CRNotifications.showNotification(type: .info, title: "Введите логин и пароль", message: "Укажите логин и пароль для авторизации в системе", dismissDelay: 4)
        } else if loginField.text == "" {
            CRNotifications.showNotification(type: .info, title: "Введите логин", message: "Укажите логин для авторизации в системе", dismissDelay: 4)
        } else if passField.text == "" {
            CRNotifications.showNotification(type: .info, title: "Введите пароль", message: "Укажите пароль для авторизации в системе", dismissDelay: 4)
        } else {
            result["login"] = loginField.text
            result["password"] = passField.text
        }
        return result
    }
}

Here's the second:

    protocol LoginDelegate {
    func checkFields() -> [String:String]
}

class SettingsRepositoryImpl: NSObject, SettingsService {

    // MARK: Authorization
    var delegate:LoginDelegate?

    func authorization() -> AnyPromise {

        let loginAndPassword = delegate?.checkFields()

        delegate? = LoginViewController()

        let login = loginAndPassword?["login"]
        let password = loginAndPassword?["password"]

        print(login)
        print(password)

        let url = "http://gps-tracker.com.ua/login.php"
        let parameters: Parameters = [
            "login": login,
            "password": password
        ]

        let promise = Promise<Bool> { fulfill, reject in

            if Reachability.isConnectedToNetwork() == true
            {
                Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default).responseJSON { response in
                    switch response.result {
                    case .success:
                        fulfill(true)
                    case .failure:
                        CRNotifications.showNotification(type: .error, title: "Ошибка авторизации", message: "Неправильный логин или пароль", dismissDelay: 4)
                        fulfill(false)
                    }
                }
            }
            else
            {
                CRNotifications.showNotification(type: .error, title: "Ошибка связи", message: "Проблема с интернет соединением", dismissDelay: 4)
            }
        }
        return AnyPromise(promise)
    }

}

What should I add that checkFields() has no nil value? I'm completely confused. I hope very much for your help.

Body:
you are creating new instance of LoginViewController inside your authorization function, but what you should do it to create an instance of SettingsRepositoryImpl inside your LoginViewController like

fileprivate let settingsAPI = SettingsRepositoryImpl()

and then inside LoginViewController

override func viewDidLoad() {
    super.viewDidLoad()
    self.settingsAPI.delegate = self
}

also you should change your delegate to be

weak var delegate: LoginDelegate?

and then delete this inside your function

delegate? = LoginViewController()

you can call authorization inside LoginViewController like

self.settingsAPI.authorization()


问:
How to hint use of UIView subclass for compiler
I have a subclass of UIViewController that is responsible for a single UIWebView.

Since this is a simple case, I override -(void)loadView, instantiate the UIWebView and assigning it the controller's view property:

```<code>- (void)loadView
{
    UIWebView *wv = [[[UIWebView alloc] initWithFrame:self.frame] autorelease];
    // other configuration here...
    self.view = wv;
}
</code>```

This is fine until I call a method of UIWebView's. For example...

```<code>[self.view loadHTMLString:HTMLString baseURL:baseURL];
</code>```

...leads to a compiler warning...

```<code>warning: 'UIView' may not respond to '-loadHTMLString:baseURL:'
</code>```

...since the view property is declared as UIView.

NOW the warning is easily solved with a cast...

```<code>[(UIWebView *)self.view loadHTMLString:HTMLString baseURL:baseURL];
</code>```

...but what I'd like to do is provide the correct type hint in the interface. I tried overriding the view property in MyViewController.h but this upsets the compiler too:

```<code>warning: property 'view' type does not match super class 'UIViewController' property type
</code>```

Is there any way of telling the compiler (and my fellows) that this is what I'm doing, and that I know that this is what I'm doing and that it's all okay? (If not I guess I'll stick with the cast.)

TIA

EDIT: I tried redeclaring the view property as per marcus.ramsden's answer: this eliminated the warning (and the need for the cast) but stopped the view appearing at all! I'm not sure why this should be as the controller will still return a UIView (subclass) when asked for it...

答:
The short answer is there's no reasonable way to do this.  And finding an unreasonable way to do it will create more problems than it will solve.  I realize this isn't the answer you want, but for the benefit of anyone who reads this question in the future I'll explain why I believe you shouldn't do this.

The view property is part of the public interface of UIViewController, and the type of the return value is part of that interface.  Changing the public interface of a class which you've subclassed is smelly.  If that's not reason enough for you, consider that the view property of a view controller is a fundamental bit of UIKit; there are few things you could mess with that could potentially have a more systemic effect on the framework.  Who knows what sort of dark machinations lie under the façade of that simple interface getter?  Based on some of the comments already left here it seeems that redefining this property breaks things in obvious ways; I would stay away.

If you come from a language like ruby, the fact that you can't send an arbitrary message to the object returned by the view property without a compiler warning probably seems unsatisfying.  However, for better or for worse, Objective C is a statically (if not particularly strongly) typed language.  When you're working with a particular tool it's worth trying to work to that tool's strengths, and avoid its weaknesses, rather than trying to shoehorn it into another tool's idioms.

If, on the other hand, you come from a strongly typed language like C++, that cast should feel extremely unsatisfactory as well.  Casts subvert the type system that statically typed languages lean heavily on, and are nearly always a nasty code smell.  C-style casts are the nuclear weapon of the C type system; they override absolutely everything, and they are nearly always the wrong thing to use.

What if you decide in the future that you want to add a label to your view along with the web view?  In that case you'll need to move the web view to be a subview; but if you're casting the view controller's base view to UIWebView everywhere, then your casts are now lies.  Sadly, the compiler won't help you find those lies, because C-style casts are unchecked; you can make a UIWebView out of a UIView, an int, a block, a function pointer, or a rhinocerous and the compiler won't make a peep.  Your app will crash mightily, though.

Finally, you say you're interested in avoiding complexity.  Consider that adding your web view as a subview of the base view would require only that you declare (and synthesize) a single property and add the subview in viewDidLoad.  Given that small amount of effort, all calls to your web view look like this:

```<code>[self.webView loadHTMLString:HTMLString baseURL:baseURL];
</code>```

Alternately, if you stick with casting, each call to your web view will look like this:

```<code>[(UIWebView *)self.view loadHTMLString:HTMLString baseURL:baseURL];
</code>```

The former seems less complex to me, and less brittle.

Body:
I have a subclass of UIViewController that is responsible for a single UIWebView.

Since this is a simple case, I override -(void)loadView, instantiate the UIWebView and assigning it the controller's view property:

- (void)loadView
{
    UIWebView *wv = [[[UIWebView alloc] initWithFrame:self.frame] autorelease];
    // other configuration here...
    self.view = wv;
}

This is fine until I call a method of UIWebView's. For example...

[self.view loadHTMLString:HTMLString baseURL:baseURL];

...leads to a compiler warning...

warning: 'UIView' may not respond to '-loadHTMLString:baseURL:'

...since the view property is declared as UIView.

NOW the warning is easily solved with a cast...

[(UIWebView *)self.view loadHTMLString:HTMLString baseURL:baseURL];

...but what I'd like to do is provide the correct type hint in the interface. I tried overriding the view property in MyViewController.h but this upsets the compiler too:

warning: property 'view' type does not match super class 'UIViewController' property type

Is there any way of telling the compiler (and my fellows) that this is what I'm doing, and that I know that this is what I'm doing and that it's all okay? (If not I guess I'll stick with the cast.)

TIA

EDIT: I tried redeclaring the view property as per marcus.ramsden's answer: this eliminated the warning (and the need for the cast) but stopped the view appearing at all! I'm not sure why this should be as the controller will still return a UIView (subclass) when asked for it...

Body:
The short answer is there's no reasonable way to do this.  And finding an unreasonable way to do it will create more problems than it will solve.  I realize this isn't the answer you want, but for the benefit of anyone who reads this question in the future I'll explain why I believe you shouldn't do this.

The view property is part of the public interface of UIViewController, and the type of the return value is part of that interface.  Changing the public interface of a class which you've subclassed is smelly.  If that's not reason enough for you, consider that the view property of a view controller is a fundamental bit of UIKit; there are few things you could mess with that could potentially have a more systemic effect on the framework.  Who knows what sort of dark machinations lie under the façade of that simple interface getter?  Based on some of the comments already left here it seeems that redefining this property breaks things in obvious ways; I would stay away.

If you come from a language like ruby, the fact that you can't send an arbitrary message to the object returned by the view property without a compiler warning probably seems unsatisfying.  However, for better or for worse, Objective C is a statically (if not particularly strongly) typed language.  When you're working with a particular tool it's worth trying to work to that tool's strengths, and avoid its weaknesses, rather than trying to shoehorn it into another tool's idioms.

If, on the other hand, you come from a strongly typed language like C++, that cast should feel extremely unsatisfactory as well.  Casts subvert the type system that statically typed languages lean heavily on, and are nearly always a nasty code smell.  C-style casts are the nuclear weapon of the C type system; they override absolutely everything, and they are nearly always the wrong thing to use.

What if you decide in the future that you want to add a label to your view along with the web view?  In that case you'll need to move the web view to be a subview; but if you're casting the view controller's base view to UIWebView everywhere, then your casts are now lies.  Sadly, the compiler won't help you find those lies, because C-style casts are unchecked; you can make a UIWebView out of a UIView, an int, a block, a function pointer, or a rhinocerous and the compiler won't make a peep.  Your app will crash mightily, though.

Finally, you say you're interested in avoiding complexity.  Consider that adding your web view as a subview of the base view would require only that you declare (and synthesize) a single property and add the subview in viewDidLoad.  Given that small amount of effort, all calls to your web view look like this:

[self.webView loadHTMLString:HTMLString baseURL:baseURL];

Alternately, if you stick with casting, each call to your web view will look like this:

[(UIWebView *)self.view loadHTMLString:HTMLString baseURL:baseURL];

The former seems less complex to me, and less brittle.


问:
Insert record in database from template record without altering template - Entity Framework
I am trying to insert a record into my database based on an existing record which functions as template using Entity Framework.

The flow right now is:

```<code>var newModel = organization.Models.Where(m => m.IsTemplate == true).FirstOrDefault();

newModel.Name = "Something New";
newModel.IsTemplate = false;

organization.Models.Add(newModel);
_organizationRepo.SaveChanges();
</code>```

Note that organization.Modelsis read from the repository beforehand.

My problem is that instead of creating a dublicate record with the new name and no tempalte flag, the template record is altered.

Criteria:

I want to create a new record which is a copy of an existing record

I want to alter the new record

I do NOT want to alter the existing record

I would assume Entity Framework would interpret the organization.Models.Add(newModel) statement as insert new record but it does not.

答:
The solution to the problem was (as Arie commented on the original question) to use AsNoTracking() as described here when finding the template entry.

One catch using this is that this workaround is not meant as

"read values (template) -> Change as needed -> insert new record"

but rather a read-only operation. This meant that I had to manually eager load all references to the template in order to ensure these getting included in the Add() operation on the DataContext.

I did this by loading properties into a variable before saving the object eg.

```<code>var modelFromTemplate = organization.Models.FirstOrDefault(m => m.IsTemplate == true);
var eagerLoadParams = modelFromTemplate.Parameters.ToList();

//Change stuff as needed on the template here
modelFromTemplate.Name = "Something New";
modelFromTemplate.IsTemplate = false;

//Save the new model
_modelRepo.Add(modelFromTemplate);
_modelRepo.SaveChanges();
</code>```

Body:
I am trying to insert a record into my database based on an existing record which functions as template using Entity Framework.

The flow right now is:

var newModel = organization.Models.Where(m => m.IsTemplate == true).FirstOrDefault();

newModel.Name = "Something New";
newModel.IsTemplate = false;

organization.Models.Add(newModel);
_organizationRepo.SaveChanges();

Note that organization.Modelsis read from the repository beforehand.

My problem is that instead of creating a dublicate record with the new name and no tempalte flag, the template record is altered.

Criteria:

I want to create a new record which is a copy of an existing record

I want to alter the new record

I do NOT want to alter the existing record

I would assume Entity Framework would interpret the organization.Models.Add(newModel) statement as insert new record but it does not.

Body:
The solution to the problem was (as Arie commented on the original question) to use AsNoTracking() as described here when finding the template entry.

One catch using this is that this workaround is not meant as

"read values (template) -> Change as needed -> insert new record"

but rather a read-only operation. This meant that I had to manually eager load all references to the template in order to ensure these getting included in the Add() operation on the DataContext.

I did this by loading properties into a variable before saving the object eg.

var modelFromTemplate = organization.Models.FirstOrDefault(m => m.IsTemplate == true);
var eagerLoadParams = modelFromTemplate.Parameters.ToList();

//Change stuff as needed on the template here
modelFromTemplate.Name = "Something New";
modelFromTemplate.IsTemplate = false;

//Save the new model
_modelRepo.Add(modelFromTemplate);
_modelRepo.SaveChanges();


问:
Converting binary lists to values required for combinations based on index of list
I generated a list of binary numbers in python with itertools, of which I want to convert all the 1 to 'ALL' and all the 0 to correspond to the index of the attribs list, where the attribs list is [1, 2], with the measure value 10 appended at the end of each list.

In essence, the list of binary numbers is

```<code>[(0, 0), (0, 1), (1, 0), (1, 1)]
</code>```

I want to convert them to

```<code>[(1, 2), (1, 'ALL'), ('ALL', 2), ('ALL', 'ALL')]
</code>```

So that these will be a form of combinations for the list [1,2].

The final lists when printed should look like these:

```<code>[1, 2, 10]
[1, 'ALL', 10]
['ALL', 2, 10]
['ALL', 'ALL', 10]
</code>```

However, I'm currently getting the following:

```<code>[2, 2, 10]
[2, 'ALL', 10]
['ALL', 2, 10]
['ALL', 'ALL', 10]
</code>```

What am I doing wrong?

```<code>import itertools as it

measure = 10
attribs = [1, 2]

# generate binary table based on number of columns
outs = [i for i in it.product(range(2), repeat=(len(attribs)))]
print(outs)

for line in outs:
    line = list(line)

    # replace binary of 1 or 0 with 'ALL' or value from input
    for index, item in enumerate(line):
        print("index of line: " + str(index) + " with value: " + str(item))

        if (item == 1):
            line[index] = 'ALL'
        elif (item == 0):
            for i in range(len(attribs)):
                print("assigning element at line index " + str(index) + " to index of attribs: " + str(i) + " with value: " + str(attribs[i]))
                line[index] = attribs[i]

    line.append(measure)
    print(line)
</code>```

答:
In your elif part your loop will executed till the end that will always assign attribs[1] to line[index] which is 2.

```<code>    elif (item == 0):
        for i in range(len(attribs)):
            print("assigning element at line index " + str(index) + " to index of attribs: " + str(i) + " with value: " + str(attribs[i]))
            line[index] = attribs[i]
</code>```

Instead you need to keep track of the index of 0 and 1 so that you can do:

```<code>    elif (item == 0):
        print("assigning element at line index " + str(index) + " to index of attribs: " + str(i) + " with value: " + str(attribs[i]))
        line[index] = attribs[bin_index]
</code>```

But after all, as a more pythonic way you can just use a nested list comprehension:

```<code>In [46]: [['ALL' if i else ind for ind, i in enumerate(items, 1)] + [10] for items in lst]
Out[46]: [[1, 2, 10], [1, 'ALL', 10], ['ALL', 2, 10], ['ALL', 'ALL', 10]]
</code>```

Body:
I generated a list of binary numbers in python with itertools, of which I want to convert all the 1 to 'ALL' and all the 0 to correspond to the index of the attribs list, where the attribs list is [1, 2], with the measure value 10 appended at the end of each list.

In essence, the list of binary numbers is

[(0, 0), (0, 1), (1, 0), (1, 1)]

I want to convert them to

[(1, 2), (1, 'ALL'), ('ALL', 2), ('ALL', 'ALL')]

So that these will be a form of combinations for the list [1,2].

The final lists when printed should look like these:

[1, 2, 10]
[1, 'ALL', 10]
['ALL', 2, 10]
['ALL', 'ALL', 10]

However, I'm currently getting the following:

[2, 2, 10]
[2, 'ALL', 10]
['ALL', 2, 10]
['ALL', 'ALL', 10]

What am I doing wrong?

import itertools as it

measure = 10
attribs = [1, 2]

# generate binary table based on number of columns
outs = [i for i in it.product(range(2), repeat=(len(attribs)))]
print(outs)

for line in outs:
    line = list(line)

    # replace binary of 1 or 0 with 'ALL' or value from input
    for index, item in enumerate(line):
        print("index of line: " + str(index) + " with value: " + str(item))

        if (item == 1):
            line[index] = 'ALL'
        elif (item == 0):
            for i in range(len(attribs)):
                print("assigning element at line index " + str(index) + " to index of attribs: " + str(i) + " with value: " + str(attribs[i]))
                line[index] = attribs[i]

    line.append(measure)
    print(line)

Body:
In your elif part your loop will executed till the end that will always assign attribs[1] to line[index] which is 2.

    elif (item == 0):
        for i in range(len(attribs)):
            print("assigning element at line index " + str(index) + " to index of attribs: " + str(i) + " with value: " + str(attribs[i]))
            line[index] = attribs[i]

Instead you need to keep track of the index of 0 and 1 so that you can do:

    elif (item == 0):
        print("assigning element at line index " + str(index) + " to index of attribs: " + str(i) + " with value: " + str(attribs[i]))
        line[index] = attribs[bin_index]

But after all, as a more pythonic way you can just use a nested list comprehension:

In [46]: [['ALL' if i else ind for ind, i in enumerate(items, 1)] + [10] for items in lst]
Out[46]: [[1, 2, 10], [1, 'ALL', 10], ['ALL', 2, 10], ['ALL', 'ALL', 10]]


问:
Label not display in subview of UITableView
I am designing an iOS hamburger menu with a table view in swift3

I want to display the number of notifications in menu tab.

```<code> let pieNotifi = UIImageView(frame: CGRectMake(cell.contentView.frame.size.width-40, cell.contentView.frame.size.height/2-7, 30, 20))
            let pieLabNotifi = UILabel(frame: CGRectMake(cell.contentView.frame.size.width-40, cell.contentView.frame.size.height/2-7, 30, 20))

            let subviews = self.view.viewWithTag(100001)
            if myGlobal.unreaddot != 0 {     //just a count for notifcaiton
                if subviews == nil {

                    pieNotifi.tag = 100001;
                    cell.addSubview(pieNotifi)
                    let pieShape = pieNotifi.layer;
                    pieShape.backgroundColor = UIColor.red.cgColor
                    pieShape.cornerRadius = pieShape.bounds.width / 4

                    pieLabNotifi.textColor = UIColor.white
                    pieLabNotifi.adjustsFontSizeToFitWidth = true;
                    pieLabNotifi.minimumScaleFactor = 0.5
                    pieLabNotifi.textAlignment = NSTextAlignment.center
                    pieNotifi.addSubview(pieLabNotifi)
                    pieLabNotifi.text = String(myGlobal.unreaddot)

                }
                else{
                    pieLabNotifi.text = String(myGlobal.unreaddot)
                }

            }else{
                let subviews = cell.viewWithTag(100001)
                subviews?.removeFromSuperview()
                print("remove red dot")
            }
</code>```

however,  it only display the red colour layer but do not have the label. refer to the picture shown below
enter image description here

I had tried to set

```<code> .sendSubview(to back:)
 .bringSubview(toFront: )
 .layer.zPosition = 1
</code>```

all these key word not work for me.

Can anyone advise me to solve this problem?

答:
You are not adding subview to UITableView. According to your code you are adding a subview to the cell of UITableView.
Try to add the subview to the content view of the cell, like:</p>

```<code>    cell.contentView.addSubView(pieNotifi)
</code>```

Body:
I am designing an iOS hamburger menu with a table view in swift3

I want to display the number of notifications in menu tab.

 let pieNotifi = UIImageView(frame: CGRectMake(cell.contentView.frame.size.width-40, cell.contentView.frame.size.height/2-7, 30, 20))
            let pieLabNotifi = UILabel(frame: CGRectMake(cell.contentView.frame.size.width-40, cell.contentView.frame.size.height/2-7, 30, 20))

            let subviews = self.view.viewWithTag(100001)
            if myGlobal.unreaddot != 0 {     //just a count for notifcaiton
                if subviews == nil {

                    pieNotifi.tag = 100001;
                    cell.addSubview(pieNotifi)
                    let pieShape = pieNotifi.layer;
                    pieShape.backgroundColor = UIColor.red.cgColor
                    pieShape.cornerRadius = pieShape.bounds.width / 4

                    pieLabNotifi.textColor = UIColor.white
                    pieLabNotifi.adjustsFontSizeToFitWidth = true;
                    pieLabNotifi.minimumScaleFactor = 0.5
                    pieLabNotifi.textAlignment = NSTextAlignment.center
                    pieNotifi.addSubview(pieLabNotifi)
                    pieLabNotifi.text = String(myGlobal.unreaddot)

                }
                else{
                    pieLabNotifi.text = String(myGlobal.unreaddot)
                }

            }else{
                let subviews = cell.viewWithTag(100001)
                subviews?.removeFromSuperview()
                print("remove red dot")
            }

however,  it only display the red colour layer but do not have the label. refer to the picture shown below
enter image description here

I had tried to set

 .sendSubview(to back:)
 .bringSubview(toFront: )
 .layer.zPosition = 1

all these key word not work for me.

Can anyone advise me to solve this problem?

Body:
You are not adding subview to UITableView. According to your code you are adding a subview to the cell of UITableView.
Try to add the subview to the content view of the cell, like:

    cell.contentView.addSubView(pieNotifi)


答:
You can provide a canvas on where the user can click on and catch the mouseDown event and you can get the current mouse position by following this example and snippet
https://www.w3schools.com/jsref/event_clientx.asp</p>

```<code>var x = event.clientX;     // Get the horizontal coordinate
var y = event.clientY;     // Get the vertical coordinate
var coor = "X coords: " + x + ", Y coords: " + y;
</code>```

Title: javascript moment the mouse is held down

Body: How do I get the coordinates from my mouse with JavaScript? How can I hold only the coordinates of the moment the mouse is held down?

Body:
You can provide a canvas on where the user can click on and catch the mouseDown event and you can get the current mouse position by following this example and snippet
https://www.w3schools.com/jsref/event_clientx.asp

var x = event.clientX;     // Get the horizontal coordinate
var y = event.clientY;     // Get the vertical coordinate
var coor = "X coords: " + x + ", Y coords: " + y;


问:
Fetching records that having their monthly period of creation date
I want to grab all the records that have been created ℕ month ago, exactly the same hour. (age of the records should be only ℕ months, 0 days, 0 hour)

ℕ = {1, 2, …}

for example if now() is 2016-11-15 13:15:00, any record having create_date as below is expected to be returned.

```<code>2010-11-15 13:15:00  -- different year
2016-02-15 13:15:00  -- different month
2016-11-15 13:46:23  -- different minute/seconds
2010-11-15 13:46:23  -- different year, month, minute and sec
</code>```

The best simple query I could think of was this:

```<code>SELECT  *
FROM    mytable
WHERE extract(day from age(now(), created_date)) = 0 -- same day any month ago
  AND extract(hour from age(now(), created_date)) = 0; -- same hour
</code>```

But the problem is there are some specific days that will be left out of the query. Such as when

```<code>created_date=2016-01-31 13:00:00
now() is 2016-02-28 13:00:00
</code>```

in this case, the age of the record is 28 days instead of 1 month; according to the age function in Postgresql.
So it will never be fetched neither at the end of Feb, or 1st of March.

Any idea about how this problem can be addressed in the most simple way is appreciated.

Here's some test data you can use to verify:

```<code>create table mytable (created_date timestamp, expected_records int);
truncate mytable;
insert into mytable (created_date, expected_records)  values
('2013-01-11 13:22:33', 2),
('2014-02-11 13:58:22', 2),
('2015-03-21 13:22:00', 1),
('2013-02-28 13:11:00', 5),
('2017-02-28 13:22:00', 5),
('2016-03-31 13:22:00', 5),
('2015-04-30 13:22:00', 5),
('2014-05-31 13:22:00', 5),
('2014-05-31 12:22:00', 1);
</code>```

the final SELECT query can be executed on any of these timstamps but should returns same amount of rows as expected_records states.
Also you can use 'some date'::timestamp instead of now() to fake time.

答:
Please try the following code segment, which has been tested and confirmed as effective...

```<code>SELECT  *
FROM mytable
WHERE EXTRACT( HOUR FROM NOW() ) = EXTRACT( HOUR FROM created_date )
  AND ( ( EXTRACT( DAY FROM NOW() ) = EXTRACT( DAY FROM created_date ) ) OR

        ( EXTRACT( DAY FROM DATE_TRUNC( 'MONTH', NOW() ) + INTERVAL '1 MONTH - 1 DAY' ) = EXTRACT( DAY FROM NOW() ) AND
          EXTRACT( DAY FROM created_date ) >= EXTRACT( DAY FROM NOW() ) ) );
</code>```

The following code tests to see both dates have the same days figure, irrespective of if one of them is the end of its month.  In that situation no further testing of the dates is required...

```<code>EXTRACT( DAY FROM NOW() ) = EXTRACT( DAY FROM created_date )
</code>```

The following code tests if NOW() is at the end of the month...

```<code>EXTRACT( DAY FROM DATE_TRUNC( 'MONTH', NOW() ) + INTERVAL '1 MONTH - 1 DAY' ) = EXTRACT( DAY FROM NOW() )
</code>```

The following code tests to see if created_date has a days value that is greater than NOW()'s...

```<code>EXTRACT( DAY FROM created_date ) >= EXTRACT( DAY FROM NOW() )
</code>```

Thus if the end of NOW() has no greater a value than the day value of created_date then they can be considered equivalent (hence the following code)  e.g. NOW()'s date = 2017-02-28 versus created_date's 2017-01-31, or NOW()'s date = 2017-04-30 versus created_date's 2017-12-31, etc.

```<code>EXTRACT( DAY FROM DATE_TRUNC( 'MONTH', NOW() ) + INTERVAL '1 MONTH - 1 DAY' ) = EXTRACT( DAY FROM NOW() ) AND
EXTRACT( DAY FROM created_date ) >= EXTRACT( DAY FROM NOW() )
</code>```

If you have any questions or comments, then please post a Comment accordingly.

Body:
I want to grab all the records that have been created ℕ month ago, exactly the same hour. (age of the records should be only ℕ months, 0 days, 0 hour)

ℕ = {1, 2, …}

for example if now() is 2016-11-15 13:15:00, any record having create_date as below is expected to be returned.

2010-11-15 13:15:00  -- different year
2016-02-15 13:15:00  -- different month
2016-11-15 13:46:23  -- different minute/seconds
2010-11-15 13:46:23  -- different year, month, minute and sec

The best simple query I could think of was this:

SELECT  *
FROM    mytable
WHERE extract(day from age(now(), created_date)) = 0 -- same day any month ago
  AND extract(hour from age(now(), created_date)) = 0; -- same hour

But the problem is there are some specific days that will be left out of the query. Such as when

created_date=2016-01-31 13:00:00
now() is 2016-02-28 13:00:00

in this case, the age of the record is 28 days instead of 1 month; according to the age function in Postgresql.
So it will never be fetched neither at the end of Feb, or 1st of March.

Any idea about how this problem can be addressed in the most simple way is appreciated.

Here's some test data you can use to verify:

create table mytable (created_date timestamp, expected_records int);
truncate mytable;
insert into mytable (created_date, expected_records)  values
('2013-01-11 13:22:33', 2),
('2014-02-11 13:58:22', 2),
('2015-03-21 13:22:00', 1),
('2013-02-28 13:11:00', 5),
('2017-02-28 13:22:00', 5),
('2016-03-31 13:22:00', 5),
('2015-04-30 13:22:00', 5),
('2014-05-31 13:22:00', 5),
('2014-05-31 12:22:00', 1);

the final SELECT query can be executed on any of these timstamps but should returns same amount of rows as expected_records states.
Also you can use 'some date'::timestamp instead of now() to fake time.

Body:
Please try the following code segment, which has been tested and confirmed as effective...

SELECT  *
FROM mytable
WHERE EXTRACT( HOUR FROM NOW() ) = EXTRACT( HOUR FROM created_date )
  AND ( ( EXTRACT( DAY FROM NOW() ) = EXTRACT( DAY FROM created_date ) ) OR

        ( EXTRACT( DAY FROM DATE_TRUNC( 'MONTH', NOW() ) + INTERVAL '1 MONTH - 1 DAY' ) = EXTRACT( DAY FROM NOW() ) AND
          EXTRACT( DAY FROM created_date ) >= EXTRACT( DAY FROM NOW() ) ) );

The following code tests to see both dates have the same days figure, irrespective of if one of them is the end of its month.  In that situation no further testing of the dates is required...

EXTRACT( DAY FROM NOW() ) = EXTRACT( DAY FROM created_date )

The following code tests if NOW() is at the end of the month...

EXTRACT( DAY FROM DATE_TRUNC( 'MONTH', NOW() ) + INTERVAL '1 MONTH - 1 DAY' ) = EXTRACT( DAY FROM NOW() )

The following code tests to see if created_date has a days value that is greater than NOW()'s...

EXTRACT( DAY FROM created_date ) >= EXTRACT( DAY FROM NOW() )

Thus if the end of NOW() has no greater a value than the day value of created_date then they can be considered equivalent (hence the following code)  e.g. NOW()'s date = 2017-02-28 versus created_date's 2017-01-31, or NOW()'s date = 2017-04-30 versus created_date's 2017-12-31, etc.

EXTRACT( DAY FROM DATE_TRUNC( 'MONTH', NOW() ) + INTERVAL '1 MONTH - 1 DAY' ) = EXTRACT( DAY FROM NOW() ) AND
EXTRACT( DAY FROM created_date ) >= EXTRACT( DAY FROM NOW() )

If you have any questions or comments, then please post a Comment accordingly.


答:
Change your code at elif loop like:

```<code>elif (item == 0):
    print("assigning element at line index " + str(index) + " to index of attribs: " + str(index) + " with value: " + str(attribs[index]))
    line[index] = attribs[index]
</code>```

you don't need extra for loop there.

Title: Converting binary lists to values required for combinations based on index of list

Body:
Change your code at elif loop like:

elif (item == 0):
    print("assigning element at line index " + str(index) + " to index of attribs: " + str(index) + " with value: " + str(attribs[index]))
    line[index] = attribs[index]

you don't need extra for loop there.


问:
Whats the difference between TTF & OTF font files?
Is there a difference in load time or quality or anything like that? I just downloaded some fonts for my site, and am wondering if there's any reasons I should use one type over the other. Basically, what would you suggest using?</p>

答:
So you can check the same question on Graphic Design https://graphicdesign.stackexchange.com/questions/5618/whats-the-difference-between-opentype-vs-truetype

For me this post from Typekit is a good starter https://blog.typekit.com/2010/12/02/the-benefits-of-opentypecff-over-truetype/

OpenType/CFF (.otf file extension) and TrueType (.ttf file extension*) are the two modern font formats available for desktop usage today. Despite being distinct formats, OT/CFF and TT fonts actually have a lot in common. They are distinguished primarily by their different outline formats and the contrasting approaches employed to rasterize those outlines.

I would also recommend to watch https://www.youtube.com/watch?v=nM5tN88CX30 (5 common misconceptions about OpenType vs TrueType)

I prefer OpenType as it's newer and it's updated regularly with new features, like color fonts or variable fonts for example.
OpenType has advanced typographic features (ligatures, alternate character forms, small caps ...).


问:
Hive External Table with Azure Blob Storage
Is there a way to create a Hive external table using SerDe with location pointing to Azure Storage, organized in such a way that the data uses the fewest number of blobs. For example if insert 10000 records, I would like it to create just 100 page blobs with 100 line records each instead of maybe 10000 with 1 record each. I am de serializing from the blob, so fewer blobs will require lesser time.What would be the most optimal format in hive?</p>

答:
First, there is a way to create a Hive external table using Serde with localtion pointing to Azure Blob Storage, but not directly, please see the section Create Hive database and tables like the HiveQL below.

```<code>create database if not exists <database name>;
CREATE EXTERNAL TABLE if not exists <database name>.<table name>
(
    field1 string,
    field2 int,
    field3 float,
    field4 double,
    ...,
    fieldN string
)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '<field separator>' lines terminated by '<line separator>'
STORED AS TEXTFILE LOCATION '<storage location>' TBLPROPERTIES("skip.header.line.count"="1");
</code>```

And focus the below content for explaination <storage location>.

<storage location>: the Azure storage location to save the data of Hive tables. If you do not specify LOCATION , the database and the tables are stored in hive/warehouse/ directory in the default container of the Hive cluster by default. If you want to specify the storage location, the storage location has to be within the default container for the database and tables. This location has to be referred as location relative to the default container of the cluster in the format of 'wasb:///<directory 1>/' or 'wasb:///<directory 1>/<directory 2>/', etc. After the query is executed, the relative directories are created within the default container.

So it means you can access Azure Blob Storage location on Hive via wasb protocol, which required hadoop-azure library that support Hadoop access HDFS on Azure Storage. If your Hive on Hadoop not deployed on Azure, you need to refer to the Hadoop offical document Hadoop Azure Support: Azure Blob Storage to configure it.

For using serde, it is depended on the file format you used, like for orc file format, the hql code using OrcSerde like below.

```<code>CREATE EXTERNAL TABLE IF NOT EXSISTS <table name> (<column_name column_type>, ...)
    ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.orc.OrcSerde'
    STORED AS ORC
    LOCATION '<orcfile path>'
</code>```

For your second, the most optimal format is ORC File Format in Hive.

Body:
First, there is a way to create a Hive external table using Serde with localtion pointing to Azure Blob Storage, but not directly, please see the section Create Hive database and tables like the HiveQL below.

create database if not exists <database name>;
CREATE EXTERNAL TABLE if not exists <database name>.<table name>
(
    field1 string,
    field2 int,
    field3 float,
    field4 double,
    ...,
    fieldN string
)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '<field separator>' lines terminated by '<line separator>'
STORED AS TEXTFILE LOCATION '<storage location>' TBLPROPERTIES("skip.header.line.count"="1");

And focus the below content for explaination <storage location>.

<storage location>: the Azure storage location to save the data of Hive tables. If you do not specify LOCATION , the database and the tables are stored in hive/warehouse/ directory in the default container of the Hive cluster by default. If you want to specify the storage location, the storage location has to be within the default container for the database and tables. This location has to be referred as location relative to the default container of the cluster in the format of 'wasb:///<directory 1>/' or 'wasb:///<directory 1>/<directory 2>/', etc. After the query is executed, the relative directories are created within the default container.

So it means you can access Azure Blob Storage location on Hive via wasb protocol, which required hadoop-azure library that support Hadoop access HDFS on Azure Storage. If your Hive on Hadoop not deployed on Azure, you need to refer to the Hadoop offical document Hadoop Azure Support: Azure Blob Storage to configure it.

For using serde, it is depended on the file format you used, like for orc file format, the hql code using OrcSerde like below.

CREATE EXTERNAL TABLE IF NOT EXSISTS <table name> (<column_name column_type>, ...)
    ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.orc.OrcSerde'
    STORED AS ORC
    LOCATION '<orcfile path>'

For your second, the most optimal format is ORC File Format in Hive.


问:
Alternative to Siebel's BrowserScript function ShowModalDialog() to work on Chrome
What is the alternative to Siebel's BrowserScript function ShowModalDialog() to launch a HTML page from Siebel on Chrome? The method is deprecated on Chrome, FireFox. It works on IE, but Chrome users get an error message.

My code:

```<code>function Applet_PreInvokeMethod (name, inputPropSet)
{
    //other code
    var ShowModalOptions = "dialogHeight:150px;dialogLeft:120px;dialogWidth:450px;scrollbars:no";
    var sFileSelected = theApplication().ShowModalDialog("FilePicker.htm", "", ShowModalOptions);

    //other code
}
</code>```

答:
We're having similar issue. In High Interactivity (only in Internet Explorer) it works fine. However, we are supporting other browsers in OpenUI where this problem emerges.

Briefly, we tackle the problem like this:

we distinguish if we are in OpenUI or High Interactivity

if it's High Interactivity (therefore it runs Internet Explorer) -> everything stays as before

if it's OpenUI -> we use our custom dialog in jquery in Presentation Model

In applet method we keep everything as before if the it's not OpenUI:

```<code>function Applet_PreInvokeMethod (name, inputPropSet)
{
    //other code
    if (!IsOpenUI) {
         var ShowModalOptions = "dialogHeight:150px;dialogLeft:120px;dialogWidth:450px;scrollbars:no";
         var sFileSelected = theApplication().ShowModalDialog("FilePicker.htm", "", ShowModalOptions);

         //other code
    }
}
</code>```

Then, we introduce Presentation Model in OpenUI for the particular applet:

```<code>presentation model for the applet {
...
    function PreInvokeMethod(methodName, psInputArgs, lp, returnStructure) {
        try {
           if (methodName == "MethodName") {
                // show jquery dialog having similar to FilePicker.htm
                ...
                // other code
            }
        }
    }
...
}
</code>```

You will need to duplicate code (for HI and OpenUI), you will need to keep your FilePicker.htm and u will need to make similar dialog for OpenUI.

Body:
What is the alternative to Siebel's BrowserScript function ShowModalDialog() to launch a HTML page from Siebel on Chrome? The method is deprecated on Chrome, FireFox. It works on IE, but Chrome users get an error message.

My code:

function Applet_PreInvokeMethod (name, inputPropSet)
{
    //other code
    var ShowModalOptions = "dialogHeight:150px;dialogLeft:120px;dialogWidth:450px;scrollbars:no";
    var sFileSelected = theApplication().ShowModalDialog("FilePicker.htm", "", ShowModalOptions);

    //other code
}

Body:
We're having similar issue. In High Interactivity (only in Internet Explorer) it works fine. However, we are supporting other browsers in OpenUI where this problem emerges.

Briefly, we tackle the problem like this:

we distinguish if we are in OpenUI or High Interactivity

if it's High Interactivity (therefore it runs Internet Explorer) -> everything stays as before

if it's OpenUI -> we use our custom dialog in jquery in Presentation Model

In applet method we keep everything as before if the it's not OpenUI:

function Applet_PreInvokeMethod (name, inputPropSet)
{
    //other code
    if (!IsOpenUI) {
         var ShowModalOptions = "dialogHeight:150px;dialogLeft:120px;dialogWidth:450px;scrollbars:no";
         var sFileSelected = theApplication().ShowModalDialog("FilePicker.htm", "", ShowModalOptions);

         //other code
    }
}

Then, we introduce Presentation Model in OpenUI for the particular applet:

presentation model for the applet {
...
    function PreInvokeMethod(methodName, psInputArgs, lp, returnStructure) {
        try {
           if (methodName == "MethodName") {
                // show jquery dialog having similar to FilePicker.htm
                ...
                // other code
            }
        }
    }
...
}

You will need to duplicate code (for HI and OpenUI), you will need to keep your FilePicker.htm and u will need to make similar dialog for OpenUI.