问:
Template not displaying using 'sub module'
So I have my main module,

```<code>var panther = angular.module('panther', ['panther.sign_in']).config(function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    })
});
</code>```

Which has a dependency of panther.sign_in,

```<code>angular.module('panther.sign_in', ['ngRoute']).config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/sign_in', {
        controller: 'controller_sign_in',
        templateUrl: 'assets/js/modules/core/sign_in/template.html'
    });
}]);
</code>```

The controller looks like this,

```<code>angular.module('panther.sign_in').controller('controller_sign_in', ['$scope', '$http', function ($scope, $http) {
    alert('test');
}]);
</code>```

The template looks like this,

```<code><h1>Test</h1>
</code>```

When I go to /sign_in it shows,

My index.html file looks like this,

```<code><!DOCTYPE html>
<html ng-app="panther">
<head>
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport"
    content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">

<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"
    integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ"
    crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/base.css">

<title>Panther</title>
</head>
<body>
    <script type="text/javascript" src="cordova.js"></script>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"
        integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
        crossorigin="anonymous"></script>

    <script type="text/javascript"
        src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>

    <script type="text/javascript"
        src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular-route.min.js"></script>

    <!-- CORE PANTHER FILES! -->
    <script type="text/javascript" src="assets/js/panther.js"></script>

    <!-- MODULE(S) INITIALISED HERE! -->
    <script type="text/javascript" src="assets/js/modules/core/sign_in/module.js"></script>

    <!-- MODULE(S) CONTROLLER(S) INITIALISED HERE! -->
    <script type="text/javascript" src="assets/js/modules/core/sign_in/controller.js"></script>
</body>
</html>
</code>```

Why does it not show the template file when I go to the URL /sign_in?

Secondly, is this the correct way to split a large application using Angular (using sub modules)?

Edit #1

In simple terms, I want it so that the user can type http://www.mysite.online/sign_in and the template/controller should show for that sub module. I've updated the main panther module as can be seen below:

```<code>var panther = angular.module('panther', ['panther.sign_in']).config(function ($routeProvider, $locationProvider) {
    /** Remove anything that has been appended to URL (#!). **/
    $locationProvider.hashPrefix('');
});
</code>```

I've changed my code to this, but it still didn't work.

答:
Fixed...

For those of you who like me are new to Angular, I forgot to add the ng-view hence the template could not be loaded. As a result nothing would work, all I did was had the following HTML and it worked.

```<code><div ng-view></div>
</code>```

Reading Material

Modular AngularJS App Design

Body:
So I have my main module,

var panther = angular.module('panther', ['panther.sign_in']).config(function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    })
});

Which has a dependency of panther.sign_in,

angular.module('panther.sign_in', ['ngRoute']).config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/sign_in', {
        controller: 'controller_sign_in',
        templateUrl: 'assets/js/modules/core/sign_in/template.html'
    });
}]);

The controller looks like this,

angular.module('panther.sign_in').controller('controller_sign_in', ['$scope', '$http', function ($scope, $http) {
    alert('test');
}]);

The template looks like this,

Test

When I go to /sign_in it shows,

My index.html file looks like this,

<!DOCTYPE html>

<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport"
    content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">

<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"
    integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ"
    crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/base.css">

<title>Panther</title>

Why does it not show the template file when I go to the URL /sign_in?

Secondly, is this the correct way to split a large application using Angular (using sub modules)?

Edit #1

In simple terms, I want it so that the user can type http://www.mysite.online/sign_in and the template/controller should show for that sub module. I've updated the main panther module as can be seen below:

var panther = angular.module('panther', ['panther.sign_in']).config(function ($routeProvider, $locationProvider) {
    /** Remove anything that has been appended to URL (#!). **/
    $locationProvider.hashPrefix('');
});

I've changed my code to this, but it still didn't work.

Body:
Fixed...

For those of you who like me are new to Angular, I forgot to add the ng-view hence the template could not be loaded. As a result nothing would work, all I did was had the following HTML and it worked.

<div ng-view></div>

Reading Material

Modular AngularJS App Design


来源: stackexchange

问:
Python: TypeError while using os.environ.get
I want to access a shell environment variable in my python script.
I am trying this

```<code>import os
print os.environ.get["HOME"]
</code>```

I get this error when I am executing in python
(I am getting the same error in bash also)

```<code>Traceback (most recent call last):
  File "C:\Users\sraparim\Desktop\GitHub issues\issue #1187\test.py", line 54, in <module>
    print os.environ.get["HOME"]
TypeError: 'instancemethod' object has no attribute '__getitem__'
[Finished in 0.2s with exit code 1]
[shell_cmd: python -u "C:\Users\sraparim\Desktop\GitHub issues\issue #1187\test.py"]
[dir: C:\Users\sraparim\Desktop\GitHub issues\issue #1187]
[path: C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\WebEx\Productivity Tools;C:\Program Files (x86)\Cisco\OSD-ShellApplications;C:\Program Files (x86)\Sennheiser\SoftphoneSDK\;C:\Program Files\PuTTY\;C:\Python27\Scripts;C:\Python27;C:\Python27]
</code>```

Please help...

答:
get() is a method on the environ object; use parentheses instead of brackets:

```<code>print os.environ.get('HOME')
</code>```

or brackets without get, which implicitly calls __getitem__():

```<code>print os.environ['HOME']
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to access a shell environment variable in my python script.
I am trying this

import os
print os.environ.get["HOME"]

I get this error when I am executing in python
(I am getting the same error in bash also)

Traceback (most recent call last):
  File "C:\Users\sraparim\Desktop\GitHub issues\issue #1187\test.py", line 54, in <module>
    print os.environ.get["HOME"]
TypeError: 'instancemethod' object has no attribute '__getitem__'
[Finished in 0.2s with exit code 1]
[shell_cmd: python -u "C:\Users\sraparim\Desktop\GitHub issues\issue #1187\test.py"]
[dir: C:\Users\sraparim\Desktop\GitHub issues\issue #1187]
[path: C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\WebEx\Productivity Tools;C:\Program Files (x86)\Cisco\OSD-ShellApplications;C:\Program Files (x86)\Sennheiser\SoftphoneSDK\;C:\Program Files\PuTTY\;C:\Python27\Scripts;C:\Python27;C:\Python27]

Please help...

Body:
get() is a method on the environ object; use parentheses instead of brackets:

print os.environ.get('HOME')

or brackets without get, which implicitly calls __getitem__():

print os.environ['HOME']


问:
Chisel: Compiling Chisel library on Windows
I have been using sbt on windows and a custom build.sbt script in conjunction with an import Chisel._ in the top-level file in order to generate Verilog from my Chisel source successfully.

I'm trying to get an IDE working on Windows to expedite Chisel development. I've gone with the Eclipse based SCALA IDE http://scala-ide.org/download/sdk.html/

I want to compile the Chisel library so that the import Chisel._ can be resolved locally, without having to go off and download the source from the repository each timeand recompile the source. When I download the Chisel-master repo from Git and include the src\main folder in my SCALA project in the SCALA IDE, I get lots of syntax errors in the Chisel SCALA files that prevent me from building the project.

Has anyone done anything like this before on Windows or have any knowledge of working with the SCALA IDE as it may just be a case of undefined symbols in the project configuration?

答:
Not sure exactly what you did with build.sbt respect to recompile (I think it download it only the first time, then it caches it for the future).  But I'm using ScalaIDE for Chisel on linux, using the default build.sbt files, maybe you can try to get it working out of the box first to help narrow down the issue.

Here are the steps I took in order to get ScalaIDE work with Chisel:

the latest Scala IDE uses 2.11.8, the current Chisel repository defaults to 2.11.7.  So I had to change all the build.sbt reference to scalaVersion from 2.11.7 to 2.11.8

I used sbteclipse
https://github.com/typesafehub/sbteclipse
To create importable the workspace to setup the compilation dependencies.

Except for chiselFrontEnd.  For some reason, this package is not added to the dependency. I have to Add chiselFrontEnd as a javabuildpath dependency manually (Properties/JavaBuildPath, under Projects) for my own projects.


问:
Java Generics in ArrayList
This code has been giving me problems. all I want to do is create methods that will allow me to add generics to this array list. Using an Array List is not necessary if there is a better class that works well with generics. before I get useless answers these objects are initialized in the constructor of the object they are in. and the getters and setters exist. the problem is that the .add() method in array list is not accepting generics</p>

```<code>private ArrayList<? extends Inputable> inputSubscriber;
private ArrayList<? extends Updateable> updateSubscriber;
private ArrayList<? extends Renderable> renderSubsciber;

public <e extends Inputable> void subscribeToInput(e inputable){
    this.getInputSubscriber().add(inputable);
}

public <e extends Updateable> void subscribeToUpdate(e updateable){
    this.getUpdateSubscriber().add(updateable);
}

public <e extends Renderable> void subscribeToRender(e renderable){
    this.getRenderSubsciber().add(renderable);
}
</code>```

答:
This was a stupid over sight on my part. I am not sure how this problem lasted me long enough to ask the question here. but for those of you having the same issue this problem does not need generics and can be solved like this. I over complicated things since inputable and others are interfaces.</p>

```<code>private ArrayList<Inputable> inputSubscriber;
private ArrayList<Updateable> updateSubscriber;
private ArrayList<Renderable> renderSubsciber;

public void subscribeToInput(inputable){
    this.getInputSubscriber().add(inputable);
}

public void subscribeToUpdate(updateable){
    this.getUpdateSubscriber().add(updateable);
}

public void subscribeToRender(renderable){
    this.getRenderSubsciber().add(renderable);
}
</code>```

Title: Java Generics in ArrayList

Body:
This code has been giving me problems. all I want to do is create methods that will allow me to add generics to this array list. Using an Array List is not necessary if there is a better class that works well with generics. before I get useless answers these objects are initialized in the constructor of the object they are in. and the getters and setters exist. the problem is that the .add() method in array list is not accepting generics

private ArrayList<? extends Inputable> inputSubscriber;
private ArrayList<? extends Updateable> updateSubscriber;
private ArrayList<? extends Renderable> renderSubsciber;

public <e extends Inputable> void subscribeToInput(e inputable){
    this.getInputSubscriber().add(inputable);
}

public <e extends Updateable> void subscribeToUpdate(e updateable){
    this.getUpdateSubscriber().add(updateable);
}

public <e extends Renderable> void subscribeToRender(e renderable){
    this.getRenderSubsciber().add(renderable);
}

Body:
This was a stupid over sight on my part. I am not sure how this problem lasted me long enough to ask the question here. but for those of you having the same issue this problem does not need generics and can be solved like this. I over complicated things since inputable and others are interfaces.

private ArrayList<Inputable> inputSubscriber;
private ArrayList<Updateable> updateSubscriber;
private ArrayList<Renderable> renderSubsciber;

public void subscribeToInput(inputable){
    this.getInputSubscriber().add(inputable);
}

public void subscribeToUpdate(updateable){
    this.getUpdateSubscriber().add(updateable);
}

public void subscribeToRender(renderable){
    this.getRenderSubsciber().add(renderable);
}


问:
guava-libraries: is Iterators.cycle() thread-safe?
Suppose I have the following class:

```<code>public class Foo {

    private List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
    private Iterator<Integer> iterator = Iterators.cycle(list);

    public void bar(){
        Integer value = iterator.next();
        doSomethingWithAnInteger(value);
    }
}
</code>```

If an instance of Foo is acessed simultaneously by two threads, I need that each thread gets a different value from iterator.next(). Does the bar() method have to be made synchronized? Or is iterator.next() guaranteed to be thread-safe?

In this example, I am using an ArrayList as the underlying Iterable. Does the thread-safety of the cyclic iterator depend on the specific iterable implementation?

答: Take a look at the source code of Iterators.cycle(final Iterable<T> iterable). Even if the underlying Iterator is thread-safe, it doesn't look like the cycling wrapper is. This is consistent with Java's policy of not implicitly synchronizing iterators.

ContentLicense: CC BY-SA 4.0

Body:
Suppose I have the following class:

public class Foo {

    private List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
    private Iterator<Integer> iterator = Iterators.cycle(list);

    public void bar(){
        Integer value = iterator.next();
        doSomethingWithAnInteger(value);
    }
}

If an instance of Foo is acessed simultaneously by two threads, I need that each thread gets a different value from iterator.next(). Does the bar() method have to be made synchronized? Or is iterator.next() guaranteed to be thread-safe?

In this example, I am using an ArrayList as the underlying Iterable. Does the thread-safety of the cyclic iterator depend on the specific iterable implementation?


问:
Perl: Verify the command line argument is an integer and not a file
I need to check if the (Perl) command line argument is only an integer and a file.

I can check is the right number of arguments are entered:

```<code>if (@ARGV != 2){
</code>```

And, I can check to make sure the order of arguments is correct:

```<code>    if ($ARGV[0] >= $ARGV[1])
</code>```

But, I don't know how to check if the argument is a file. I want to print and error message if it is a file.

Thanks

答:
You can use -f to check if a given string is a file or not. For more options, see perldoc -X.

In your example as I understood it:

```<code>die 'First argument is a filename!' if -f $ARGV[0];
</code>```

Body:
I need to check if the (Perl) command line argument is only an integer and a file.

I can check is the right number of arguments are entered:

if (@ARGV != 2){

And, I can check to make sure the order of arguments is correct:

    if ($ARGV[0] >= $ARGV[1])

But, I don't know how to check if the argument is a file. I want to print and error message if it is a file.

Thanks

Body:
You can use -f to check if a given string is a file or not. For more options, see perldoc -X.

In your example as I understood it:

die 'First argument is a filename!' if -f $ARGV[0];


问:
Modifying django object model for better admin CRUD management
I am writing a blog app using django 1.10

This is a snippet of my object model:

model.py

```<code>class Attachment(models.Model):
    title = models.CharField(max_length=50)
    image = models.ImageField(upload_to='attachments')

class FileAttachments(models.Model):
    title = models.CharField(max_length=50)
    attachments = models.ManyToManyField(Attachment)

class Post(models.Model):
    title = models.CharField(max_length=200)
    text = models.CharField(max_length=2000)
    file_attachments = models.ForeignKey(FileAttachments, blank=True, null=True)
    slug = models.SlugField(max_length=40, default='', unique=True)
    author = models.ForeignKey(User, default=1)
    pub_date = models.DateTimeField(blank=True, null=True)

    def get_absolute_url(self):
        return "/blog/%s/%s/%s/%s/" % (self.pub_date.year, self.pub_date.month, self.pub_date.day, self.slug)

    def __unicode__(self):
        return self.title

    class Meta:
        verbose_name = "Blog Post"
        verbose_name_plural = "Blog Posts"
        ordering = ["-create_date"]

        permissions = (
            ( "create", "Create Post" ),
            ( "modify", "Modify Post" ),
            ( "delete", "Delete Post" ),
        )
</code>```

(simplified) admin.py:

```<code>class PostAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("title",)}
    exclude = ('author',)

    def save_model(self, request, obj, form, change):
        obj.author = request.user
        obj.save()

# Register your models here.
admin.site.register(Post, PostAdmin)
</code>```

when I try to access the Post object via the admin page - in the list view, I only see 'Post object' - whereas I want to see the title of the post (and possibly, a few other attributes of the Post object) - how do I modify the admin view to achieve this?

答:
Change __unicode__ for __str__ in your Post class and print whatever you want.  For example: return "Blog %s published on %s" %(self.title, self.pub_date).

Your Post model only includes one attachment through a foreign key.  That way it will be impossible to upload more than one file.  In other words, you have to change your models, for example including a key in FileAttachments relating to a Post and removing the key from Post model.

Hope this helps.

Body:
I am writing a blog app using django 1.10

This is a snippet of my object model:

model.py

class Attachment(models.Model):
    title = models.CharField(max_length=50)
    image = models.ImageField(upload_to='attachments')

class FileAttachments(models.Model):
    title = models.CharField(max_length=50)
    attachments = models.ManyToManyField(Attachment)

class Post(models.Model):
    title = models.CharField(max_length=200)
    text = models.CharField(max_length=2000)
    file_attachments = models.ForeignKey(FileAttachments, blank=True, null=True)
    slug = models.SlugField(max_length=40, default='', unique=True)
    author = models.ForeignKey(User, default=1)
    pub_date = models.DateTimeField(blank=True, null=True)

    def get_absolute_url(self):
        return "/blog/%s/%s/%s/%s/" % (self.pub_date.year, self.pub_date.month, self.pub_date.day, self.slug)

    def __unicode__(self):
        return self.title

    class Meta:
        verbose_name = "Blog Post"
        verbose_name_plural = "Blog Posts"
        ordering = ["-create_date"]

        permissions = (
            ( "create", "Create Post" ),
            ( "modify", "Modify Post" ),
            ( "delete", "Delete Post" ),
        )

(simplified) admin.py:

class PostAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("title",)}
    exclude = ('author',)

    def save_model(self, request, obj, form, change):
        obj.author = request.user
        obj.save()

# Register your models here.
admin.site.register(Post, PostAdmin)

when I try to access the Post object via the admin page - in the list view, I only see 'Post object' - whereas I want to see the title of the post (and possibly, a few other attributes of the Post object) - how do I modify the admin view to achieve this?


问:
Turning an array into a multidimensional array? Javascript
I am struggling to create a simple function that will taking an array such as

```<code>["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"]
</code>```

and turn it into a multidimensional array that looks like this

```<code>[["chicken","10 lbs"],["hot sauce","4 cups"],["celery","1 stalk"]]
</code>```

essentially index 0 and 1 merge into a new sub array then 2 and 3 merge and so on...

i am trying for loops where i increases +2 but i can't get it quite right, i thought this would be a simple solution but the loops i've made so far are almost crashing my browser...any help would be appreciated. thanks

EDIT:  WOW Thanks for all the rapid responses!  I looked at everything and learned a lot!

答:
Using Array#reduce(), Array#concat() & Array#slice()

var data = ["chicken", "10 lbs", "hot sauce", "4 cups", "celery", "1 stalk"];

var res = data.reduce((a, c, i) => {
  return i % 2 === 0 ? a.concat([data.slice(i, i + 2)]) : a;
}, []);

console.log(res)```

Body:
I am struggling to create a simple function that will taking an array such as

["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"]

and turn it into a multidimensional array that looks like this

[["chicken","10 lbs"],["hot sauce","4 cups"],["celery","1 stalk"]]

essentially index 0 and 1 merge into a new sub array then 2 and 3 merge and so on...

i am trying for loops where i increases +2 but i can't get it quite right, i thought this would be a simple solution but the loops i've made so far are almost crashing my browser...any help would be appreciated. thanks

EDIT:  WOW Thanks for all the rapid responses!  I looked at everything and learned a lot!


问:
Laravel 5.2 MSSQL connection issue
I'm using FreeTDS + UnixOdbc to connect to a remote MSSQL DB through a VPN. I'm also using Vagrant. I can SSH into my vagrant box and run my tsql command and connect to the instance I've set in my freetds.conf file.

But the Laravel app itself doesnt connect. It's being powered with Nginx. I get a PDOException: SQLSTATE[HY000] Read from the server failed message in the laravel.log.

Here is my freetds.conf file:

```<code>[SDSQL2DEV]
host = xx.xxx.xx.xx
instance = sdsql2\dev
port = 65156
client charset = UTF-8
tds version = 4.2
</code>```

Note that I have to set the tds version to 4.2 or else no matter what I do I cannot connect or run queries with tsql. Seems like I may have a deeper issue.

I'm sure the correct freetds.conf file is being used. I can run tsql -C and see settings I toggle take effect. Here is the output from that:

```<code>Version: freetds v0.91
freetds.conf directory: /etc/freetds
MS db-lib source compatibility: no
Sybase binary compatibility: yes
Thread safety: yes
iconv library: yes
TDS version: 4.2
iODBC: no
unixodbc: yes
SSPI "trusted" logins: no
Kerberos: yes
</code>```

If I change the version to 7.2 which I would think is supported by freetds v 0.91 then I receive this message:

```<code>locale is "en_US.UTF-8"
locale charset is "UTF-8"
using default charset "UTF-8"
Error 100 (severity 11):
unrecognized msgno
</code>```

I'm pretty experienced with Laravel, just not integrating with MSSQL but I think I have the Laravel settings configured properly. Here they are:

```<code>// .env
MS_CONNECTION="sqlsrv"
MS_HOST="xx.xxx.x.x"
MS_PORT="65156"
MS_DATABASE="dbname"
MS_USERNAME="dbuser"
MS_PASSWORD="dbpass"

// config/database.php
'sqlsrv' => [
    'driver' => 'sqlsrv',
    'host' => env('MS_HOST', 'SDSQL2DEV'),
    'port' => env('MS_PORT', '65156'),
    'database' => env('MS_DATABASE', 'forge'),
    'username' => env('MS_USERNAME', 'forge'),
    'password' => env('MS_PASSWORD', ''),
    'collation' => 'SQL_Latin1_General_CP1_CI_AS',
    'prefix' => '',
],
</code>```

答:
I finally figured this out. It wasn't an issue related to Laravel, FreeTDS or MSSQL, but rather an issue with my OpenVPN config and data compression. The OpenVPN client config file I was using had comp-lzo off set but in order to get this working I needed to update it to comp-lzo yes. I noticed this when I saw compression related notices in the log file and the OpenVPN docs led me to make the change.

Hope this helps someone in the future.

Title: Laravel 5.2 MSSQL connection issue

Body:
I'm using FreeTDS + UnixOdbc to connect to a remote MSSQL DB through a VPN. I'm also using Vagrant. I can SSH into my vagrant box and run my tsql command and connect to the instance I've set in my freetds.conf file.

But the Laravel app itself doesnt connect. It's being powered with Nginx. I get a PDOException: SQLSTATE[HY000] Read from the server failed message in the laravel.log.

Here is my freetds.conf file:

[SDSQL2DEV]
host = xx.xxx.xx.xx
instance = sdsql2\dev
port = 65156
client charset = UTF-8
tds version = 4.2

Note that I have to set the tds version to 4.2 or else no matter what I do I cannot connect or run queries with tsql. Seems like I may have a deeper issue.

I'm sure the correct freetds.conf file is being used. I can run tsql -C and see settings I toggle take effect. Here is the output from that:

Version: freetds v0.91
freetds.conf directory: /etc/freetds
MS db-lib source compatibility: no
Sybase binary compatibility: yes
Thread safety: yes
iconv library: yes
TDS version: 4.2
iODBC: no
unixodbc: yes
SSPI "trusted" logins: no
Kerberos: yes

If I change the version to 7.2 which I would think is supported by freetds v 0.91 then I receive this message:

locale is "en_US.UTF-8"
locale charset is "UTF-8"
using default charset "UTF-8"
Error 100 (severity 11):
unrecognized msgno

I'm pretty experienced with Laravel, just not integrating with MSSQL but I think I have the Laravel settings configured properly. Here they are:

// .env
MS_CONNECTION="sqlsrv"
MS_HOST="xx.xxx.x.x"
MS_PORT="65156"
MS_DATABASE="dbname"
MS_USERNAME="dbuser"
MS_PASSWORD="dbpass"

// config/database.php
'sqlsrv' => [
    'driver' => 'sqlsrv',
    'host' => env('MS_HOST', 'SDSQL2DEV'),
    'port' => env('MS_PORT', '65156'),
    'database' => env('MS_DATABASE', 'forge'),
    'username' => env('MS_USERNAME', 'forge'),
    'password' => env('MS_PASSWORD', ''),
    'collation' => 'SQL_Latin1_General_CP1_CI_AS',
    'prefix' => '',
],


问:
malloc'ing for field inside struct
I have, roughly speaking, a function prototype like this:

```<code>init_superstruct(const char *name, Superstruct **super, int num_substructs) {...
</code>```

where superstruct looks like

```<code>typedef struct superstruct {
    char *name,
    Substruct **substructs,
    int num_substructs;
} Superstruct
</code>```

The function is supposed to

1) allocate memory for (and initialize) super, by...

2) ...assigning the name field of super enough memory to hold the name argument, and...

3) ...assigning the substructs field enough memory to hold an array pointers to Substructs (of size num_substructs).

My question: will the following code accomplish these goals?

```<code>*super = malloc(sizeof(*super));
*super->name = malloc(sizeof(strlen(name) + 1)));
*super->substructs = calloc(num_substructs, sizeof(Substruct));
</code>```

This is literally my first foray into dynamic memory allocation. Any advice you have would be helpful for me!

答:
First:

```<code>*super = malloc(sizeof(*super));
</code>```

You want sizeof(**super). *super is a pointer, with type Superstruct *, so this won't allocate enough memory.

Really, you should probably allocate the structure normally, then assign it to the pointer separately. This will make your code much easier to write:

```<code>Superstruct *r = malloc(sizeof *r);
r->name = …
*super = r;
</code>```

Second:

```<code>*super->name = malloc(sizeof(strlen(name) + 1)));
</code>```

This is wrong. sizeof(strlen(name) + 1) is sizeof(int) (or perhaps sizeof(size_t); either way it's not what you want) -- strlen() won't even be called! Remove the sizeof() from this expression to make it correct.

Third: to allocate a single array of Substruct objects, define the structure member as Substruct *substructs, and allocate it using the exact code you've got right now. You don't need a double pointer unless you want an array of pointers to the structures, which is more complicated than you need.

If you really think you do need an array of pointers here (you probably don't), you need to allocate the array using sizeof(Substruct *) as the size argument to calloc(), not sizeof(Substruct).

Title: malloc'ing for field inside struct

Body:
I have, roughly speaking, a function prototype like this:

init_superstruct(const char *name, Superstruct **super, int num_substructs) {...

where superstruct looks like

typedef struct superstruct {
    char *name,
    Substruct **substructs,
    int num_substructs;
} Superstruct

The function is supposed to

1) allocate memory for (and initialize) super, by...

2) ...assigning the name field of super enough memory to hold the name argument, and...

3) ...assigning the substructs field enough memory to hold an array pointers to Substructs (of size num_substructs).

My question: will the following code accomplish these goals?

*super = malloc(sizeof(*super));
*super->name = malloc(sizeof(strlen(name) + 1)));
*super->substructs = calloc(num_substructs, sizeof(Substruct));

This is literally my first foray into dynamic memory allocation. Any advice you have would be helpful for me!

Body:
First:

*super = malloc(sizeof(*super));

You want sizeof(**super). *super is a pointer, with type Superstruct *, so this won't allocate enough memory.

Really, you should probably allocate the structure normally, then assign it to the pointer separately. This will make your code much easier to write:

Superstruct *r = malloc(sizeof *r);
r->name = …
*super = r;

Second:

*super->name = malloc(sizeof(strlen(name) + 1)));

This is wrong. sizeof(strlen(name) + 1) is sizeof(int) (or perhaps sizeof(size_t); either way it's not what you want) -- strlen() won't even be called! Remove the sizeof() from this expression to make it correct.

Third: to allocate a single array of Substruct objects, define the structure member as Substruct *substructs, and allocate it using the exact code you've got right now. You don't need a double pointer unless you want an array of pointers to the structures, which is more complicated than you need.

If you really think you do need an array of pointers here (you probably don't), you need to allocate the array using sizeof(Substruct *) as the size argument to calloc(), not sizeof(Substruct).


问:
I need to do the piglatin exercise in ruby
I need to check if a word starts with a vowel or consonant. For words starting with a vowel I need to ad "ay" to the end of the word. This part was easy. I managed it like this:

```<code>def translate string
  vowels = ["a", "e", "i", "o", "u"]
   if vowels.include? (string[0])
   string +'ay'
  else
   *the consonant part goes here*
  end
end
</code>```

I need help with the syntax for the consonant part. If a word begins with a consonant sound, move it to the end of the word, and then add an "ay" sound to the end of the word.
Here's what I'm trying to do in the else part of my if statement:

```<code>consonant = string(0)
new_word = string - string(0)
pig_latin_word = new_word << consonant << "ay"
</code>```

Thank you.

答:
An elegant solution would be to to concatenate slices of the string, using same syntax as you would with an array, with 'ay' in a neat one liner:</p>

```<code>string[1..-1] + string[0] + 'ay'
</code>```

Body:
I need to check if a word starts with a vowel or consonant. For words starting with a vowel I need to ad "ay" to the end of the word. This part was easy. I managed it like this:

def translate string
  vowels = ["a", "e", "i", "o", "u"]
   if vowels.include? (string[0])
   string +'ay'
  else
   *the consonant part goes here*
  end
end

I need help with the syntax for the consonant part. If a word begins with a consonant sound, move it to the end of the word, and then add an "ay" sound to the end of the word.
Here's what I'm trying to do in the else part of my if statement:

consonant = string(0)
new_word = string - string(0)
pig_latin_word = new_word << consonant << "ay"

Thank you.

Body:
An elegant solution would be to to concatenate slices of the string, using same syntax as you would with an array, with 'ay' in a neat one liner:

string[1..-1] + string[0] + 'ay'


问:
How to call strings from strings.xml in arraylist
I am using an ArrayList and all the strings are hard coded in the adapter but now I need multi-language support for my app. I think the best way to do this is to move all my hard coded strings to my strings.xml file and then make all the string files I need for the different languages.

I already moved the hard coded strings to my strings.xml but I am not sure now how to call them in the Arraylist instead of having the hard coded string in there.

```<code>public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {

List<AdapterData> mItems;

public Adapter() {
super();
mItems = new ArrayList<>();
AdapterData data = new AdapterData();
data.setQuestion("How Old Are You?");
data.setAnswer("I Am 21 Years Old");
mItems.add(data);

data = new AdapterData();
data.setQuestion("Where Were You Born?");
data.setAnswer("I Was Born In The USA");
mItems.add(data);

data = new AdapterData();
data.setQuestion("Are You Male or Female?");
data.setAnswer("I Am Male");
mItems.add(data);

}

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
        .inflate(R.layout.recycler_view_card_item, viewGroup, false);
return new ViewHolder(v);
}

@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
AdapterData data = mItems.get(i);
viewHolder.mName.setText(data.getQuestion());
viewHolder.mNameTwo.setText(data.getAnswer());
 }

@Override
public int getItemCount() {

return mItems.size();
}

class ViewHolder extends RecyclerView.ViewHolder{

public TextView mQuestion;
public TextView mAnswer;

public ViewHolder(View itemView) {
    super(itemView);
    mQuestion = (TextView)itemView.findViewById(R.id.layoutQuestion);
    mAnswer = (TextView)itemView.findViewById(R.id.layoutAnswer);

}
}

}
</code>```

答:
You can getResources(), getString(string from strings.xml).

So you can do:

```<code>mItems.add(getResources().getString(R.string.yourString));
</code>```

Body:
I am using an ArrayList and all the strings are hard coded in the adapter but now I need multi-language support for my app. I think the best way to do this is to move all my hard coded strings to my strings.xml file and then make all the string files I need for the different languages.

I already moved the hard coded strings to my strings.xml but I am not sure now how to call them in the Arraylist instead of having the hard coded string in there.

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {

List<AdapterData> mItems;

public Adapter() {
super();
mItems = new ArrayList<>();
AdapterData data = new AdapterData();
data.setQuestion("How Old Are You?");
data.setAnswer("I Am 21 Years Old");
mItems.add(data);

data = new AdapterData();
data.setQuestion("Where Were You Born?");
data.setAnswer("I Was Born In The USA");
mItems.add(data);

data = new AdapterData();
data.setQuestion("Are You Male or Female?");
data.setAnswer("I Am Male");
mItems.add(data);

}

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
        .inflate(R.layout.recycler_view_card_item, viewGroup, false);
return new ViewHolder(v);
}

@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
AdapterData data = mItems.get(i);
viewHolder.mName.setText(data.getQuestion());
viewHolder.mNameTwo.setText(data.getAnswer());
 }

@Override
public int getItemCount() {

return mItems.size();
}

class ViewHolder extends RecyclerView.ViewHolder{

public TextView mQuestion;
public TextView mAnswer;

public ViewHolder(View itemView) {
    super(itemView);
    mQuestion = (TextView)itemView.findViewById(R.id.layoutQuestion);
    mAnswer = (TextView)itemView.findViewById(R.id.layoutAnswer);

}
}

}

Body:
You can getResources(), getString(string from strings.xml).

So you can do:

mItems.add(getResources().getString(R.string.yourString));


问:
Which direction should the arrows point in a sorted table?
In a sorted table, it's common to have an up or a down arrow indicating the sort style. However, I'm having some trouble determining which direction the arrow should point. In an ASC sort, characters are sorted 1-9A-Za-z. Should the arrow point up or down?

I've found implementations of both on the web, so that didn't help me much: Up and Down (you have to create the table first).

Is there a hard and fast rule for this? I find myself able to justify both implementations. Which method do you use? Which is more intuitive to you and why?

Edit: Some of you have suggested alternate implementations like rising bars or having letters with an arrow indicating sort direction. Great suggestions. I'm definitely open to other options. The less ambiguous, the better. It might be picky, but I'd really like there to be minimal or no confusion on the part of the user.

Edit: I ended up going with the rising and falling bars for now. It's not standard, but seems less ambiguous than the triangles. The current sort column shows three bars, small to large (left to right) for ASC, the opposite for DESC. Other sortable columns have no bars by default, but hovering over any sortable column heading (including the current) shows bars depicting how the table will be sorted if that column heading is clicked.

答: Remember that descending is for down. So, I would use the down arrow for descending. But, I always get confused by this anyway. I recommend that you use letters instead, like A-Z and Z-A instead of the arrows. Or, use them in conjunction with the arrows.

OwnerDisplayName: VirtuosiMedia

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: VirtuosiMedia

OwnerDisplayName: p1nk g33k


问:
SqlAlchemy equivalent of pyodbc connect string using FreeTDS
The following works:

```<code>import pyodbc
pyodbc.connect('DRIVER={FreeTDS};Server=my.db.server;Database=mydb;UID=myuser;PWD=mypwd;TDS_Version=8.0;Port=1433;')
</code>```

The following fails:

```<code>import sqlalchemy
sqlalchemy.create_engine("mssql://myuser:mypwd@my.db.server:1433/mydb?driver=FreeTDS& odbc_options='TDS_Version=8.0'").connect()
</code>```

The error message for above is:

DBAPIError: (Error) ('08001', '[08001] [unixODBC][FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnectW)') None None

Can someone please point me in the right direction?  Is there a way I can simply tell sqlalchemy to pass a specific connect string through to pyodbc?

Please Note: I want to keep this DSN-less.

答:
I'm still interested in a way to do this in one line within the sqlalchemy create_engine statement, but I found the following workaround detailed here:

```<code>import pyodbc, sqlalchemy

def connect():
    pyodbc.connect('DRIVER={FreeTDS};Server=my.db.server;Database=mydb;UID=myuser;PWD=mypwd;TDS_Version=8.0;Port=1433;')

sqlalchemy.create_engine('mssql://', creator=connect)
</code>```

UPDATE: Addresses a concern I raised in my own comment about not being able to pass arguments to the connect string.  The following is a general solution if you need to dynamically connect to different databases at runtime.  I only pass the database name as a parameter, but additional parameters could easily be used as needed:

```<code>import pyodbc
import os

class Creator:
    def __init__(self, db_name='MyDB'):
        """Initialization procedure to receive the database name"""
        self.db_name = db_name

    def __call__(self):
        """Defines a custom creator to be passed to sqlalchemy.create_engine
           http://stackoverflow.com/questions/111234/what-is-a-callable-in-python#111255"""
        if os.name == 'posix':
            return pyodbc.connect('DRIVER={FreeTDS};'
                                  'Server=my.db.server;'
                                  'Database=%s;'
                                  'UID=myuser;'
                                  'PWD=mypassword;'
                                  'TDS_Version=8.0;'
                                  'Port=1433;' % self.db_name)
        elif os.name == 'nt':
            # use development environment
            return pyodbc.connect('DRIVER={SQL Server};'
                                  'Server=127.0.0.1;'
                                  'Database=%s_Dev;'
                                  'UID=user;'
                                  'PWD=;'
                                  'Trusted_Connection=Yes;'
                                  'Port=1433;' % self.db_name)

def en(db_name):
    """Returns a sql_alchemy engine"""
    return sqlalchemy.create_engine('mssql://', creator=Creator(db_name))
</code>```

Body:
The following works:

import pyodbc
pyodbc.connect('DRIVER={FreeTDS};Server=my.db.server;Database=mydb;UID=myuser;PWD=mypwd;TDS_Version=8.0;Port=1433;')

The following fails:

import sqlalchemy
sqlalchemy.create_engine("mssql://myuser:mypwd@my.db.server:1433/mydb?driver=FreeTDS& odbc_options='TDS_Version=8.0'").connect()

The error message for above is:

DBAPIError: (Error) ('08001', '[08001] [unixODBC][FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnectW)') None None

Can someone please point me in the right direction?  Is there a way I can simply tell sqlalchemy to pass a specific connect string through to pyodbc?

Please Note: I want to keep this DSN-less.

Body:
I'm still interested in a way to do this in one line within the sqlalchemy create_engine statement, but I found the following workaround detailed here:

import pyodbc, sqlalchemy

def connect():
    pyodbc.connect('DRIVER={FreeTDS};Server=my.db.server;Database=mydb;UID=myuser;PWD=mypwd;TDS_Version=8.0;Port=1433;')

sqlalchemy.create_engine('mssql://', creator=connect)

UPDATE: Addresses a concern I raised in my own comment about not being able to pass arguments to the connect string.  The following is a general solution if you need to dynamically connect to different databases at runtime.  I only pass the database name as a parameter, but additional parameters could easily be used as needed:

import pyodbc
import os

class Creator:
    def __init__(self, db_name='MyDB'):
        """Initialization procedure to receive the database name"""
        self.db_name = db_name

    def __call__(self):
        """Defines a custom creator to be passed to sqlalchemy.create_engine
           http://stackoverflow.com/questions/111234/what-is-a-callable-in-python#111255"""
        if os.name == 'posix':
            return pyodbc.connect('DRIVER={FreeTDS};'
                                  'Server=my.db.server;'
                                  'Database=%s;'
                                  'UID=myuser;'
                                  'PWD=mypassword;'
                                  'TDS_Version=8.0;'
                                  'Port=1433;' % self.db_name)
        elif os.name == 'nt':
            # use development environment
            return pyodbc.connect('DRIVER={SQL Server};'
                                  'Server=127.0.0.1;'
                                  'Database=%s_Dev;'
                                  'UID=user;'
                                  'PWD=;'
                                  'Trusted_Connection=Yes;'
                                  'Port=1433;' % self.db_name)

def en(db_name):
    """Returns a sql_alchemy engine"""
    return sqlalchemy.create_engine('mssql://', creator=Creator(db_name))


问:
PDFsharp Ximage does not contain a constructor that contains 1 argument
I am trying to write an XImage function that reads an image from a given URL and it looks like:

```<code>    public static XImage FromURI(string uri)
    {
        HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
        webRequest.AllowWriteStreamBuffering = true;
        WebResponse webResponse = webRequest.GetResponse();
        System.Drawing.Image image = System.Drawing.Image.FromStream(webResponse.GetResponseStream());
        webResponse.Close();
        PdfSharp.Drawing.XImage ximg = new PdfSharp.Drawing.XImage(image);
        return new PdfSharp.Drawing.XImage(image);
    }
</code>```

but I am getting an error on the line

```<code>        return new PdfSharp.Drawing.XImage(image);
</code>```

It says:

```<code>XImage does not contain a constructor that contains 1 argument.
</code>```

When I look at the XImage.cs file, it seems like it has a constructor that has 1 argument.

```<code>namespace PdfSharp.Drawing
{
    //
    // Summary:
    //     Defines an object used to draw image files (bmp, png, jpeg, gif) and PDF forms.
    //     An abstract base class that provides functionality for the Bitmap and Metafile
    //     descended classes.
    public class XImage : IDisposable
    {
        //
        // Summary:
        //     Initializes a new instance of the PdfSharp.Drawing.XImage class.
        protected XImage();

        //
        // Summary:
        //     Gets the vertical resolution of the image.
        public virtual double VerticalResolution { get; }
        //
        // Summary:
        //     Gets the horizontal resolution of the image.
        public virtual double HorizontalResolution { get; }
        //
        // Summary:
        //     Gets the size in point of the image.
        public virtual XSize Size { get; }
        //
        // Summary:
        //     Gets the height of the image in pixels.
        public virtual int PixelHeight { get; }
        //
        // Summary:
        //     Gets the width of the image in pixels.
        public virtual int PixelWidth { get; }
        //
        // Summary:
        //     Gets the height of the image in point.
        public virtual double PointHeight { get; }
        //
        // Summary:
        //     Gets the width of the image in point.
        public virtual double PointWidth { get; }
        //
        // Summary:
        //     Gets the height of the image.
        [Obsolete("Use either PixelHeight or PointHeight. Temporarily obsolete because of rearrangements for WPF. Currently same as PixelHeight, but will become PointHeight in future releases of PDFsharp.")]
        public virtual double Height { get; }
        //
        // Summary:
        //     Gets the width of the image.
        [Obsolete("Use either PixelWidth or PointWidth. Temporarily obsolete because of rearrangements for WPF. Currently same as PixelWidth, but will become PointWidth in future releases of PDFsharp.")]
        public virtual double Width { get; }
        //
        // Summary:
        //     Gets or sets a flag indicating whether image interpolation is to be performed.
        public virtual bool Interpolate { get; set; }
        //
        // Summary:
        //     Gets the format of the image.
        public XImageFormat Format { get; }

        //
        // Summary:
        //     Tests if a file exist. Supports PDF files with page number suffix.
        //
        // Parameters:
        //   path:
        //     The path to a BMP, PNG, GIF, JPEG, TIFF, or PDF file.
        public static bool ExistsFile(string path);
        //
        // Summary:
        //     Creates an image from the specified file.
        //
        // Parameters:
        //   path:
        //     The path to a BMP, PNG, GIF, JPEG, TIFF, or PDF file.
        public static XImage FromFile(string path);
        //
        // Summary:
        //     Conversion from Image to XImage.
        public static XImage FromGdiPlusImage(Image image);
        //
        // Summary:
        //     Under construction
        public void Dispose();
        //
        // Summary:
        //     Disposes underlying GDI+ object.
        protected virtual void Dispose(bool disposing);

        //
        // Summary:
        //     Implicit conversion from Image to XImage.
        public static implicit operator XImage(Image image);
    }
}
</code>```

And even if I try to fix this file, it cannot be fixed because it has a [from metadata] label.

答:
The last line in the class is an implicit operator, not a constructor. This will convert the Image to XImage imlicitly i.e. without any data loss. You cannot create XImage from Image as you have done. You need to do it like:

```<code> XImage xImage = new PdfSharp.Drawing.XImage();
 xImage = image;
 return xImage;
</code>```

You can read about implice https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/implicit

Body:
I am trying to write an XImage function that reads an image from a given URL and it looks like:

    public static XImage FromURI(string uri)
    {
        HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
        webRequest.AllowWriteStreamBuffering = true;
        WebResponse webResponse = webRequest.GetResponse();
        System.Drawing.Image image = System.Drawing.Image.FromStream(webResponse.GetResponseStream());
        webResponse.Close();
        PdfSharp.Drawing.XImage ximg = new PdfSharp.Drawing.XImage(image);
        return new PdfSharp.Drawing.XImage(image);
    }

but I am getting an error on the line

        return new PdfSharp.Drawing.XImage(image);

It says:

XImage does not contain a constructor that contains 1 argument.

When I look at the XImage.cs file, it seems like it has a constructor that has 1 argument.

namespace PdfSharp.Drawing
{
    //
    // Summary:
    //     Defines an object used to draw image files (bmp, png, jpeg, gif) and PDF forms.
    //     An abstract base class that provides functionality for the Bitmap and Metafile
    //     descended classes.
    public class XImage : IDisposable
    {
        //
        // Summary:
        //     Initializes a new instance of the PdfSharp.Drawing.XImage class.
        protected XImage();

        //
        // Summary:
        //     Gets the vertical resolution of the image.
        public virtual double VerticalResolution { get; }
        //
        // Summary:
        //     Gets the horizontal resolution of the image.
        public virtual double HorizontalResolution { get; }
        //
        // Summary:
        //     Gets the size in point of the image.
        public virtual XSize Size { get; }
        //
        // Summary:
        //     Gets the height of the image in pixels.
        public virtual int PixelHeight { get; }
        //
        // Summary:
        //     Gets the width of the image in pixels.
        public virtual int PixelWidth { get; }
        //
        // Summary:
        //     Gets the height of the image in point.
        public virtual double PointHeight { get; }
        //
        // Summary:
        //     Gets the width of the image in point.
        public virtual double PointWidth { get; }
        //
        // Summary:
        //     Gets the height of the image.
        [Obsolete("Use either PixelHeight or PointHeight. Temporarily obsolete because of rearrangements for WPF. Currently same as PixelHeight, but will become PointHeight in future releases of PDFsharp.")]
        public virtual double Height { get; }
        //
        // Summary:
        //     Gets the width of the image.
        [Obsolete("Use either PixelWidth or PointWidth. Temporarily obsolete because of rearrangements for WPF. Currently same as PixelWidth, but will become PointWidth in future releases of PDFsharp.")]
        public virtual double Width { get; }
        //
        // Summary:
        //     Gets or sets a flag indicating whether image interpolation is to be performed.
        public virtual bool Interpolate { get; set; }
        //
        // Summary:
        //     Gets the format of the image.
        public XImageFormat Format { get; }

        //
        // Summary:
        //     Tests if a file exist. Supports PDF files with page number suffix.
        //
        // Parameters:
        //   path:
        //     The path to a BMP, PNG, GIF, JPEG, TIFF, or PDF file.
        public static bool ExistsFile(string path);
        //
        // Summary:
        //     Creates an image from the specified file.
        //
        // Parameters:
        //   path:
        //     The path to a BMP, PNG, GIF, JPEG, TIFF, or PDF file.
        public static XImage FromFile(string path);
        //
        // Summary:
        //     Conversion from Image to XImage.
        public static XImage FromGdiPlusImage(Image image);
        //
        // Summary:
        //     Under construction
        public void Dispose();
        //
        // Summary:
        //     Disposes underlying GDI+ object.
        protected virtual void Dispose(bool disposing);

        //
        // Summary:
        //     Implicit conversion from Image to XImage.
        public static implicit operator XImage(Image image);
    }
}

And even if I try to fix this file, it cannot be fixed because it has a [from metadata] label.

Body:
The last line in the class is an implicit operator, not a constructor. This will convert the Image to XImage imlicitly i.e. without any data loss. You cannot create XImage from Image as you have done. You need to do it like:

 XImage xImage = new PdfSharp.Drawing.XImage();
 xImage = image;
 return xImage;

You can read about implice https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/implicit


问:
Can I import and bind python-2.7's function to another function in python-3.x?
Some python-2.7 and python-3.x functions have the same name, but perform differently. Can I import use a py2.7 function in python-3.x one, by changing its name?

The motivating example is python-2.7's "print", i.e. print "TEXT" which does not use without parenthesis, compared to print("TEXT") in python 3. Can I keep the python 2 "print" by binding it to something like pr?

(By the way, the issue for me is typing and escaping the brackets. The keys ( and ) are harder to press than a space bar. Also, because my IDE puts them in automatically, I then need to move my cursor out of it.)

Note: I asked this previously, yet has been wrongly marked as a duplicate.
   Again, to be clear, I'm specifically asking if I can bind a python 2 function to a new name in order to use its functionality in python-3.x.

Can I bind python-2.7's `print` in python-3.x, allowing me to use `print` without parenthesis in python-3.x?

I do not know how to contact moderators via internal message or correct this wrongful flag.

答:
The real solution is to configure your IDE, rather than try and hack your way around those configuration problems.

That said, the Python 2 print statement with a space and no parenthesis does not exist in Python 3. While you can find ways to use the function from Python 2, the syntax cannot be used.


问:
How to convert the results from a query in to a JSON in oracle 12c?
Trying to update a new column with JSON,
i need to convert the selected data in to JSON first.

Here is my code (updated from comment):

```<code>SELECT a.col1 a.col2 b.col3 b.col4
from table AS JSON
</code>```

and I want my output to look like:

[{"col1": "value1", "col2": 2}, {"col3": "value3", "col4": "value4"}]

答:
You might want to look at APEX_JSON which comes with APEX. It is designed to backfill JSON functionality in older version of the database.

https://docs.oracle.com/cd/E59726_01/doc.50/e39149/apex_json.htm#AEAPI29635

Body:
Trying to update a new column with JSON,
i need to convert the selected data in to JSON first.

Here is my code (updated from comment):

SELECT a.col1 a.col2 b.col3 b.col4
from table AS JSON

and I want my output to look like:

[{"col1": "value1", "col2": 2}, {"col3": "value3", "col4": "value4"}]


问:
Method Chaining override variables
I have implemented a method chaining of database. My problem is that when I call Database class it overrides the variable with a new one. How can I preserve my variable. This is my code.

When I use this code:

```<code>Database::('table')
           ->set(['name', 'test'])
           ->select([
             Database::('table2')
                ->set(['name', 'test2')])
           ]);
</code>```

It overrides the $set variable used on Database::('table')->set and overrides with the new Database::('table2')->set variables.

Database Class:

```<code>namespace VendorName;

class Database
{
    private static $reserved_words = [
        'NOW()', 'IS NOT NULL', 'IS NULL',
    ];

    private static $connection = null;
    private static $table = '';
    private static $join = '';
    private static $values = '';
    private static $set = '';
    private static $where = '';
    private static $show = null;
    private static $select = null;
    private static $order_by = '';
    private static $params = [];

    /**
     * Call the database table to be used.
     *
     * @param string $table
     */
    public static function table($table)
    {
        self::$table .= $table;

        return new static;
    }

    public static function set($set)
    {
        self::$set .= ' SET';

        $index = 0;

        foreach ($set as $value) {
            if ($index++ > 0) {
                self::$set .= ', ';
            }

            if (in_array($value[1], self::$reserved_words)) {
                self::$set .= " {$value[0]} = {$value[1]}";
            } else {
                self::$set .= " {$value[0]} = ?";
            }
        }

        if (self::checkColumn('updated_at') && self::checkColumn('updated_by')) {
            self::$set .= ', updated_at = NOW(), updated_by = ' . Authentication::getAuthenticatedUser();
        }

        self::$params = array_merge(self::$params, $set);

        return new static;
    }

    /**
     * Create a WHERE query based on given parameters.
     *
     * @param array $where
     */
    public static function where($where)
    {
        self::$where .= ' WHERE';

        $index = 0;

        foreach ($where as $value) {
            if ($index++ > 0) {
                self::$where .= ' AND';
            }

            if (in_array($value[1], self::$reserved_words)) {
                self::$where .= " {$value[0]} {$value[1]}";
            } else {
                self::$where .= " {$value[0]} {$value[1]} ?";
            }
        }

        self::$params = array_merge(self::$params, $where);

        return new static;
    }

    /**
     * select data from the database.
     *
     * @param array $columns
     */
    public static function select($columns = ['*'])
    {
        self::$select = self::$connection->prepare('SELECT ' . implode(',', $columns) . ' FROM ' . self::$table . self::$join . self::$where . self::$order_by . self::$show);

        $index = 1;

        foreach (self::$params as $key => $value) {
            if (!in_array($value[count($value) - 1], self::$reserved_words)) {
                self::$select->bindValue($index++, $value[count($value) - 1]);
            }
        }

        //echo 'SELECT ' . implode(',', $columns) . ' FROM ' . self::$table . self::$join . self::$where . self::$show;

        self::$select->execute();

        return new static;
    }

    /**
     * fetch data from the database.
     *
     * @return array
     */
    public static function fetch()
    {
        $result = self::$select->fetch();

        self::clean();

        return $result;
    }

    /**
     * fetch data as associative array from the database.
     *
     * @return array
     */
    public static function fetchAll()
    {
        $result = self::$select->fetchAll(\PDO::FETCH_ASSOC);

        self::clean();

        return $result;
    }
}
</code>```

答:
It looks like you're trying to implement a Singleton pattern design. In this design, the class is limited to having only one instantiation, which is controlled by the class:</p>

```<code><?php

class Database {
    static private $singleton;
    private $data; // Some other data members...

    static public function getInstance() {
        if (!isset(self::$singleton)) {
            self::$singleton = new self; // works for derived classes also
        }

        return self::$singleton;
    }

    private function __construct() {
        // Do some useful initialization...
    }

    public function chainedOperation($param) {
        // Do some useful database operation...
        echo "I did something useful with '$param'." . PHP_EOL;

        return $this;
    }
}

Database::getInstance()->chainedOperation('apple')
                       ->chainedOperation('pear')
                       ->chainedOperation('php');

// I cannot create a Database instance conventionally.
// error: Call to private Database::__construct() from invalid context
// $db = new Database;
</code>```

Title: Method Chaining override variables

Body:
I have implemented a method chaining of database. My problem is that when I call Database class it overrides the variable with a new one. How can I preserve my variable. This is my code.

When I use this code:

Database::('table')
           ->set(['name', 'test'])
           ->select([
             Database::('table2')
                ->set(['name', 'test2')])
           ]);

It overrides the $set variable used on Database::('table')->set and overrides with the new Database::('table2')->set variables.

Database Class:

namespace VendorName;

class Database
{
    private static $reserved_words = [
        'NOW()', 'IS NOT NULL', 'IS NULL',
    ];

    private static $connection = null;
    private static $table = '';
    private static $join = '';
    private static $values = '';
    private static $set = '';
    private static $where = '';
    private static $show = null;
    private static $select = null;
    private static $order_by = '';
    private static $params = [];

    /**
     * Call the database table to be used.
     *
     * @param string $table
     */
    public static function table($table)
    {
        self::$table .= $table;

        return new static;
    }

    public static function set($set)
    {
        self::$set .= ' SET';

        $index = 0;

        foreach ($set as $value) {
            if ($index++ > 0) {
                self::$set .= ', ';
            }

            if (in_array($value[1], self::$reserved_words)) {
                self::$set .= " {$value[0]} = {$value[1]}";
            } else {
                self::$set .= " {$value[0]} = ?";
            }
        }

        if (self::checkColumn('updated_at') && self::checkColumn('updated_by')) {
            self::$set .= ', updated_at = NOW(), updated_by = ' . Authentication::getAuthenticatedUser();
        }

        self::$params = array_merge(self::$params, $set);

        return new static;
    }

    /**
     * Create a WHERE query based on given parameters.
     *
     * @param array $where
     */
    public static function where($where)
    {
        self::$where .= ' WHERE';

        $index = 0;

        foreach ($where as $value) {
            if ($index++ > 0) {
                self::$where .= ' AND';
            }

            if (in_array($value[1], self::$reserved_words)) {
                self::$where .= " {$value[0]} {$value[1]}";
            } else {
                self::$where .= " {$value[0]} {$value[1]} ?";
            }
        }

        self::$params = array_merge(self::$params, $where);

        return new static;
    }

    /**
     * select data from the database.
     *
     * @param array $columns
     */
    public static function select($columns = ['*'])
    {
        self::$select = self::$connection->prepare('SELECT ' . implode(',', $columns) . ' FROM ' . self::$table . self::$join . self::$where . self::$order_by . self::$show);

        $index = 1;

        foreach (self::$params as $key => $value) {
            if (!in_array($value[count($value) - 1], self::$reserved_words)) {
                self::$select->bindValue($index++, $value[count($value) - 1]);
            }
        }

        //echo 'SELECT ' . implode(',', $columns) . ' FROM ' . self::$table . self::$join . self::$where . self::$show;

        self::$select->execute();

        return new static;
    }

    /**
     * fetch data from the database.
     *
     * @return array
     */
    public static function fetch()
    {
        $result = self::$select->fetch();

        self::clean();

        return $result;
    }

    /**
     * fetch data as associative array from the database.
     *
     * @return array
     */
    public static function fetchAll()
    {
        $result = self::$select->fetchAll(\PDO::FETCH_ASSOC);

        self::clean();

        return $result;
    }
}

Body:
It looks like you're trying to implement a Singleton pattern design. In this design, the class is limited to having only one instantiation, which is controlled by the class:

<?php

class Database {
    static private $singleton;
    private $data; // Some other data members...

    static public function getInstance() {
        if (!isset(self::$singleton)) {
            self::$singleton = new self; // works for derived classes also
        }

        return self::$singleton;
    }

    private function __construct() {
        // Do some useful initialization...
    }

    public function chainedOperation($param) {
        // Do some useful database operation...
        echo "I did something useful with '$param'." . PHP_EOL;

        return $this;
    }
}

Database::getInstance()->chainedOperation('apple')
                       ->chainedOperation('pear')
                       ->chainedOperation('php');

// I cannot create a Database instance conventionally.
// error: Call to private Database::__construct() from invalid context
// $db = new Database;


问:
Find enclosed points of 2D polygon
I am building a game where the player moves 1 point a time, and leaves a path behind them. They can not cross their own path, and when the path is completed, I need to capture all enclosed points. I don't have a ton of math experience to identify what algorithms I need to look at, but I imagine I need to break the shape in to sub-rectangles, and then find the contained points in each sub-rectangle.

I was pointed towards the convex hull algorithm, and after looking at it for some time, it seems it just finds the convex perimeter of a given group of points. So that won't work.

I haven't found any algorithms for solving any problem, so if I'm looking for direction on algorithms to explore or perhaps one that could solve the problem directly.

As the player can only move up / down / left / right and no diagonals, all vertices of the polygon(?) will always be right angles.

Example Plane:

```<code>   0   1   2   3   4
0 [x] [x] [x] [ ] [ ]

1 [x] [o] [x] [ ] [ ]

2 [x] [o] [x] [x] [x]

3 [x] [o] [o] [o] [x]

4 [x] [x] [x] [x] [x]
</code>```

Stored Points: (marked as 'x' on example plane)

```<code>[
  [0,0],
  [0,1],
  [0,2],
  [1,2],
  [2,2],
  [2,3],
  [2,4],
  [3,4],
  [4,4],
  [4,3],
  [4,2],
  [4,1],
  [4,0],
  [3,0],
  [2,0],
  [1,0]
]
</code>```

Objective Points: (marked as 'o' on example plane)

```<code>[
  [1,1],
  [2,1],
  [3,1],
  [3,2],
  [3,3],
]
</code>```

Other example planes:

```<code>   0   1   2   3   4
0 [ ] [x] [x] [x] [ ]

1 [ ] [x] [o] [x] [ ]

2 [x] [x] [o] [x] [x]

3 [x] [o] [o] [o] [x]

4 [x] [x] [x] [x] [x]

   0   1   2   3   4
0 [x] [x] [x] [ ] [ ]

1 [x] [o] [x] [ ] [ ]

2 [x] [x] [x] [x] [x]

3 [ ] [x] [o] [o] [x]

4 [ ] [x] [x] [x] [x]
</code>```

答:
I suggest the Even-Odd ray casting algorithm.

First determine the highest and lowest X & Y in the user's points.

For each Y, start scanning from minimumX-1 to maximumX+1.

Count how many times you encounter a user point.

Note: this has some issues if the user draws horizontal lines, read the lit for more info.

Title: Find enclosed points of 2D polygon

Body:
I am building a game where the player moves 1 point a time, and leaves a path behind them. They can not cross their own path, and when the path is completed, I need to capture all enclosed points. I don't have a ton of math experience to identify what algorithms I need to look at, but I imagine I need to break the shape in to sub-rectangles, and then find the contained points in each sub-rectangle.

I was pointed towards the convex hull algorithm, and after looking at it for some time, it seems it just finds the convex perimeter of a given group of points. So that won't work.

I haven't found any algorithms for solving any problem, so if I'm looking for direction on algorithms to explore or perhaps one that could solve the problem directly.

As the player can only move up / down / left / right and no diagonals, all vertices of the polygon(?) will always be right angles.

Example Plane:

   0   1   2   3   4
0 [x] [x] [x] [ ] [ ]

1 [x] [o] [x] [ ] [ ]

2 [x] [o] [x] [x] [x]

3 [x] [o] [o] [o] [x]

4 [x] [x] [x] [x] [x]

Stored Points: (marked as 'x' on example plane)

[
  [0,0],
  [0,1],
  [0,2],
  [1,2],
  [2,2],
  [2,3],
  [2,4],
  [3,4],
  [4,4],
  [4,3],
  [4,2],
  [4,1],
  [4,0],
  [3,0],
  [2,0],
  [1,0]
]

Objective Points: (marked as 'o' on example plane)

[
  [1,1],
  [2,1],
  [3,1],
  [3,2],
  [3,3],
]

Other example planes:

   0   1   2   3   4
0 [ ] [x] [x] [x] [ ]

1 [ ] [x] [o] [x] [ ]

2 [x] [x] [o] [x] [x]

3 [x] [o] [o] [o] [x]

4 [x] [x] [x] [x] [x]

   0   1   2   3   4
0 [x] [x] [x] [ ] [ ]

1 [x] [o] [x] [ ] [ ]

2 [x] [x] [x] [x] [x]

3 [ ] [x] [o] [o] [x]

4 [ ] [x] [x] [x] [x]


问:
Kubernetes client for Go - ERRORS only encoded map or array can be decoded into a struct
I am trying to update the existing deployments in Openshift using Kubernetes Client for Go. I am using the following JSON to update the replicas to 3:

JSON:

```<code>{
  "kind": "Deployment",
  "spec": {
    "template": {
      "spec": {
        "containers": {
          "image": "docker.fmr.com\/fmr-pr000105\/testcontainer:1.0.0",
          "name": "testcontainer",
          "resources": {
            "requests": {
              "cpu": "50m"
            },
            "limits": {
              "cpu": "50m",
              "memory": "50M"
            }
          },
          "ports": {
            "protocol": "TCP",
            "name": "test-con-http",
            "containerPort": 22
          }
        }
      },
      "metadata": {
        "labels": {
          "app": "testcontainer"
        }
      }
    },
    "replicas": 3
  },
  "apiVersion": "extensions\/v1beta1",
  "metadata": {
    "name": "testcontainer"
  }
}
</code>```

But keep on getting the error:

```<code>only encoded map or array can be decoded into a struct
</code>```

I am using the following code :

```<code>import (
"fmt"
"flag"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/kubernetes"
apiv1 "k8s.io/client-go/pkg/api/v1"

"k8s.io/client-go/pkg/api"
"k8s.io/client-go/pkg/apis/extensions"
"k8s.io/client-go/pkg/apis/extensions/v1beta1"

"bufio"
"os"

)

func main() {
    var jsonBody []byte
    jsonBody = rteMockedUp.GetJsonBody()
    d := api.Codecs.UniversalDecoder()
    obj, _, err := d.Decode(jsonBody, nil, nil)
    if err != nil {
        log.Fatalf("could not decode json: %s\n%s", jsonBody, err)
    }
    src := obj.(*extensions.Deployment)
    dst := &v1beta1.Deployment{}
    err = api.Scheme.Convert(src,dst,0)
    if err != nil {
        log.Fatalf("failed to convert: %s", err)
    }
    updateStatus, err := deploymentsClient.Update(dst)
    if err != nil {
        log.Fatalf("Update failed %s", err)
    }
}
</code>```

An error is thrown over here:

```<code>obj, _, err := d.Decode(jsonBody, nil, nil)
</code>```

Is there a problem with my JSON?

答: Normally when this happens it means there is something wrong with the definition. In your case the containers should be an array and not an object.

Body:
I am trying to update the existing deployments in Openshift using Kubernetes Client for Go. I am using the following JSON to update the replicas to 3:

JSON:

{
  "kind": "Deployment",
  "spec": {
    "template": {
      "spec": {
        "containers": {
          "image": "docker.fmr.com\/fmr-pr000105\/testcontainer:1.0.0",
          "name": "testcontainer",
          "resources": {
            "requests": {
              "cpu": "50m"
            },
            "limits": {
              "cpu": "50m",
              "memory": "50M"
            }
          },
          "ports": {
            "protocol": "TCP",
            "name": "test-con-http",
            "containerPort": 22
          }
        }
      },
      "metadata": {
        "labels": {
          "app": "testcontainer"
        }
      }
    },
    "replicas": 3
  },
  "apiVersion": "extensions\/v1beta1",
  "metadata": {
    "name": "testcontainer"
  }
}

But keep on getting the error:

only encoded map or array can be decoded into a struct

I am using the following code :

import (
"fmt"
"flag"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/kubernetes"
apiv1 "k8s.io/client-go/pkg/api/v1"

"k8s.io/client-go/pkg/api"
"k8s.io/client-go/pkg/apis/extensions"
"k8s.io/client-go/pkg/apis/extensions/v1beta1"

"bufio"
"os"

)

func main() {
    var jsonBody []byte
    jsonBody = rteMockedUp.GetJsonBody()
    d := api.Codecs.UniversalDecoder()
    obj, _, err := d.Decode(jsonBody, nil, nil)
    if err != nil {
        log.Fatalf("could not decode json: %s\n%s", jsonBody, err)
    }
    src := obj.(*extensions.Deployment)
    dst := &v1beta1.Deployment{}
    err = api.Scheme.Convert(src,dst,0)
    if err != nil {
        log.Fatalf("failed to convert: %s", err)
    }
    updateStatus, err := deploymentsClient.Update(dst)
    if err != nil {
        log.Fatalf("Update failed %s", err)
    }
}

An error is thrown over here:

obj, _, err := d.Decode(jsonBody, nil, nil)

Is there a problem with my JSON?


答:
For your first problem - you need to define list_display in your PostAdmin, like that:

```<code>class PostAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("title",)}
    exclude = ('author',)
    list_display = ('title', 'pub_date')
</code>```

As for your second problem - please stick to the 'One post, one problem' rule; hint - ForeignKey means only one FileAttachment can be related to your Post.

Title: Modifying django object model for better admin CRUD management

Body:
I am writing a blog app using django 1.10

This is a snippet of my object model:

model.py

class Attachment(models.Model):
    title = models.CharField(max_length=50)
    image = models.ImageField(upload_to='attachments')

class FileAttachments(models.Model):
    title = models.CharField(max_length=50)
    attachments = models.ManyToManyField(Attachment)

class Post(models.Model):
    title = models.CharField(max_length=200)
    text = models.CharField(max_length=2000)
    file_attachments = models.ForeignKey(FileAttachments, blank=True, null=True)
    slug = models.SlugField(max_length=40, default='', unique=True)
    author = models.ForeignKey(User, default=1)
    pub_date = models.DateTimeField(blank=True, null=True)

    def get_absolute_url(self):
        return "/blog/%s/%s/%s/%s/" % (self.pub_date.year, self.pub_date.month, self.pub_date.day, self.slug)

    def __unicode__(self):
        return self.title

    class Meta:
        verbose_name = "Blog Post"
        verbose_name_plural = "Blog Posts"
        ordering = ["-create_date"]

        permissions = (
            ( "create", "Create Post" ),
            ( "modify", "Modify Post" ),
            ( "delete", "Delete Post" ),
        )

(simplified) admin.py:

class PostAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("title",)}
    exclude = ('author',)

    def save_model(self, request, obj, form, change):
        obj.author = request.user
        obj.save()

# Register your models here.
admin.site.register(Post, PostAdmin)

when I try to access the Post object via the admin page - in the list view, I only see 'Post object' - whereas I want to see the title of the post (and possibly, a few other attributes of the Post object) - how do I modify the admin view to achieve this?

Body:
For your first problem - you need to define list_display in your PostAdmin, like that:

class PostAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("title",)}
    exclude = ('author',)
    list_display = ('title', 'pub_date')

As for your second problem - please stick to the 'One post, one problem' rule; hint - ForeignKey means only one FileAttachment can be related to your Post.