问:
Why am I getting "unbound variable or constructor" in my SML program
I have written a method to return the first element in a list that satisfies a function (passed in via currying). The function returns NONE or SOME depending on whether or not the element satisfies a condition.  I'm using Pattern Matching
However, I'm getting the dreaded error:
Error: unbound variable or constructor: my_function

I'm new to SML and one of the hardest things I find is understanding the error messages.  From previous experience with the message, I would think the problem is that my_function never returns, but I'm having trouble seeing the logic problem here. Can someone take a quick look and tell me the problem?  Is the problem that I'm raising an error when there is no element that satisfies the input function f?

I'm interested in what's wrong and perhaps more importantly, is there any way to get more information when you see this sort of error?

```<code>val  my_function = fn f => fn lst =>  (* Notice currying *)
  case lst of
      [] => raise NoAnswer  (* Get here is nothing in lst saf

    | x::xs => case f(x) of NONE => ( my_function f xs)
                 | SOME y  =>  x

 val test = my_function(fn x => if x < 3 then SOME x else NONE) [1,2,3,4] = 2
</code>```

Thanks, Dave

答:
If you declare a function with the val keyword, the function can't be defined recursively. Hence, the problem is here:

```<code>... NONE => ( my_function f xs) ...
</code>```

You can say that you want the function to be defined recursively by adding the rec keyword to the declaration.

```<code>val rec my_function = fn f => fn list => ...
</code>```

Alternatively, the fun keyword is syntactic sugar for val rec. fun also includes nice syntactic sugar for currying:

```<code>fun my_function f lst = (* This is equivalent to your first line *)
</code>```

Sometimes you still want to use just the val keyword and not val rec. For instance,

```<code>val f = fn x => x + 3
val f = fn y => f y + 4 (* f here refers to the previous declaration of f *)
</code>```

Body:
I have written a method to return the first element in a list that satisfies a function (passed in via currying). The function returns NONE or SOME depending on whether or not the element satisfies a condition.  I'm using Pattern Matching
However, I'm getting the dreaded error:
Error: unbound variable or constructor: my_function

I'm new to SML and one of the hardest things I find is understanding the error messages.  From previous experience with the message, I would think the problem is that my_function never returns, but I'm having trouble seeing the logic problem here. Can someone take a quick look and tell me the problem?  Is the problem that I'm raising an error when there is no element that satisfies the input function f?

I'm interested in what's wrong and perhaps more importantly, is there any way to get more information when you see this sort of error?

val  my_function = fn f => fn lst =>  (* Notice currying *)
  case lst of
      [] => raise NoAnswer  (* Get here is nothing in lst saf

    | x::xs => case f(x) of NONE => ( my_function f xs)
                 | SOME y  =>  x

 val test = my_function(fn x => if x < 3 then SOME x else NONE) [1,2,3,4] = 2

Thanks, Dave

Body:
If you declare a function with the val keyword, the function can't be defined recursively. Hence, the problem is here:

... NONE => ( my_function f xs) ...

You can say that you want the function to be defined recursively by adding the rec keyword to the declaration.

val rec my_function = fn f => fn list => ...

Alternatively, the fun keyword is syntactic sugar for val rec. fun also includes nice syntactic sugar for currying:

fun my_function f lst = (* This is equivalent to your first line *)

Sometimes you still want to use just the val keyword and not val rec. For instance,

val f = fn x => x + 3
val f = fn y => f y + 4 (* f here refers to the previous declaration of f *)


来源: stackexchange

问:
Strange error with matplotlib axes labels
I'm very new to Python and programming in general, so apologies in advance if I'm missing something obvious. I'm trying to plot a graph and label the axes, but every time I try to label the y axis an exception is raised. I wrote the code below in a new script to make sure the problem wasn't coming from somewhere else in the module. I'm using Python 3.4.

```<code>from numpy import *
from matplotlib import *

a = [1, 2, 3, 4, 5]
b = [2, 3, 2, 3, 2]
pyplot.plot(a, b)
pylab.xlabel("Time")
pylab.ylabel("Speed")
</code>```

Every time, I get the error 'TypeError: 'str' object is not callable' for the final line. If I change the y to an x, everything is fine. If I change the x to a y, I get the same error. However, ylabel comes up on the drop down list for ylabel so the function does exist and the documentation says a string is the only necessary argument, exactly as for xlabel (matplotlib.pyplot.ylabel(s, *args, **kwargs) and matplotlib.pyplot.xlabel(s, *args, **kwargs)). What on earth could be going on here?

答: I saved the checkpoint and halted the ipython notebook. Then I restarted it which solved the problem.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm very new to Python and programming in general, so apologies in advance if I'm missing something obvious. I'm trying to plot a graph and label the axes, but every time I try to label the y axis an exception is raised. I wrote the code below in a new script to make sure the problem wasn't coming from somewhere else in the module. I'm using Python 3.4.

from numpy import *
from matplotlib import *

a = [1, 2, 3, 4, 5]
b = [2, 3, 2, 3, 2]
pyplot.plot(a, b)
pylab.xlabel("Time")
pylab.ylabel("Speed")

Every time, I get the error 'TypeError: 'str' object is not callable' for the final line. If I change the y to an x, everything is fine. If I change the x to a y, I get the same error. However, ylabel comes up on the drop down list for ylabel so the function does exist and the documentation says a string is the only necessary argument, exactly as for xlabel (matplotlib.pyplot.ylabel(s, *args, **kwargs) and matplotlib.pyplot.xlabel(s, *args, **kwargs)). What on earth could be going on here?


问:
About C# object scope
So I've created a class and instantiate an object in the main window. Then, when I'm trying to use that object in a button within the same window, I don't know how to indicate the context for this object. I know this is a very basic question, but I'm learning and haven't been able to figure it out just yet.

```<code>public MainWindow()
{
    InitializeComponent();
    DeltaMotor M2 = new DeltaMotor();
    M2.Card.Set8255();
    M2.Stop();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    M2.Move(1); // this can't find M2 within the context
}
</code>```

I know this is basic, but help will be greatly appreciated.

答:
As you've discovered, the M2 object is not in scope inside the click handler, because it is a local variable inside the MainWindow constructor.

You can make M2 an instance variable of the class, and access it from both methods, along the lines of:

```<code>private DeltaMotor M2;

public MainWindow()
{
    InitializeComponent();
    M2 = new DeltaMotor();
    M2.Card.Set8255();
    M2.Stop();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    M2.Move(1);
}
</code>```

Title: About C# object scope

Body:
So I've created a class and instantiate an object in the main window. Then, when I'm trying to use that object in a button within the same window, I don't know how to indicate the context for this object. I know this is a very basic question, but I'm learning and haven't been able to figure it out just yet.

public MainWindow()
{
    InitializeComponent();
    DeltaMotor M2 = new DeltaMotor();
    M2.Card.Set8255();
    M2.Stop();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    M2.Move(1); // this can't find M2 within the context
}

I know this is basic, but help will be greatly appreciated.

Body:
As you've discovered, the M2 object is not in scope inside the click handler, because it is a local variable inside the MainWindow constructor.

You can make M2 an instance variable of the class, and access it from both methods, along the lines of:

private DeltaMotor M2;

public MainWindow()
{
    InitializeComponent();
    M2 = new DeltaMotor();
    M2.Card.Set8255();
    M2.Stop();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    M2.Move(1);
}


问:
How to find invalid Char in a SQL table
This has been a major headache for the last couple of weeks. I have a largish table (165 columns x 11000+ rows). In this table, there are several comment columns that are set to varchar(max). There is one in particular that keeps getting invalid characters pasted into it by various users. This causes the reports in SSRS to fail. I then have to go and find these invalid characters and remove them. This has been a very painstaking time-consuming task.

What I would like to do is find a way to search automatically for these invalid characters and replace them with nothing. The problem is that I have no idea how to go about a search directly for these characters. Here is what they look like:

and here's another image of the same:

And here is what it looks like when I paste it into Notepad++:

I am not sure if it'll work and show up the way I see it, but here are the characters:

㹊潮Ņ᯸ࢹᖈư㹨ƶ槹鎤⻄ƺ綐ڌ⸀ƺ삸)䀤ƍ샄)Ņᛡ鎤ꗘᖃᒨ쬵Ğᘍ鎤ᐜᏰ>֔υ赸Ƹ쳰డ촜)鉀௿촜)쮜)Ἡ屰山舰霡ࣆ  耏Аం畠Ư놐ᓜતᏛ֔Ꮫ֨Ꮫ꯼ᓜƒ
  邰఍厰ఆ邰఍드)抉鎤듄)繟Ĺ띨)᯸ࢹ䮸ࣉ᯸ࢹ䮸ࣉ샰)ԌƏŅ֐ᕄ홑Ņᛙ鎤ꗘᖃᒨ᯸ࢹ

They look like they are Chinese or something similar, but I've tried using Google Translate and it detects them as English.

Any help in figuring out a way to search for these? Create a Function or an SP would be fine as long as it works!

UPDATE

I've tried part of a solution I found here: How can I find Unicode/non-ASCII characters in an NTEXT field in a SQL Server 2005 table?
and used this:

```<code>-- Start with tab, line feed, carriage return
declare @str varchar(1024)
set @str = '|' + char(9) + '|' + char(10) + '|' + char(13)

-- Add all normal ASCII characters (32 -> 127)
declare @i int
set @i = 32
while @i <= 127
    begin
    -- Uses | to escape, could be any character
    set @str = @str + '|' + char(@i)
    set @i = @i + 1
    end

select MEETING_NOTES from pmdb.TrackerData
where MEETING_NOTES like '%[^' + @str + ']%' escape '|'
</code>```

But it is returning a lot more rows than it should be. I currently only have 1 row that has these invalid characters and it is returning 1708.

UPDATE 2

I have created a Function to try and remove all the invalid characters like this:

```<code>ALTER FUNCTION [dbo].[RemoveNonPrintable]
(
    @inputtext nvarchar(max)
)
RETURNS nvarchar(max)
AS
BEGIN

    DECLARE @counter int = 1;
    DECLARE @colString nvarchar(1000)
    set @inputtext = REPLACE(@inputtext, char(0), '') -- 'NULL'
    set @inputtext = REPLACE(@inputtext, char(1), '') -- 'Start of Heading'
    set @inputtext = REPLACE(@inputtext, char(2), '') -- 'Start of Text'
    set @inputtext = REPLACE(@inputtext, char(3), '') -- 'End of Text'
    set @inputtext = REPLACE(@inputtext, char(4), '') -- 'End of Transmission'
    set @inputtext = REPLACE(@inputtext, char(5), '') -- 'Enquiry'
    set @inputtext = REPLACE(@inputtext, char(6), '') -- 'Acknowledgement'
    set @inputtext = REPLACE(@inputtext, char(7), '') -- 'Bell'
    set @inputtext = REPLACE(@inputtext, char(8), '') -- 'Backspace'
    set @inputtext = REPLACE(@inputtext, char(9), '') -- 'Horizontal Tab'
    -- replace line feed with blank, so words that were in different lines before are still separated
    set @inputtext = REPLACE(@inputtext, char(10), ' ') -- 'Line Feed'
    set @inputtext = REPLACE(@inputtext, char(11), '') -- 'Vertical Tab'
    set @inputtext = REPLACE(@inputtext, char(12), '') -- 'Form Feed'
    -- replace carriage return with blank, so words that were in different lines before are still separated
    set @inputtext = REPLACE(@inputtext, char(13), ' ') -- 'Carriage Return'
    set @inputtext = REPLACE(@inputtext, char(14), '') -- 'Shift Out'
    set @inputtext = REPLACE(@inputtext, char(15), '') -- 'Shift In'
    set @inputtext = REPLACE(@inputtext, char(16), '') -- 'Data Link Escape'
    set @inputtext = REPLACE(@inputtext, char(17), '') -- 'Device Control 1'
    set @inputtext = REPLACE(@inputtext, char(18), '') -- 'Device Control 2'
    set @inputtext = REPLACE(@inputtext, char(19), '') -- 'Device Control 3'
    set @inputtext = REPLACE(@inputtext, char(20), '') -- 'Device Control 4'
    set @inputtext = REPLACE(@inputtext, char(21), '') -- 'Negative Acknowledgment'
    set @inputtext = REPLACE(@inputtext, char(22), '') -- 'Synchronous Idle'
    set @inputtext = REPLACE(@inputtext, char(23), '') -- 'End of Transmission Block'
    set @inputtext = REPLACE(@inputtext, char(24), '') -- 'Cancel'
    set @inputtext = REPLACE(@inputtext, char(25), '') -- 'End of Medium'
    set @inputtext = REPLACE(@inputtext, char(26), '') -- 'Substitute'
    set @inputtext = REPLACE(@inputtext, char(27), '') -- 'Escape'
    set @inputtext = REPLACE(@inputtext, char(28), '') -- 'File Separator'
    set @inputtext = REPLACE(@inputtext, char(29), '') -- 'Group Separator'
    set @inputtext = REPLACE(@inputtext, char(30), '') -- 'Record Separator'
    set @inputtext = REPLACE(@inputtext, char(31), '') -- 'Unit Separator'
    set @inputtext = REPLACE(@inputtext, char(127), '') -- 'Delete'

    set @colString = @inputtext

    WHILE @counter <= DATALENGTH(@colString)
       BEGIN
           set @colString   = REPLACE(@colString,isnull(NCHAR(UNICODE(SUBSTRING(@colString, @counter, 1))),'|'),'|')
           set @colString = REPLACE(@colString,'|','')

           SET @counter = @counter + 1
       END
    return @inputtext
END
</code>```

I call it like this:

```<code>BEGIN TRAN  --COMMIT    ROLLBACK
update pmdb.TrackerData
set CIRCUIT_COMMENTS = [dbo].[RemoveNonPrintable](CIRCUIT_COMMENTS),
    COE_COMMENTS = [dbo].[RemoveNonPrintable](COE_COMMENTS),
    MEETING_NOTES = [dbo].[RemoveNonPrintable](MEETING_NOTES),
    OSP_COMMENTS = [dbo].[RemoveNonPrintable](OSP_COMMENTS),
    COE_COMMENTS2 = [dbo].[RemoveNonPrintable](COE_COMMENTS2)
</code>```

Then I run the code from the previous update to see if there is any difference. There is no difference. What gives? Am I doing this wrong?

EDIT 3

I've updated my function to have this:

```<code>    set @colString = @inputtext

    WHILE @counter <= DATALENGTH(@colString)
       BEGIN
           --set @colString = REPLACE(@colString,isnull(NCHAR(UNICODE(SUBSTRING(@colString, @counter, 1))),'|'),'|')
           --set @colString = REPLACE(@colString,'|','')
           if (UNICODE(SUBSTRING(@colString, @counter,1)) > 126)
           BEGIN
            SET @colString = REPLACE(@colString, CONVERT(nvarchar(1),(SUBSTRING(@colString, @counter,1))), CHAR(32))
           END
           ELSE IF(UNICODE(SUBSTRING(@colString, @counter, 1)) < 32)
           BEGIN
            SET @colString = REPLACE(@colString, CONVERT(nvarchar(1),(SUBSTRING(@colString, @counter,1))), CHAR(32))
           END

           set @inputtext = @colString

           SET @counter = @counter + 1
       END
</code>```

It removes most of the invalid characters, but then it leaves others. I call it on a temp table that I created that holds the sample of invalid characters shown above like this:

```<code>update #Temp
set Notes = [dbo].[RemoveNonPrintable](Notes),
    Notes2 = [dbo].[RemoveNonPrintable](Notes2)
</code>```

Then I'm left with the following in the two Notes:

```<code>Notes: ????N???u?z?????????)???)?N??????G????>???????)???)?)???????? ????U??????????  ???????)???)?L?)?????????)?????N???N???????

Notes2:     ᯸ࢹᖈ 㹨   ⻄   ⸀  )䀤  )  ᛡ ꗘᖃᒨ  ᘍ ᐜᏰ>֔      ) ௿ ) )Ἡ      ࣆ       ᓜ Ꮫ֔Ꮫ֨Ꮫ꯼ᓜ   ఍   ఍ )   )   )᯸ࢹ䮸ࣉ᯸ࢹ䮸ࣉ )Ԍ   ֐ᕄ  ᛙ ꗘᖃᒨ᯸ࢹ
</code>```

Which is better than what I started with, but still not good enough.

答:
I have found a solution in another users question here

I modified it slightly though. What ends up working for me is this:

```<code>ALTER FUNCTION [dbo].[RemoveNonASCII]
(
    -- Parameters
    @nstring nvarchar(max)
)
RETURNS varchar(max)
AS
BEGIN
    -- Variables
    DECLARE @Result varchar(max) = '',@nchar nvarchar(1), @position int

    -- T-SQL statements to compute the return value
    set @position = 1
    while @position <= LEN(@nstring)
    BEGIN
        set @nchar = SUBSTRING(@nstring, @position, 1)
        if UNICODE(@nchar) between 32 and 127
            set @Result = @Result + @nchar
        set @position = @position + 1
        set @Result = REPLACE(@Result,'))','')
        set @Result = REPLACE(@Result,'?','')
    END

    -- Return the result
    RETURN @Result

END
</code>```

Title: How to find invalid Char in a SQL table

Body:
This has been a major headache for the last couple of weeks. I have a largish table (165 columns x 11000+ rows). In this table, there are several comment columns that are set to varchar(max). There is one in particular that keeps getting invalid characters pasted into it by various users. This causes the reports in SSRS to fail. I then have to go and find these invalid characters and remove them. This has been a very painstaking time-consuming task.

What I would like to do is find a way to search automatically for these invalid characters and replace them with nothing. The problem is that I have no idea how to go about a search directly for these characters. Here is what they look like:

and here's another image of the same:

And here is what it looks like when I paste it into Notepad++:

I am not sure if it'll work and show up the way I see it, but here are the characters:

㹊潮Ņ᯸ࢹᖈư㹨ƶ槹鎤⻄ƺ綐ڌ⸀ƺ삸)䀤ƍ샄)Ņᛡ鎤ꗘᖃᒨ쬵Ğᘍ鎤ᐜᏰ>֔υ赸Ƹ쳰డ촜)鉀௿촜)쮜)Ἡ屰山舰霡ࣆ  耏Аం畠Ư놐ᓜતᏛ֔Ꮫ֨Ꮫ꯼ᓜƒ
  邰఍厰ఆ邰఍드)抉鎤듄)繟Ĺ띨)᯸ࢹ䮸ࣉ᯸ࢹ䮸ࣉ샰)ԌƏŅ֐ᕄ홑Ņᛙ鎤ꗘᖃᒨ᯸ࢹ

They look like they are Chinese or something similar, but I've tried using Google Translate and it detects them as English.

Any help in figuring out a way to search for these? Create a Function or an SP would be fine as long as it works!

UPDATE

I've tried part of a solution I found here: How can I find Unicode/non-ASCII characters in an NTEXT field in a SQL Server 2005 table?
and used this:

-- Start with tab, line feed, carriage return
declare @str varchar(1024)
set @str = '|' + char(9) + '|' + char(10) + '|' + char(13)

-- Add all normal ASCII characters (32 -> 127)
declare @i int
set @i = 32
while @i <= 127
    begin
    -- Uses | to escape, could be any character
    set @str = @str + '|' + char(@i)
    set @i = @i + 1
    end

select MEETING_NOTES from pmdb.TrackerData
where MEETING_NOTES like '%[^' + @str + ']%' escape '|'

But it is returning a lot more rows than it should be. I currently only have 1 row that has these invalid characters and it is returning 1708.

UPDATE 2

I have created a Function to try and remove all the invalid characters like this:

ALTER FUNCTION [dbo].[RemoveNonPrintable]
(
    @inputtext nvarchar(max)
)
RETURNS nvarchar(max)
AS
BEGIN

    DECLARE @counter int = 1;
    DECLARE @colString nvarchar(1000)
    set @inputtext = REPLACE(@inputtext, char(0), '') -- 'NULL'
    set @inputtext = REPLACE(@inputtext, char(1), '') -- 'Start of Heading'
    set @inputtext = REPLACE(@inputtext, char(2), '') -- 'Start of Text'
    set @inputtext = REPLACE(@inputtext, char(3), '') -- 'End of Text'
    set @inputtext = REPLACE(@inputtext, char(4), '') -- 'End of Transmission'
    set @inputtext = REPLACE(@inputtext, char(5), '') -- 'Enquiry'
    set @inputtext = REPLACE(@inputtext, char(6), '') -- 'Acknowledgement'
    set @inputtext = REPLACE(@inputtext, char(7), '') -- 'Bell'
    set @inputtext = REPLACE(@inputtext, char(8), '') -- 'Backspace'
    set @inputtext = REPLACE(@inputtext, char(9), '') -- 'Horizontal Tab'
    -- replace line feed with blank, so words that were in different lines before are still separated
    set @inputtext = REPLACE(@inputtext, char(10), ' ') -- 'Line Feed'
    set @inputtext = REPLACE(@inputtext, char(11), '') -- 'Vertical Tab'
    set @inputtext = REPLACE(@inputtext, char(12), '') -- 'Form Feed'
    -- replace carriage return with blank, so words that were in different lines before are still separated
    set @inputtext = REPLACE(@inputtext, char(13), ' ') -- 'Carriage Return'
    set @inputtext = REPLACE(@inputtext, char(14), '') -- 'Shift Out'
    set @inputtext = REPLACE(@inputtext, char(15), '') -- 'Shift In'
    set @inputtext = REPLACE(@inputtext, char(16), '') -- 'Data Link Escape'
    set @inputtext = REPLACE(@inputtext, char(17), '') -- 'Device Control 1'
    set @inputtext = REPLACE(@inputtext, char(18), '') -- 'Device Control 2'
    set @inputtext = REPLACE(@inputtext, char(19), '') -- 'Device Control 3'
    set @inputtext = REPLACE(@inputtext, char(20), '') -- 'Device Control 4'
    set @inputtext = REPLACE(@inputtext, char(21), '') -- 'Negative Acknowledgment'
    set @inputtext = REPLACE(@inputtext, char(22), '') -- 'Synchronous Idle'
    set @inputtext = REPLACE(@inputtext, char(23), '') -- 'End of Transmission Block'
    set @inputtext = REPLACE(@inputtext, char(24), '') -- 'Cancel'
    set @inputtext = REPLACE(@inputtext, char(25), '') -- 'End of Medium'
    set @inputtext = REPLACE(@inputtext, char(26), '') -- 'Substitute'
    set @inputtext = REPLACE(@inputtext, char(27), '') -- 'Escape'
    set @inputtext = REPLACE(@inputtext, char(28), '') -- 'File Separator'
    set @inputtext = REPLACE(@inputtext, char(29), '') -- 'Group Separator'
    set @inputtext = REPLACE(@inputtext, char(30), '') -- 'Record Separator'
    set @inputtext = REPLACE(@inputtext, char(31), '') -- 'Unit Separator'
    set @inputtext = REPLACE(@inputtext, char(127), '') -- 'Delete'

    set @colString = @inputtext

    WHILE @counter <= DATALENGTH(@colString)
       BEGIN
           set @colString   = REPLACE(@colString,isnull(NCHAR(UNICODE(SUBSTRING(@colString, @counter, 1))),'|'),'|')
           set @colString = REPLACE(@colString,'|','')

           SET @counter = @counter + 1
       END
    return @inputtext
END

I call it like this:

BEGIN TRAN  --COMMIT    ROLLBACK
update pmdb.TrackerData
set CIRCUIT_COMMENTS = [dbo].[RemoveNonPrintable](CIRCUIT_COMMENTS),
    COE_COMMENTS = [dbo].[RemoveNonPrintable](COE_COMMENTS),
    MEETING_NOTES = [dbo].[RemoveNonPrintable](MEETING_NOTES),
    OSP_COMMENTS = [dbo].[RemoveNonPrintable](OSP_COMMENTS),
    COE_COMMENTS2 = [dbo].[RemoveNonPrintable](COE_COMMENTS2)

Then I run the code from the previous update to see if there is any difference. There is no difference. What gives? Am I doing this wrong?

EDIT 3

I've updated my function to have this:

    set @colString = @inputtext

    WHILE @counter <= DATALENGTH(@colString)
       BEGIN
           --set @colString = REPLACE(@colString,isnull(NCHAR(UNICODE(SUBSTRING(@colString, @counter, 1))),'|'),'|')
           --set @colString = REPLACE(@colString,'|','')
           if (UNICODE(SUBSTRING(@colString, @counter,1)) > 126)
           BEGIN
            SET @colString = REPLACE(@colString, CONVERT(nvarchar(1),(SUBSTRING(@colString, @counter,1))), CHAR(32))
           END
           ELSE IF(UNICODE(SUBSTRING(@colString, @counter, 1)) < 32)
           BEGIN
            SET @colString = REPLACE(@colString, CONVERT(nvarchar(1),(SUBSTRING(@colString, @counter,1))), CHAR(32))
           END

           set @inputtext = @colString

           SET @counter = @counter + 1
       END

It removes most of the invalid characters, but then it leaves others. I call it on a temp table that I created that holds the sample of invalid characters shown above like this:

update #Temp
set Notes = [dbo].[RemoveNonPrintable](Notes),
    Notes2 = [dbo].[RemoveNonPrintable](Notes2)

Then I'm left with the following in the two Notes:

Notes: ????N???u?z?????????)???)?N??????G????>???????)???)?)???????? ????U??????????  ???????)???)?L?)?????????)?????N???N???????

Notes2:     ᯸ࢹᖈ 㹨   ⻄   ⸀  )䀤  )  ᛡ ꗘᖃᒨ  ᘍ ᐜᏰ>֔      ) ௿ ) )Ἡ      ࣆ       ᓜ Ꮫ֔Ꮫ֨Ꮫ꯼ᓜ   ఍   ఍ )   )   )᯸ࢹ䮸ࣉ᯸ࢹ䮸ࣉ )Ԍ   ֐ᕄ  ᛙ ꗘᖃᒨ᯸ࢹ

Which is better than what I started with, but still not good enough.

Body:
I have found a solution in another users question here

I modified it slightly though. What ends up working for me is this:

ALTER FUNCTION [dbo].[RemoveNonASCII]
(
    -- Parameters
    @nstring nvarchar(max)
)
RETURNS varchar(max)
AS
BEGIN
    -- Variables
    DECLARE @Result varchar(max) = '',@nchar nvarchar(1), @position int

    -- T-SQL statements to compute the return value
    set @position = 1
    while @position <= LEN(@nstring)
    BEGIN
        set @nchar = SUBSTRING(@nstring, @position, 1)
        if UNICODE(@nchar) between 32 and 127
            set @Result = @Result + @nchar
        set @position = @position + 1
        set @Result = REPLACE(@Result,'))','')
        set @Result = REPLACE(@Result,'?','')
    END

    -- Return the result
    RETURN @Result

END


答:
You could declare M2 as a class property:

```<code>private DeltaMotor M2 { get; set; }

public MainWindow()
{
    InitializeComponent();
    M2 = new DeltaMotor();
    M2.Card.Set8255();
    M2.Stop();
}
</code>```

and then access it from whatever method you want:

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    M2.Move(1);
}
</code>```

Title: About C# object scope

Body:
You could declare M2 as a class property:

private DeltaMotor M2 { get; set; }

public MainWindow()
{
    InitializeComponent();
    M2 = new DeltaMotor();
    M2.Card.Set8255();
    M2.Stop();
}

and then access it from whatever method you want:

private void Button_Click(object sender, RoutedEventArgs e)
{
    M2.Move(1);
}


问:
Delete unused ViewController from memory
I have 3 ViewController.
The first ViewController is checking if the user is logged in.
If yes performSegue to the mainVC and if no performSegue to loginVC.

When I am in loginVC, I log in and performSegue to mainVC.

What I want now is, I want to have all ViewControllers which are unused being "deleted", to save memory.
How is that going to work?

I found here in StackOverflow this piece of code:

```<code>class ManualSegue: UIStoryboardSegue {

  override func perform() {
    sourceViewController.presentViewController(destinationViewController, animated: true) {
      self.sourceViewController.navigationController?.popToRootViewControllerAnimated(false)
      UIApplication.sharedApplication().delegate?.window??.rootViewController = self.destinationViewController
    }
  }
}
</code>```

Is that going to do what I want? It seems like yes because this method is popping the ViewController.

I am using "Show Detail" - segues only, except when using this method I created a custom Segue Segue.

答:
Deletion should be handled by Apple, you (theoretically) shouldn't have to worry about it, so long as you don't create any retain cycles. As a rule, just don't have any strong references to self in blocks. Funny enough, the code you have above, that should dismiss the ViewController (and therefore delete it) also has a retain cycle. Adding [weak self] and strongSelf casts as needed should help:

```<code>override func perform() {
    sourceViewController.presentViewController(destinationViewController, animated: true) { [weak self] in
        guard let strongSelf = self else { return }
        strongSelf.sourceViewController.navigationController?.popToRootViewControllerAnimated(false)
        UIApplication.sharedApplication().delegate?.window??.rootViewController = strongSelf.destinationViewController
    }
}
</code>```

Body:
I have 3 ViewController.
The first ViewController is checking if the user is logged in.
If yes performSegue to the mainVC and if no performSegue to loginVC.

When I am in loginVC, I log in and performSegue to mainVC.

What I want now is, I want to have all ViewControllers which are unused being "deleted", to save memory.
How is that going to work?

I found here in StackOverflow this piece of code:

class ManualSegue: UIStoryboardSegue {

  override func perform() {
    sourceViewController.presentViewController(destinationViewController, animated: true) {
      self.sourceViewController.navigationController?.popToRootViewControllerAnimated(false)
      UIApplication.sharedApplication().delegate?.window??.rootViewController = self.destinationViewController
    }
  }
}

Is that going to do what I want? It seems like yes because this method is popping the ViewController.

I am using "Show Detail" - segues only, except when using this method I created a custom Segue Segue.

Body:
Deletion should be handled by Apple, you (theoretically) shouldn't have to worry about it, so long as you don't create any retain cycles. As a rule, just don't have any strong references to self in blocks. Funny enough, the code you have above, that should dismiss the ViewController (and therefore delete it) also has a retain cycle. Adding [weak self] and strongSelf casts as needed should help:

override func perform() {
    sourceViewController.presentViewController(destinationViewController, animated: true) { [weak self] in
        guard let strongSelf = self else { return }
        strongSelf.sourceViewController.navigationController?.popToRootViewControllerAnimated(false)
        UIApplication.sharedApplication().delegate?.window??.rootViewController = strongSelf.destinationViewController
    }
}


问:
Analysis Services C#
Currently we use the following lines of code to connect to our SSAS server using C#. This server only runs in multidimensional mode.

```<code>Server objServer = new Server();
objServer.Connect("ServerName");
</code>```

Our new server runs in both multidimensional and tabular modes and we are getting generic errors trying to connect using the same code in this fashion.

```<code>Server objServer = new Server();
objServer.Connect("ServerName\Instance");
</code>```

Connecting using the ServerName\Instance format works fine using SQL Server Management Studio but our C# code is apparently missing something.

答:
Try escaping the \ in ServerName\Instance

objServer.Connect("ServerName\\Instance");

or

objServer.Connect(@"ServerName\Instance");

Title: Analysis Services C#

Body:
Currently we use the following lines of code to connect to our SSAS server using C#. This server only runs in multidimensional mode.

Server objServer = new Server();
objServer.Connect("ServerName");

Our new server runs in both multidimensional and tabular modes and we are getting generic errors trying to connect using the same code in this fashion.

Server objServer = new Server();
objServer.Connect("ServerName\Instance");

Connecting using the ServerName\Instance format works fine using SQL Server Management Studio but our C# code is apparently missing something.


问:
Condition and row and column with a double loop
I get a problem about "subscript out of bounds", what I want is to get the first and last month for each observation where I have three consecutive "1" or "True". I want to create 2 new column "begin" and "end" where I get repectively the first month and the last month.
In my example for the first observation : begin equal to avril and end equal to juin
In the 5 observation : begin equal to fevrier and end equal to avril
In the 9 observation : begin equal to janvier and end equal to mars
...

I tried to do this :

```<code>nom <- letters[1:5]
pseudo <- paste(name, 21:25, sep = "")
janvier <- c(0, 1, 1, 1, 0)
fevrier <- c(1, 1, 1, 1, 1)
mars <- c(0, 0, 0, 1, 1)
avril <- c(1, 1, 1, 0, 1)
mai <- c(1, 0, 1, 1, 1)
juin <- c(1, 1, 0, 1, 0)

df <- data.frame(nom =nom, pseudo = pseudo, janvier = janvier,
                 fevrier = fevrier, mars = mars, avril = avril,
                 mai = mai, juin = juin)

dfm <- as.matrix(df[, -c(1, 2)])

my_matrix <- matrix(nrow = 10, ncol = 6)

for(i in 1:dim(dfm)[1]){
  for(j in 1:dim(dfm)[2]){
    if(dfm[i, j] + dfm[i, j+1] + dfm[i, j+2] == 3){
      my_matrix[i, j] <- "periode_ok"
      my_matrix[i, j+1] <- "periode_ok"
      my_matrix[i, j+2] <- "periode_ok"
    }
  }
}
</code>```

The ouput should be this :

```<code>begin <- c("avril", "no  info", "no info",
           "janvier", "fevrier", "avril", "no info",
           "no info", "janvier", "fevrier")
end <- c("juin", "no info", "no info", "mars",
         "avril", "juin", "no info", "no info",
         "mars", "avril")

output <- data.frame(nom =nom, pseudo = pseudo, janvier = janvier,
                 fevrier = fevrier, mars = mars, avril = avril,
                 mai = mai, juin = juin, begin = begin,end = end)
</code>```

Any help will be apreciated

答:
First of all, constructs like 1:dim(dfm)[1]are dangerous because if dim(dfm)[1]is zero you will get the perfectly valid vector 1:0 and the loop will try to address element zero of a vector or, in this case, matrix. This is illegal and will throw an error. The recommended solution is to use seq_len(...).
Second, instead of dim(dfm)[.] I've used nrow and ncol.
Now for the error you've got. You are trying to address columns j + 1 and j + 2, so when j reaches ncol(dfm) you're out of bonds. The code below removes the last two elements of the loop limit.

```<code>n <- ncol(dfm)
for(i in seq_len(nrow(dfm))){
  for(j in seq_len(n)[-c(n - 1, n)]){
    if(dfm[i, j] + dfm[i, j+1] + dfm[i, j+2] == 3){
      my_matrix[i, j] <- "periode_ok"
      my_matrix[i, j+1] <- "periode_ok"
      my_matrix[i, j+2] <- "periode_ok"
    }
  }
}

my_matrix
</code>```

Body:
I get a problem about "subscript out of bounds", what I want is to get the first and last month for each observation where I have three consecutive "1" or "True". I want to create 2 new column "begin" and "end" where I get repectively the first month and the last month.
In my example for the first observation : begin equal to avril and end equal to juin
In the 5 observation : begin equal to fevrier and end equal to avril
In the 9 observation : begin equal to janvier and end equal to mars
...

I tried to do this :

nom <- letters[1:5]
pseudo <- paste(name, 21:25, sep = "")
janvier <- c(0, 1, 1, 1, 0)
fevrier <- c(1, 1, 1, 1, 1)
mars <- c(0, 0, 0, 1, 1)
avril <- c(1, 1, 1, 0, 1)
mai <- c(1, 0, 1, 1, 1)
juin <- c(1, 1, 0, 1, 0)

df <- data.frame(nom =nom, pseudo = pseudo, janvier = janvier,
                 fevrier = fevrier, mars = mars, avril = avril,
                 mai = mai, juin = juin)

dfm <- as.matrix(df[, -c(1, 2)])

my_matrix <- matrix(nrow = 10, ncol = 6)

for(i in 1:dim(dfm)[1]){
  for(j in 1:dim(dfm)[2]){
    if(dfm[i, j] + dfm[i, j+1] + dfm[i, j+2] == 3){
      my_matrix[i, j] <- "periode_ok"
      my_matrix[i, j+1] <- "periode_ok"
      my_matrix[i, j+2] <- "periode_ok"
    }
  }
}

The ouput should be this :

begin <- c("avril", "no  info", "no info",
           "janvier", "fevrier", "avril", "no info",
           "no info", "janvier", "fevrier")
end <- c("juin", "no info", "no info", "mars",
         "avril", "juin", "no info", "no info",
         "mars", "avril")

output <- data.frame(nom =nom, pseudo = pseudo, janvier = janvier,
                 fevrier = fevrier, mars = mars, avril = avril,
                 mai = mai, juin = juin, begin = begin,end = end)

Any help will be apreciated

Body:
First of all, constructs like 1:dim(dfm)[1]are dangerous because if dim(dfm)[1]is zero you will get the perfectly valid vector 1:0 and the loop will try to address element zero of a vector or, in this case, matrix. This is illegal and will throw an error. The recommended solution is to use seq_len(...).
Second, instead of dim(dfm)[.] I've used nrow and ncol.
Now for the error you've got. You are trying to address columns j + 1 and j + 2, so when j reaches ncol(dfm) you're out of bonds. The code below removes the last two elements of the loop limit.

n <- ncol(dfm)
for(i in seq_len(nrow(dfm))){
  for(j in seq_len(n)[-c(n - 1, n)]){
    if(dfm[i, j] + dfm[i, j+1] + dfm[i, j+2] == 3){
      my_matrix[i, j] <- "periode_ok"
      my_matrix[i, j+1] <- "periode_ok"
      my_matrix[i, j+2] <- "periode_ok"
    }
  }
}

my_matrix


问:
Select deserialiser based on Serialised data
Sorry for the bad title, but I wasn't sure on how to name it. I need to find a way to handle the following:

I have a class

```<code>public class Event
{
     public ushort Id;
}
</code>```

This class consumer of my framework have to inherit their custom event of. So let's say if they want to create the following:

```<code>public class OnConnect : Event
{
     ...
}
</code>```

The ID is used to identify in a server/client enviroment, when the serialized byte[] data is transfered, to which event you have to deserialize the byte data. So basically in the byte[] data, the first 2 bytes contain the ushort id. Then I can read this, get the associacted type and call the correct deserializer.

But as the time showed, one potential issue or wrong usage, is, that the consumer forgets to assign a unique ushort id in their custom events or use the same id for multiple events as they don't check for that. Teaching them to use an enum as an example, tended to cause some additional problems. Anyways even if it seem easy to manage, our reports claim that this is a common issue.

So I want now to automate this to remove this possible issue. But I have really hard times, finding a possible way to solve this, as I have the following structure:

A server/client enviroment, where the process I choose, has to deliver the same result on both ends

The events itself cannot be used to initialize this number as it isn't always the same order when event x is first used.

First I thought about dependency injection with an interface like IRequireId or so and on my retrieve medthod like x.componentes.Where(c=>c is IRequireId) I assign a unique id to the event and store it somewhere else and when the event is initialized I can get the id from there. The problem with this is, that I cannot ensure, that the x.components.Where is retrieving the components in the same order as on the other peers on the network. Thus different id's could be assigned.

So I think DI is off the road. Has someone else any idea, or an idea on how to make sure, that my retrievement method does save any order, so that it is the same on each peer on the network?

As of writing this I had the idea of maybe using a HashSet and write my own GetHashcode that does reproduce the same hashcode on each peer. And then iterating over the hashset and doe the DI on the IRequireId interface. But how could I write a hashcode generation that is the same on each peer on the network? That would need and id again. Damn it.

Please help x) I'm a bit lost currently.
tia Synergi

EDIT

I forgot to note, as someone already asked this, why not simply add the type as a string into the byte array?

As this is a network enviroment, we do care about the size of the byte array. And if we just want to send let's say 4 bytes of data in an event and the byte[] itself is 20 bytes long because of 16 bytes of a string containing the type, than this is inacceptable.

EDIT

Thx to the hint with the class name I'm now able to solve it.

I use the class name to generate a hashcode

I can then use this to ensure order in my get method

And finally I can do DI with creating an ushort id

awesome thx for the help

答:
If I understand, you're serializing an object as a byte array, and you need some sort of identifier to tell you to what the original type was so that you can deserialize it to the correct type.

Instead of a number, why not just use the Type of the object you serialized? Or if this itself needs to be serialized, the name of the type? That way there's no need to match a number to a type. You already have the type.

Body:
Sorry for the bad title, but I wasn't sure on how to name it. I need to find a way to handle the following:

I have a class

public class Event
{
     public ushort Id;
}

This class consumer of my framework have to inherit their custom event of. So let's say if they want to create the following:

public class OnConnect : Event
{
     ...
}

The ID is used to identify in a server/client enviroment, when the serialized byte[] data is transfered, to which event you have to deserialize the byte data. So basically in the byte[] data, the first 2 bytes contain the ushort id. Then I can read this, get the associacted type and call the correct deserializer.

But as the time showed, one potential issue or wrong usage, is, that the consumer forgets to assign a unique ushort id in their custom events or use the same id for multiple events as they don't check for that. Teaching them to use an enum as an example, tended to cause some additional problems. Anyways even if it seem easy to manage, our reports claim that this is a common issue.

So I want now to automate this to remove this possible issue. But I have really hard times, finding a possible way to solve this, as I have the following structure:

A server/client enviroment, where the process I choose, has to deliver the same result on both ends

The events itself cannot be used to initialize this number as it isn't always the same order when event x is first used.

First I thought about dependency injection with an interface like IRequireId or so and on my retrieve medthod like x.componentes.Where(c=>c is IRequireId) I assign a unique id to the event and store it somewhere else and when the event is initialized I can get the id from there. The problem with this is, that I cannot ensure, that the x.components.Where is retrieving the components in the same order as on the other peers on the network. Thus different id's could be assigned.

So I think DI is off the road. Has someone else any idea, or an idea on how to make sure, that my retrievement method does save any order, so that it is the same on each peer on the network?

As of writing this I had the idea of maybe using a HashSet and write my own GetHashcode that does reproduce the same hashcode on each peer. And then iterating over the hashset and doe the DI on the IRequireId interface. But how could I write a hashcode generation that is the same on each peer on the network? That would need and id again. Damn it.

Please help x) I'm a bit lost currently.
tia Synergi

EDIT

I forgot to note, as someone already asked this, why not simply add the type as a string into the byte array?

As this is a network enviroment, we do care about the size of the byte array. And if we just want to send let's say 4 bytes of data in an event and the byte[] itself is 20 bytes long because of 16 bytes of a string containing the type, than this is inacceptable.

EDIT

Thx to the hint with the class name I'm now able to solve it.

I use the class name to generate a hashcode

I can then use this to ensure order in my get method

And finally I can do DI with creating an ushort id

awesome thx for the help


问:
How to open update electron browser window with a new html file
I am new to electron. I have two html pages and I want to open the second page when a button clicked. I have code this as follow, but I just get a blank window; not the second page.

This is index.js

```<code>const electron = require('electron')
const {app, BrowserWindow} = electron

app.on('ready',()=>{
  let win = new BrowserWindow({width:960, hehight:540})
  win.loadURL(`file://${__dirname}/login.html`)
})

exports.openWindow = (fileName) => {
  let win = new BrowserWindow({width:960, height:540})
  win.loadURL(`file://${__dirname}/` + fileName + `.html`)
}
</code>```

This is login.js

```<code>const remote = require('electron').remote
const index = remote.require('./index.js')

var login = document.getElementById('login')
login.addEventListner('click', () => {
  var window = remote.getCurrentWindow()
  index.openWindow('pageTwo')
  window.close()
}, false)
</code>```

login is the id of the html button.

I want to get the page two. How can I perform this?

答:
accessing a required functionality with the remote api from the renderer process at times result in a deadlock when ever you call that functionlaity with an argument. You should do this , using ipc

```<code> // main process
  const { app, BrowserWindow, ipcMain: ipc } = require("electron");
  let win;
  app.on("ready", () => {
    win = new BrowserWindow();
    win.loadURL(`file://${__dirname}/index.html`);
 });

 ipc.on("send-window-id", (event) => {
    event.sender.send("window-id-sent", win.id);
 });

// renderer process

<html>
   <head></head>
   <body>
      <button>new window</button>
      <script>
         const { remote: { BrowserWindow }, ipcRenderer: ipc } = require("electron");

         var button = document.querySelector("button");
         button.addEventListener("click", event => {
           let win = new BrowserWindow();
           win.loadURL(`file://${__dirname}/page2.html`);
           ipc.send("send-window-id");
        });
        ipc.on("window-id-sent", (event,id) => {
           BrowserWindow.fromId(id).close();
        });
     </script>
   </body>
</html>
</code>```

The BrowserWindow.fromId recieves the id of a window and returns the window object of that id

Body:
I am new to electron. I have two html pages and I want to open the second page when a button clicked. I have code this as follow, but I just get a blank window; not the second page.

This is index.js

const electron = require('electron')
const {app, BrowserWindow} = electron

app.on('ready',()=>{
  let win = new BrowserWindow({width:960, hehight:540})
  win.loadURL(`file://${__dirname}/login.html`)
})

exports.openWindow = (fileName) => {
  let win = new BrowserWindow({width:960, height:540})
  win.loadURL(`file://${__dirname}/` + fileName + `.html`)
}

This is login.js

const remote = require('electron').remote
const index = remote.require('./index.js')

var login = document.getElementById('login')
login.addEventListner('click', () => {
  var window = remote.getCurrentWindow()
  index.openWindow('pageTwo')
  window.close()
}, false)

login is the id of the html button.

I want to get the page two. How can I perform this?

Body:
accessing a required functionality with the remote api from the renderer process at times result in a deadlock when ever you call that functionlaity with an argument. You should do this , using ipc

 // main process
  const { app, BrowserWindow, ipcMain: ipc } = require("electron");
  let win;
  app.on("ready", () => {
    win = new BrowserWindow();
    win.loadURL(`file://${__dirname}/index.html`);
 });

 ipc.on("send-window-id", (event) => {
    event.sender.send("window-id-sent", win.id);
 });

// renderer process

<html>
   <head></head>
   <body>
      <button>new window</button>
      <script>
         const { remote: { BrowserWindow }, ipcRenderer: ipc } = require("electron");

         var button = document.querySelector("button");
         button.addEventListener("click", event => {
           let win = new BrowserWindow();
           win.loadURL(`file://${__dirname}/page2.html`);
           ipc.send("send-window-id");
        });
        ipc.on("window-id-sent", (event,id) => {
           BrowserWindow.fromId(id).close();
        });
     </script>
   </body>
</html>

The BrowserWindow.fromId recieves the id of a window and returns the window object of that id


问:
How can I get full package names from sdkmanager --list?
I am trying to use the android SDK manager to install a system image. However, when I use tools/bin/sdkmanager --list, the output I get looks like this (truncated for brevity):

```<code>Available Packages:
  Path                              | Version      | Description
  -------                           | -------      | -------
...
system-images;a...-15;default;x86 | 4            | Intel x86 Atom System Image
system-images;a...pis;armeabi-v7a | 5            | Google APIs ARM EABI v7a Syste...
system-images;a...google_apis;x86 | 5            | Google APIs Intel x86 Atom Sys...
system-images;a...ult;armeabi-v7a | 4            | ARM EABI v7a System Image
system-images;a...16;default;mips | 1            | MIPS System Image
system-images;a...-16;default;x86 | 5            | Intel x86 Atom System Image
system-images;a...pis;armeabi-v7a | 5            | Google APIs ARM EABI v7a Syste...
system-images;a...google_apis;x86 | 5            | Google APIs Intel x86 Atom Sys...
system-images;a...ult;armeabi-v7a | 5            | ARM EABI v7a System Image
system-images;a...17;default;mips | 1            | MIPS System Image
system-images;a...-17;default;x86 | 3            | Intel x86 Atom System Image
system-images;a...pis;armeabi-v7a | 5            | Google APIs ARM EABI v7a Syste...
...
</code>```

Unfortunately, I cannot use a path of this form to install.

```<code>sdkmanager system-images;a...-17;default;x86
Failed to find package system-images;a...ult;armeabi-v7a
</code>```

How can I get the long form of the package name so I can actually install it?

答:
Another answer mentioned that you can use the --list and --verbose flags combined in the newer versions of sdkmanager (starting with version 26.0.1).

If it helps, though, the format is basically the path relative to your android_sdk folder, with the slashes (\ or /) replaced with semicolons.  Of course, you have to know what the path of something should be in order to install that particular thing...

Body:
I am trying to use the android SDK manager to install a system image. However, when I use tools/bin/sdkmanager --list, the output I get looks like this (truncated for brevity):

Available Packages:
  Path                              | Version      | Description
  -------                           | -------      | -------
...
system-images;a...-15;default;x86 | 4            | Intel x86 Atom System Image
system-images;a...pis;armeabi-v7a | 5            | Google APIs ARM EABI v7a Syste...
system-images;a...google_apis;x86 | 5            | Google APIs Intel x86 Atom Sys...
system-images;a...ult;armeabi-v7a | 4            | ARM EABI v7a System Image
system-images;a...16;default;mips | 1            | MIPS System Image
system-images;a...-16;default;x86 | 5            | Intel x86 Atom System Image
system-images;a...pis;armeabi-v7a | 5            | Google APIs ARM EABI v7a Syste...
system-images;a...google_apis;x86 | 5            | Google APIs Intel x86 Atom Sys...
system-images;a...ult;armeabi-v7a | 5            | ARM EABI v7a System Image
system-images;a...17;default;mips | 1            | MIPS System Image
system-images;a...-17;default;x86 | 3            | Intel x86 Atom System Image
system-images;a...pis;armeabi-v7a | 5            | Google APIs ARM EABI v7a Syste...
...

Unfortunately, I cannot use a path of this form to install.

sdkmanager system-images;a...-17;default;x86
Failed to find package system-images;a...ult;armeabi-v7a

How can I get the long form of the package name so I can actually install it?


问:
Jackson deserialization/serialization does not sort properties
I'm using Jackson 2.8.9 in my application to generate some JSON. I have some unit tests in which I compare generated JSON with some files content.

When I compare my generated JSON with my file content, it does not match due to the properties order.

For the tests to be repeatable I need to have the properties sorted alphabetically. But with Jackson, it does not seems to work.

I wrote some tests for illustation. Only should_indent_properties pass.

```<code>public class FormatJsonWithJacksonTest {

private static final String INDENTED_UNSORTED = "{\r\n" +
        "  \"firstChild\" : {\r\n" +
        "    \"subChild\" : {\r\n" +
        "      \"alphaItem\" : \"1234567891234567\",\r\n" +
        "      \"otherProperty\" : \"2017-06-21\",\r\n" +
        "      \"someOtherProperty\" : \"NONE\",\r\n" +
        "      \"alphaType\" : \"KIND_OF_TYPE\"\r\n" +
        "    }\r\n" +
        "  }\r\n" +
        "}";

private static final String INDENTED_SORTED = "{\r\n" +
        "  \"firstChild\" : {\r\n" +
        "    \"subChild\" : {\r\n" +
        "      \"alphaItem\" : \"1234567891234567\",\r\n" +
        "      \"alphaType\" : \"KIND_OF_TYPE\",\r\n" +
        "      \"otherProperty\" : \"2017-06-21\",\r\n" +
        "      \"someOtherProperty\" : \"NONE\"\r\n" +
        "    }\r\n" +
        "  }\r\n" +
        "}";

private static final String UNINDENTED_UNSORTED = "{" +
        "\"firstChild\":{" +
        "\"subChild\":{" +
        "\"alphaItem\":\"1234567891234567\"," +
        "\"otherProperty\":\"2017-06-21\"," +
        "\"someOtherProperty\":\"NONE\"," +
        "\"alphaType\":\"KIND_OF_TYPE\"" +
        "}" +
        "}" +
        "}";

private static final String UNINDENTED_SORTED = "{" +
        "\"firstChild\":{" +
        "\"subChild\":{" +
        "\"alphaItem\":\"1234567891234567\"," +
        "\"alphaType\":\"KIND_OF_TYPE\"," +
        "\"otherProperty\":\"2017-06-21\"," +
        "\"someOtherProperty\":\"NONE\"" +
        "}" +
        "}" +
        "}";

@Test
public void should_sort_properties() throws Exception {
    // Given
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper = objectMapper
            .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);

    // When
    String formattedJson = tryingToFormatJson(objectMapper, INDENTED_UNSORTED);

    // Then
    assertEquals(UNINDENTED_SORTED, formattedJson);
}

@Test
public void should_indent_properties() throws Exception {
    // Given
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper = objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    // When
    String formattedJson = tryingToFormatJson(objectMapper, UNINDENTED_UNSORTED);

    // Then
    assertEquals(INDENTED_UNSORTED, formattedJson);
}

@Test
public void should_sort_and_indent_properties() throws Exception {
    // Given
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper = objectMapper
            .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
            .enable(SerializationFeature.INDENT_OUTPUT);

    // When
    String formattedJson = tryingToFormatJson(objectMapper, INDENTED_UNSORTED);

    // Then
    assertEquals(INDENTED_SORTED, formattedJson);
}

//
// Utils
//

private String tryingToFormatJson(ObjectMapper objectMapper, String unformattedJson)
        throws IOException, JsonProcessingException {
    JsonNode unsortedTree = objectMapper.readTree(unformattedJson);
    Object treeToValue = objectMapper.treeToValue(unsortedTree, Object.class);
    return objectMapper.writeValueAsString(treeToValue);
}

}
</code>```

How could I sort my JSON with Jackson?

Do you have any solution for implementing my method tryingToFormatJson?

Is Jackson the right tool I want for doing this?

答:
When you call objectMapper.treeToValue(unsortedTree, Object.class), the Object's type is a subclass of Map - just put a System.out.println(treeToValue.getClass()) to check.

And according to javadoc, SORT_PROPERTIES_ALPHABETICALLY doesn't sort map keys:

Feature that defines default property serialization order used for POJO fields (note: does not apply to Map serialization!)

If you want to sort the fields, you have to create a custom class for you structure, like this:

```<code>public class Tree {
    private Map<String, Child> firstChild;

    // getters and setters
}

public class Child {
    private String alphaItem;

    private String otherProperty;

    private String someOtherProperty;

    private String alphaType;

    // getters and setters
}
</code>```

And change the treeToValue call to:

```<code>Tree treeToValue = objectMapper.treeToValue(unsortedTree, Tree.class);
</code>```

With this, the fields will be sorted and the test will work.

Body:
I'm using Jackson 2.8.9 in my application to generate some JSON. I have some unit tests in which I compare generated JSON with some files content.

When I compare my generated JSON with my file content, it does not match due to the properties order.

For the tests to be repeatable I need to have the properties sorted alphabetically. But with Jackson, it does not seems to work.

I wrote some tests for illustation. Only should_indent_properties pass.

public class FormatJsonWithJacksonTest {

private static final String INDENTED_UNSORTED = "{\r\n" +
        "  \"firstChild\" : {\r\n" +
        "    \"subChild\" : {\r\n" +
        "      \"alphaItem\" : \"1234567891234567\",\r\n" +
        "      \"otherProperty\" : \"2017-06-21\",\r\n" +
        "      \"someOtherProperty\" : \"NONE\",\r\n" +
        "      \"alphaType\" : \"KIND_OF_TYPE\"\r\n" +
        "    }\r\n" +
        "  }\r\n" +
        "}";

private static final String INDENTED_SORTED = "{\r\n" +
        "  \"firstChild\" : {\r\n" +
        "    \"subChild\" : {\r\n" +
        "      \"alphaItem\" : \"1234567891234567\",\r\n" +
        "      \"alphaType\" : \"KIND_OF_TYPE\",\r\n" +
        "      \"otherProperty\" : \"2017-06-21\",\r\n" +
        "      \"someOtherProperty\" : \"NONE\"\r\n" +
        "    }\r\n" +
        "  }\r\n" +
        "}";

private static final String UNINDENTED_UNSORTED = "{" +
        "\"firstChild\":{" +
        "\"subChild\":{" +
        "\"alphaItem\":\"1234567891234567\"," +
        "\"otherProperty\":\"2017-06-21\"," +
        "\"someOtherProperty\":\"NONE\"," +
        "\"alphaType\":\"KIND_OF_TYPE\"" +
        "}" +
        "}" +
        "}";

private static final String UNINDENTED_SORTED = "{" +
        "\"firstChild\":{" +
        "\"subChild\":{" +
        "\"alphaItem\":\"1234567891234567\"," +
        "\"alphaType\":\"KIND_OF_TYPE\"," +
        "\"otherProperty\":\"2017-06-21\"," +
        "\"someOtherProperty\":\"NONE\"" +
        "}" +
        "}" +
        "}";

@Test
public void should_sort_properties() throws Exception {
    // Given
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper = objectMapper
            .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);

    // When
    String formattedJson = tryingToFormatJson(objectMapper, INDENTED_UNSORTED);

    // Then
    assertEquals(UNINDENTED_SORTED, formattedJson);
}

@Test
public void should_indent_properties() throws Exception {
    // Given
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper = objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    // When
    String formattedJson = tryingToFormatJson(objectMapper, UNINDENTED_UNSORTED);

    // Then
    assertEquals(INDENTED_UNSORTED, formattedJson);
}

@Test
public void should_sort_and_indent_properties() throws Exception {
    // Given
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper = objectMapper
            .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
            .enable(SerializationFeature.INDENT_OUTPUT);

    // When
    String formattedJson = tryingToFormatJson(objectMapper, INDENTED_UNSORTED);

    // Then
    assertEquals(INDENTED_SORTED, formattedJson);
}

//
// Utils
//

private String tryingToFormatJson(ObjectMapper objectMapper, String unformattedJson)
        throws IOException, JsonProcessingException {
    JsonNode unsortedTree = objectMapper.readTree(unformattedJson);
    Object treeToValue = objectMapper.treeToValue(unsortedTree, Object.class);
    return objectMapper.writeValueAsString(treeToValue);
}

}

How could I sort my JSON with Jackson?

Do you have any solution for implementing my method tryingToFormatJson?

Is Jackson the right tool I want for doing this?

Body:
When you call objectMapper.treeToValue(unsortedTree, Object.class), the Object's type is a subclass of Map - just put a System.out.println(treeToValue.getClass()) to check.

And according to javadoc, SORT_PROPERTIES_ALPHABETICALLY doesn't sort map keys:

Feature that defines default property serialization order used for POJO fields (note: does not apply to Map serialization!)

If you want to sort the fields, you have to create a custom class for you structure, like this:

public class Tree {
    private Map<String, Child> firstChild;

    // getters and setters
}

public class Child {
    private String alphaItem;

    private String otherProperty;

    private String someOtherProperty;

    private String alphaType;

    // getters and setters
}

And change the treeToValue call to:

Tree treeToValue = objectMapper.treeToValue(unsortedTree, Tree.class);

With this, the fields will be sorted and the test will work.


问:
GetWindowRect returns NullReferenceException
I'm trying to get size and position of a certain window attached to javaw.exe process.

Sadly, GetWindowRect throws an error: "NullReferenceException" - and I've checked, none of it's arguments == null.

Here's the piece of code

Invoking sample:

```<code>    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetWindowRect(IntPtr handle, out WindowRect rect);
    [StructLayout(LayoutKind.Sequential)]
    private class WindowRect
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }
</code>```

Running static function to attach process:

NB.Attach( Process.GetProcessesByName("javaw")[0] );

Usage sample:

```<code>    public static void Attach( Process process )
    {
        FocusProcess = process;
        FocusWindow = FindWindow(null, process.MainWindowTitle);
    }

    public static int[] GetWindowPosition()
    {
        WindowRect rect = new WindowRect();

        Console.WriteLine(FocusProcess == null);
        Console.WriteLine(FocusProcess.MainWindowHandle == null);
        Console.WriteLine(rect==null);
        GetWindowRect(FocusProcess.MainWindowHandle, out rect);
        if ( rect.Top != 0 )
        {
            return new int[] { rect.Left, rect.Top };
        }
        return new int[] { 0, 0 };
    }
</code>```

Thanks in advance, I'm totally inexperienced if it comes to usage of native functions.

答:
You declared the struct as a C# class. That's a reference type already. So when you pass it as an out param you now have a double pointer. Either

Change from class to struct,

or pass the class by value.

Body:
I'm trying to get size and position of a certain window attached to javaw.exe process.

Sadly, GetWindowRect throws an error: "NullReferenceException" - and I've checked, none of it's arguments == null.

Here's the piece of code

Invoking sample:

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetWindowRect(IntPtr handle, out WindowRect rect);
    [StructLayout(LayoutKind.Sequential)]
    private class WindowRect
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }

Running static function to attach process:

NB.Attach( Process.GetProcessesByName("javaw")[0] );

Usage sample:

    public static void Attach( Process process )
    {
        FocusProcess = process;
        FocusWindow = FindWindow(null, process.MainWindowTitle);
    }

    public static int[] GetWindowPosition()
    {
        WindowRect rect = new WindowRect();

        Console.WriteLine(FocusProcess == null);
        Console.WriteLine(FocusProcess.MainWindowHandle == null);
        Console.WriteLine(rect==null);
        GetWindowRect(FocusProcess.MainWindowHandle, out rect);
        if ( rect.Top != 0 )
        {
            return new int[] { rect.Left, rect.Top };
        }
        return new int[] { 0, 0 };
    }

Thanks in advance, I'm totally inexperienced if it comes to usage of native functions.


问:
Excel vba Error 5 Invalid procedure call or argument with power operand
Please consider this sub:

```<code>Sub TestPower()

    Dim dbl As Double

    dbl = -0.682434999562851

    Debug.Print (-0.682434999562851 ^ 0.2)
    Debug.Print (dbl ^ 0.2)
End Sub
</code>```

On the second "debug.print" command, I'm getting an Error 5: Invalid procedure call or argument.

Excel Office 2016.

Any ideas?

答:
Here is a solution to your problem:

```<code>Sub TestPower()
    Dim dbl As Double

    dbl = 0.682434999562851

    Debug.Print (-0.682434999562851 ^ 0.2)
    Debug.Print -(dbl ^ 0.2)
End Sub
</code>```

Notice that I placed the negative sign outside the parenthesis (and changed dbl accordingly).

From the MSDN library, "A number can be negative only if exponent is an integer value."  I'm not a mathematician but it has something to do with the result being a Complex Number.

Body:
Please consider this sub:

Sub TestPower()

    Dim dbl As Double

    dbl = -0.682434999562851

    Debug.Print (-0.682434999562851 ^ 0.2)
    Debug.Print (dbl ^ 0.2)
End Sub

On the second "debug.print" command, I'm getting an Error 5: Invalid procedure call or argument.

Excel Office 2016.

Any ideas?

Body:
Here is a solution to your problem:

Sub TestPower()
    Dim dbl As Double

    dbl = 0.682434999562851

    Debug.Print (-0.682434999562851 ^ 0.2)
    Debug.Print -(dbl ^ 0.2)
End Sub

Notice that I placed the negative sign outside the parenthesis (and changed dbl accordingly).

From the MSDN library, "A number can be negative only if exponent is an integer value."  I'm not a mathematician but it has something to do with the result being a Complex Number.


问:
htaccess - RewriteRule for static files
how to rewrite urls for images and other static files to specific folder, i.e. I am using this so far:

```<code>RewriteRule \.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt)$ /MyFolder/$1
</code>```

but its not working,

please help.

------------------- update ---------------------

ok so now I have:

```<code>RewriteCond %{HTTP_HOST} ^(www.)?exmpale.com$
RewriteCond %{REQUEST_URI} !^/exmpale.com/
RewriteRule ^(.*\.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt))$ /exmpale.com/$1

RewriteCond %{HTTP_HOST} ^(www.)?exmpale.com$
RewriteRule !\.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt)$ /exmpale.com/index.php
</code>```

so images redirected to exmpale folders work but now I would like to rewrite everything else to index.php, above solution is not working so far.

cheers,
/Marcin

答:
You are not capturing the initial request. Try the following:

```<code>RewriteRule (.*)\.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt)$ /MyFolder/$1.$2
</code>```

This will get anything that ends in the extension specified and redirect under /MyFolder/ For example: /something/image.jpg will now go to /MyFolder/something/image.jpg

Note: There may be better ways to do this by adding conditions to check for file type.

ContentLicense: CC BY-SA 2.5

Title: htaccess - RewriteRule for static files

Body:
how to rewrite urls for images and other static files to specific folder, i.e. I am using this so far:

RewriteRule \.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt)$ /MyFolder/$1

but its not working,

please help.

------------------- update ---------------------

ok so now I have:

RewriteCond %{HTTP_HOST} ^(www.)?exmpale.com$
RewriteCond %{REQUEST_URI} !^/exmpale.com/
RewriteRule ^(.*\.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt))$ /exmpale.com/$1

RewriteCond %{HTTP_HOST} ^(www.)?exmpale.com$
RewriteRule !\.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt)$ /exmpale.com/index.php

so images redirected to exmpale folders work but now I would like to rewrite everything else to index.php, above solution is not working so far.

cheers,
/Marcin

Body:
You are not capturing the initial request. Try the following:

RewriteRule (.*)\.(woff|ttf|svg|js|ico|gif|jpg|png|css|htc|xml|txt)$ /MyFolder/$1.$2

This will get anything that ends in the extension specified and redirect under /MyFolder/ For example: /something/image.jpg will now go to /MyFolder/something/image.jpg

Note: There may be better ways to do this by adding conditions to check for file type.


答:
You need to create an instance member of DeltaMotor at the class level.

```<code>private DeltaMotor _m2;

public MainWindow()
{
    InitializeComponent();
    _m2 = new DeltaMotor();
    _m2.Card.Set8255();
    _m2.Stop();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    _m2.Move(1);
}
</code>```

Title: About C# object scope

Body:
So I've created a class and instantiate an object in the main window. Then, when I'm trying to use that object in a button within the same window, I don't know how to indicate the context for this object. I know this is a very basic question, but I'm learning and haven't been able to figure it out just yet.

public MainWindow()
{
    InitializeComponent();
    DeltaMotor M2 = new DeltaMotor();
    M2.Card.Set8255();
    M2.Stop();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    M2.Move(1); // this can't find M2 within the context
}

I know this is basic, but help will be greatly appreciated.

Body:
You need to create an instance member of DeltaMotor at the class level.

private DeltaMotor _m2;

public MainWindow()
{
    InitializeComponent();
    _m2 = new DeltaMotor();
    _m2.Card.Set8255();
    _m2.Stop();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    _m2.Move(1);
}


问:
String to ObjectId using JSON.parse
I am looking to create a dynamic where clause which includes a ObjectId. Not able to convert string into ObjectId with JSON parse.

Here is what I am trying to make work ...

```<code>var className = 'maths';
var studentId = '595d193cd4832d53bfc22cea'
var where = JSON.parse('{ "class.' + className + '.student":' + studentId + '}')

College.findOne(where);
</code>```

My where clause should look below and above statement should run without error

```<code>{class.math.student: 595d193cd4832d53bfc22cea }
</code>```

or

```<code>{class.math.student: ObjectId('595d193cd4832d53bfc22cea') }
</code>```

Please help

答:
You can build the where object without parsing a string:

```<code>var ObjectId = require('mongoose').Types.ObjectId;

var where = { class: {} };
where.class[className] = { student: new ObjectId(studentId) };
</code>```

Title: String to ObjectId using JSON.parse

Body:
I am looking to create a dynamic where clause which includes a ObjectId. Not able to convert string into ObjectId with JSON parse.

Here is what I am trying to make work ...

var className = 'maths';
var studentId = '595d193cd4832d53bfc22cea'
var where = JSON.parse('{ "class.' + className + '.student":' + studentId + '}')

College.findOne(where);

My where clause should look below and above statement should run without error

{class.math.student: 595d193cd4832d53bfc22cea }

or

{class.math.student: ObjectId('595d193cd4832d53bfc22cea') }

Please help

Body:
You can build the where object without parsing a string:

var ObjectId = require('mongoose').Types.ObjectId;

var where = { class: {} };
where.class[className] = { student: new ObjectId(studentId) };


问:
Should URL be case sensitive?
I noticed that

```<code>HTTP://STACKOVERFLOW.COM/QUESTIONS/ASK
</code>```

and

```<code>http://stackoverflow.com/questions/ask
</code>```

both works fine - actually the previous one is converted to lowercase.

I think that this makes sense for the user.

If I look at Google then this URL works fine:

```<code>http://www.google.com/intl/en/about/corporate/index.html
</code>```

but this one with "ABOUT" is not working:

```<code>http://www.google.com/intl/en/ABOUT/corporate/index.html
</code>```

Should the URL be case sensitive?

答: I think this and many of the answers around what the spec does or does not say is missing the point of the question.Should they be case sensitive? That's a loaded question really. From a user's point of view, case sensitivity is a pain point, not all know makes a difference. The question of whether URIs should or shouldn't be, depends on the context of the question. For technical flexibility, yes, they should be. For usability, no, they should not be.

Title: Should URL be case sensitive?

Body:
I noticed that

HTTP://STACKOVERFLOW.COM/QUESTIONS/ASK

and

http://stackoverflow.com/questions/ask

both works fine - actually the previous one is converted to lowercase.

I think that this makes sense for the user.

If I look at Google then this URL works fine:

http://www.google.com/intl/en/about/corporate/index.html

but this one with "ABOUT" is not working:

http://www.google.com/intl/en/ABOUT/corporate/index.html

Should the URL be case sensitive?


问:
Exception safety and make_unique
Just to clarify, using make_unique only adds exception safety when you have multiple allocations in an expression, not just one, correct? For example

```<code>void f(T*);

f(new T);
</code>```

is perfectly exception safe (as far as allocations and stuff), while

```<code>void f(T*, T*);

f(new T, new T);
</code>```

is not, correct?

答:
As of C++17, the exception safety issue is fixed by a rewording of [expr.call]

The initialization of a parameter, including every associated value computation and side effect, is indeterminately sequenced with respect to that of any other parameter.

Here indeterminately sequenced means that one is sequenced before another, but it is not specified which.

```<code>f(unique_ptr<T>(new T), function_that_can_throw());
</code>```

Can have only two possible order of execution

new T unique_ptr<T>::unique_ptr function_that_can_throw

function_that_can_throw new T unique_ptr<T>::unique_ptr

Which means it is now exception safe.

Title: Exception safety and make_unique

Body:
Just to clarify, using make_unique only adds exception safety when you have multiple allocations in an expression, not just one, correct? For example

void f(T*);

f(new T);

is perfectly exception safe (as far as allocations and stuff), while

void f(T*, T*);

f(new T, new T);

is not, correct?

Body:
As of C++17, the exception safety issue is fixed by a rewording of [expr.call]

The initialization of a parameter, including every associated value computation and side effect, is indeterminately sequenced with respect to that of any other parameter.

Here indeterminately sequenced means that one is sequenced before another, but it is not specified which.

f(unique_ptr<T>(new T), function_that_can_throw());

Can have only two possible order of execution

new T unique_ptr<T>::unique_ptr function_that_can_throw

function_that_can_throw new T unique_ptr<T>::unique_ptr

Which means it is now exception safe.


问:
Google Cloud Datastore Queries using Node.js
There is a method to get all the data using Node.js and Google Cloud Datastore.

```<code>var query = ContactModel.query();//contact model is a schema which instantiates gstore schema

query.run().then((result) => {
    const response = result[0];
     var entities       = response.entities;
    callback('',entities);
});
</code>```

Is there a way to run custom query or simply say filters using Node.js and Google Cloud Datastore. I could find only one query example using Node.js and Google Cloud Datastore.

答:
I suggest you use gstore-node, it has a very simple and efficient API, and the documentation has many examples of how to make advanced querys

For example in the documentation it is detailed how to list all the elements

```<code>// blog-post.model.js

// Create Schema
const blogPostSchema = new gstore.Schema({
    title : { type: 'string' },
    isDraft: { type: 'boolean' }
});

// List query settings
const listQuerySettings = {
    limit : 10,
    order : { property: 'title', descending: true }, // descending defaults to false and is optional
    select : 'title',
    ancestors : ['Parent', 123],  // will add an "hasAncestor" filter
    filters : ['isDraft', false] // operator defaults to "=",
};

// Add settings to schema
blogPostSchema.queries('list', listQuerySettings);

// Create Model
const BlogPost = gstore.model('BlogPost', blogPostSchema);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There is a method to get all the data using Node.js and Google Cloud Datastore.

var query = ContactModel.query();//contact model is a schema which instantiates gstore schema

query.run().then((result) => {
    const response = result[0];
     var entities       = response.entities;
    callback('',entities);
});

Is there a way to run custom query or simply say filters using Node.js and Google Cloud Datastore. I could find only one query example using Node.js and Google Cloud Datastore.

Body:
I suggest you use gstore-node, it has a very simple and efficient API, and the documentation has many examples of how to make advanced querys

For example in the documentation it is detailed how to list all the elements

// blog-post.model.js

// Create Schema
const blogPostSchema = new gstore.Schema({
    title : { type: 'string' },
    isDraft: { type: 'boolean' }
});

// List query settings
const listQuerySettings = {
    limit : 10,
    order : { property: 'title', descending: true }, // descending defaults to false and is optional
    select : 'title',
    ancestors : ['Parent', 123],  // will add an "hasAncestor" filter
    filters : ['isDraft', false] // operator defaults to "=",
};

// Add settings to schema
blogPostSchema.queries('list', listQuerySettings);

// Create Model
const BlogPost = gstore.model('BlogPost', blogPostSchema);


问:
Retrieve Steam game data using API request
I'd like to know how to create an API call to the Steam web API in order to retrieve all the relevant data for a specified game.  I found an example call that almost does what I need, except this call requires you to know the Steam app ID as you can see below:

http://store.steampowered.com/api/appdetails/?appids=730

As you can see if you click on the link, all the information I need is returned with the API call.  However I'd like to know if it's possible to modify this API call so that it returns the required information using the game name rather than the Steam ID number?

答:
Unfortunately I don't think this is possible (although the lack of official documentation of the API means I may be wrong).

Firstly, from a design perspective it probably wouldn't work - games could have the same name and so name is not a unique enough reference to identify an item (which is a fundamental concept of a correctly designed REST API).

Secondly, all examples (such as this here) I have come across on the web of people self-documenting the API use appID to identify a game/software and have found no cases of being able to use name. The other documented Steam DEV APIs also use AppId


答:
Of course there's a vectorized solution for this but if you want to correct your for loop you need to limit j to dimension of dfm minus 2 as you are checking for two columns ahead. Based on what you provided this would help you; however, it is not clear how you get 10 rows (repeated twice) from 5 rows of df.

```<code>      my_matrix <- matrix("no info", nrow = 5, ncol = 2)
      colnames(my_matrix) <- c("begin", "end")

      for(i in 1:dim(dfm)[1]){
        for(j in 1:(dim(dfm)[2]-2)){
          if(dfm[i, j] + dfm[i, j+1] + dfm[i, j+2] == 3){
            my_matrix[i, 1] <- colnames(dfm)[j]
            my_matrix[i, 2] <- colnames(dfm)[j+2]
            break
          }
        }
      }

output <- cbind(df, my_matrix)
</code>```

Then result would be:

```<code>output

#   nom pseudo janvier fevrier mars avril mai juin   begin     end
# 1   a name21       0       1    0     1   1    1   avril    juin
# 2   b name22       1       1    0     1   0    1 no info no info
# 3   c name23       1       1    0     1   1    0 no info no info
# 4   d name24       1       1    1     0   1    1 janvier    mars
# 5   e name25       0       1    1     1   1    0 fevrier   avril
</code>```

Title: Condition and row and column with a double loop

Body:
I get a problem about "subscript out of bounds", what I want is to get the first and last month for each observation where I have three consecutive "1" or "True". I want to create 2 new column "begin" and "end" where I get repectively the first month and the last month.
In my example for the first observation : begin equal to avril and end equal to juin
In the 5 observation : begin equal to fevrier and end equal to avril
In the 9 observation : begin equal to janvier and end equal to mars
...

I tried to do this :

nom <- letters[1:5]
pseudo <- paste(name, 21:25, sep = "")
janvier <- c(0, 1, 1, 1, 0)
fevrier <- c(1, 1, 1, 1, 1)
mars <- c(0, 0, 0, 1, 1)
avril <- c(1, 1, 1, 0, 1)
mai <- c(1, 0, 1, 1, 1)
juin <- c(1, 1, 0, 1, 0)

df <- data.frame(nom =nom, pseudo = pseudo, janvier = janvier,
                 fevrier = fevrier, mars = mars, avril = avril,
                 mai = mai, juin = juin)

dfm <- as.matrix(df[, -c(1, 2)])

my_matrix <- matrix(nrow = 10, ncol = 6)

for(i in 1:dim(dfm)[1]){
  for(j in 1:dim(dfm)[2]){
    if(dfm[i, j] + dfm[i, j+1] + dfm[i, j+2] == 3){
      my_matrix[i, j] <- "periode_ok"
      my_matrix[i, j+1] <- "periode_ok"
      my_matrix[i, j+2] <- "periode_ok"
    }
  }
}

The ouput should be this :

begin <- c("avril", "no  info", "no info",
           "janvier", "fevrier", "avril", "no info",
           "no info", "janvier", "fevrier")
end <- c("juin", "no info", "no info", "mars",
         "avril", "juin", "no info", "no info",
         "mars", "avril")

output <- data.frame(nom =nom, pseudo = pseudo, janvier = janvier,
                 fevrier = fevrier, mars = mars, avril = avril,
                 mai = mai, juin = juin, begin = begin,end = end)

Any help will be apreciated

Body:
Of course there's a vectorized solution for this but if you want to correct your for loop you need to limit j to dimension of dfm minus 2 as you are checking for two columns ahead. Based on what you provided this would help you; however, it is not clear how you get 10 rows (repeated twice) from 5 rows of df.

      my_matrix <- matrix("no info", nrow = 5, ncol = 2)
      colnames(my_matrix) <- c("begin", "end")

      for(i in 1:dim(dfm)[1]){
        for(j in 1:(dim(dfm)[2]-2)){
          if(dfm[i, j] + dfm[i, j+1] + dfm[i, j+2] == 3){
            my_matrix[i, 1] <- colnames(dfm)[j]
            my_matrix[i, 2] <- colnames(dfm)[j+2]
            break
          }
        }
      }

output <- cbind(df, my_matrix)

Then result would be:

output

#   nom pseudo janvier fevrier mars avril mai juin   begin     end
# 1   a name21       0       1    0     1   1    1   avril    juin
# 2   b name22       1       1    0     1   0    1 no info no info
# 3   c name23       1       1    0     1   1    0 no info no info
# 4   d name24       1       1    1     0   1    1 janvier    mars
# 5   e name25       0       1    1     1   1    0 fevrier   avril


问:
SAS Summing a dynamic range in array
I have an array with totals for 210 days. I need to find the sum of all 90 day ranges. The new array is med_sum. So med_sum(1) =sum(of Total(32)-total(121)), then med_sum(2)=sum(of total(33)-total(122)), and so on, 90 different times all the way to med_sum(90)=sum(of total(121)-total(210)).
Below is the syntax, but the sum(of) function isn't allowing me to do this and errors out. I have tried quite a few different options but have been unable to find anything that works.
Thank you in advance!!</p>

```<code>data work.total_base_3;
set work.total_base_2;
array med_total(*) total1-total210;
array med_sum(*) avg1-avg90;
do i = 1 to 90;
med_sum(i)=sum(of med_total(i+31)-med_total(i+120));
end;
run;
</code>```

答:
You cannot use array references in variable lists, just actual variable names. So you want to generate 90 sums of 90 values with the window sliding. In essence you want

```<code>avg1 = sum(of total32 - total121);
avg2 = sum(of total33 - total122);
avg3 = sum(of total34 - total123);
</code>```

You could use macro logic to just generate that series of statements.  But if you look at the relationship between the variables you can see that

```<code>med_sum(n+1) = sum(med_sum(n),med_total(n+1+120),-1*med_total(n+31));
</code>```

So your loop will look something like:

```<code>med_sum(1) = sum(of total32-total121);
do n=1 to dim(med_sum)-1;
  med_sum(n+1) = sum(med_sum(n),med_total(n+1+120),-1*med_total(n+31));
end;
</code>```

Title: SAS Summing a dynamic range in array

Body:
I have an array with totals for 210 days. I need to find the sum of all 90 day ranges. The new array is med_sum. So med_sum(1) =sum(of Total(32)-total(121)), then med_sum(2)=sum(of total(33)-total(122)), and so on, 90 different times all the way to med_sum(90)=sum(of total(121)-total(210)).
Below is the syntax, but the sum(of) function isn't allowing me to do this and errors out. I have tried quite a few different options but have been unable to find anything that works.
Thank you in advance!!

data work.total_base_3;
set work.total_base_2;
array med_total(*) total1-total210;
array med_sum(*) avg1-avg90;
do i = 1 to 90;
med_sum(i)=sum(of med_total(i+31)-med_total(i+120));
end;
run;

Body:
You cannot use array references in variable lists, just actual variable names. So you want to generate 90 sums of 90 values with the window sliding. In essence you want

avg1 = sum(of total32 - total121);
avg2 = sum(of total33 - total122);
avg3 = sum(of total34 - total123);

You could use macro logic to just generate that series of statements.  But if you look at the relationship between the variables you can see that

med_sum(n+1) = sum(med_sum(n),med_total(n+1+120),-1*med_total(n+31));

So your loop will look something like:

med_sum(1) = sum(of total32-total121);
do n=1 to dim(med_sum)-1;
  med_sum(n+1) = sum(med_sum(n),med_total(n+1+120),-1*med_total(n+31));
end;


问:
jQuery - Given a DIV with a bunch of
 tags, how to find the first
 that isn't empty
Given a DIV with a lot of paragraph tags:

```<code><div>
 <p></p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
</div>
</code>```

How to magically find the first
 which isn't empty using just jQUery? ideas?

答:
You can use either of the following...

```<code>var firstNonEmptyP1 = $('p').not(':empty').first();
var firstNonEmptyP2 = $('p:not(:empty):first');
</code>```

Working example: http://jsfiddle.net/WTdMh/

Title: jQuery - Given a DIV with a bunch of <P> tags, how to find the first <P> that isn't empty

Body:
Given a DIV with a lot of paragraph tags:

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

How to magically find the first
 which isn't empty using just jQUery? ideas?

Body:
You can use either of the following...

var firstNonEmptyP1 = $('p').not(':empty').first();
var firstNonEmptyP2 = $('p:not(:empty):first');

Working example: http://jsfiddle.net/WTdMh/


问:
How to load 15.000.000 registers into a table with pentaho?
I have created an ETL process with Pentaho that selects data from a table in a Database and load this into another database.

The main problem that I have to make front is that for 1.500.000 rows it takes 6 hours. The full table is 15.000.000 and I have to load 5 tables like that.

Can anyone explain how is supposed to load a large size of data with pentaho?

Thank you.

答:
I never had problem with volume with Pentaho PDI. Check the following in order.

Can you check the problem is really coming from Pentaho: what happens if you drop the query in SQL-Developer or Toad or SQL-IDE-Fancy-JDBC-Compilant.

In principle, PDI is meant to import data with a SELECT * FROM ... WHERE ... and do all the rest in the transformation. I have a set of transformation here which take hours to execute because they do complex queries. The problem is not due to PDI but complexity of the query. The solutions is to export the GROUP BY and SELECT FROM (SELECT...) into PDI steps, which can start before the query result is finished. The result is like 4 hours to 56 seconds. No joke.

What is your memory size? It is defined in the spoon.bat / spoon.sh.

Near the end you have a line which looks like PENTAHO_DI_JAVA_OPTIONS="-Xms1024m" "-Xmx4096m" "-XX:MaxPermSize=256m". The important parameter is -Xmx.... If it is -Xmx256K, your jvm has only 256KB of RAM to work with.

Change it to 1/2 or 3/4 of the available memory, in order to leave room for the other processes.

Is the output step the bottleneck? Check by disabling it and watch you clock during the run.

If it is long , increase the commit size and allow batch inserts.

Disable all the index and constraints and restore them when loaded. You have nice SQL script executor steps to automate that, but check first manually then in a job, otherwise the reset index may trigger before to load begins.

You have also to check that you do not lock your self: as PDI launches the steps alltogether, you may have truncates which are waiting on another truncate to unlock. If you are not in an never ending block, it may take quite while before to db is able to cascade everything.


问:
Without Same Origin Policy could an evil site read the CSRF token?
From wikipedia about Same Origin Policy

https://en.wikipedia.org/wiki/Same-origin_policy

The same-origin policy helps protect sites that use authenticated sessions. The following example illustrates a potential security risk that could arise without the same-origin policy. Assume that a user is visiting a banking website and doesn't log out. Then, the user goes to another site that has some malicious JavaScript code running in the background that requests data from the banking site. Because the user is still logged in on the banking site, the malicious code could do anything the user could do on the banking site. For example, it could get a list of the user's last transactions, create a new transaction, etc. This is because the browser can send and receive session cookies to the banking site based on the domain of the banking site.

This part i understood but now...

The user visiting the malicious site would expect that the site he or she is visiting has no access to the banking session cookie. While it is true that the JavaScript has no direct access to the banking session cookie ...

Because the session cookie is httpOnly flagged?

... it could still send and receive requests to the banking site with the banking site's session cookie. Because the script can essentially do the same as the user would do, even CSRF protections by the banking site would not be effective.

Same Origin Policy prohibits Cross-Origin reads. Thus, if we assume that SOP is not enforced, the malicious site could read the CSRF token from the response? Is that the reason why wikipedia is saying that even CSRF protections would not be effective?

答:
Yes, you've understood it. Without the SOP, the malicious script would simply request whatever page has the CSRF token, read it, and then use that token to construct its unsafe requests.

So SOP and CSRF protection are both necessary to protect the user in a world where the browser sends authentication cookies with requests from foreign domains.


答:
You can easily achieve this by using IPCRenderer and IPCMain in order to pass the messages between the main process and the renderer.

index.js

```<code>const electron = require('electron')
const {app, BrowserWindow, ipcMain} = electron

app.on('ready',()=>{
  let win = new BrowserWindow({width:960, hehight:540})
  win.loadURL(`file://${__dirname}/login.html`)
})

ipcMain.on('open-new-window', (event, fileName) => {
  let win = new BrowserWindow({width:960, height:540})
  win.loadURL(`file://${__dirname}/` + fileName + `.html`)
}
</code>```

As you can see, I altered your code only to add ipcMain and receive the message from the renderer.

login.js

```<code>const {ipcRenderer} = require('electron');

let login = document.getElementById('login');
login.addEventListner('click', () => {
  ipcRenderer.send('open-new-window', 'pageTwo');
}, false);
</code>```

The same goes for login.js and ipcRenderer.

The documentation explains way better than I do and can be found here for ipcMain and here for ipcRenderer.

Title: How to open update electron browser window with a new html file

Body:
I am new to electron. I have two html pages and I want to open the second page when a button clicked. I have code this as follow, but I just get a blank window; not the second page.

This is index.js

const electron = require('electron')
const {app, BrowserWindow} = electron

app.on('ready',()=>{
  let win = new BrowserWindow({width:960, hehight:540})
  win.loadURL(`file://${__dirname}/login.html`)
})

exports.openWindow = (fileName) => {
  let win = new BrowserWindow({width:960, height:540})
  win.loadURL(`file://${__dirname}/` + fileName + `.html`)
}

This is login.js

const remote = require('electron').remote
const index = remote.require('./index.js')

var login = document.getElementById('login')
login.addEventListner('click', () => {
  var window = remote.getCurrentWindow()
  index.openWindow('pageTwo')
  window.close()
}, false)

login is the id of the html button.

I want to get the page two. How can I perform this?

Body:
You can easily achieve this by using IPCRenderer and IPCMain in order to pass the messages between the main process and the renderer.

index.js

const electron = require('electron')
const {app, BrowserWindow, ipcMain} = electron

app.on('ready',()=>{
  let win = new BrowserWindow({width:960, hehight:540})
  win.loadURL(`file://${__dirname}/login.html`)
})

ipcMain.on('open-new-window', (event, fileName) => {
  let win = new BrowserWindow({width:960, height:540})
  win.loadURL(`file://${__dirname}/` + fileName + `.html`)
}

As you can see, I altered your code only to add ipcMain and receive the message from the renderer.

login.js

const {ipcRenderer} = require('electron');

let login = document.getElementById('login');
login.addEventListner('click', () => {
  ipcRenderer.send('open-new-window', 'pageTwo');
}, false);

The same goes for login.js and ipcRenderer.

The documentation explains way better than I do and can be found here for ipcMain and here for ipcRenderer.


问:
How to move focus when error in bound field?
I have VB.Net Application with some fields bound to a datatable.

Here is my code :

```<code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Me.DxErrorProvider1 = New DevExpress.XtraEditors.DXErrorProvider.DXErrorProvider(Me.components)
    Dim DT As DataTable = GetDT()
    Me.TextEdit1.DataBindings.Add("EditValue", DT, "C1", True, DataSourceUpdateMode.OnValidation, "")
End Sub

Function GetDT() As DataTable
    Dim DT As New DataTable

    Dim i As Integer = 0
    DT.Columns.Add(New DataColumn("C1", i.GetType))

    Dim R As DataRow = DT.NewRow
    R.Item(0) = 15
    DT.Rows.Add(R)

    Return DT
End Function
</code>```

When the user types a wrong value on the field. The focus can not move anymore.

The full code contains actually multiple fields and I would like to allow the user to be able to move the next field even if there is wrong value. A red icon shows, so he may want to correct it later.

Is there anyway to achieve that please ?

Thanks.

答:
Here is the solution : </p>

```<code>Me.AutoValidate = Windows.Forms.AutoValidate.EnableAllowFocusChange
</code>```

Body:
I have VB.Net Application with some fields bound to a datatable.

Here is my code :

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Me.DxErrorProvider1 = New DevExpress.XtraEditors.DXErrorProvider.DXErrorProvider(Me.components)
    Dim DT As DataTable = GetDT()
    Me.TextEdit1.DataBindings.Add("EditValue", DT, "C1", True, DataSourceUpdateMode.OnValidation, "")
End Sub

Function GetDT() As DataTable
    Dim DT As New DataTable

    Dim i As Integer = 0
    DT.Columns.Add(New DataColumn("C1", i.GetType))

    Dim R As DataRow = DT.NewRow
    R.Item(0) = 15
    DT.Rows.Add(R)

    Return DT
End Function

When the user types a wrong value on the field. The focus can not move anymore.

The full code contains actually multiple fields and I would like to allow the user to be able to move the next field even if there is wrong value. A red icon shows, so he may want to correct it later.

Is there anyway to achieve that please ?

Thanks.

Body:
Here is the solution :

Me.AutoValidate = Windows.Forms.AutoValidate.EnableAllowFocusChange