问:
ASP.NET MVC error when using CRUD
I'm creating MVC application, trying to get records out of database using CRUD, but then I get this error

"Multiple object sets per type are not supported. The object sets
  'ApplicationUsers' and 'Users' can both contain instances of type
  'WebApplication1.Models.ApplicationUser'."

I can't find "Users" property used anywhere, and when I replace all "ApplicationUser" with "User", I get this error:

"Multiple object sets per type are not supported. The object sets
  'Users' and 'Users' can both contain instances of type
  'WebApplication1.Models.ApplicationUser'."

I'm stuck and I have no idea what to do...

Edit:

```<code>    namespace WebApplication1.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {

        public string Name { get; set; }
        public string DoB { get; set; }
        public string Additional { get; set; }

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

        public System.Data.Entity.DbSet<WebApplication1.Models.ApplicationUser> ApplicationUser { get; set; }
    }
</code>```

答:
Just remove this line:

```<code>public System.Data.Entity.DbSet<WebApplication1.Models.ApplicationUser> ApplicationUser { get; set; }
</code>```

Because when you inherit from IdentityDbContext<ApplicationUser> your class already have property DbSet<T> Users where T is class specified by you (ApplicationUser)

Edit: For now to access users dbset use dbContext.Users.

If you want to use dbContext.ApplicationUser create wrapper property in ApplicationDbContext:

```<code>public DbSet<ApplicationUser> ApplicationUser
{
  get { return Users; }
  set { Users = value; }
}
</code>```

Title: ASP.NET MVC error when using CRUD

Body:
I'm creating MVC application, trying to get records out of database using CRUD, but then I get this error

"Multiple object sets per type are not supported. The object sets
  'ApplicationUsers' and 'Users' can both contain instances of type
  'WebApplication1.Models.ApplicationUser'."

I can't find "Users" property used anywhere, and when I replace all "ApplicationUser" with "User", I get this error:

"Multiple object sets per type are not supported. The object sets
  'Users' and 'Users' can both contain instances of type
  'WebApplication1.Models.ApplicationUser'."

I'm stuck and I have no idea what to do...

Edit:

    namespace WebApplication1.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {

        public string Name { get; set; }
        public string DoB { get; set; }
        public string Additional { get; set; }

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

        public System.Data.Entity.DbSet<WebApplication1.Models.ApplicationUser> ApplicationUser { get; set; }
    }

Body:
Just remove this line:

public System.Data.Entity.DbSet<WebApplication1.Models.ApplicationUser> ApplicationUser { get; set; }

Because when you inherit from IdentityDbContext<ApplicationUser> your class already have property DbSet<T> Users where T is class specified by you (ApplicationUser)

Edit: For now to access users dbset use dbContext.Users.

If you want to use dbContext.ApplicationUser create wrapper property in ApplicationDbContext:

public DbSet<ApplicationUser> ApplicationUser
{
  get { return Users; }
  set { Users = value; }
}


来源: stackexchange

问:
Using a for loop on string values of my array and getting a string value back
Pretty dumb question to ask and clearly shows I'm just getting started but I do have some trouble with this. Here's the array I'm dealing with:

```<code>var stuff = ["ken", "kenneth", "kenny", "kennayyy"];
</code>```

Now here's the for loop I'm using:

```<code>for (i = 0; i < stuff.length; i++) {
  console.log(i);
};
</code>```

All I get in my chrome developer console is 0, 1, 2, 3.

How do I get each string value to show up?

答:
```<code>for (i = 0; i < stuff.length; i++) {
    console.log(stuff[i]);
};
</code>```

that will work for you

ContentLicense: CC BY-SA 3.0

Body:
Pretty dumb question to ask and clearly shows I'm just getting started but I do have some trouble with this. Here's the array I'm dealing with:

var stuff = ["ken", "kenneth", "kenny", "kennayyy"];

Now here's the for loop I'm using:

for (i = 0; i < stuff.length; i++) {
  console.log(i);
};

All I get in my chrome developer console is 0, 1, 2, 3.

How do I get each string value to show up?

Body:
for (i = 0; i < stuff.length; i++) {
    console.log(stuff[i]);
};

that will work for you


问:
Open PDF file in Acrobat from ruby script?
i am using a ruby script to generate PDF files, which i always open by hand afterwards to print them.

Is there a way to do this automatically from the script (to open them)?

I googled a bit and found exec(), but this does not seem to work for non-exe files:

```<code>generate.rb:624:in `exec': Exec format error - test.pdf (Errno::ENOEXEC)
        from generate.rb:624:in `<main>'
</code>```

Also, the generated PDF is one folder above where the script is. How could i address the file in a relative way? exec("../whatever.pdf")? This approach ended in:

```<code>generate.rb:624:in `exec': No such file or directory - ../test.pdf (Errno::ENOENT)
        from generate.rb:624:in `<main>'
</code>```

I also tried spawn, same results.

I am using Windows 10, and would like to have the PDF started by whatever tool is set as standard in Windows. Is there a way to do this? Any help is very appreciated.

Thanks

答:
If your file is one folder above the current folder then we need to get the parent folder of the current directory and then append the file name to it.To get the file path you can use

```<code>file_path = File.expand_path("..", Dir.pwd) + '/filename.pdf'
</code>```

And I assume you want to open the pdf in Pdf reader after creating it using ruby. Try this option.

```<code>system ('start "" "file_path\filename.pdf"')
</code>```

The final code would be like this

```<code>filepath =  File.expand_path("..", Dir.pwd) + "/filename.pdf"
str = 'start "" "' + "#{filepath}" + '"'
system (str)
</code>```

Body:
i am using a ruby script to generate PDF files, which i always open by hand afterwards to print them.

Is there a way to do this automatically from the script (to open them)?

I googled a bit and found exec(), but this does not seem to work for non-exe files:

generate.rb:624:in `exec': Exec format error - test.pdf (Errno::ENOEXEC)
        from generate.rb:624:in `'

Also, the generated PDF is one folder above where the script is. How could i address the file in a relative way? exec("../whatever.pdf")? This approach ended in:

generate.rb:624:in `exec': No such file or directory - ../test.pdf (Errno::ENOENT)
        from generate.rb:624:in `'

I also tried spawn, same results.

I am using Windows 10, and would like to have the PDF started by whatever tool is set as standard in Windows. Is there a way to do this? Any help is very appreciated.

Thanks

Body:
If your file is one folder above the current folder then we need to get the parent folder of the current directory and then append the file name to it.To get the file path you can use

file_path = File.expand_path("..", Dir.pwd) + '/filename.pdf'

And I assume you want to open the pdf in Pdf reader after creating it using ruby. Try this option.

system ('start "" "file_path\filename.pdf"')

The final code would be like this

filepath =  File.expand_path("..", Dir.pwd) + "/filename.pdf"
str = 'start "" "' + "#{filepath}" + '"'
system (str)


问:
How do you go about batch processing poorly formatted text files?
People complain a lot about XML but, when compared to EDI and some of the proprietary file formats I've dealt with in my career, I think XML is bliss.  The work I did on importing data files from Automotive Comparative Raters, each with it's own creative and nightmarish file format, still gives me nightmares.

That being said I'm curious how other programmers approach automated parsing of poorly formatted text files.  Do you have a language preference?  Are there any automation tools that you find invaluable?  How do you make your code reusable?

答: I know I'll receive scathing responses for this, but I like Java as an all-around language. In the case of file parsing, generic regexes (I know, now I have 2 problems...) work well for me.</p>

ContentLicense: CC BY-SA 2.5


问:
How to get Number of male and female friends and what is their percentage facebook apps
```<code>$query = 'SELECT friend_count FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) and sex='male'';

$url = "https://graph.facebook.com/fql?q=" . urlencode($query) .
     "&access_token=" . $access_token;
$data = json_decode( file_get_contents ($url));
$boys = count($data[data]);
echo $boys;
</code>```

i have tried this method but unable to get the desired result...
I want to make an app like this

答:
```<code>{
   "error": {
      "message": "An active access token must be used to query information about the current user.",
      "type": "OAuthException",
      "code": 2500,
      "fbtrace_id": "FJgpERmm460"
   }
}
</code>```

Body:
$query = 'SELECT friend_count FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) and sex='male'';

$url = "https://graph.facebook.com/fql?q=" . urlencode($query) .
     "&access_token=" . $access_token;
$data = json_decode( file_get_contents ($url));
$boys = count($data[data]);
echo $boys;

i have tried this method but unable to get the desired result...
I want to make an app like this


问:
Crash when updating NSTextStorage font
My UITextView responds to UIContentSizeCategoryDidChangeNotification to respond to dynamic font changes, and I implemented the following code:

```<code> NSTextStorage * textStorage = [self textStorage];
[textStorage beginEditing];
[textStorage enumerateAttribute: NSFontAttributeName
                        inRange: NSMakeRange(0, [textStorage length])
                        options: 0
                     usingBlock: ^(id value, NSRange range, BOOL * stop) {
                         UIFont *newFont = [UIFont fontWithDescriptor: [UIFontDescriptor preferredFixedFontDescriptorWithTextStyle: IDFontTextStyleFixed] size: 0.0f];

                         if (newFont) {
                             [textStorage removeAttribute: NSFontAttributeName
                                                    range: range];
                             [textStorage addAttribute: NSFontAttributeName
                                                 value: newFont
                                                 range: range];
                         }
                     }];

[textStorage endEditing];
</code>```

It always crashes on the last line, [textStorage endEditing];. I have enabled exception breakpoints, but there is no additional information in the debug pane see the backtrace below. If I remove 'beginEditing and endEditing, it crashes on the removeAttribute line. I'm using [UIFont fontWithDescriptor: [UIFontDescriptor preferredFixedFontDescriptorWithTextStyle: IDFontTextStyleFixed] size: 0.0f]; all over my app, and it works everywhere, except for in the UITextView.

Anyone sees what's going wrong and how I could fix it?

EDIT: here's the backtrace:

```<code>    (lldb) bt
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=2, address=0x10f3c0060)
    frame #0: 0x000000010c77f29d libobjc.A.dylib`realizeClass(objc_class*) + 145
    frame #1: 0x000000010c783125 libobjc.A.dylib`lookUpImpOrForward + 127
    frame #2: 0x000000010c792554 libobjc.A.dylib`_objc_msgSend_uncached + 68
    frame #3: 0x0000000118d39ce7 UIFoundation`-[NSGlyphGenerator generateGlyphsForGlyphStorage:desiredNumberOfCharacters:glyphIndex:characterIndex:] + 251
    frame #4: 0x0000000118d06d47 UIFoundation`-[NSLayoutManager(NSPrivate) _fillGlyphHoleForCharacterRange:startGlyphIndex:desiredNumberOfCharacters:] + 736
    frame #5: 0x0000000118d091b0 UIFoundation`_NSFastFillAllGlyphHolesForCharacterRange + 726
    frame #6: 0x0000000118d47f2e UIFoundation`-[NSLayoutManager glyphRangeForCharacterRange:actualCharacterRange:] + 64
    frame #7: 0x0000000118d071af UIFoundation`-[NSLayoutManager(NSPrivate) _fillLayoutHoleForCharacterRange:desiredNumberOfLines:isSoft:] + 617
    frame #8: 0x0000000118d08e9a UIFoundation`-[NSLayoutManager(NSPrivate) _fillLayoutHoleAtIndex:desiredNumberOfLines:] + 208
    frame #9: 0x0000000118d0954a UIFoundation`-[NSLayoutManager(NSPrivate) _markSelfAsDirtyForBackgroundLayout:] + 325
    frame #10: 0x0000000118d13d10 UIFoundation`-[NSLayoutManager(NSPrivate) _invalidateLayoutForExtendedCharacterRange:isSoft:invalidateUsage:] + 2212
    frame #11: 0x0000000118d44743 UIFoundation`-[NSLayoutManager textStorage:edited:range:changeInLength:invalidatedRange:] + 226
    frame #12: 0x0000000118d448f9 UIFoundation`-[NSLayoutManager processEditingForTextStorage:edited:range:changeInLength:invalidatedRange:] + 47
    frame #13: 0x0000000118d6c216 UIFoundation`-[NSTextStorage _notifyEdited:range:changeInLength:invalidatedRange:] + 168
    frame #14: 0x0000000118d6bd4c UIFoundation`-[NSTextStorage processEditing] + 372
    frame #15: 0x0000000118d6b995 UIFoundation`-[NSTextStorage endEditing] + 83
  * frame #16: 0x000000010bee435b MyApp`-[MyUITextView updateFonts](self=0x00007fc26208c000, _cmd="updateFonts") at MyUITextView.m:107
</code>```

答:
OK, I solved it.

I am using a helper class to handle the NSTextStorage, NSTextContainer, and NSLayoutManager objects. When creating MyTextView, I didn't hold on to the helper object (I only passed the textContainer to init of MyTextView). I now made the helper object a @property of MyTextView so it has a strong reference, and the crash is gone.

Title: Crash when updating NSTextStorage font

Body:
My UITextView responds to UIContentSizeCategoryDidChangeNotification to respond to dynamic font changes, and I implemented the following code:

 NSTextStorage * textStorage = [self textStorage];
[textStorage beginEditing];
[textStorage enumerateAttribute: NSFontAttributeName
                        inRange: NSMakeRange(0, [textStorage length])
                        options: 0
                     usingBlock: ^(id value, NSRange range, BOOL * stop) {
                         UIFont *newFont = [UIFont fontWithDescriptor: [UIFontDescriptor preferredFixedFontDescriptorWithTextStyle: IDFontTextStyleFixed] size: 0.0f];

                         if (newFont) {
                             [textStorage removeAttribute: NSFontAttributeName
                                                    range: range];
                             [textStorage addAttribute: NSFontAttributeName
                                                 value: newFont
                                                 range: range];
                         }
                     }];

[textStorage endEditing];

It always crashes on the last line, [textStorage endEditing];. I have enabled exception breakpoints, but there is no additional information in the debug pane see the backtrace below. If I remove 'beginEditing and endEditing, it crashes on the removeAttribute line. I'm using [UIFont fontWithDescriptor: [UIFontDescriptor preferredFixedFontDescriptorWithTextStyle: IDFontTextStyleFixed] size: 0.0f]; all over my app, and it works everywhere, except for in the UITextView.

Anyone sees what's going wrong and how I could fix it?

EDIT: here's the backtrace:

    (lldb) bt
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=2, address=0x10f3c0060)
    frame #0: 0x000000010c77f29d libobjc.A.dylib`realizeClass(objc_class*) + 145
    frame #1: 0x000000010c783125 libobjc.A.dylib`lookUpImpOrForward + 127
    frame #2: 0x000000010c792554 libobjc.A.dylib`_objc_msgSend_uncached + 68
    frame #3: 0x0000000118d39ce7 UIFoundation`-[NSGlyphGenerator generateGlyphsForGlyphStorage:desiredNumberOfCharacters:glyphIndex:characterIndex:] + 251
    frame #4: 0x0000000118d06d47 UIFoundation`-[NSLayoutManager(NSPrivate) _fillGlyphHoleForCharacterRange:startGlyphIndex:desiredNumberOfCharacters:] + 736
    frame #5: 0x0000000118d091b0 UIFoundation`_NSFastFillAllGlyphHolesForCharacterRange + 726
    frame #6: 0x0000000118d47f2e UIFoundation`-[NSLayoutManager glyphRangeForCharacterRange:actualCharacterRange:] + 64
    frame #7: 0x0000000118d071af UIFoundation`-[NSLayoutManager(NSPrivate) _fillLayoutHoleForCharacterRange:desiredNumberOfLines:isSoft:] + 617
    frame #8: 0x0000000118d08e9a UIFoundation`-[NSLayoutManager(NSPrivate) _fillLayoutHoleAtIndex:desiredNumberOfLines:] + 208
    frame #9: 0x0000000118d0954a UIFoundation`-[NSLayoutManager(NSPrivate) _markSelfAsDirtyForBackgroundLayout:] + 325
    frame #10: 0x0000000118d13d10 UIFoundation`-[NSLayoutManager(NSPrivate) _invalidateLayoutForExtendedCharacterRange:isSoft:invalidateUsage:] + 2212
    frame #11: 0x0000000118d44743 UIFoundation`-[NSLayoutManager textStorage:edited:range:changeInLength:invalidatedRange:] + 226
    frame #12: 0x0000000118d448f9 UIFoundation`-[NSLayoutManager processEditingForTextStorage:edited:range:changeInLength:invalidatedRange:] + 47
    frame #13: 0x0000000118d6c216 UIFoundation`-[NSTextStorage _notifyEdited:range:changeInLength:invalidatedRange:] + 168
    frame #14: 0x0000000118d6bd4c UIFoundation`-[NSTextStorage processEditing] + 372
    frame #15: 0x0000000118d6b995 UIFoundation`-[NSTextStorage endEditing] + 83
  * frame #16: 0x000000010bee435b MyApp`-[MyUITextView updateFonts](self=0x00007fc26208c000, _cmd="updateFonts") at MyUITextView.m:107


问:
help with Jsonp and jQuery
I have a web service served in jsonp, but since I'm new to this I have difficulties retrieving the data. Here's my code:

```<code>$(document).ready(function(){
   $.getJSON("http://api.tubeupdates.com/?method=get.status&lines=central,victoria&return=name&jsonp=myData",
       function myData(result){
           $('#status').append(result.name.text);
        }
   );

});
</code>```

the div #status returns empty.

could you help?

Thanks in advance

Mauro

Update: now it works! Bout it does't when I'm trying to loop though the data:

```<code>$.getJSON("http://api.tubeupdates.com/?method=get.status&lines=central,victoria&return=name&jsonp=?",
         function (result){
              $.each(result.items, function(item){
                 $('#status').append(item.response.lines[0].name);
        });
     }
);
</code>```

What am I doing wrong?

Thanks

答:
From jQuery API:

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead.

I think your code should look something like this

```<code>$.getJSON("http://api.tubeupdates.com/?method=get.status&lines=central,victoria&return=name&jsonp=?", function (result){
    $('#status').append(result.name.text);
});
</code>```

The trick is the json=? part of the URL. I think jQuery creates a function on the fly to parse de JSONp data and feeds the result to your callback function.

Excuse my English :)

Update: to access the data you must iterate over result.response.lines inside the callback function

```<code>$.each(result.response.lines, function() {
    $('#status').append(this.name);
}
</code>```

Title: help with Jsonp and jQuery

Body:
I have a web service served in jsonp, but since I'm new to this I have difficulties retrieving the data. Here's my code:

$(document).ready(function(){
   $.getJSON("http://api.tubeupdates.com/?method=get.status&lines=central,victoria&return=name&jsonp=myData",
       function myData(result){
           $('#status').append(result.name.text);
        }
   );

});

the div #status returns empty.

could you help?

Thanks in advance

Mauro

Update: now it works! Bout it does't when I'm trying to loop though the data:

$.getJSON("http://api.tubeupdates.com/?method=get.status&lines=central,victoria&return=name&jsonp=?",
         function (result){
              $.each(result.items, function(item){
                 $('#status').append(item.response.lines[0].name);
        });
     }
);

What am I doing wrong?

Thanks

Body:
From jQuery API:

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead.

I think your code should look something like this

$.getJSON("http://api.tubeupdates.com/?method=get.status&lines=central,victoria&return=name&jsonp=?", function (result){
    $('#status').append(result.name.text);
});

The trick is the json=? part of the URL. I think jQuery creates a function on the fly to parse de JSONp data and feeds the result to your callback function.

Excuse my English :)

Update: to access the data you must iterate over result.response.lines inside the callback function

$.each(result.response.lines, function() {
    $('#status').append(this.name);
}


问:
Jackcess: wrong charset for MSAccess database
I have a MS-Access database which has "encrypted" Strings in it. These look like that:

However, I quickly noticed that the length of these Strings matches exactly the length of the plaintext (I know the plaintext). So with a bit of trying with Excel, I found out that if you use the =CODE(<char>)-function (so you get the character-code in the default charset, and =CHAR(<number>) viceversa) and xor this number with the character code of the letter the symbol should represent you always get the same result. Which means I just have to create an array with these values in java and voila. Excel example (on the right the mentioned "Array"):

Example: ">>" has an index of (dec) 187, so 187xor253 yields 70 => "F"

Now, I use jackcess to access these values and the "decryption" is mostly fine but I sometimes get the wrong character out of strings. In Excel everything works just fine. Code with the best results:

```<code>public static final int[] DECRYPT_KEY = { 253, 203, 204, 217, 226, 205, 128, 201, 222, 183, 58, 217, 230, 201, 183, 211, 158, 203, 167, 213, 35, 33, 201, 123, 186, 247 };

public static void main(String[] args) throws IOException
{
    System.out.println(System.getProperty("file.encoding"));

    Database db = DatabaseBuilder.open(new File("/home/***/TM.db"));
    Table table = db.getTable("personal");

    for (Row row : table)
    {
        String vorname = row.getString("vorname");
        byte[] vornameArr = vorname.getBytes("cp1252");
        for (int i1 = 0; i1 < vornameArr.length; i1++)
        {
            vornameArr[i1] = (byte) ((vornameArr[i1] & 0xff) ^ DECRYPT_KEY[i1]);
        }

        System.out.println(new String(vornameArr, "cp1252"));
    }
}
</code>```

But as I said, some characters are still wrong, in Excel however everything is fine. When I print out the number which getBytes("cp1272") gives, it is completely different to the Excel one.

Do you have any ideas, what I could be doing wrong and why java gives sometimes such different values than Excel? What would be a better approach? I already tried all combinations of charsets, some worked where others failed but then had other wrong results.

答:
I was able to recreate your issue by hacking a database file with the byte values in your question. The line

byte[] vornameArr = vorname.getBytes("cp1252");
```

<p>tries to convert the <code>vorname</code> characters to cp1252 bytes, but there is no cp1252 character corresponding to U+008F (decimal 143, SINGLE SHIFT THREE), so Java converts that character to a question mark (0x3F). Therefore, your decoding step is decoding 0x3F instead of 0x8F, which is why you get "FadiÝa" instead of "Fadima".</p>

<p>I was able to get the correct result by replacing the single line above with</p>

<pre class="lang-java prettyprint-override"><code>byte[] doubleBytes = vorname.getBytes("UTF-16LE");  // 187 0 170 0 168 0 ...
byte[] vornameArr = new byte[doubleBytes.length / 2];
for (int i = 0; i < vornameArr.length; i++) {
    vornameArr[i] = doubleBytes[i * 2];  // remove nulls
}
</code>```

and then running the vornameArr bytes through your decoding loop. (You could also apply the decoding transformation in the above loop if you preferred.)

Body:
I have a MS-Access database which has "encrypted" Strings in it. These look like that:

However, I quickly noticed that the length of these Strings matches exactly the length of the plaintext (I know the plaintext). So with a bit of trying with Excel, I found out that if you use the =CODE(<char>)-function (so you get the character-code in the default charset, and =CHAR(<number>) viceversa) and xor this number with the character code of the letter the symbol should represent you always get the same result. Which means I just have to create an array with these values in java and voila. Excel example (on the right the mentioned "Array"):

Example: ">>" has an index of (dec) 187, so 187xor253 yields 70 => "F"

Now, I use jackcess to access these values and the "decryption" is mostly fine but I sometimes get the wrong character out of strings. In Excel everything works just fine. Code with the best results:

public static final int[] DECRYPT_KEY = { 253, 203, 204, 217, 226, 205, 128, 201, 222, 183, 58, 217, 230, 201, 183, 211, 158, 203, 167, 213, 35, 33, 201, 123, 186, 247 };

public static void main(String[] args) throws IOException
{
    System.out.println(System.getProperty("file.encoding"));

    Database db = DatabaseBuilder.open(new File("/home/***/TM.db"));
    Table table = db.getTable("personal");

    for (Row row : table)
    {
        String vorname = row.getString("vorname");
        byte[] vornameArr = vorname.getBytes("cp1252");
        for (int i1 = 0; i1 < vornameArr.length; i1++)
        {
            vornameArr[i1] = (byte) ((vornameArr[i1] & 0xff) ^ DECRYPT_KEY[i1]);
        }

        System.out.println(new String(vornameArr, "cp1252"));
    }
}

But as I said, some characters are still wrong, in Excel however everything is fine. When I print out the number which getBytes("cp1272") gives, it is completely different to the Excel one.

Do you have any ideas, what I could be doing wrong and why java gives sometimes such different values than Excel? What would be a better approach? I already tried all combinations of charsets, some worked where others failed but then had other wrong results.

Body:
I was able to recreate your issue by hacking a database file with the byte values in your question. The line

byte[] vornameArr = vorname.getBytes("cp1252");

tries to convert the vorname characters to cp1252 bytes, but there is no cp1252 character corresponding to U+008F (decimal 143, SINGLE SHIFT THREE), so Java converts that character to a question mark (0x3F). Therefore, your decoding step is decoding 0x3F instead of 0x8F, which is why you get "FadiÝa" instead of "Fadima".

I was able to get the correct result by replacing the single line above with

byte[] doubleBytes = vorname.getBytes("UTF-16LE");  // 187 0 170 0 168 0 ...
byte[] vornameArr = new byte[doubleBytes.length / 2];
for (int i = 0; i < vornameArr.length; i++) {
    vornameArr[i] = doubleBytes[i * 2];  // remove nulls
}

and then running the vornameArr bytes through your decoding loop. (You could also apply the decoding transformation in the above loop if you preferred.)


问:
How to use intervals in Android CountdownTimer
I am creating a countdown time in Android and I have the timer part working perfectly. However, I want to add a feature where the user can set the number of times they wish the timer to repeat. This is my current attempt at implementation

```<code>    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = (TextView) findViewById(R.id.textView);
    minutesText = (EditText) findViewById(R.id.minutesText);
    secondsText = (EditText) findViewById(R.id.secondsText);
    startButton = (Button) findViewById(R.id.startButton);
    intervalCount = (EditText) findViewById(R.id.intervalCount);

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

            if (minutesText.getText().toString().equals("")) {
                minutesInt = 0;
            } else {
                minutesString = minutesText.getText().toString();
                minutesInt = Integer.parseInt(minutesString);

            }

            secondsString = secondsText.getText().toString();
            if (secondsText.getText().toString().equals("")) {
                secondsInt = 0;

            } else {
                secondsString = secondsText.getText().toString();
                secondsInt = Integer.parseInt(secondsString);

            }
            intervalsString = intervalCount.getText().toString();
            intervals = Integer.parseInt(intervalsString);

            final int timerAmount = ((minutesInt * 60) + (secondsInt)) * 1000;
            CountDownTimer timer = new CountDownTimer(timerAmount, 1000) {
                @RequiresApi(api = Build.VERSION_CODES.N)
                public void onTick(long millisUntilFinished) {
                    isRunning = true;
                    String timeLeft = String.format("%02d : %02d",
                            TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
                            TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))
                    );
                    textView.setText("Reamining: " + timeLeft);
                }
                public void onFinish() {
                    isRunning = false;
                    intervals--;
                    if (intervals > 0) {
                        timer.start();
                    }

                    try {
                        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                        r.play();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };timer.start();

        }
    });
</code>```

My error is in the onFinish()
it wont let me use timer.start()

答:
CountDownTimer basically uses a Handler thread which is like other threads can not be restarted once its ended.

You need to use a new instance of the CountDownTimer in each interval.

So in your case, bring the

```<code>intervals--;
if (intervals > 0) {

    // for each interval left create a new CountDownTimer here and start it.
}
</code>```

outside of

```<code>new CountDownTimer(timerAmount, 1000 } {

    // do your operations here.

}
</code>```

Body:
I am creating a countdown time in Android and I have the timer part working perfectly. However, I want to add a feature where the user can set the number of times they wish the timer to repeat. This is my current attempt at implementation

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = (TextView) findViewById(R.id.textView);
    minutesText = (EditText) findViewById(R.id.minutesText);
    secondsText = (EditText) findViewById(R.id.secondsText);
    startButton = (Button) findViewById(R.id.startButton);
    intervalCount = (EditText) findViewById(R.id.intervalCount);

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

            if (minutesText.getText().toString().equals("")) {
                minutesInt = 0;
            } else {
                minutesString = minutesText.getText().toString();
                minutesInt = Integer.parseInt(minutesString);

            }

            secondsString = secondsText.getText().toString();
            if (secondsText.getText().toString().equals("")) {
                secondsInt = 0;

            } else {
                secondsString = secondsText.getText().toString();
                secondsInt = Integer.parseInt(secondsString);

            }
            intervalsString = intervalCount.getText().toString();
            intervals = Integer.parseInt(intervalsString);

            final int timerAmount = ((minutesInt * 60) + (secondsInt)) * 1000;
            CountDownTimer timer = new CountDownTimer(timerAmount, 1000) {
                @RequiresApi(api = Build.VERSION_CODES.N)
                public void onTick(long millisUntilFinished) {
                    isRunning = true;
                    String timeLeft = String.format("%02d : %02d",
                            TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
                            TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))
                    );
                    textView.setText("Reamining: " + timeLeft);
                }
                public void onFinish() {
                    isRunning = false;
                    intervals--;
                    if (intervals > 0) {
                        timer.start();
                    }

                    try {
                        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                        r.play();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };timer.start();

        }
    });

My error is in the onFinish()
it wont let me use timer.start()

Body:
CountDownTimer basically uses a Handler thread which is like other threads can not be restarted once its ended.

You need to use a new instance of the CountDownTimer in each interval.

So in your case, bring the

intervals--;
if (intervals > 0) {

    // for each interval left create a new CountDownTimer here and start it.
}

outside of

new CountDownTimer(timerAmount, 1000 } {

    // do your operations here.

}


问:
codeigniter array session issue after move site one server(godaddy) to another server(bluehost)
There is issue  in  session.  This is my array.

print_r($this->session->userdata("user_data"));

```<code>       Array
         (
           [useremail] => myid@gmail.com
           [user_id] => 1
           [is_login] => 1
          )
</code>```

I want to get the useremail . so I am writing this code.

```<code>         print_r($this->session->userdata("user_data")['useremail']);
</code>```

It gives the error .  Parse error: syntax error, unexpected '['

If I am writing the code like this :

$dataval = $this->session->userdata("user_data");

```<code> print_r($dataval['useremail']);
</code>```

Then it it working fine .

Please help me what is issue ?

答:
It is because you (probably) moved from newer php version (5.4+) to older version (5.2).
Accessing array items directly by calling function name is only available on php 5.4 and newer: array dereferencing.

Only solution is to use temporary variable (like your $dataval). Or you can switch to newere php version, if the bluehost allows it.

Body:
There is issue  in  session.  This is my array.

print_r($this->session->userdata("user_data"));

       Array
         (
           [useremail] => myid@gmail.com
           [user_id] => 1
           [is_login] => 1
          )

I want to get the useremail . so I am writing this code.

         print_r($this->session->userdata("user_data")['useremail']);

It gives the error .  Parse error: syntax error, unexpected '['

If I am writing the code like this :

$dataval = $this->session->userdata("user_data");

 print_r($dataval['useremail']);

Then it it working fine .

Please help me what is issue ?


问:
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.1)">UP</button>

Use the UP button to stay in the air

How long can you stay alive?

Refresh your page to restart the game

```
</div>
</div>
</p>

<p>to</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
    border:1px solid #000000;
    background-color: #000000;
}
</style>
</head>
<body onload="startGame()">
<p>
<script>// <![CDATA[
var myGamePiece;
var myObstacles = [];
var myScore;

function startGame() {
    myGamePiece = new component(30, 30, "red", 10, 120);
    myGamePiece.gravity = 0.05;
    myScore = new component("30px", "Consolas", "Red", 280, 40, "text");
    myGameArea.start();
}

var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.frameNo = 0;
        this.interval = setInterval(updateGameArea, 20);
        },
    clear : function() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
}

function component(width, height, color, x, y, type) {
    this.type = type;
    this.score = 0;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    this.x = x;
    this.y = y;
    this.gravity = 0;
    this.gravitySpeed = 0;
    this.update = function() {
        ctx = myGameArea.context;
        if (this.type == "text") {
            ctx.font = this.width + " " + this.height;
            ctx.fillStyle = color;
            ctx.fillText(this.text, this.x, this.y);
        } else {
            ctx.fillStyle = color;
            ctx.fillRect(this.x, this.y, this.width, this.height);
        }
    }
    this.newPos = function() {
        this.gravitySpeed += this.gravity;
        this.x += this.speedX;
        this.y += this.speedY + this.gravitySpeed;
        this.hitBottom();
    }
    this.hitBottom = function() {
        var rockbottom = myGameArea.canvas.height - this.height;
        if (this.y > rockbottom) {
            this.y = rockbottom;
            this.gravitySpeed = 0;
        }
    }
    this.crashWith = function(otherobj) {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var otherleft = otherobj.x;
        var otherright = otherobj.x + (otherobj.width);
        var othertop = otherobj.y;
        var otherbottom = otherobj.y + (otherobj.height);
        var crash = true;
        if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
            crash = false;
        }
        return crash;
    }
}

function updateGameArea() {
    var x, height, gap, minHeight, maxHeight, minGap, maxGap;
    for (i = 0; i < myObstacles.length; i += 1) {
        if (myGamePiece.crashWith(myObstacles[i])) {
            return;
        }
    }
    myGameArea.clear();
    myGameArea.frameNo += 1;
    if (myGameArea.frameNo == 1 || everyinterval(150)) {
        x = myGameArea.canvas.width;
        minHeight = 20;
        maxHeight = 200;
        height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
        minGap = 50;
        maxGap = 200;
        gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
        myObstacles.push(new component(10, height, "red", x, 0));
        myObstacles.push(new component(10, x - height - gap, "red", x, height + gap));
    }
    for (i = 0; i < myObstacles.length; i += 1) {
        myObstacles[i].x += -1;
        myObstacles[i].update();
    }
    myScore.text="SCORE: " + myGameArea.frameNo;
    myScore.update();
    myGamePiece.newPos();
    myGamePiece.update();
}

function everyinterval(n) {
    if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
    return false;
}

function accelerate(n) {
    myGamePiece.gravity = n;
}
// ]]></script>
</p>
<p><br /> <button>UP</button></p>
<p>Use the UP button to stay in the air</p>
<p>How long can you stay alive?</p>
<p>Refresh your page to restart the game</p>
</body>
</html></code>```

If anyone could help me in fixing this that'd be appreciated

答:
You put your code of script in body part, but you should have put your script in your head tag:

```<code>  <html>
    <head>
    <script>
    ----add your script here----
    </script>
    </head>

    <body>
    <form>
     ----- your contents-----
    </form>
    </body>
  </html>
</code>```

The reason you are getting this error is that you have the wrong code in the button tag. You should replace your button tag with:

```<code>   <form>   <button>UP</button></form>   //replace this with below command and its working
</code>```

Put onmousedown in button tag and remove  tag because Javascript works on the DOM property, so you can't put an extra tag.

```<code><button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.1)">UP</button>
</code>```

Title: <script> Not Working in HTML file

Body:
Im a noob at js, but I have a somewhat decent comprehension of how it works...
Anyways, I found this code and tried to post it to my website annane.us/games/blockup as a test and the script is unresponsive. When I went to my domain host's file manager I found the code edited from

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.1)">UP</button>

Use the UP button to stay in the air

How long can you stay alive?

Refresh your page to restart the game

to

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

 <button>UP</button>

Use the UP button to stay in the air

How long can you stay alive?

Refresh your page to restart the game

If anyone could help me in fixing this that'd be appreciated

Body:
You put your code of script in body part, but you should have put your script in your head tag:

  <html>
    <head>
    <script>
    ----add your script here----
    </script>
    </head>

    <body>
    <form>
     ----- your contents-----
    </form>
    </body>
  </html>

The reason you are getting this error is that you have the wrong code in the button tag. You should replace your button tag with:

   <form>   <button>UP</button></form>   //replace this with below command and its working

Put onmousedown in button tag and remove  tag because Javascript works on the DOM property, so you can't put an extra tag.

<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.1)">UP</button>


问:
Error: Tried to guess R's HOME but no command (R) in the PATH on centos
I am using R 2.7.2 and python 2.6.6 and downloaded rpy2-2.7.6 on centos 6.7 . I am trying to install ryp2 on centos using multiple ways .

python setup.py build --r-home=/usr/lib64/R/lib  install

pip install ryp2

getting common error:

```<code>Error: Tried to guess R's HOME but no command (R) in the PATH " .
</code>```

Beside this I also added the PATH as well as the LD_LIBRARY_PATH in .bashrc having the R_home and R bin path.

Still getting same error. Please help me to solve this issue.

答:
Why use pip while you can install the package as follows:</p>

```<code>sudo apt-get update

sudo apt-get install python-rpy2
</code>```

Body:
I am using R 2.7.2 and python 2.6.6 and downloaded rpy2-2.7.6 on centos 6.7 . I am trying to install ryp2 on centos using multiple ways .

python setup.py build --r-home=/usr/lib64/R/lib  install

pip install ryp2

getting common error:

Error: Tried to guess R's HOME but no command (R) in the PATH " .

Beside this I also added the PATH as well as the LD_LIBRARY_PATH in .bashrc having the R_home and R bin path.

Still getting same error. Please help me to solve this issue.

Body:
Why use pip while you can install the package as follows:

sudo apt-get update

sudo apt-get install python-rpy2


问:
Pass on a Column range of values to a variable in Apps Script
So I have this script which deletes rows if it regex matches one value ('/exe' here). I would like to pass on an entire column (A2:A) of values from another sheet (lets say Sheet1) to regex variable so that all the values are compared and deleted in Sheet2. Anyhelp would be apprecaiated.

SAMPLE SHEET HERE

```<code>function deleteRows() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Sheet2");
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  var toDelete = [];

var re = new RegExp('/exe');
  for (var row = 0; row < values.length; row++) {
  for(var column = 0;column<values[row].length;column++){
  if (re.exec(values[row][column])){
  toDelete.push(row); } } }

  for(var deleteRow = toDelete.length-1; deleteRow >= 0;deleteRow--){
    sheet.deleteRow(toDelete[deleteRow]+1);
  }

  SpreadsheetApp.flush();
};
</code>```

答:
You can concatenate them in a regexy way.
within delete rows you can add

```<code>var pattern = "(" + ss
    .getSheetByName("Sheet1")
    .getDataRange()
    .getValues()
    .map(function(row) {return row[0];})
    .filter(function(row, rowI) {return rowI > 0 && row !== "";})
    .join("|") + ")";
</code>```

Which gets the data from Sheet1,, extracts the first column as an Array, removes the header and empty rows and concatenates them with |, finally we wrap it in parens.

Then you can var re = new RegExp(pattern);

Body:
So I have this script which deletes rows if it regex matches one value ('/exe' here). I would like to pass on an entire column (A2:A) of values from another sheet (lets say Sheet1) to regex variable so that all the values are compared and deleted in Sheet2. Anyhelp would be apprecaiated.

SAMPLE SHEET HERE

function deleteRows() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Sheet2");
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  var toDelete = [];

var re = new RegExp('/exe');
  for (var row = 0; row < values.length; row++) {
  for(var column = 0;column<values[row].length;column++){
  if (re.exec(values[row][column])){
  toDelete.push(row); } } }

  for(var deleteRow = toDelete.length-1; deleteRow >= 0;deleteRow--){
    sheet.deleteRow(toDelete[deleteRow]+1);
  }

  SpreadsheetApp.flush();
};

Body:
You can concatenate them in a regexy way.
within delete rows you can add

var pattern = "(" + ss
    .getSheetByName("Sheet1")
    .getDataRange()
    .getValues()
    .map(function(row) {return row[0];})
    .filter(function(row, rowI) {return rowI > 0 && row !== "";})
    .join("|") + ")";

Which gets the data from Sheet1,, extracts the first column as an Array, removes the header and empty rows and concatenates them with |, finally we wrap it in parens.

Then you can var re = new RegExp(pattern);


问:
RAISERROR never caught using EF 6 with proper severity
I feel like I'm about to scrap this whole project and start over with the amount of frustration this is bringing me. So I definitely appreciate any insight anyone has...

I have SQL Server Stored Procedures that need to do certain logical checks in order to proceed. If these checks fail, RAISERROR() is called and the SP returns. Here's an example of one of these checks:

```<code>IF DATALENGTH(@LastName) < 2
BEGIN
    SELECT @err_msg = CONVERT(NVARCHAR(200), @LastName);
    RAISERROR('The "Single / Last Name" param provided is too short: %s',16,1, @err_msg);
    RETURN;
END
</code>```

This SP is imported into a C# project using EF 6 model-first. The SP is imported into the Function Imports section of the model. An example of the above SP imported  (simplified parameters):

```<code>public virtual ObjectResult<Nullable<int>> CreatePendingContact(string lastName)
    {
        var lastNameParameter = lastName != null ?
            new ObjectParameter("LastName", lastName) :
            new ObjectParameter("LastName", typeof(string));

        return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Nullable<int>>("CreatePendingContact", lastNameParameter);
    }
</code>```

And this function can be called in C# code with a try/catch block is called like so (where _model is the EF-generated dbContext subclass):

```<code>try
    {
        var result = _model.CreatePendingContact(
            LastName
            );
    }
catch (SqlException ex)
    {
        Debug.WriteLine(ex.Message);
        throw;
    }
</code>```

Right now I should be able to pass LastName = "" (or anything else < 2 chars) and get back an SqlException with the above RAISERROR text - however nothing I have been able to do has gotten this SqlException to trigger when it should!

So far here are the things I've tried:

Using THROW keyword instead of simply RETURN (nothing caught)

Running SQL Server Profiler, grabbing the query the C# client sends, and manually executing it in SSMS (results in the error being shown correctly in output)

Modifying the EF generated to add a try/catch block at the ExecuteFunction<>() line (nothing caught)

Right now most threads online either fix the issue with a severity level set to 16, so I'm at a loss to what else I should be setting or looking for...

答:
When I did a test proc with Your sample code

```<code>IF DATALENGTH(@LastName) < 2
BEGIN
    SELECT @err_msg = CONVERT(NVARCHAR(200), @LastName);
    RAISERROR('The "Single / Last Name" param provided is too short: %s',16,1, @err_msg);
    RETURN;
END
</code>```

My proc was not failing. When I used LTRIM and RTRIM like below it did fail

```<code>IF DATALENGTH(LTRIM(RTRIM(@LastName))) < 2
BEGIN
    SELECT @err_msg = CONVERT(NVARCHAR(200), @LastName);
</code>```

RAISERROR('The "Single / Last Name" param provided is too short: %s',16,1, @err_msg);
    END

There is a more solid way to code the procedure by providing the a return value for error and clean execution. Then Grab the return value in .Net and evaluate it. Below is modified stored procedure to demonstrate what I mean.

```<code>CREATE Procedure dbo.TestError @LastName Char(10)
AS
BEGIN
DECLARE @err_msg nvarchar(200)
IF DATALENGTH(LTRIM(RTRIM(@LastName))) < 2
BEGIN
    SELECT @err_msg = CONVERT(NVARCHAR(200), @LastName);
    GOTO ErrorExit
END

CleanExit:
BEGIN
  RETURN 0
END

ErrorExit:
BEGIN
   RAISERROR('The "Single / Last Name" param provided is too short: %s',16,1, @err_msg);
    RETURN 1;
END
END
</code>```

Body:
I feel like I'm about to scrap this whole project and start over with the amount of frustration this is bringing me. So I definitely appreciate any insight anyone has...

I have SQL Server Stored Procedures that need to do certain logical checks in order to proceed. If these checks fail, RAISERROR() is called and the SP returns. Here's an example of one of these checks:

IF DATALENGTH(@LastName) < 2
BEGIN
    SELECT @err_msg = CONVERT(NVARCHAR(200), @LastName);
    RAISERROR('The "Single / Last Name" param provided is too short: %s',16,1, @err_msg);
    RETURN;
END

This SP is imported into a C# project using EF 6 model-first. The SP is imported into the Function Imports section of the model. An example of the above SP imported  (simplified parameters):

public virtual ObjectResult<Nullable<int>> CreatePendingContact(string lastName)
    {
        var lastNameParameter = lastName != null ?
            new ObjectParameter("LastName", lastName) :
            new ObjectParameter("LastName", typeof(string));

        return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Nullable<int>>("CreatePendingContact", lastNameParameter);
    }

And this function can be called in C# code with a try/catch block is called like so (where _model is the EF-generated dbContext subclass):

try
    {
        var result = _model.CreatePendingContact(
            LastName
            );
    }
catch (SqlException ex)
    {
        Debug.WriteLine(ex.Message);
        throw;
    }

Right now I should be able to pass LastName = "" (or anything else < 2 chars) and get back an SqlException with the above RAISERROR text - however nothing I have been able to do has gotten this SqlException to trigger when it should!

So far here are the things I've tried:

Using THROW keyword instead of simply RETURN (nothing caught)

Running SQL Server Profiler, grabbing the query the C# client sends, and manually executing it in SSMS (results in the error being shown correctly in output)

Modifying the EF generated to add a try/catch block at the ExecuteFunction<>() line (nothing caught)

Right now most threads online either fix the issue with a severity level set to 16, so I'm at a loss to what else I should be setting or looking for...

Body:
When I did a test proc with Your sample code

IF DATALENGTH(@LastName) < 2
BEGIN
    SELECT @err_msg = CONVERT(NVARCHAR(200), @LastName);
    RAISERROR('The "Single / Last Name" param provided is too short: %s',16,1, @err_msg);
    RETURN;
END

My proc was not failing. When I used LTRIM and RTRIM like below it did fail

IF DATALENGTH(LTRIM(RTRIM(@LastName))) < 2
BEGIN
    SELECT @err_msg = CONVERT(NVARCHAR(200), @LastName);

RAISERROR('The "Single / Last Name" param provided is too short: %s',16,1, @err_msg);
    END

There is a more solid way to code the procedure by providing the a return value for error and clean execution. Then Grab the return value in .Net and evaluate it. Below is modified stored procedure to demonstrate what I mean.

CREATE Procedure dbo.TestError @LastName Char(10)
AS
BEGIN
DECLARE @err_msg nvarchar(200)
IF DATALENGTH(LTRIM(RTRIM(@LastName))) < 2
BEGIN
    SELECT @err_msg = CONVERT(NVARCHAR(200), @LastName);
    GOTO ErrorExit
END

CleanExit:
BEGIN
  RETURN 0
END

ErrorExit:
BEGIN
   RAISERROR('The "Single / Last Name" param provided is too short: %s',16,1, @err_msg);
    RETURN 1;
END
END


问:
How can I simplify this code? (Chess game obstruction testing)
I'm making a chess game in Java, and testing to make sure there are no pieces blocking the path of the piece being moved. The piece moves from (srcX,srcY) to (dstX,dstY).

I've written this code which checks if there are any obstructions for a rook:

```<code>    if(dstY == srcY) {

            // No change on Y axis, so moving east or west

            if(dstX > srcX) {
                // Moving east
                // Test every cell the piece will pass over
                for(int x = srcX+1; x < dstX; x++) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            } else {
                // Must be moving west
                // Test every cell the piece will pass over
                for(int x = srcX-1; x > dstX; x--) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            }

        } else if(dstX == srcX) {

            // No change on X axis, so moving north or south

            if(dstY > srcY) {
                // Moving north
                // Test every cell the piece will pass over
                for(int y = srcY+1; y < dstY; y++) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            } else {
                // Must be moving south
                // Test every cell the piece will pass over
                for(int y = srcY-1; y > dstY; y--) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            }
        }
</code>```

but it's a bit big and I'm sure it can be simplied.. any ideas?

ps, this is ONLY obstruction testing. I've already validated everything else.

答:
Nearly the same, but with for loops:</p>

```<code>// move along x axis
for (int x = 1; x < Math.abs(srcX - dstX); x++) {
    int curX = (srcX - dstX) < 0 ? srcX - x : srcX + x;
    if (isPiece(curX, srcY))
        return true;
}
// move along y axis
for (int y = 1; y <= Math.abs(srcY - dstY); y++) {
    int curY = (srcY - dstY) < 0 ? srcY - y : srcY + y;
    if (isPiece(srcX, curY))
        return true;
}
</code>```

Body:
I'm making a chess game in Java, and testing to make sure there are no pieces blocking the path of the piece being moved. The piece moves from (srcX,srcY) to (dstX,dstY).

I've written this code which checks if there are any obstructions for a rook:

    if(dstY == srcY) {

            // No change on Y axis, so moving east or west

            if(dstX > srcX) {
                // Moving east
                // Test every cell the piece will pass over
                for(int x = srcX+1; x < dstX; x++) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            } else {
                // Must be moving west
                // Test every cell the piece will pass over
                for(int x = srcX-1; x > dstX; x--) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            }

        } else if(dstX == srcX) {

            // No change on X axis, so moving north or south

            if(dstY > srcY) {
                // Moving north
                // Test every cell the piece will pass over
                for(int y = srcY+1; y < dstY; y++) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            } else {
                // Must be moving south
                // Test every cell the piece will pass over
                for(int y = srcY-1; y > dstY; y--) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            }
        }

but it's a bit big and I'm sure it can be simplied.. any ideas?

ps, this is ONLY obstruction testing. I've already validated everything else.

Body:
Nearly the same, but with for loops:

// move along x axis
for (int x = 1; x < Math.abs(srcX - dstX); x++) {
    int curX = (srcX - dstX) < 0 ? srcX - x : srcX + x;
    if (isPiece(curX, srcY))
        return true;
}
// move along y axis
for (int y = 1; y <= Math.abs(srcY - dstY); y++) {
    int curY = (srcY - dstY) < 0 ? srcY - y : srcY + y;
    if (isPiece(srcX, curY))
        return true;
}


问:
Slim external route file error
Im starting to work with Slim (3.8.1). I am playing with the tickets sample.

Since I am thinking of a larger application I want the have my routes in separate files. But when I include the route file in my index.php I am getting this error:

"Catchable fatal error: Argument 1 passed to Closure::{closure}() must be an instance of Request, instance of Slim\Http\Request given"

This is my route file (simple copy of what was in index.php before, enclosed in php tags):

```<code><?php
$app->get('/tickets', function (Request $request, Response $response) {
   $this->logger->addInfo("Ticket list");
   $mapper = new TicketMapper($this->db);
   $tickets = $mapper->getTickets();

   $response = $this->view->render($response, "tickets.phtml", ["tickets" => $tickets, "router" => $this->router]);
   return $response;
});
?>
</code>```

In my index.php file I have this instead now:

```<code>require '../routes/tickets.php';
</code>```

Do I have to register the path of the route files somehow?

Any help is appreciated.

Best regards,
George

答:
I figured that the following works in the external route file:</p>

```<code><?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

$app->get('/', function (Request $request, Response $response)
{
    $response = $this->view->render($response, "home.phtml");
    return $response;
});
?>
</code>```

Title: Slim external route file error

Body:
Im starting to work with Slim (3.8.1). I am playing with the tickets sample.

Since I am thinking of a larger application I want the have my routes in separate files. But when I include the route file in my index.php I am getting this error:

"Catchable fatal error: Argument 1 passed to Closure::{closure}() must be an instance of Request, instance of Slim\Http\Request given"

This is my route file (simple copy of what was in index.php before, enclosed in php tags):

<?php
$app->get('/tickets', function (Request $request, Response $response) {
   $this->logger->addInfo("Ticket list");
   $mapper = new TicketMapper($this->db);
   $tickets = $mapper->getTickets();

   $response = $this->view->render($response, "tickets.phtml", ["tickets" => $tickets, "router" => $this->router]);
   return $response;
});
?>

In my index.php file I have this instead now:

require '../routes/tickets.php';

Do I have to register the path of the route files somehow?

Any help is appreciated.

Best regards,
George

Body:
I figured that the following works in the external route file:

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

$app->get('/', function (Request $request, Response $response)
{
    $response = $this->view->render($response, "home.phtml");
    return $response;
});
?>


问:
Java - SQLite connection (No suitable driver found for JDBC:sqlite:main.db)
I have problem with SQLite connection on my Java project. Error looks like this :

No suitable driver found for JDBC:sqlite:main.db

That's my code:

```<code>public static void main(String[] args)  {

    Connection c = null;
    try {
      //  Class.forName("org.sqlite.JDBC");
        String url = "JDBC:sqlite:main.db";
        c = DriverManager.getConnection(url);
        System.out.println("Connection to sql");
    } catch ( SQLException e ) {
        System.err.println( e.getMessage() );
    } finally {
        try{
            if( c!= null ) {
                c.close();
            }
        }catch( SQLException ex )
        {
            System.out.println(ex.getMessage());
        }
    }
}
</code>```

Can You help me please?

答:
I think you have not added the SQLITE JDBC driver to your classpath. Just download the jar FROM HERE and add it to your classpath. Your error would be resolved.

You should also have a look on This answer and This resource.
By reading both of them you will learn more about SQLITE as well as how to make a connection with JDBC.

Body:
I have problem with SQLite connection on my Java project. Error looks like this :

No suitable driver found for JDBC:sqlite:main.db

That's my code:

public static void main(String[] args)  {

    Connection c = null;
    try {
      //  Class.forName("org.sqlite.JDBC");
        String url = "JDBC:sqlite:main.db";
        c = DriverManager.getConnection(url);
        System.out.println("Connection to sql");
    } catch ( SQLException e ) {
        System.err.println( e.getMessage() );
    } finally {
        try{
            if( c!= null ) {
                c.close();
            }
        }catch( SQLException ex )
        {
            System.out.println(ex.getMessage());
        }
    }
}

Can You help me please?


问:
How to write if and else statement more elegantly in Swift
I'm having a bit of a brain fart in Swift and I know this code could be written better. Basically what it is, I have two images and I check if a value is over 3 to show an image and hide the other.
currently I have it like this

```<code>let greaterThanThree = value > 3
image1.isHidden = greaterThanThree
image2.isHidden = !greaterThanThree
</code>```

But I feel like there is a more elegant way to write this.

答:
You can do this:

(image1.isHidden, image2.isHidden) =  (value > 3) ? (true, false) : (false, true)

Basically if the value is greater than 3, the first image will be hidden and the second one won't. Otherwise, the second image will be hidden and the first one will not.

Body:
I'm having a bit of a brain fart in Swift and I know this code could be written better. Basically what it is, I have two images and I check if a value is over 3 to show an image and hide the other.
currently I have it like this

let greaterThanThree = value > 3
image1.isHidden = greaterThanThree
image2.isHidden = !greaterThanThree

But I feel like there is a more elegant way to write this.