问:
What is causing UnsatisfiedLinkError for jniwrap64.dll?
We've got a GWT web app that uses JNI to call a dll. We build the dll as well. It works fine on my developer machine, which is a 64-bit Windows 7 machine, running Java 6 and running the webapps in Tomcat 6. But when we run it on the tester's VM which is running 32-bit WinXP, it errors with

```<code>java.lang.UnsatisfiedLinkError: Cannot load native JNIWrapper library (jniwrap64.dll)
at com.jniwrapper.Library.loadNativeCode(SourceFile:78)
at com.jniwrapper.Library.loadNativeCode(SourceFile:103)
at com.jniwrapper.Library.ensureNativeCode(SourceFile:113)
at com.jniwrapper.Library.load(SourceFile:189)
</code>```

My JRE_HOME is set to a 32-bit version of Java 6, because I wanted the build to be able to work on a 32-bit machine, but clearly I'm mis-understanding something about how the 32 or 64-bit versions of java work in compiling the web app.

And yes, the dll that we call is built in to the .war, since it works on my machine.

I also googled the jniwrap64.dll but didn't find much that was relevant.

Added for clarification : jniwrap64.dll is not the dll that I've built, and my code is not explicitly loading this library. That's part of my confusion, is what is this library, why is it being loaded, etc. I have assumed that jniwrap64.dll is some kind of system library that needs to be installed. My code that loads our library is as follows:

```<code>Library myLib = Library(path);
myLib.load(this.getClass().getClassLoader());
</code>```

答: When you load the dll with System.loadLibrary() do you load "jniwrap64.dll" or "jniwrap32.dll" ? Cna you show us the line of code which loads this library?</p>

Body:
We've got a GWT web app that uses JNI to call a dll. We build the dll as well. It works fine on my developer machine, which is a 64-bit Windows 7 machine, running Java 6 and running the webapps in Tomcat 6. But when we run it on the tester's VM which is running 32-bit WinXP, it errors with

java.lang.UnsatisfiedLinkError: Cannot load native JNIWrapper library (jniwrap64.dll)
at com.jniwrapper.Library.loadNativeCode(SourceFile:78)
at com.jniwrapper.Library.loadNativeCode(SourceFile:103)
at com.jniwrapper.Library.ensureNativeCode(SourceFile:113)
at com.jniwrapper.Library.load(SourceFile:189)

My JRE_HOME is set to a 32-bit version of Java 6, because I wanted the build to be able to work on a 32-bit machine, but clearly I'm mis-understanding something about how the 32 or 64-bit versions of java work in compiling the web app.

And yes, the dll that we call is built in to the .war, since it works on my machine.

I also googled the jniwrap64.dll but didn't find much that was relevant.

Added for clarification : jniwrap64.dll is not the dll that I've built, and my code is not explicitly loading this library. That's part of my confusion, is what is this library, why is it being loaded, etc. I have assumed that jniwrap64.dll is some kind of system library that needs to be installed. My code that loads our library is as follows:

Library myLib = Library(path);
myLib.load(this.getClass().getClassLoader());


来源: stackexchange

问:
VS Selenium - System.ArgumentNullException: text cannot be null Parameter name: text
I'm writing (Selenium) Unit Tests and am running into a NULL issue. This code was previously running and working, but now is failing and not entering values into the needed fields. Can anyone give me some suggestions as to what may be wrong?

Unit Test Objective: Navigate Web Service UI and enter a value that should display results.

DMPage.cs

```<code>using System;
using OpenQA.Selenium;

namespace Framework.WebServicePages
{
    public class DMPage
    {
        public static void GoTo()
        {
            WebServiceDriver.Instance.Navigate().GoToUrl("URL");
        }

        public static void Wait()
        {
            WebServiceDriver.Instance.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
        }

        public static string IsAt
        {
            get
            {
                var title = WebServiceDriver.Instance.FindElement(By.XPath(""));
                if (title != null)
                    return title.GetAttribute("Title");
                return string.Empty;
            }
        }

        public static ValueCommand EnterValue(string valuenum)
        {
            return new ValueCommand();
        }
    }

    public class ValueCommand
    {
        private readonly string valuenum;

        public ValueCommand()
        {
            this.valuenum = valuenum;
        }

        public void SearchValue()
        {
            var inputValue = WebServiceDriver.Instance.FindElement(By.XPath(""));
            inputValue.SendKeys(valuenum);

            var submitValue = WebServiceDriver.Instance.FindElement(By.XPath(""));
            submitValue.Click();
        }
    }
}
</code>```

DMTests.cs

```<code>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ValueMedAutomation.WebServicePages;

namespace Tests.WebServiceTestScripts
{
    [TestClass]
    public class DMTests
    {

        [TestInitialize]
        public void Init()
        {
            WebServiceDriver.Initialize();
        }

        [TestMethod]
        public void DM_Meds()
        {
            DMPage.GoTo();
            DMPage.Wait();
            DMPage.EnterValue("123456789").SearchValue();
            DMPage.Wait();

            Assert.AreEqual(DMPage.IsAt, "TEST", "Value failed.");
        }

        [TestCleanup]
        public void Cleanup()
        {
            WebServiceDriver.Close();
        }

    }
}
</code>```

Errors After Running Unit Test

Message: Test method Tests.WebServiceTestScripts.DMTests.DM_Med threw exception:

System.ArgumentNullException: text cannot be null
Parameter name: text

StackTrace:

RemoteWebElement.SendKeys(string text)

ValueCommand.SearchValue()

DMTests.DM_Med()

CS1717 Assignment made to same variable; did you mean to assign something else?

Errors When Debugging

The following lines break when running Debug:

```<code>L41    this.valuenum = valuenum;

L47    inputValue.SendKeys(valuenum);
</code>```

答:
You forgot to pass in string valuenum in the constructor of the ValueCommand class:

Within DMPage class:

```<code>public static ValueCommand EnterValue(string valuenum)
{
    return new ValueCommand(valuenum);
}
</code>```

Within ValueCommand class:

```<code>public ValueCommand(string valuenum)
{
    this.valuenum = valuenum;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm writing (Selenium) Unit Tests and am running into a NULL issue. This code was previously running and working, but now is failing and not entering values into the needed fields. Can anyone give me some suggestions as to what may be wrong?

Unit Test Objective: Navigate Web Service UI and enter a value that should display results.

DMPage.cs

using System;
using OpenQA.Selenium;

namespace Framework.WebServicePages
{
    public class DMPage
    {
        public static void GoTo()
        {
            WebServiceDriver.Instance.Navigate().GoToUrl("URL");
        }

        public static void Wait()
        {
            WebServiceDriver.Instance.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
        }

        public static string IsAt
        {
            get
            {
                var title = WebServiceDriver.Instance.FindElement(By.XPath(""));
                if (title != null)
                    return title.GetAttribute("Title");
                return string.Empty;
            }
        }

        public static ValueCommand EnterValue(string valuenum)
        {
            return new ValueCommand();
        }
    }

    public class ValueCommand
    {
        private readonly string valuenum;

        public ValueCommand()
        {
            this.valuenum = valuenum;
        }

        public void SearchValue()
        {
            var inputValue = WebServiceDriver.Instance.FindElement(By.XPath(""));
            inputValue.SendKeys(valuenum);

            var submitValue = WebServiceDriver.Instance.FindElement(By.XPath(""));
            submitValue.Click();
        }
    }
}

DMTests.cs

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ValueMedAutomation.WebServicePages;

namespace Tests.WebServiceTestScripts
{
    [TestClass]
    public class DMTests
    {

        [TestInitialize]
        public void Init()
        {
            WebServiceDriver.Initialize();
        }

        [TestMethod]
        public void DM_Meds()
        {
            DMPage.GoTo();
            DMPage.Wait();
            DMPage.EnterValue("123456789").SearchValue();
            DMPage.Wait();

            Assert.AreEqual(DMPage.IsAt, "TEST", "Value failed.");
        }

        [TestCleanup]
        public void Cleanup()
        {
            WebServiceDriver.Close();
        }

    }
}

Errors After Running Unit Test

Message: Test method Tests.WebServiceTestScripts.DMTests.DM_Med threw exception:

System.ArgumentNullException: text cannot be null
Parameter name: text

StackTrace:

RemoteWebElement.SendKeys(string text)

ValueCommand.SearchValue()

DMTests.DM_Med()

CS1717 Assignment made to same variable; did you mean to assign something else?

Errors When Debugging

The following lines break when running Debug:

L41    this.valuenum = valuenum;

L47    inputValue.SendKeys(valuenum);

Body:
You forgot to pass in string valuenum in the constructor of the ValueCommand class:

Within DMPage class:

public static ValueCommand EnterValue(string valuenum)
{
    return new ValueCommand(valuenum);
}

Within ValueCommand class:

public ValueCommand(string valuenum)
{
    this.valuenum = valuenum;
}


问:
Why TO_UTC_TIMESTAMP in hive returns wrong year?
Trying to run a simple query in hive CLI -

```<code>select to_utc_timestamp(unix_timestamp("04/24/2017 01:59:01","MM/dd/YYYY HH:mm:ss"),'EST');
</code>```

result:

```<code>OK
1970-01-18 09:00:35.941
Time taken: 0.448 seconds, Fetched: 1 row(s)
</code>```

Shouldn't the output be just date plus 4 hours?

答:
yyyy (and not YYYY)

unix_timestamp returns bigint and to_utc_timestamp considers integer values as milliseconds

```<code>select to_utc_timestamp(1000*unix_timestamp("04/24/2017 01:59:01","MM/dd/yyyy HH:mm:ss"),'EST');
</code>```

Body:
Trying to run a simple query in hive CLI -

select to_utc_timestamp(unix_timestamp("04/24/2017 01:59:01","MM/dd/YYYY HH:mm:ss"),'EST');

result:

OK
1970-01-18 09:00:35.941
Time taken: 0.448 seconds, Fetched: 1 row(s)

Shouldn't the output be just date plus 4 hours?

Body:
yyyy (and not YYYY)

unix_timestamp returns bigint and to_utc_timestamp considers integer values as milliseconds

select to_utc_timestamp(1000*unix_timestamp("04/24/2017 01:59:01","MM/dd/yyyy HH:mm:ss"),'EST');


问:
Within each td/box, how to make it so the header in each box is fixed with scrollable div beneath?
I have 9 boxes, I want each box to have a "heading", and scrollable content beneath the "Box n" heading.

Am looking for 1) Ensure the "header" is vertically aligned to the top of each box. 2) The scrollable content takes up the max height of each box.

How do I do this? My HTML is the following:

html,
body {
  width: 100%;
  height: 100%;
}

table {
  border: 1;
  width: 100%;
  height: 100%;
}

td {
  text-align: center;
  background: red;
}

div {
  overflow: auto;
  height: 100%;
  background: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>
      <div>
        Box1<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>
    </td>
    <td>
      <div>Box2</div>
      <div>
        Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>
    </td>
    <td>
      <div>
        Box3<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>
    </td>
  </tr>
  <tr>
    <td>Box4</td>
    <td>Box5</td>
    <td>Box6</td>
  </tr>
  <tr>
    <td>Box7</td>
    <td>Box8</td>
    <td>Box9</td>
  </tr>
</table></code>```

The fiddle I have is here:
https://jsfiddle.net/ba5qxzmo/

Box 1 is bad, because the Box1 header text is not "fixed at the top of the box and scrolls with the content.
Box 2 is my attempt at creating a fixed header, but it messes up the look of the box entirely.
Box 3 and the rest of the boxes also do not have a fixed header.

How can I make it such that each box has a "fixed" header? (Box1, Box2, Box3), with scrollable content (overflow) beneath each of them?

答:
like this:</p>

```<code>    <div class="fixed_parent">
        <div class="fixed">
            Some Heading
        </div>
    </div>
    <div class="content">
            Some content
    </div>

 .fixed_parent{
    height:100px; (or if it's depends on height of fixed div and it can changes you can right overflow:hidden; without writhing about height)
  }

 .heading{
    position:fixed;
  }

 .content{
    overflow:scroll;
  }
</code>```

Body:
I have 9 boxes, I want each box to have a "heading", and scrollable content beneath the "Box n" heading.

Am looking for 1) Ensure the "header" is vertically aligned to the top of each box. 2) The scrollable content takes up the max height of each box.

How do I do this? My HTML is the following:

html,
body {
  width: 100%;
  height: 100%;
}

table {
  border: 1;
  width: 100%;
  height: 100%;
}

td {
  text-align: center;
  background: red;
}

div {
  overflow: auto;
  height: 100%;
  background: yellow;
}

        Box1
 Some TExt
 Some TExt
 Some TExt
 Some TExt
Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt

Box2

        Some TExt
 Some TExt
 Some TExt
 Some TExt
Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt

        Box3
 Some TExt
 Some TExt
 Some TExt
 Some TExt
Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt

    Box4
    Box5
    Box6

    Box7
    Box8
    Box9

The fiddle I have is here:
https://jsfiddle.net/ba5qxzmo/

Box 1 is bad, because the Box1 header text is not "fixed at the top of the box and scrolls with the content.
Box 2 is my attempt at creating a fixed header, but it messes up the look of the box entirely.
Box 3 and the rest of the boxes also do not have a fixed header.

How can I make it such that each box has a "fixed" header? (Box1, Box2, Box3), with scrollable content (overflow) beneath each of them?

Body:
like this:

    <div class="fixed_parent">
        <div class="fixed">
            Some Heading
        </div>
    </div>
    <div class="content">
            Some content
    </div>

 .fixed_parent{
    height:100px; (or if it's depends on height of fixed div and it can changes you can right overflow:hidden; without writhing about height)
  }

 .heading{
    position:fixed;
  }

 .content{
    overflow:scroll;
  }


问:
NSUserDefaults: How to get value
I am new in iOS, Object-C and I am trying to do a simple login/registerLogin using NSUserDefaults.

My problem is: How could I access/get the value saved in NSUserDefaults to verify if an user already exist?

This is the code for registering a new user:

```<code>-(void)registerNewUser {

// Getting username and the password
NSString *newUsername = self.usernameRegisterTextField.text;
NSString *newPassword = self.passwordRegisterTextField.text;

// Using NSUserDefaults to storage username and password
NSUserDefaults *newUser = [NSUserDefaults standardUserDefaults];

[newUser setObject:newUsername forKey:@"username"];
[newUser setObject:newPassword forKey:@"password"];
[newUser setBool:YES forKey:@"registered"];

[newUser synchronize];

[self performSegueWithIdentifier:@"registerSucessSegue" sender:nil];
</code>```

}

And I am trying to get the value saved in NSUserDefaults to verify if an user already exist instead of calling the login screen again:

```<code>- (IBAction)productTableButton:(id)sender {
// Verification if an user exist
NSUserDefaults *newUser = [NSUserDefaults standardUserDefaults];

BOOL newUserExist = [newUser valueForKey:@"registered"];

if (newUserExist == YES) {
    [self performSegueWithIdentifier:@"productSegue" sender:nil];
} else {
    [self performSegueWithIdentifier:@"loginSegue" sender:nil];
}
</code>```

}

Is there something that I am doing wrong when I am trying to access the value of an user saved in NSUserDefaults?

答:
Try to get the value by using boolForKey:

BOOL newUserExist = [defaults boolForKey:@"registered"];

Title: NSUserDefaults: How to get value

Body:
I am new in iOS, Object-C and I am trying to do a simple login/registerLogin using NSUserDefaults.

My problem is: How could I access/get the value saved in NSUserDefaults to verify if an user already exist?

This is the code for registering a new user:

-(void)registerNewUser {

// Getting username and the password
NSString *newUsername = self.usernameRegisterTextField.text;
NSString *newPassword = self.passwordRegisterTextField.text;

// Using NSUserDefaults to storage username and password
NSUserDefaults *newUser = [NSUserDefaults standardUserDefaults];

[newUser setObject:newUsername forKey:@"username"];
[newUser setObject:newPassword forKey:@"password"];
[newUser setBool:YES forKey:@"registered"];

[newUser synchronize];

[self performSegueWithIdentifier:@"registerSucessSegue" sender:nil];

}

And I am trying to get the value saved in NSUserDefaults to verify if an user already exist instead of calling the login screen again:

- (IBAction)productTableButton:(id)sender {
// Verification if an user exist
NSUserDefaults *newUser = [NSUserDefaults standardUserDefaults];

BOOL newUserExist = [newUser valueForKey:@"registered"];

if (newUserExist == YES) {
    [self performSegueWithIdentifier:@"productSegue" sender:nil];
} else {
    [self performSegueWithIdentifier:@"loginSegue" sender:nil];
}

}

Is there something that I am doing wrong when I am trying to access the value of an user saved in NSUserDefaults?


问:
Can't get my Ranges set up from my spreadsheet using VBA
My overall goal here is to grab the values and row indices of three different columns on the original spreadsheet, evaluate them, and then save them to a new spreadsheet. I am wanted to accomplish this by using a macro initiated by a button on the original spreadsheet.

The plan to accomplish this was to

create a Range for each column

Loop through the most significant Range to grab and evaluate the each cell      value

perform nested loops within the first loop to further evaluate the other two Ranges and grab their values

assign values to variables

create the new spreadsheet from a template

write the values to the respective columns

save the new spreadsheet

When I run the code below I get the error listed below. I'm confused because I thought this is how you reference an entire column:

```<code>Sub Transfer2NewWorkbook()
  Dim currentsheet As String
  Dim newsheet As String
  Dim analysisDate As String
  Dim initial As String
  Dim aInitial() As String
  Dim analystInit As String
  Dim batchNo As String

  Dim wb As Object
  Dim dataRangeA As Range, dataRangeB As Range, dataRangeI As Range
  Set dataA = CreateObject("Scripting.Dictionary")

  ' Grab and Create filenames
  currentsheet = ActiveWorkbook.Name
  newsheet = currentsheet & "-" & "uploadable"

  ' Grab data from original spreadsheet
  analysisDate = ActiveWorkbook.Sheets(1).Cells(1, 9).Value

  initial = ActiveWorkbook.Sheets(1).Cells(1, 2).Value
  aInitial = Split(initial, "/")
  analystInit = aInitial(1)

  Set dataRangeA = Range("A4:A").Select ' <-- Line causing error
  Set dataRangeB = Range("B4:B").Select
  Set dataRangeI = Range("I4:I").Select

  For i = 1 To dataRangeA.Rows.Count
    dataA.Add Key:=i, Item:=dataRangeA.Cells.Value
  Next i

  Set wb = Workbooks.Add("C:\Users\dalythe\documents\uploadtemp.xlsx")

  ActiveWorkbook.Sheets(1).Cells(3, 2).Value = analysisDate
  ActiveWorkbook.Sheets(1).Cells(3, 4).Value = analystInit

  ActiveWorkbook.SaveAs (newsheet & ".xlsx")

End Sub
</code>```

答:
Your problems with the particular line throwing the error are caused by two things:

"A4:A" is not a valid address in Excel.  You can either use "A:A" for the entire column or define the end of the range, e.g. "A4:A272".

The Range.Select method does not return an object, so Set dataRangeA = Range("A4:A").Select is effectively Set dataRangeA =.

To fix your specific error, you could do something like:

```<code>Set dataRangeA = Range("A4", Cells(Rows.Count, "A").End(xlUp))
</code>```

However, using unqualified Cells and Range and Rows is a dangerous habit to get into once you have more than one worksheet / workbook being used in your code, because those objects default to referring to the ActiveSheet in the ActiveWorkbook and that may not be the one you are expecting it to be.

The code below ensures that each object is qualified, plus makes some other improvements to your code (such as the inevitable out-of-memory error that would arise in populating the Dictionary).

```<code>Sub Transfer2NewWorkbook()
  Dim currentsheet As String
  Dim newsheet As String
  Dim analysisDate As String
  Dim initial As String
  Dim aInitial() As String
  Dim analystInit As String
  Dim batchNo As String

  Dim wb As Object
  Dim dataRangeA As Range, dataRangeB As Range, dataRangeI As Range
  Dim dataA As Object ' declare this, unless you have declared it at a higher
                      ' level scope

  Set dataA = CreateObject("Scripting.Dictionary")

  ' Grab and Create filenames
  currentsheet = ActiveWorkbook.Name
  newsheet = currentsheet & "-" & "uploadable"

  'Use a With block to avoid having to constantly refer
  ' to "ActiveWorkbook.Sheets(1)"
  With ActiveWorkbook.Sheets(1)
    ' Grab data from original spreadsheet
    analysisDate = .Cells(1, 9).Value

    initial = .Cells(1, 2).Value
    aInitial = Split(initial, "/")
    analystInit = aInitial(1)

    Set dataRangeA = .Range("A4", .Cells(.Rows.Count, "A").End(xlUp))
    Set dataRangeB = .Range("B4", .Cells(.Rows.Count, "B").End(xlUp))
    Set dataRangeI = .Range("I4", .Cells(.Rows.Count, "I").End(xlUp))

    'This loop is making every entry in the Dictionary contain the value of
    'every cell in the range - i.e. each of the 1048573 entries in the Dictionary
    'would have contained an array which was dimensioned As (1 To 1048573, 1 To 1)
    'For i = 1 To dataRangeA.Rows.Count
    '  dataA.Add Key:=i, Item:=dataRangeA.Cells.Value
    'Next i
    Dim cel As Range
    For Each cel in dataRangeA
      dataA.Add Key:=cel.Row, Item:=cel.Value
      'or
      'dataA.Add Key:=cel.Row - 3, Item:=cel.Value
      'if you wanted A4's value to have a key of 1
    Next

    'Note: If you just wanted an array of values, you could have used
    '  Dim dataA As Variant
    '  dataA = Application.Transpose(.Range("A4", .Cells(.Rows.Count, "A").End(xlUp)))
    'and then access each value using dataA(1) for the value from A4,
    'dataA(2) for the value from A5, etc.
    'This then gets rid of the need for dataRangeA, and the need for a
    ' dictionary object, and the need for the loop populating the dictionary.
  End With

  Set wb = Workbooks.Add("C:\Users\dalythe\documents\uploadtemp.xlsx")
  With wb.Worksheets(1)

    .Cells(3, 2).Value = analysisDate
    .Cells(3, 4).Value = analystInit

  End With
  wb.SaveAs newsheet & ".xlsx"

End Sub
</code>```

Body:
My overall goal here is to grab the values and row indices of three different columns on the original spreadsheet, evaluate them, and then save them to a new spreadsheet. I am wanted to accomplish this by using a macro initiated by a button on the original spreadsheet.

The plan to accomplish this was to

create a Range for each column

Loop through the most significant Range to grab and evaluate the each cell      value

perform nested loops within the first loop to further evaluate the other two Ranges and grab their values

assign values to variables

create the new spreadsheet from a template

write the values to the respective columns

save the new spreadsheet

When I run the code below I get the error listed below. I'm confused because I thought this is how you reference an entire column:

Sub Transfer2NewWorkbook()
  Dim currentsheet As String
  Dim newsheet As String
  Dim analysisDate As String
  Dim initial As String
  Dim aInitial() As String
  Dim analystInit As String
  Dim batchNo As String

  Dim wb As Object
  Dim dataRangeA As Range, dataRangeB As Range, dataRangeI As Range
  Set dataA = CreateObject("Scripting.Dictionary")

  ' Grab and Create filenames
  currentsheet = ActiveWorkbook.Name
  newsheet = currentsheet & "-" & "uploadable"

  ' Grab data from original spreadsheet
  analysisDate = ActiveWorkbook.Sheets(1).Cells(1, 9).Value

  initial = ActiveWorkbook.Sheets(1).Cells(1, 2).Value
  aInitial = Split(initial, "/")
  analystInit = aInitial(1)

  Set dataRangeA = Range("A4:A").Select ' <-- Line causing error
  Set dataRangeB = Range("B4:B").Select
  Set dataRangeI = Range("I4:I").Select

  For i = 1 To dataRangeA.Rows.Count
    dataA.Add Key:=i, Item:=dataRangeA.Cells.Value
  Next i

  Set wb = Workbooks.Add("C:\Users\dalythe\documents\uploadtemp.xlsx")

  ActiveWorkbook.Sheets(1).Cells(3, 2).Value = analysisDate
  ActiveWorkbook.Sheets(1).Cells(3, 4).Value = analystInit

  ActiveWorkbook.SaveAs (newsheet & ".xlsx")

End Sub

Body:
Your problems with the particular line throwing the error are caused by two things:

"A4:A" is not a valid address in Excel.  You can either use "A:A" for the entire column or define the end of the range, e.g. "A4:A272".

The Range.Select method does not return an object, so Set dataRangeA = Range("A4:A").Select is effectively Set dataRangeA =.

To fix your specific error, you could do something like:

Set dataRangeA = Range("A4", Cells(Rows.Count, "A").End(xlUp))

However, using unqualified Cells and Range and Rows is a dangerous habit to get into once you have more than one worksheet / workbook being used in your code, because those objects default to referring to the ActiveSheet in the ActiveWorkbook and that may not be the one you are expecting it to be.

The code below ensures that each object is qualified, plus makes some other improvements to your code (such as the inevitable out-of-memory error that would arise in populating the Dictionary).

Sub Transfer2NewWorkbook()
  Dim currentsheet As String
  Dim newsheet As String
  Dim analysisDate As String
  Dim initial As String
  Dim aInitial() As String
  Dim analystInit As String
  Dim batchNo As String

  Dim wb As Object
  Dim dataRangeA As Range, dataRangeB As Range, dataRangeI As Range
  Dim dataA As Object ' declare this, unless you have declared it at a higher
                      ' level scope

  Set dataA = CreateObject("Scripting.Dictionary")

  ' Grab and Create filenames
  currentsheet = ActiveWorkbook.Name
  newsheet = currentsheet & "-" & "uploadable"

  'Use a With block to avoid having to constantly refer
  ' to "ActiveWorkbook.Sheets(1)"
  With ActiveWorkbook.Sheets(1)
    ' Grab data from original spreadsheet
    analysisDate = .Cells(1, 9).Value

    initial = .Cells(1, 2).Value
    aInitial = Split(initial, "/")
    analystInit = aInitial(1)

    Set dataRangeA = .Range("A4", .Cells(.Rows.Count, "A").End(xlUp))
    Set dataRangeB = .Range("B4", .Cells(.Rows.Count, "B").End(xlUp))
    Set dataRangeI = .Range("I4", .Cells(.Rows.Count, "I").End(xlUp))

    'This loop is making every entry in the Dictionary contain the value of
    'every cell in the range - i.e. each of the 1048573 entries in the Dictionary
    'would have contained an array which was dimensioned As (1 To 1048573, 1 To 1)
    'For i = 1 To dataRangeA.Rows.Count
    '  dataA.Add Key:=i, Item:=dataRangeA.Cells.Value
    'Next i
    Dim cel As Range
    For Each cel in dataRangeA
      dataA.Add Key:=cel.Row, Item:=cel.Value
      'or
      'dataA.Add Key:=cel.Row - 3, Item:=cel.Value
      'if you wanted A4's value to have a key of 1
    Next

    'Note: If you just wanted an array of values, you could have used
    '  Dim dataA As Variant
    '  dataA = Application.Transpose(.Range("A4", .Cells(.Rows.Count, "A").End(xlUp)))
    'and then access each value using dataA(1) for the value from A4,
    'dataA(2) for the value from A5, etc.
    'This then gets rid of the need for dataRangeA, and the need for a
    ' dictionary object, and the need for the loop populating the dictionary.
  End With

  Set wb = Workbooks.Add("C:\Users\dalythe\documents\uploadtemp.xlsx")
  With wb.Worksheets(1)

    .Cells(3, 2).Value = analysisDate
    .Cells(3, 4).Value = analystInit

  End With
  wb.SaveAs newsheet & ".xlsx"

End Sub


问:
AWS Lambda becomes unresponsive after TypeError (Node.js 4.3)
I'm using AWS Lambda with Node.js 4.3, and has DynamoDB get in the code:

```<code>dynamodb.get(params, function(err, data) {
    if (err) {
        console.log("Error: " + JSON.stringify(err));
        callback("Error: DB problem");
    }
    else {
            callback(null, data.Item.someAttribute);
    }
});
</code>```

I know that it's wrong, and I need to check that Item actually exists before accessing it. That's not the point now.

I get TypeError:
TypeError: Cannot read property 'someAttribute' of undefined

Which is ok, when there is no such item, it fails. The problem that after that lambda became to be unresponsive, there are other healthy requests come to that lambda, and lambda just fails every time with timeout.
As you can see in the logs below (from CloudWatch) even 40(!) minutes after the error, the lambda is still unresponsive. And I know nothing happens there, as in the beginning if the code I'm printing "Input to Lambda" which can be seen in first request. In all times out requests there is no such print, Lambda just became dead.

```<code>START RequestId: xxx Version: 1
2017-05-12T09:20:18.739Z    Input to Lambda: ...
2017-05-12T09:20:19.770Z    xxx TypeError: Cannot read property 'someAttribute' of undefined at ...
END RequestId: xxx
REPORT RequestId: xxx   Duration: 1094.61 ms    Billed Duration: 1100 ms
RequestId: xxx Process exited before completing request

START RequestId: xxx Version: 1
END RequestId: xxx
REPORT RequestId: xxx   Duration: 3002.12 ms    Billed Duration: 3000 ms
2017-05-12T09:24:08.556Z xxx Task timed out after 3.00 seconds

...

START RequestId: xxx Version: 1
END RequestId: xxx
REPORT RequestId: xxx   Duration: 3001.15 ms    Billed Duration: 3000 ms
2017-05-12T10:01:14.672Z xxx Task timed out after 3.00 seconds
</code>```

Fixing the code and reuploading it to the Lambda makes it working, but how can this be that some error make the whole endpoint unresponsive. Waiting some hours also makes Lambda work again.
I'm thinking of removing "use strict", but it doesn't look like a good solution.
Any thoughts on what can be the reason to dead lambda and how to avoid this in future?

答:
In fact there are many cases when Lambda becomes unresponsive, e.g.:

Parsing not valid json:

```<code>exports.handler = function(event, context, callback)
{
    var nonValidJson = "Not even Json";
    var jsonParse = JSON.parse(nonValidJson);
</code>```

Accessing property of undefined variable:

```<code>exports.handler = function(event, context, callback)
{
    var emptyObject = {};
    var value = emptyObject.Item.Key;
</code>```

Not closing mySql connection after accessing RDS leads to Lambda timeout and then it becomes non-responsive.

It's revealed that it's a bug, known by AWS team for almost a year:

https://forums.aws.amazon.com/thread.jspa?threadID=238434&tstart=0

Unfortunately it's still not fixed, after some tests it's revealed that in fact Lambda tries to restart (reload the container?), there is just not enough time. If you set the timeout to be 10s, after ~4s of execution time Lambda starts working, and then in next runs comes to behave normally. I've also tried playing with setting:

```<code>context.callbackWaitsForEmptyEventLoop = false;
</code>```

and putting all 'require' blocks inside handler, nothing really worked. The only way to prevent Lambda becoming dead is setting bigger timeout, 10s should be more than enough as a workaround protection against this bug.

Body:
I'm using AWS Lambda with Node.js 4.3, and has DynamoDB get in the code:

dynamodb.get(params, function(err, data) {
    if (err) {
        console.log("Error: " + JSON.stringify(err));
        callback("Error: DB problem");
    }
    else {
            callback(null, data.Item.someAttribute);
    }
});

I know that it's wrong, and I need to check that Item actually exists before accessing it. That's not the point now.

I get TypeError:
TypeError: Cannot read property 'someAttribute' of undefined

Which is ok, when there is no such item, it fails. The problem that after that lambda became to be unresponsive, there are other healthy requests come to that lambda, and lambda just fails every time with timeout.
As you can see in the logs below (from CloudWatch) even 40(!) minutes after the error, the lambda is still unresponsive. And I know nothing happens there, as in the beginning if the code I'm printing "Input to Lambda" which can be seen in first request. In all times out requests there is no such print, Lambda just became dead.

START RequestId: xxx Version: 1
2017-05-12T09:20:18.739Z    Input to Lambda: ...
2017-05-12T09:20:19.770Z    xxx TypeError: Cannot read property 'someAttribute' of undefined at ...
END RequestId: xxx
REPORT RequestId: xxx   Duration: 1094.61 ms    Billed Duration: 1100 ms
RequestId: xxx Process exited before completing request

START RequestId: xxx Version: 1
END RequestId: xxx
REPORT RequestId: xxx   Duration: 3002.12 ms    Billed Duration: 3000 ms
2017-05-12T09:24:08.556Z xxx Task timed out after 3.00 seconds

...

START RequestId: xxx Version: 1
END RequestId: xxx
REPORT RequestId: xxx   Duration: 3001.15 ms    Billed Duration: 3000 ms
2017-05-12T10:01:14.672Z xxx Task timed out after 3.00 seconds

Fixing the code and reuploading it to the Lambda makes it working, but how can this be that some error make the whole endpoint unresponsive. Waiting some hours also makes Lambda work again.
I'm thinking of removing "use strict", but it doesn't look like a good solution.
Any thoughts on what can be the reason to dead lambda and how to avoid this in future?

Body:
In fact there are many cases when Lambda becomes unresponsive, e.g.:

Parsing not valid json:

exports.handler = function(event, context, callback)
{
    var nonValidJson = "Not even Json";
    var jsonParse = JSON.parse(nonValidJson);

Accessing property of undefined variable:

exports.handler = function(event, context, callback)
{
    var emptyObject = {};
    var value = emptyObject.Item.Key;

Not closing mySql connection after accessing RDS leads to Lambda timeout and then it becomes non-responsive.

It's revealed that it's a bug, known by AWS team for almost a year:

https://forums.aws.amazon.com/thread.jspa?threadID=238434&tstart=0

Unfortunately it's still not fixed, after some tests it's revealed that in fact Lambda tries to restart (reload the container?), there is just not enough time. If you set the timeout to be 10s, after ~4s of execution time Lambda starts working, and then in next runs comes to behave normally. I've also tried playing with setting:

context.callbackWaitsForEmptyEventLoop = false;

and putting all 'require' blocks inside handler, nothing really worked. The only way to prevent Lambda becoming dead is setting bigger timeout, 10s should be more than enough as a workaround protection against this bug.


问:
Opening Magnific popup using API shows no images
When I try to open a Magnific popup using the API, nothing is displayed other than the overlay.  In this code I want to display the two images in the href in the gallery.

$(document).ready(function() {
  $.magnificPopup.open({
    items: {
      src: '#gallery'
    },
    type: 'inline'
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.min.js"></script>

<div id='gallery' class="popup-gallery">

</div></code>```

答:
A way to achieve   your result is to built the items as an array of objects:

var itemsVal = $('#gallery a').map(function(idx, ele) {
    return {src: $(ele).attr('href'), type: 'image'};
}).get();
$.magnificPopup.open({
    items: itemsVal,
    gallery:{
        enabled:true
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.min.js"></script>

<div id='gallery' class="popup-gallery">

</div></code>```

Body:
When I try to open a Magnific popup using the API, nothing is displayed other than the overlay.  In this code I want to display the two images in the href in the gallery.

$(document).ready(function() {
  $.magnificPopup.open({
    items: {
      src: '#gallery'
    },
    type: 'inline'
  });
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css" rel="stylesheet" />

Body:
A way to achieve   your result is to built the items as an array of objects:

var itemsVal = $('#gallery a').map(function(idx, ele) {
    return {src: $(ele).attr('href'), type: 'image'};
}).get();
$.magnificPopup.open({
    items: itemsVal,
    gallery:{
        enabled:true
    }
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.min.js"></script>

<div id='gallery' class="popup-gallery">
    <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Planets_and_sun_size_comparison.jpg/640px-Planets_and_sun_size_comparison.jpg" title="Image 1"></a>
    <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Telluric_planets_size_comparison.jpg/640px-Telluric_planets_size_comparison.jpg" title="Image 2"></a>
</div>


问:
GRAILS + Spring Security Plugin --- password is not encrypted when adding users
Clean installation of Grails 3.2.9 + Spring Security Plugin 3.1.0.

Default User/Role/UserRole domains created by s2-quickstart com.raf.app User Role.

BootStrap init code:

```<code>...
def init = { servletContext ->
    def adminRole = Role.findOrSaveWhere(authority: 'ROLE_ADMIN')
    def user = User.findOrSaveWhere(username: 'raf',
            password: 'password')
    if (!user.authorities.contains(adminRole)){
        UserRole.create(user, adminRole)
    }
...
</code>```

I saw in a tutorial that the password for this user should appear encoded in the db (using dbconsole to check this out), but in my case it does not (it's just 'password' like in here).

So I went to the User domain and made these horrible changes:

```<code>def beforeUpdate() {
        encodePassword()
    }

    protected void encodePassword() {
        password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : springSecurityService.encodePassword(password)
    }
</code>```

And this on the other hand throws NullPointer exception. Why?

```<code> Cannot invoke method encodePassword() on null object
</code>```

So what do I do to have my passwords encrypted, like I like 'em?

答:
Okay, so I believe the NullPointer was caused by what vahid described.

However, to have my passwords encoded by default, I had to set

```<code>autowire: true
</code>```

in Configs/application.yml. Don't ask me why, but it works.

ContentLicense: CC BY-SA 4.0

Body:
Clean installation of Grails 3.2.9 + Spring Security Plugin 3.1.0.

Default User/Role/UserRole domains created by s2-quickstart com.raf.app User Role.

BootStrap init code:

...
def init = { servletContext ->
    def adminRole = Role.findOrSaveWhere(authority: 'ROLE_ADMIN')
    def user = User.findOrSaveWhere(username: 'raf',
            password: 'password')
    if (!user.authorities.contains(adminRole)){
        UserRole.create(user, adminRole)
    }
...

I saw in a tutorial that the password for this user should appear encoded in the db (using dbconsole to check this out), but in my case it does not (it's just 'password' like in here).

So I went to the User domain and made these horrible changes:

def beforeUpdate() {
        encodePassword()
    }

    protected void encodePassword() {
        password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : springSecurityService.encodePassword(password)
    }

And this on the other hand throws NullPointer exception. Why?

 Cannot invoke method encodePassword() on null object

So what do I do to have my passwords encrypted, like I like 'em?

Body:
Okay, so I believe the NullPointer was caused by what vahid described.

However, to have my passwords encoded by default, I had to set

autowire: true

in Configs/application.yml. Don't ask me why, but it works.


问:
Writing a C program to call another program without using any built-in libraries
I am trying to write a simple 'go-command' for boot-loader that takes me to specific address in RAM say 0x18000000 and it should execute a program that blinks led. I have two .c files say led.c and go.c in which led.c blinks two leds. But I am wondering and don't know that how can I pass a control/invoke its main() to this go.c file to go to that address and start blinking leds? But it should be done without including other header files, libraries, etc. Kindly help me!! Thanks in advance. Below code is for led.c

```<code>void delay ()
{
    volatile int i;
    for(i=0;i<1000000;i++)
    {}

}
int main(void)
{
    *led0=0;
    *led1=0;
    while(1)
    {
        *led0=1;
        delay();
        *led0=0;
        *led1=1;
        delay();
        *led1=0;
    }
}
</code>```

In my go.c file I want to pass a control to invoke this led.c main() func

答:
There is a lot you have omitted that is likely to be relevant, but taken at face value, you simply declare a function pointer, initialised with the absolute address and invoke the function through that pointer.

However it may not be that simple since the called program will use the C run-time environment of the calling program; any global static objects will not be initialised  - you need to call the program entry point (which is notmain()) to establish the run-time environment expected by the program.  In simple case it may work or appear to work to some extent.

Body:
I am trying to write a simple 'go-command' for boot-loader that takes me to specific address in RAM say 0x18000000 and it should execute a program that blinks led. I have two .c files say led.c and go.c in which led.c blinks two leds. But I am wondering and don't know that how can I pass a control/invoke its main() to this go.c file to go to that address and start blinking leds? But it should be done without including other header files, libraries, etc. Kindly help me!! Thanks in advance. Below code is for led.c

void delay ()
{
    volatile int i;
    for(i=0;i<1000000;i++)
    {}

}
int main(void)
{
    *led0=0;
    *led1=0;
    while(1)
    {
        *led0=1;
        delay();
        *led0=0;
        *led1=1;
        delay();
        *led1=0;
    }
}

In my go.c file I want to pass a control to invoke this led.c main() func


问:
Netty + NioDatagram(UDP) + ProtoBuf issue - Discarded inbound message DatagramPacket
I am trying to build a UDP server using netty with NioDatagramChannel and protoBuf as the message. Here is the server implementation:

```<code>EventLoopGroup group = new NioEventLoopGroup();
try {
  Bootstrap b = new Bootstrap();
  b.group(group)
      .channel(NioDatagramChannel.class)
      .option(ChannelOption.SO_BROADCAST, true)
      .handler(new UdpProtoBufServerChannelInitializer());

  b.bind(port).sync().channel().closeFuture().await();
} finally {
  group.shutdownGracefully();
}
</code>```

UdpProtoBufServerChannelInitializer:

```<code>public class UdpProtoBufServerChannelInitializer extends ChannelInitializer<NioDatagramChannel> {

    static final Logger logger = Logger.getLogger(UdpProtoBufServerChannelInitializer.class);
    @Override
      protected void initChannel(NioDatagramChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();
        p.addFirst(new ProtobufVarint32FrameDecoder());
        p.addFirst(new ProtobufDecoder(Message.getDefaultInstance()));
        p.addFirst(new ProtobufVarint32LengthFieldPrepender());
        p.addFirst(new ProtobufEncoder());

        p.addFirst(new UdpProtoBufServerHandler());
    }
  }
</code>```

However, I am seeing the following error after receiving message from java client before running UdpProtoBufServerChannelInitializer.

DEBUG DefaultChannelPipeline:76 - Discarded inbound message DatagramPacket(/127.0.0.1:60556 => 0.0.0.0/0.0.0.0:55559, PooledUnsafeHeapByteBuf(ridx: 0, widx: 34, cap: 2048)) that reached at the tail of the pipeline. Please check your pipeline configuration.

Also, not sure if this exception when launching the application is related:

```<code>    2017-05-22 14:31:09 DEBUG PlatformDependent0:91 - jdk.internal.misc.Unsafe.allocateUninitializedArray(int): unavailable
java.lang.ClassNotFoundException: jdk.internal.misc.Unsafe
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at io.netty.util.internal.PlatformDependent0$6.run(PlatformDependent0.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at io.netty.util.internal.PlatformDependent0.<clinit>(PlatformDependent0.java:288)
    at io.netty.util.internal.PlatformDependent.getSystemClassLoader(PlatformDependent.java:895)
    at io.netty.util.internal.PlatformDependent.isAndroid0(PlatformDependent.java:919)
    at io.netty.util.internal.PlatformDependent.<clinit>(PlatformDependent.java:70)
    at io.netty.util.ConstantPool.<init>(ConstantPool.java:32)
    at io.netty.util.Signal$1.<init>(Signal.java:27)
    at io.netty.util.Signal.<clinit>(Signal.java:27)
    at io.netty.util.concurrent.DefaultPromise.<clinit>(DefaultPromise.java:43)
    at io.netty.util.concurrent.MultithreadEventExecutorGroup.<init>(MultithreadEventExecutorGroup.java:36)
    at io.netty.util.concurrent.MultithreadEventExecutorGroup.<init>(MultithreadEventExecutorGroup.java:58)
    at io.netty.channel.MultithreadEventLoopGroup.<init>(MultithreadEventLoopGroup.java:52)
    at io.netty.channel.nio.NioEventLoopGroup.<init>(NioEventLoopGroup.java:87)
    at io.netty.channel.nio.NioEventLoopGroup.<init>(NioEventLoopGroup.java:82)
    at io.netty.channel.nio.NioEventLoopGroup.<init>(NioEventLoopGroup.java:63)
    at io.netty.channel.nio.NioEventLoopGroup.<init>(NioEventLoopGroup.java:51)
    at io.netty.channel.nio.NioEventLoopGroup.<init>(NioEventLoopGroup.java:43)
</code>```

答:
Thanks all. I figured out the way to do this, finally:

```<code>public class DatagramServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
      Message message = SocketProtos.Message.parseFrom(packet.content().nioBuffer());
      ctx.writeAndFlush(packet.retain());
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
      cause.printStackTrace();
      ctx.close();
   }
}
</code>```

Just use the NioDatagram UDP standard implementation and then parse the message into byte[] to ProtoBuf message.

Body:
I am trying to build a UDP server using netty with NioDatagramChannel and protoBuf as the message. Here is the server implementation:

EventLoopGroup group = new NioEventLoopGroup();
try {
  Bootstrap b = new Bootstrap();
  b.group(group)
      .channel(NioDatagramChannel.class)
      .option(ChannelOption.SO_BROADCAST, true)
      .handler(new UdpProtoBufServerChannelInitializer());

  b.bind(port).sync().channel().closeFuture().await();
} finally {
  group.shutdownGracefully();
}

UdpProtoBufServerChannelInitializer:

public class UdpProtoBufServerChannelInitializer extends ChannelInitializer<NioDatagramChannel> {

    static final Logger logger = Logger.getLogger(UdpProtoBufServerChannelInitializer.class);
    @Override
      protected void initChannel(NioDatagramChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();
        p.addFirst(new ProtobufVarint32FrameDecoder());
        p.addFirst(new ProtobufDecoder(Message.getDefaultInstance()));
        p.addFirst(new ProtobufVarint32LengthFieldPrepender());
        p.addFirst(new ProtobufEncoder());

        p.addFirst(new UdpProtoBufServerHandler());
    }
  }

However, I am seeing the following error after receiving message from java client before running UdpProtoBufServerChannelInitializer.

DEBUG DefaultChannelPipeline:76 - Discarded inbound message DatagramPacket(/127.0.0.1:60556 => 0.0.0.0/0.0.0.0:55559, PooledUnsafeHeapByteBuf(ridx: 0, widx: 34, cap: 2048)) that reached at the tail of the pipeline. Please check your pipeline configuration.

Also, not sure if this exception when launching the application is related:

    2017-05-22 14:31:09 DEBUG PlatformDependent0:91 - jdk.internal.misc.Unsafe.allocateUninitializedArray(int): unavailable
java.lang.ClassNotFoundException: jdk.internal.misc.Unsafe
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at io.netty.util.internal.PlatformDependent0$6.run(PlatformDependent0.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at io.netty.util.internal.PlatformDependent0.<clinit>(PlatformDependent0.java:288)
    at io.netty.util.internal.PlatformDependent.getSystemClassLoader(PlatformDependent.java:895)
    at io.netty.util.internal.PlatformDependent.isAndroid0(PlatformDependent.java:919)
    at io.netty.util.internal.PlatformDependent.<clinit>(PlatformDependent.java:70)
    at io.netty.util.ConstantPool.<init>(ConstantPool.java:32)
    at io.netty.util.Signal$1.<init>(Signal.java:27)
    at io.netty.util.Signal.<clinit>(Signal.java:27)
    at io.netty.util.concurrent.DefaultPromise.<clinit>(DefaultPromise.java:43)
    at io.netty.util.concurrent.MultithreadEventExecutorGroup.<init>(MultithreadEventExecutorGroup.java:36)
    at io.netty.util.concurrent.MultithreadEventExecutorGroup.<init>(MultithreadEventExecutorGroup.java:58)
    at io.netty.channel.MultithreadEventLoopGroup.<init>(MultithreadEventLoopGroup.java:52)
    at io.netty.channel.nio.NioEventLoopGroup.<init>(NioEventLoopGroup.java:87)
    at io.netty.channel.nio.NioEventLoopGroup.<init>(NioEventLoopGroup.java:82)
    at io.netty.channel.nio.NioEventLoopGroup.<init>(NioEventLoopGroup.java:63)
    at io.netty.channel.nio.NioEventLoopGroup.<init>(NioEventLoopGroup.java:51)
    at io.netty.channel.nio.NioEventLoopGroup.<init>(NioEventLoopGroup.java:43)

Body:
Thanks all. I figured out the way to do this, finally:

public class DatagramServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
      Message message = SocketProtos.Message.parseFrom(packet.content().nioBuffer());
      ctx.writeAndFlush(packet.retain());
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
      cause.printStackTrace();
      ctx.close();
   }
}

Just use the NioDatagram UDP standard implementation and then parse the message into byte[] to ProtoBuf message.


问:
UITableViewCell UIView Alignment issue
I design custom table view cell. When I scroll TableView then Cell View move x position of the first and last cell. Any idea why this problem has occurred.?

I put some code and image for your understanding the problems.

```<code>public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CreateQuestionViewCell
        //let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CreateQuestionViewCell

        //let subview = cell.viewWithTag(1)!

        //let textDetail = cell.viewWithTag(2) as! UILabel
        cell.quesLbl.text = ((arrTableData[indexPath.row] as! Question).que).convertHTMLtoSymbols()

        //let edit = cell.viewWithTag(3) as? UIButton
        cell.editBtn.tag = indexPath.row
        cell.editBtn.addTarget(self, action: #selector(EditButActions(sender:)), for: .touchUpInside)

        //let deleteBut = cell.viewWithTag(4) as? UIButton
        cell.deleteBtn.tag = indexPath.row
        cell.deleteBtn.addTarget(self, action: #selector(deleteButActions(sender:)), for: .touchUpInside)

        if NotEditable {
            cell.editBtn.isHidden = true
            cell.deleteBtn.isHidden = true
        } else {
            cell.editBtn.isHidden = false
            cell.deleteBtn.isHidden = false
        }
        cell.quesLbl.font = UIFont(name: "Roboto-Regular", size: 14)!
        let desiredWidth: CGFloat = UIScreen.main.bounds.size.width - 60
        let size: CGSize = cell.quesLbl.sizeThatFits(CGSize.init(width: desiredWidth, height: CGFloat.greatestFiniteMagnitude))
        cell.quesLbl.numberOfLines = 0
        cell.quesLbl.lineBreakMode = NSLineBreakMode.byWordWrapping
        if NotEditable {
            cell.subview.frame = CGRect.init(x: 10, y: 10, width: Int(UIScreen.main.bounds.width - 40), height: Int(20 + size.height))
        } else {
            cell.subview.frame = CGRect.init(x: 10, y: 10, width: Int(UIScreen.main.bounds.width - 40), height: Int(50 + size.height))
        }
        cell.subview.layer.cornerRadius = 2.0
        cell.subview.layer.borderWidth = 1.0
        cell.subview.layer.borderColor = UIColor.clear.cgColor
        // SubView.layer.masksToBounds = true;

        cell.subview.layer.shadowColor = UIColor.init(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1).cgColor
        cell.subview.layer.shadowOffset = CGSize.init(width: 0.5, height: 0.5)
        cell.subview.layer.shadowRadius = 2.0
        cell.subview.layer.shadowOpacity = 1.0
        cell.subview.layer.masksToBounds = false
        //cell.subview.layer.shadowPath = UIBezierPath(roundedRect: cell.subview.bounds, cornerRadius: cell.subview.layer.cornerRadius).cgPath
        cell.layoutIfNeeded()
        return cell
    }
</code>```

答:
So, remember that the cells are reused, and anytime you add anything to a cell in cellForRowAt:, you are adding it to every subsequent cell that is displayed by the table.

Set up everything you can in the storyboard cell prototype. Add the buttons and subviews, set the targets, and add any constraints using the storyboard interface builder.

Then in cellForRowAt:, you'll just need to set anything that changes from cell to cell, text strings in labels or images in image views... If you use buttons in the cell, continue to set the button tag like cell.editBtn.tag = indexPath.row, so as to identify the cell in the buttons target function. However, avoid changing the cell directly in the target function, rather get the data from the data source based on the tag, and use reloadData to redraw the table.

Hope this helps.

Title: UITableViewCell UIView Alignment issue

Body:
I design custom table view cell. When I scroll TableView then Cell View move x position of the first and last cell. Any idea why this problem has occurred.?

I put some code and image for your understanding the problems.

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CreateQuestionViewCell
        //let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CreateQuestionViewCell

        //let subview = cell.viewWithTag(1)!

        //let textDetail = cell.viewWithTag(2) as! UILabel
        cell.quesLbl.text = ((arrTableData[indexPath.row] as! Question).que).convertHTMLtoSymbols()

        //let edit = cell.viewWithTag(3) as? UIButton
        cell.editBtn.tag = indexPath.row
        cell.editBtn.addTarget(self, action: #selector(EditButActions(sender:)), for: .touchUpInside)

        //let deleteBut = cell.viewWithTag(4) as? UIButton
        cell.deleteBtn.tag = indexPath.row
        cell.deleteBtn.addTarget(self, action: #selector(deleteButActions(sender:)), for: .touchUpInside)

        if NotEditable {
            cell.editBtn.isHidden = true
            cell.deleteBtn.isHidden = true
        } else {
            cell.editBtn.isHidden = false
            cell.deleteBtn.isHidden = false
        }
        cell.quesLbl.font = UIFont(name: "Roboto-Regular", size: 14)!
        let desiredWidth: CGFloat = UIScreen.main.bounds.size.width - 60
        let size: CGSize = cell.quesLbl.sizeThatFits(CGSize.init(width: desiredWidth, height: CGFloat.greatestFiniteMagnitude))
        cell.quesLbl.numberOfLines = 0
        cell.quesLbl.lineBreakMode = NSLineBreakMode.byWordWrapping
        if NotEditable {
            cell.subview.frame = CGRect.init(x: 10, y: 10, width: Int(UIScreen.main.bounds.width - 40), height: Int(20 + size.height))
        } else {
            cell.subview.frame = CGRect.init(x: 10, y: 10, width: Int(UIScreen.main.bounds.width - 40), height: Int(50 + size.height))
        }
        cell.subview.layer.cornerRadius = 2.0
        cell.subview.layer.borderWidth = 1.0
        cell.subview.layer.borderColor = UIColor.clear.cgColor
        // SubView.layer.masksToBounds = true;

        cell.subview.layer.shadowColor = UIColor.init(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1).cgColor
        cell.subview.layer.shadowOffset = CGSize.init(width: 0.5, height: 0.5)
        cell.subview.layer.shadowRadius = 2.0
        cell.subview.layer.shadowOpacity = 1.0
        cell.subview.layer.masksToBounds = false
        //cell.subview.layer.shadowPath = UIBezierPath(roundedRect: cell.subview.bounds, cornerRadius: cell.subview.layer.cornerRadius).cgPath
        cell.layoutIfNeeded()
        return cell
    }


问:
DataTables API - ColumnDefs and Render
Without the ColumnnDefs + Rendering function, it works and renders the table correctly. With the ColumnDefs + Render I get the following error. The version of datatables I'm using is located at http://rawgit.com/DataTables/DataTables/master/media/js/jquery.dataTables.js</p>

```<code> Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined
        at _fnCreateTr (jquery.dataTables.js:3115)
        at _fnAddData (jquery.dataTables.js:2434)
        at HTMLTableRowElement.<anonymous> (jquery.dataTables.js:2462)
        at jquery-2.1.1.js:144
        at Function.map (jquery-2.1.1.js:468)
        at jQuery.fn.init.map (jquery-2.1.1.js:143)
        at _fnAddTr (jquery.dataTables.js:2460)
        at loadedInit (jquery.dataTables.js:1307)
        at HTMLTableElement.<anonymous> (jquery.dataTables.js:1332)
        at Function.each (jquery-2.1.1.js:375)

<script>
                $(document).ready(function () {

                    $('#main_table').DataTable(
                        {
                            'fixedHeader': true,
                            'order': [[14, 'desc']],
                            'aoColumns': [
                                null,
                                null,
                                null,
                                null,
                                null,
                                null,
                                null,
                                null,
                                null,
                                null,
                                null,
                                null,
                                null,
                                null,
                                null,
                                null,
                                null
                            ],
                            'columnDefs': [{
                                'render': function (data, type, row) {
                                    //add case logic to convert 0 to 'N' and 1 to 'Y' in Exclude field
                                    if (data == row["Exclude"] && data != null)
                                        if (data == "1") {
                                            return "Y";
                                        } else {
                                            return "N";
                                        }
                                    }
                                },
                                "targets": 17
                            }
                            ]
                        }

                        );

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

答:
You have 17 columns (17 entries in aoColumns array) but using "targets": 17 which targets 18th column because it is interpreted as zero-based index.

Change "targets": 17 to "targets": 16 to target the cell in the last column.

Title: DataTables API - ColumnDefs and Render

Body:
Without the ColumnnDefs + Rendering function, it works and renders the table correctly. With the ColumnDefs + Render I get the following error. The version of datatables I'm using is located at http://rawgit.com/DataTables/DataTables/master/media/js/jquery.dataTables.js

 Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined
        at _fnCreateTr (jquery.dataTables.js:3115)
        at _fnAddData (jquery.dataTables.js:2434)
        at HTMLTableRowElement.<anonymous> (jquery.dataTables.js:2462)
        at jquery-2.1.1.js:144
        at Function.map (jquery-2.1.1.js:468)
        at jQuery.fn.init.map (jquery-2.1.1.js:143)
        at _fnAddTr (jquery.dataTables.js:2460)
        at loadedInit (jquery.dataTables.js:1307)
        at HTMLTableElement.<anonymous> (jquery.dataTables.js:1332)
        at Function.each (jquery-2.1.1.js:375)


问:
Django autocomplete light queryset filter
models

```<code>class Reservation(models.Model):
    company = models.ForeignKey(GuestContact, on_delete=models.PROTECT)

class GuestContact(models.Model):
    company = models.CharField(max_lenght=30)
    last_name = models.CharField(max_lenght=30)
    first_name = models.CharField(max_lenght=30)
    contact_genere_id = models.ForeignKey(ContactGenere, on_delete=models.PROTECT) # 1 = company 2 = guest
</code>```

form

```<code>class ReservationForm(ModelForm):

    class Meta:
        model = Reservation
        fields = '__all__'
        widgets = {
            'company': autocomplete.ModelSelect2()
    }
</code>```

views

```<code>class GuestContactAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):

    qs = GuestContact.objects.filter(contact_genere_id=1)

    return qs
</code>```

this QuerySet filter works in python shell, in my views this not work i see all contacts not only company contacts. Can you help me ?

答:
I think that you need an url for you view:
something like this:

```<code>from .views import GuestContactAutocomplete

urlpatterns = [
    url(
        r'^guest-contact-autocomplete/$',
        GuestContactAutocomplete.as_view(),
        name='guest-contact-autocomplete'
    ),
]
</code>```

To then in the form, set this url name to the form field widget, like this:

```<code>class ReservationForm(ModelForm):

class Meta:
    model = Reservation
    fields = '__all__'
    widgets = {
        'company': autocomplete.ModelSelect2(url='guest-contact-autocomplete')
}
</code>```

Body:
models

class Reservation(models.Model):
    company = models.ForeignKey(GuestContact, on_delete=models.PROTECT)

class GuestContact(models.Model):
    company = models.CharField(max_lenght=30)
    last_name = models.CharField(max_lenght=30)
    first_name = models.CharField(max_lenght=30)
    contact_genere_id = models.ForeignKey(ContactGenere, on_delete=models.PROTECT) # 1 = company 2 = guest

form

class ReservationForm(ModelForm):

    class Meta:
        model = Reservation
        fields = '__all__'
        widgets = {
            'company': autocomplete.ModelSelect2()
    }

views

class GuestContactAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):

    qs = GuestContact.objects.filter(contact_genere_id=1)

    return qs

this QuerySet filter works in python shell, in my views this not work i see all contacts not only company contacts. Can you help me ?

Body:
I think that you need an url for you view:
something like this:

from .views import GuestContactAutocomplete

urlpatterns = [
    url(
        r'^guest-contact-autocomplete/$',
        GuestContactAutocomplete.as_view(),
        name='guest-contact-autocomplete'
    ),
]

To then in the form, set this url name to the form field widget, like this:

class ReservationForm(ModelForm):

class Meta:
    model = Reservation
    fields = '__all__'
    widgets = {
        'company': autocomplete.ModelSelect2(url='guest-contact-autocomplete')
}


问:
Creating an IONIC Project without using sudo [MacOS]
I am facing problems everyday where i have to create a project using sudo and then when i add plugins or cocoapods it gives errors related to root users. How to add permissions that will be set once and for all and i don't have to use sudo for every action.</p>

答:
How to add permissions that will be set once and for all and i don't have to use sudo for every action.

This is a very bad practice and poses huge security concerns!

Anyone could have you install a specific malevolent package that could make changes or even even downright harm your system, steal information, etc.

You usually only need sudo to add packages globally. For adding them per project, which is what you usually do, you don't need sudo.

For example to create a new Ionic project, as you are asking in the title, you have to run in your terminal:

ionic start myNewProject tabs

and you don't need sudo for that.

I strongly suggest you let the system ask you to authenticate yourself whenever it needs elevated privileges.


问:
using sprintf to print out stings on a LCD how can i use a percent sign in this function
Hello I am new to most coding and i am writing code onto PSoC4 creator for PSoC 3 chip that uses sprintf to display a string to LCD but my function looks like

```<code>sprintf(line1Str,"Local T" );           //TOP row of LCD
sprintf(line2Str,"TL=%.1f", CurrentTemp ) //Bottom row of LCD
</code>```

My problem is that i want to be able to display the % sign in this as well as floating point.
I have tried the special character stuff like Char38 and so forth and leaving white space and such but it seams to skip when i have this style of format. can anyone help me?

答:
To display the % character in a string created or outputted by a  printf-family function, use the %% escape sequence:

```<code>printf("Your grade is 100%% on this assignment\n");
</code>```

Output:

```<code>Your grade is 100% on this assignment
</code>```

See this page, particularly the last entry in the first table:

A % followed by another % character will write a single % to the stream.

Body:
Hello I am new to most coding and i am writing code onto PSoC4 creator for PSoC 3 chip that uses sprintf to display a string to LCD but my function looks like

sprintf(line1Str,"Local T" );           //TOP row of LCD
sprintf(line2Str,"TL=%.1f", CurrentTemp ) //Bottom row of LCD

My problem is that i want to be able to display the % sign in this as well as floating point.
I have tried the special character stuff like Char38 and so forth and leaving white space and such but it seams to skip when i have this style of format. can anyone help me?

Body:
To display the % character in a string created or outputted by a  printf-family function, use the %% escape sequence:

printf("Your grade is 100%% on this assignment\n");

Output:

Your grade is 100% on this assignment

See this page, particularly the last entry in the first table:

A % followed by another % character will write a single % to the stream.


问:
Consumer<T> mapped Class<T> in HashMap
I want to create an IdentityHashMap<Class<T>, Consumer<T>>. Basically, I want to map a type with a method saying what to do with this type.

I want to dynamically be able to say with objects X, execute Y. I can do

```<code>private IdentityHashMap<Class<?>, Consumer<?>> interceptor = new IdentityHashMap<>();
</code>```

but it sucks because then I have to cast the object in the lamba when using it.

Example:

```<code>interceptor.put(Train.class, train -> {
    System.out.println(((Train)train).getSpeed());
});
</code>```

What I would like to do is

```<code>private <T> IdentityHashMap<Class<T>, Consumer<T>> interceptor = new IdentityHashMap<>();
</code>```

But it doesn't seem to be allowed. Is there a way to do this ? What is the best workaround to map types with a method for this type ?

答:
This is essentially just like the type-safe heterogeneous container described by Joshua Bloch, except you can't use the Class to cast the result.

Weirdly, I can't find a great example existing on SO, so here is one:

```<code>package mcve;
import java.util.*;
import java.util.function.*;

class ClassToConsumerMap {
    private final Map<Class<?>, Consumer<?>> map =
        new HashMap<>();

    @SuppressWarnings("unchecked")
    public <T> Consumer<? super T> put(Class<T> key, Consumer<? super T> c) {
        return (Consumer<? super T>) map.put(key, c);
    }

    @SuppressWarnings("unchecked")
    public <T> Consumer<? super T> get(Class<T> key) {
        return (Consumer<? super T>) map.get(key);
    }
}
</code>```

That's type-safe, because the relation between keys and values is enforced by the signature of the put method.

One annoying thing about the limitations of Java's generics is that one of these containers can't be written for a generic value type, because there's no way to do e.g.:

```<code>class ClassToGenericValueMap<V> {
    ...
    public <T> V<T> put(Class<T> key, V<T> val) {...}
    public <T> V<T> get(Class<T> key) {...}
}
</code>```

Other notes:

I would use a regular HashMap or a LinkedHashMap for this. HashMap is better maintained and has many optimizations that IdentityHashMap doesn't have.

If it's necessary to use generic types, like Consumer<List<String>>, then you need to use something like Guava TypeToken as the key, because Class can only represent the erasure of a type.

Guava has a ClassToInstanceMap for when you need a Map<Class<T>, T>.

Sometimes people want to do something like this, with a class-to-consumer map:

```<code>public <T> void accept(T obj) {
   Consumer<? super T> c = get(obj.getClass());
   if (c != null)
       c.accept(obj);
}
</code>```

That is, given any object, find the consumer in the map bound to that object's class and pass the object to the consumer's accept method.

That example won't compile, though, because getClass() is actually specified to return a Class<? extends |T|>, where |T| means the erasure of T. (See JLS §4.3.2.) In the above example, the erasure of T is Object, so obj.getClass() returns a plain Class<?>.

This issue can be solved with a capturing helper method:

```<code>public void accept(Object obj) {
    accept(obj.getClass(), obj);
}
private <T> void accept(Class<T> key, Object obj) {
    Consumer<? super T> c = get(key);
    if (c != null)
        c.accept(key.cast(obj));
}
</code>```

Also, if you want a modified version of get which returns any applicable consumer, you could use something like this:

```<code>public <T> Consumer<? super T> findApplicable(Class<T> key) {
    Consumer<? super T> c = get(key);
    if (c == null) {
        for (Map.Entry<Class<?>, Consumer<?>> e : map.entrySet()) {
            if (e.getKey().isAssignableFrom(key)) {
                @SuppressWarnings("unchecked")
                Consumer<? super T> value =
                    (Consumer<? super T>) e.getValue();
                c = value;
                break;
            }
        }
    }
    return c;
}
</code>```

That lets us put general supertype consumers in the map, like this:

```<code>ctcm.put(Object.class, System.out::println);
</code>```

And then retrieve with a subtype class:

```<code>Consumer<? super String> c = ctcm.findApplicable(String.class);
c.accept("hello world");
</code>```

Here's a slightly more general example, this time using UnaryOperator and no bounded wildcards:

```<code>package mcve;
import java.util.*;
import java.util.function.*;

public class ClassToUnaryOpMap {
    private final Map<Class<?>, UnaryOperator<?>> map =
        new HashMap<>();

    @SuppressWarnings("unchecked")
    public <T> UnaryOperator<T> put(Class<T> key, UnaryOperator<T> op) {
        return (UnaryOperator<T>) map.put(key, op);
    }

    @SuppressWarnings("unchecked")
    public <T> UnaryOperator<T> get(Class<T> key) {
        return (UnaryOperator<T>) map.get(key);
    }
}
</code>```

The ? super bounded wildcard in the first example is specific to consumers, and I thought an example without wildcards might be easier to read.

Title: Consumer<T> mapped Class<T> in HashMap

Body:
I want to create an IdentityHashMap<Class<T>, Consumer<T>>. Basically, I want to map a type with a method saying what to do with this type.

I want to dynamically be able to say with objects X, execute Y. I can do

private IdentityHashMap<Class<?>, Consumer<?>> interceptor = new IdentityHashMap<>();

but it sucks because then I have to cast the object in the lamba when using it.

Example:

interceptor.put(Train.class, train -> {
    System.out.println(((Train)train).getSpeed());
});

What I would like to do is

private <T> IdentityHashMap<Class<T>, Consumer<T>> interceptor = new IdentityHashMap<>();

But it doesn't seem to be allowed. Is there a way to do this ? What is the best workaround to map types with a method for this type ?

Body:
This is essentially just like the type-safe heterogeneous container described by Joshua Bloch, except you can't use the Class to cast the result.

Weirdly, I can't find a great example existing on SO, so here is one:

package mcve;
import java.util.*;
import java.util.function.*;

class ClassToConsumerMap {
    private final Map<Class<?>, Consumer<?>> map =
        new HashMap<>();

    @SuppressWarnings("unchecked")
    public <T> Consumer<? super T> put(Class<T> key, Consumer<? super T> c) {
        return (Consumer<? super T>) map.put(key, c);
    }

    @SuppressWarnings("unchecked")
    public <T> Consumer<? super T> get(Class<T> key) {
        return (Consumer<? super T>) map.get(key);
    }
}

That's type-safe, because the relation between keys and values is enforced by the signature of the put method.

One annoying thing about the limitations of Java's generics is that one of these containers can't be written for a generic value type, because there's no way to do e.g.:

class ClassToGenericValueMap<V> {
    ...
    public <T> V<T> put(Class<T> key, V<T> val) {...}
    public <T> V<T> get(Class<T> key) {...}
}

Other notes:

I would use a regular HashMap or a LinkedHashMap for this. HashMap is better maintained and has many optimizations that IdentityHashMap doesn't have.

If it's necessary to use generic types, like Consumer<List<String>>, then you need to use something like Guava TypeToken as the key, because Class can only represent the erasure of a type.

Guava has a ClassToInstanceMap for when you need a Map<Class<T>, T>.

Sometimes people want to do something like this, with a class-to-consumer map:

public <T> void accept(T obj) {
   Consumer<? super T> c = get(obj.getClass());
   if (c != null)
       c.accept(obj);
}

That is, given any object, find the consumer in the map bound to that object's class and pass the object to the consumer's accept method.

That example won't compile, though, because getClass() is actually specified to return a Class<? extends |T|>, where |T| means the erasure of T. (See JLS §4.3.2.) In the above example, the erasure of T is Object, so obj.getClass() returns a plain Class<?>.

This issue can be solved with a capturing helper method:

public void accept(Object obj) {
    accept(obj.getClass(), obj);
}
private <T> void accept(Class<T> key, Object obj) {
    Consumer<? super T> c = get(key);
    if (c != null)
        c.accept(key.cast(obj));
}

Also, if you want a modified version of get which returns any applicable consumer, you could use something like this:

public <T> Consumer<? super T> findApplicable(Class<T> key) {
    Consumer<? super T> c = get(key);
    if (c == null) {
        for (Map.Entry<Class<?>, Consumer<?>> e : map.entrySet()) {
            if (e.getKey().isAssignableFrom(key)) {
                @SuppressWarnings("unchecked")
                Consumer<? super T> value =
                    (Consumer<? super T>) e.getValue();
                c = value;
                break;
            }
        }
    }
    return c;
}

That lets us put general supertype consumers in the map, like this:

ctcm.put(Object.class, System.out::println);

And then retrieve with a subtype class:

Consumer<? super String> c = ctcm.findApplicable(String.class);
c.accept("hello world");

Here's a slightly more general example, this time using UnaryOperator and no bounded wildcards:

package mcve;
import java.util.*;
import java.util.function.*;

public class ClassToUnaryOpMap {
    private final Map<Class<?>, UnaryOperator<?>> map =
        new HashMap<>();

    @SuppressWarnings("unchecked")
    public <T> UnaryOperator<T> put(Class<T> key, UnaryOperator<T> op) {
        return (UnaryOperator<T>) map.put(key, op);
    }

    @SuppressWarnings("unchecked")
    public <T> UnaryOperator<T> get(Class<T> key) {
        return (UnaryOperator<T>) map.get(key);
    }
}

The ? super bounded wildcard in the first example is specific to consumers, and I thought an example without wildcards might be easier to read.


问:
Invalid entitlements error when adding push notifications
I'm trying to add push notifications to my chat app following this tutorial: https://www.appcoda.com/firebase-push-notifications/

I've toggled Push Notifications to On in "Capabilities":

My provisioning profile is set up for push notifications:

I downloaded it, and double clicked it to install.

For Code Signing, in Target -> Code Signing:

And Project -> Code Signing:

Entitlements file:

When I ran the project it succeeded, then said "The executable was signed with invalid entitlements". Full error The entitlements specified in your application’s Code Signing Entitlements file are invalid, not permitted, or do not match those specified in your provisioning profile. (0xE8008016).

Thanks for reading.. Any help on this will be hugely appreciated!

EDIT: Additional Information

Using Xcode 8.2.1

In my App ID in the developers portal, Game Center, In-App Purchases, and Push Notifications are enabled. It's my understanding that Game Center and IAP are enabled by default.

I've tried turning GC and IAP On, and then Off again. Restart Xcode, clean, build. No luck

I've tried turning GC and IAP On, then regenerating my provisioning profiles, installing them, cleaning and building. No luck.

My Bundle ID matches everywhere.

答:
Delete any unknown entries in entitlements file, which are not added by you.

Example: you can delete keychainAccessGroup entry from your entitlements file, if that is not added by you intentionally.

Have a look at your test target, the Team identifier should be same for both Test and Main target.
Courtesy: https://stackoverflow.com/a/40464055/2959346


问:
sha256 string starting with custom like aaaaaa
i want to generate a SHA256 string but I want it first 15 characters are same like aaaaaaaa....

and how can I do that?

```<code>FOUND: 9481011 aaaaaa4da30538b171d69304aba8a3a3d8bf4b83761c1fa30b8e40dd2f97b899
</code>```

I need the exact string encrypted and decrypted so I need two strings

I need it created so when checked by other side it must be validated

```<code>don't down vote if you cant able to solve this
</code>```

答:
A sha256 hash is as its name implies, 256 bits long. That means there are $2^256$ different possibilities. That's about a trillion, trillion, trillion, trillion, trillion, trillion possibilities. (This is not a typo. That is trillion 6 times) Now, you want to find a string whose sha256 hash has a 15-character prefix. The best way we know how to do this is to guess random strings and check if they match your criteria. For every string that matches your criteria, there are roughly one trillion, trillion, trillion that do not. That is more than the number of stars in the observable universe.

Imagine laying next to a friend looking up at the night sky. Your friend picks a star and you have to guess which one they picked. You would not expect to win that game. Answering your question is more than a thousand times harder than winning at that game.

Body:
i want to generate a SHA256 string but I want it first 15 characters are same like aaaaaaaa....

and how can I do that?

FOUND: 9481011 aaaaaa4da30538b171d69304aba8a3a3d8bf4b83761c1fa30b8e40dd2f97b899

I need the exact string encrypted and decrypted so I need two strings

I need it created so when checked by other side it must be validated

don't down vote if you cant able to solve this


问:
What's wrong with this steganography extract code?
I want to try extracting message from images that have been inserted messages before..but there is an error with the description bellow..

this code extract :

```<code>% Read Image Stego
IS = imread('imagestego.bmp');

% Extract RedChannel
RedChannel = IS(:,:,1);

% Convert RedChannel to biner
bitstego = uint8(reshape(dec2bin(RedChannel,8)',1,[]) = '0');
nBitstego = length(bitstego);

% Extraction
extBits = bitget(RedChannel(1:end),1).';
extMessage = char(bin2dec(reshape(int2str(extBits),8,[]).').');
</code>```

and this error from extract code :

```<code>>> latihanextract
Error: File: latihanextract.m Line: 8 Column: 55
The expression to the left of the equals sign is not a valid target for an assignment.
</code>```

and this is embedding code before..it's work!

```<code>coverImage = imread('foto1.jpg');
message = 'IMRON';

%EMBEDDING
RedChannel = coverImage(:,:,1);
GreenChannel = coverImage(:,:,2);
BlueChannel = coverImage(:,:,3);
bits = uint8(reshape(dec2bin(message,8)',1,[]) - '0');
nBits = length(bits);
RedChannel(1:nBits) = bitset(RedChannel(1:nBits),1,bits);
Imageresults = cat(3,RedChannel,GreenChannel,BlueChannel);
imwrite(Imageresults,'imagestego.bmp');
</code>```

so what's the problem ?

答:
Here's your problem...

```<code>% Read Image Stego
IS = imread('stegosaurus.bmp');

% Extract RedChannel
RedChannel = IS(:,:,1);

% Convert RedChannel to binary
bitstego = uint8(reshape(dec2bin(RedChannel,8)',1,[]) - '0');
nBitstego = length(bitstego);
% the previous 2 lines are actually unnecessary and can be deleted...
% see explanation in text below

% Extrication
extBits = bitget(RedChannel(1:end),1).';   % (1:end) gives you all of the elements
extMessage = char(bin2dec(reshape(int2str(extBits),8,[]).').')
</code>```

You were trying to loop over the number of bits in the image instead of the number of bytes. bitstego is the binary representation of all of the bytes in bitstego, so bitstego is 8 times as long as RedChannel.

It's much easier in this case just to take the number of elements in RedChannel using the special index end.

Body:
I want to try extracting message from images that have been inserted messages before..but there is an error with the description bellow..

this code extract :

% Read Image Stego
IS = imread('imagestego.bmp');

% Extract RedChannel
RedChannel = IS(:,:,1);

% Convert RedChannel to biner
bitstego = uint8(reshape(dec2bin(RedChannel,8)',1,[]) = '0');
nBitstego = length(bitstego);

% Extraction
extBits = bitget(RedChannel(1:end),1).';
extMessage = char(bin2dec(reshape(int2str(extBits),8,[]).').');

and this error from extract code :

>> latihanextract
Error: File: latihanextract.m Line: 8 Column: 55
The expression to the left of the equals sign is not a valid target for an assignment.

and this is embedding code before..it's work!

coverImage = imread('foto1.jpg');
message = 'IMRON';

%EMBEDDING
RedChannel = coverImage(:,:,1);
GreenChannel = coverImage(:,:,2);
BlueChannel = coverImage(:,:,3);
bits = uint8(reshape(dec2bin(message,8)',1,[]) - '0');
nBits = length(bits);
RedChannel(1:nBits) = bitset(RedChannel(1:nBits),1,bits);
Imageresults = cat(3,RedChannel,GreenChannel,BlueChannel);
imwrite(Imageresults,'imagestego.bmp');

so what's the problem ?

Body:
Here's your problem...

% Read Image Stego
IS = imread('stegosaurus.bmp');

% Extract RedChannel
RedChannel = IS(:,:,1);

% Convert RedChannel to binary
bitstego = uint8(reshape(dec2bin(RedChannel,8)',1,[]) - '0');
nBitstego = length(bitstego);
% the previous 2 lines are actually unnecessary and can be deleted...
% see explanation in text below

% Extrication
extBits = bitget(RedChannel(1:end),1).';   % (1:end) gives you all of the elements
extMessage = char(bin2dec(reshape(int2str(extBits),8,[]).').')

You were trying to loop over the number of bits in the image instead of the number of bytes. bitstego is the binary representation of all of the bytes in bitstego, so bitstego is 8 times as long as RedChannel.

It's much easier in this case just to take the number of elements in RedChannel using the special index end.


问:
MySQL 5.6 - Procedure to remove all duplicates except one with the highest value?
I have the following table where I want to remove all duplicates of col_2, and keep only the one with the largest value.

```<code>-----------------------
| col_1 | col_2 | ... |
----------------|-----|
| 2     |  2    | ... |
| 3     |  2    | ... |
| 4     |  2    | ... |
----------------------
</code>```

Would return:

```<code>-----------------------
| col_1 | col_2 | ... |
----------------|-----|
| 4     |  2    | ... |
----------------------
</code>```

However I unfortunately designed my table such that there are no unique indices or keys.

What is the procedure I have to make in order to accomplish this?

答:
you could use a couple of group by and a tuple

```<code>delete from my_table a
inner join (
    select col_2
    from my_table
    group by col_2
    having count(*)> 1
) t on a.col_2 = t.col_2
where (a.col_2, a.col_1) not in (
    select col_2, max(col_1)
    from my_table
    group by col_2
    having count(*) > 1
)
</code>```

the join is for get only the col_2 with at least a duplicated  row and the not in is for delete the row not max(col_1)

Body:
I have the following table where I want to remove all duplicates of col_2, and keep only the one with the largest value.

-----------------------
| col_1 | col_2 | ... |
----------------|-----|
| 2     |  2    | ... |
| 3     |  2    | ... |
| 4     |  2    | ... |
----------------------

Would return:

-----------------------
| col_1 | col_2 | ... |
----------------|-----|
| 4     |  2    | ... |
----------------------

However I unfortunately designed my table such that there are no unique indices or keys.

What is the procedure I have to make in order to accomplish this?

Body:
you could use a couple of group by and a tuple

delete from my_table a
inner join (
    select col_2
    from my_table
    group by col_2
    having count(*)> 1
) t on a.col_2 = t.col_2
where (a.col_2, a.col_1) not in (
    select col_2, max(col_1)
    from my_table
    group by col_2
    having count(*) > 1
)

the join is for get only the col_2 with at least a duplicated  row and the not in is for delete the row not max(col_1)


答:
Use %% like this:

```<code>sprintf(line2Str,"TL=%%%.1f", CurrentTemp );
</code>```

Note that need one percentage character for the float number as well.

Title: using sprintf to print out stings on a LCD how can i use a percent sign in this function

Body:
Use %% like this:

sprintf(line2Str,"TL=%%%.1f", CurrentTemp );

Note that need one percentage character for the float number as well.


问:
Revert select lines of a file in Git
I committed changes that added some code and deleted some code.  Now, I want to undo this.  There are other changes in the file (along with other files changed in the commit) which I don't want undone, so a standard git revert will not do.  What I want is to create a commit that undoes these select changes by providing the line numbers.  And preferably a technique which allows me to use my GUI client (Github Desktop) to select the changes / line numbers in the diff.  How would I go about this?</p>

答:
There are probably a number of ways to achieve this but I'd go with something like:</p>
```<code># stage a revision of the given commit without making a commit of this revision
git revert -n <hash-of-commit-to-partially revert>

# Unstage these changes so the revision is only in the working tree
git reset

# Selectively stage only the parts which make the revisions which you want
git add -p <path-of-interest>

# Optional: discard other changes from the working tree for testing
# (you might need to "git clean" if you are discarding the revision
#  of a change that originally removed a file)
git checkout -- .

# Commit the selected revision
git commit
</code>```

Title: Revert select lines of a file in Git

Body:
There are probably a number of ways to achieve this but I'd go with something like:

# stage a revision of the given commit without making a commit of this revision
git revert -n <hash-of-commit-to-partially revert>

# Unstage these changes so the revision is only in the working tree
git reset

# Selectively stage only the parts which make the revisions which you want
git add -p <path-of-interest>

# Optional: discard other changes from the working tree for testing
# (you might need to "git clean" if you are discarding the revision
#  of a change that originally removed a file)
git checkout -- .

# Commit the selected revision
git commit


答:
The best you can do is try lots of inputs until you find one that works:

x = 0
while True:
    x += 1
    if sha256(str(x)).startswith('a' * 15):
        return str(x)
```

Unfortunately, you want so many a in a row that it will take decades for this method to finish. Every extra a increases the runtime by a factor 16.

If there was a simple way to find strings starting with lots of a, the hash function would not be secure. So this is the best you will be able to do, short of performing groundbreaking research in cryptography.

Title: sha256 string starting with custom like aaaaaa

Body:
The best you can do is try lots of inputs until you find one that works:

x = 0
while True:
    x += 1
    if sha256(str(x)).startswith('a' * 15):
        return str(x)

Unfortunately, you want so many a in a row that it will take decades for this method to finish. Every extra a increases the runtime by a factor 16.

If there was a simple way to find strings starting with lots of a, the hash function would not be secure. So this is the best you will be able to do, short of performing groundbreaking research in cryptography.


问:
R Markdown Footnote in xtable
I'm having issues with a footnote not appearing under a table in my R Markdown report.  Below is the code I'm using to process which does successfully but with no footnote appearing under the table.

```<code>```{r ccxtable7, results="asis", echo=FALSE}
comment <- list(pos = list(0), command = NULL)
comment$pos[[1]] <- c(nrow(indPctChgCC))
comment$command <- c(paste("\\hline\n",
                          "{\\footnotesize Note: * signifies number of
properties used was 35 or less.}\n", sep = ""))

print(xtable(valPctCon(indPctChgCC, indfreqCC, 35), align = "crrrrr",
             label = "tab:indCC", add.to.row = comment, hline.after = c(-1,0),
caption = "Industrial Certified-Certified Percentage Change per Value Segment"))
```
</code>```

indPctChCC is a 3x5 matrix of strings.  Could someone help me understand why the footnote is not appearing under the table with this current code?

答:
add.to.row (and also hline.after) are arguments of the print function, not xtable().

This should get you where you want:

```<code>print(xtable(tab, align = "crrr",
             label = "tab:indCC",
             caption = "Industrial Certified-Certified Percentage Change per Value Segment"),
      add.to.row = comment,
      hline.after = c(-1,0))
</code>```

Title: R Markdown Footnote in xtable

Body:
I'm having issues with a footnote not appearing under a table in my R Markdown report.  Below is the code I'm using to process which does successfully but with no footnote appearing under the table.

```{r ccxtable7, results="asis", echo=FALSE}
comment <- list(pos = list(0), command = NULL)
comment$pos[[1]] <- c(nrow(indPctChgCC))
comment$command <- c(paste("\\hline\n",
                          "{\\footnotesize Note: * signifies number of
properties used was 35 or less.}\n", sep = ""))

print(xtable(valPctCon(indPctChgCC, indfreqCC, 35), align = "crrrrr",
             label = "tab:indCC", add.to.row = comment, hline.after = c(-1,0),
caption = "Industrial Certified-Certified Percentage Change per Value Segment"))
```

indPctChCC is a 3x5 matrix of strings.  Could someone help me understand why the footnote is not appearing under the table with this current code?

Body:
add.to.row (and also hline.after) are arguments of the print function, not xtable().

This should get you where you want:

print(xtable(tab, align = "crrr",
             label = "tab:indCC",
             caption = "Industrial Certified-Certified Percentage Change per Value Segment"),
      add.to.row = comment,
      hline.after = c(-1,0))