问:
Dynamically populating a static variable in PHP
I have two static values: "type" and "typeID".  Type is human readable and constant, and typeID needs to be looked up from the database, based on the value of type.  I need the lookup to happen once, when the class definition is first loaded

To illustrate, here is some code that doesn't work because you can't call functions in the declaration space.

```<code>MyClass extends BaseClass {
  protected static $type = "communities";
  protected static $typeID = MyClass::lookupTypeID(self::$type);
}
</code>```

Is there a magic method that is called exactly once when the class definition is loaded?  If there is something obvious I'm missing it.

答:
shamelessly pulled from the php manual's static keyword comments:</p>

```<code>Because php does not have a static constructor and you may want to initialize static class vars, there is one easy way, just call your own function directly after the class definition.

for example.

<?php
function Demonstration()
{
    return 'This is the result of demonstration()';
}

class MyStaticClass
{
    //public static $MyStaticVar = Demonstration(); //!!! FAILS: syntax error
    public static $MyStaticVar = null;

    public static function MyStaticInit()
    {
        //this is the static constructor
        //because in a function, everything is allowed, including initializing using other functions

        self::$MyStaticVar = Demonstration();
    }
} MyStaticClass::MyStaticInit(); //Call the static constructor

echo MyStaticClass::$MyStaticVar;
//This is the result of demonstration()
?>
</code>```

Body:
I have two static values: "type" and "typeID".  Type is human readable and constant, and typeID needs to be looked up from the database, based on the value of type.  I need the lookup to happen once, when the class definition is first loaded

To illustrate, here is some code that doesn't work because you can't call functions in the declaration space.

MyClass extends BaseClass {
  protected static $type = "communities";
  protected static $typeID = MyClass::lookupTypeID(self::$type);
}

Is there a magic method that is called exactly once when the class definition is loaded?  If there is something obvious I'm missing it.

Body:
shamelessly pulled from the php manual's static keyword comments:

Because php does not have a static constructor and you may want to initialize static class vars, there is one easy way, just call your own function directly after the class definition.

for example.

<?php
function Demonstration()
{
    return 'This is the result of demonstration()';
}

class MyStaticClass
{
    //public static $MyStaticVar = Demonstration(); //!!! FAILS: syntax error
    public static $MyStaticVar = null;

    public static function MyStaticInit()
    {
        //this is the static constructor
        //because in a function, everything is allowed, including initializing using other functions

        self::$MyStaticVar = Demonstration();
    }
} MyStaticClass::MyStaticInit(); //Call the static constructor

echo MyStaticClass::$MyStaticVar;
//This is the result of demonstration()
?>


来源: stackexchange

问:
No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered
I'm having this problem: No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered. In asp.net core 1.0, it seems that when the action try to render the view i have that exception.

I've searched a lot but I dont found a solution to this, if somebody can help me to figure out what's happening and how can I fix it, i will appreciate it.

My code bellow:

My project.json file

```<code>{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"

    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final",
    "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
    "EntityFramework.Commands": "7.0.0-rc1-final"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}
</code>```

My Startup.cs file

```<code>using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OdeToFood.Services;

namespace OdeToFood
{
    public class Startup
    {
        public IConfiguration configuration { get; set; }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddScoped<IRestaurantData, InMemoryRestaurantData>();
            services.AddMvcCore();
            services.AddSingleton(provider => configuration);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //app.UseRuntimeInfoPage();

            app.UseFileServer();

            app.UseMvc(ConfigureRoutes);

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }

        private void ConfigureRoutes(IRouteBuilder routeBuilder)
        {
            routeBuilder.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}");
        }
    }
}
</code>```

答:
Right now i has same problem, I was using AddMcvCore like you. I found error self descriptive, as an assumption I added AddControllersWithViews service to ConfigureServices function and it fixed problem for me. (I still use AddMvcCore as well.)</p>

```<code>    public void ConfigureServices(IServiceCollection services)
    {
        //...
        services.AddControllers();
        services.AddControllersWithViews();
        services.AddMvcCore();
        //...
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm having this problem: No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered. In asp.net core 1.0, it seems that when the action try to render the view i have that exception.

I've searched a lot but I dont found a solution to this, if somebody can help me to figure out what's happening and how can I fix it, i will appreciate it.

My code bellow:

My project.json file

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"

    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final",
    "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
    "EntityFramework.Commands": "7.0.0-rc1-final"
  },

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dnxcore50",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

My Startup.cs file

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OdeToFood.Services;

namespace OdeToFood
{
    public class Startup
    {
        public IConfiguration configuration { get; set; }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddScoped<IRestaurantData, InMemoryRestaurantData>();
            services.AddMvcCore();
            services.AddSingleton(provider => configuration);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //app.UseRuntimeInfoPage();

            app.UseFileServer();

            app.UseMvc(ConfigureRoutes);

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }

        private void ConfigureRoutes(IRouteBuilder routeBuilder)
        {
            routeBuilder.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}");
        }
    }
}

Body:
Right now i has same problem, I was using AddMcvCore like you. I found error self descriptive, as an assumption I added AddControllersWithViews service to ConfigureServices function and it fixed problem for me. (I still use AddMvcCore as well.)

    public void ConfigureServices(IServiceCollection services)
    {
        //...
        services.AddControllers();
        services.AddControllersWithViews();
        services.AddMvcCore();
        //...
    }

ContentLicense: CC BY-SA 4.0


问:
'NoneType' object is not callable in Django App
I have made a product model in django. I'm able to insert products, but now i'hanving problems to get the products. When i list the products, i get all items. But when i try get only one, the restframework is giving me this error:

I'm trying to acessing the product by using this url http://localhost:4444/products/1

```<code>TypeError at /products/1
'NoneType' object is not callable
Request Method: GET
Request URL:    http://localhost:4444/products/1
Django Version: 2.2.8
Exception Type: TypeError
Exception Value:
'NoneType' object is not callable
Exception Location: C:\Users\vini\Documents\VirtualEnv\mystore\lib\site-packages\rest_framework\generics.py in get_serializer, line 110
Python Executable:  C:\Users\vini\Documents\VirtualEnv\mystore\Scripts\python.exe
Python Version: 3.8.0
Python Path:
['C:\\Users\\vini\\Documents\\GitHub\\mystore-backend',
 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\Scripts\\python38.zip',
 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\DLLs',
 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\lib',
 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\Scripts',
 'c:\\users\\vini\\appdata\\local\\programs\\python\\python38\\Lib',
 'c:\\users\\vini\\appdata\\local\\programs\\python\\python38\\DLLs',
 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore',
 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\lib\\site-packages']
Server time:    Sab, 15 Fev 2020 19:41:00 +0000
</code>```

Model:

class Product(UGCModel):

    class Meta:
        app_label = 'product'

    avatar = models.ForeignKey('image.Image',
                               related_name='product_image',
                               on_delete=models.CASCADE)
    # Variable to hide in store
    hide = models.BooleanField(default=False)
    # Value of product
    value = models.DecimalField(max_digits=6, decimal_places=2,
                                validators=[MinValueValidator(0)])
    # Name of the product
    title = models.CharField(max_length=150, null=False, blank=False)
    # Quantity of product in stock
    quantity = models.IntegerField(default=0, blank=False, null=False,
                                   validators=[MinValueValidator(0)])
    # Discount of the product
    discount = models.IntegerField(default=0,
                                   validators=[MaxValueValidator(100),
                                               MinValueValidator(0)])
    # description of the product
    resume = models.CharField(max_length=1000, blank=True)

    def __str__(self):
        return '(Product)%s' % self.uid

```

<p>Url: </p>

<pre class="lang-py prettyprint-override"><code>from django.urls import path

from . import views
import product.views as v

product_detail = v.ProductViewSet.as_view({'get': 'retrieve',
                                           'delete': 'destroy',
                                           'patch': 'partial_update'})

product_list = v.ProductViewSet.as_view({'post': 'create', 'get': 'list'})

urlpatterns = [
    path('products/<int:id>', product_detail),
    path('products', product_list),
]

</code>```

View:

from rest_framework import viewsets
from .models import Product
from .serializers import (ProductListSerializer, ProductCreateSerializer)
from rest_framework.response import Response
from rest_framework import status, generics

class ProductViewSet(viewsets.ModelViewSet):

    lookup_field = 'id'
    model = Product
    queryset = Product.objects.all()
    serializer_class = ProductListSerializer

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return ProductListSerializer
        elif self.request.method == 'POST':
            return ProductCreateSerializer
```

<p>serializers:</p>

<pre class="lang-py prettyprint-override"><code>from .models import Product
from rest_framework import serializers
import image.fields as f
import image.serializers as s

class ProductListSerializer(serializers.ModelSerializer):

    class Meta:
        model = Product
        fields = ['uid', 'title', 'avatar', 'value',
                  'quantity', 'discount', 'resume']

    avatar = s.ImageListSerializer()

class ProductCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = Product
        fields = ['uid', 'title', 'avatar', 'value', 'hide',
                  'quantity', 'discount', 'resume']

    avatar = f.ImageField()
</code>```

答: As @Vinicus Morais said you need to make the serializer_class = ProductListSerializer. that should fix the error.

Body:
I have made a product model in django. I'm able to insert products, but now i'hanving problems to get the products. When i list the products, i get all items. But when i try get only one, the restframework is giving me this error:

I'm trying to acessing the product by using this url http://localhost:4444/products/1

TypeError at /products/1
'NoneType' object is not callable
Request Method: GET
Request URL:    http://localhost:4444/products/1
Django Version: 2.2.8
Exception Type: TypeError
Exception Value:
'NoneType' object is not callable
Exception Location: C:\Users\vini\Documents\VirtualEnv\mystore\lib\site-packages\rest_framework\generics.py in get_serializer, line 110
Python Executable:  C:\Users\vini\Documents\VirtualEnv\mystore\Scripts\python.exe
Python Version: 3.8.0
Python Path:
['C:\\Users\\vini\\Documents\\GitHub\\mystore-backend',
 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\Scripts\\python38.zip',
 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\DLLs',
 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\lib',
 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\Scripts',
 'c:\\users\\vini\\appdata\\local\\programs\\python\\python38\\Lib',
 'c:\\users\\vini\\appdata\\local\\programs\\python\\python38\\DLLs',
 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore',
 'C:\\Users\\vini\\Documents\\VirtualEnv\\mystore\\lib\\site-packages']
Server time:    Sab, 15 Fev 2020 19:41:00 +0000

Model:

class Product(UGCModel):

    class Meta:
        app_label = 'product'

    avatar = models.ForeignKey('image.Image',
                               related_name='product_image',
                               on_delete=models.CASCADE)
    # Variable to hide in store
    hide = models.BooleanField(default=False)
    # Value of product
    value = models.DecimalField(max_digits=6, decimal_places=2,
                                validators=[MinValueValidator(0)])
    # Name of the product
    title = models.CharField(max_length=150, null=False, blank=False)
    # Quantity of product in stock
    quantity = models.IntegerField(default=0, blank=False, null=False,
                                   validators=[MinValueValidator(0)])
    # Discount of the product
    discount = models.IntegerField(default=0,
                                   validators=[MaxValueValidator(100),
                                               MinValueValidator(0)])
    # description of the product
    resume = models.CharField(max_length=1000, blank=True)

    def __str__(self):
        return '(Product)%s' % self.uid

Url:

from django.urls import path

from . import views
import product.views as v

product_detail = v.ProductViewSet.as_view({'get': 'retrieve',
                                           'delete': 'destroy',
                                           'patch': 'partial_update'})

product_list = v.ProductViewSet.as_view({'post': 'create', 'get': 'list'})

urlpatterns = [
    path('products/<int:id>', product_detail),
    path('products', product_list),
]

View:

from rest_framework import viewsets
from .models import Product
from .serializers import (ProductListSerializer, ProductCreateSerializer)
from rest_framework.response import Response
from rest_framework import status, generics

class ProductViewSet(viewsets.ModelViewSet):

    lookup_field = 'id'
    model = Product
    queryset = Product.objects.all()
    serializer_class = ProductListSerializer

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return ProductListSerializer
        elif self.request.method == 'POST':
            return ProductCreateSerializer

serializers:

from .models import Product
from rest_framework import serializers
import image.fields as f
import image.serializers as s

class ProductListSerializer(serializers.ModelSerializer):

    class Meta:
        model = Product
        fields = ['uid', 'title', 'avatar', 'value',
                  'quantity', 'discount', 'resume']

    avatar = s.ImageListSerializer()

class ProductCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = Product
        fields = ['uid', 'title', 'avatar', 'value', 'hide',
                  'quantity', 'discount', 'resume']

    avatar = f.ImageField()


问:
Asynchronous nodejs and promises in a loop
I have some problems understanding asyncronous nodejs in a loop and the associated scope I guess.

Basically, I want to extract different values and store it in a "template" object that I will implement each loop and store in an array of promises in order to use it when resolved.

It might seem (a lot) far fetched  for this code's actual goal but i struggle understanding why does the promise variable is only returning the last element each loop even if i pass the index value to the function and use it in then().

Code :

```<code>(async ()=>{

let tab = ["a","b","c","d"];
let data = { name:"Random Array", data:null, idx:null};
let promise = {};
let promisesArray = [];

for(let i = 0 ; i < tab.length; i++){
 promise = wait(3000).then(()=>{
   let d = data;
   d.data = tab[i];
   d.idx = i;
   d.success = true;
   console.log(d);
   return d;
   });

   promisesArray.push(promise);
}

let fullData = await Promise.all(promisesArray);
console.log(fullData);

})();

function wait(time){
 return new Promise((resolve,reject)=>{
   setTimeout(resolve,time)
 });
}
</code>```

Output :

```<code>[{ name: 'Random Array', data: 'd', idx: 3, success: true },
 { name: 'Random Array', data: 'd', idx: 3, success: true },
 { name: 'Random Array', data: 'd', idx: 3, success: true },
 { name: 'Random Array', data: 'd', idx: 3, success: true }]
</code>```

Intended Output :

```<code>[{ name: 'Random Array', data: 'a', idx: 0, success: true },
 { name: 'Random Array', data: 'b', idx: 1, success: true },
 { name: 'Random Array', data: 'c', idx: 2, success: true },
 { name: 'Random Array', data: 'd', idx: 3, success: true }]
</code>```

Sorry if this is some trivial knowledge but I didn't find anything about it so far.
Thanks in advance for your time!

答:
The thing is, you're using the same data object all the time, so that's why you got 4 exactly same objects in your array, it's all due to this line in your loop:

```<code>let d = data;
</code>```

You just assigning data to d, it doesn't make a copy of data, but now they both have a reference to the same data object. If you just copied value of data into d you would be fine:

```<code>const d = { ...data }

// or

const d = { name:"Random Array", data:null, idx:null}

// or

const getData = () => ({ name:"Random Array", data:null, idx:null})
const d = getData()
</code>```

Hope it helps <3

Body:
I have some problems understanding asyncronous nodejs in a loop and the associated scope I guess.

Basically, I want to extract different values and store it in a "template" object that I will implement each loop and store in an array of promises in order to use it when resolved.

It might seem (a lot) far fetched  for this code's actual goal but i struggle understanding why does the promise variable is only returning the last element each loop even if i pass the index value to the function and use it in then().

Code :

(async ()=>{

let tab = ["a","b","c","d"];
let data = { name:"Random Array", data:null, idx:null};
let promise = {};
let promisesArray = [];

for(let i = 0 ; i < tab.length; i++){
 promise = wait(3000).then(()=>{
   let d = data;
   d.data = tab[i];
   d.idx = i;
   d.success = true;
   console.log(d);
   return d;
   });

   promisesArray.push(promise);
}

let fullData = await Promise.all(promisesArray);
console.log(fullData);

})();

function wait(time){
 return new Promise((resolve,reject)=>{
   setTimeout(resolve,time)
 });
}

Output :

[{ name: 'Random Array', data: 'd', idx: 3, success: true },
 { name: 'Random Array', data: 'd', idx: 3, success: true },
 { name: 'Random Array', data: 'd', idx: 3, success: true },
 { name: 'Random Array', data: 'd', idx: 3, success: true }]

Intended Output :

[{ name: 'Random Array', data: 'a', idx: 0, success: true },
 { name: 'Random Array', data: 'b', idx: 1, success: true },
 { name: 'Random Array', data: 'c', idx: 2, success: true },
 { name: 'Random Array', data: 'd', idx: 3, success: true }]

Sorry if this is some trivial knowledge but I didn't find anything about it so far.
Thanks in advance for your time!

Body:
The thing is, you're using the same data object all the time, so that's why you got 4 exactly same objects in your array, it's all due to this line in your loop:

let d = data;

You just assigning data to d, it doesn't make a copy of data, but now they both have a reference to the same data object. If you just copied value of data into d you would be fine:

const d = { ...data }

// or

const d = { name:"Random Array", data:null, idx:null}

// or

const getData = () => ({ name:"Random Array", data:null, idx:null})
const d = getData()

Hope it helps <3


问:
Replacements for switch statement in Python?
I want to write a function in Python that returns different fixed values based on the value of an input index.

In other languages I would use a switch or case statement, but Python does not appear to have a switch statement.  What are the recommended Python solutions in this scenario?

答:
There's a pattern that I learned from Twisted Python code.

```<code>class SMTP:
    def lookupMethod(self, command):
        return getattr(self, 'do_' + command.upper(), None)
    def do_HELO(self, rest):
        return 'Howdy ' + rest
    def do_QUIT(self, rest):
        return 'Bye'

SMTP().lookupMethod('HELO')('foo.bar.com') # => 'Howdy foo.bar.com'
SMTP().lookupMethod('QUIT')('') # => 'Bye'
</code>```

You can use it any time you need to dispatch on a token and execute extended piece of code. In a state machine you would have state_ methods, and dispatch on self.state. This switch can be cleanly extended by inheriting from base class and defining your own do_ methods. Often times you won't even have do_ methods in the base class.

Edit: how exactly is that used

In case of SMTP you will receive HELO from the wire. The relevant code (from twisted/mail/smtp.py, modified for our case) looks like this

```<code>class SMTP:
    # ...

    def do_UNKNOWN(self, rest):
        raise NotImplementedError, 'received unknown command'

    def state_COMMAND(self, line):
        line = line.strip()
        parts = line.split(None, 1)
        if parts:
            method = self.lookupMethod(parts[0]) or self.do_UNKNOWN
            if len(parts) == 2:
                return method(parts[1])
            else:
                return method('')
        else:
            raise SyntaxError, 'bad syntax'

SMTP().state_COMMAND('   HELO   foo.bar.com  ') # => Howdy foo.bar.com
</code>```

You'll receive '  HELO   foo.bar.com ' (or you might get 'QUIT' or 'RCPT TO: foo'). This is tokenized into parts as ['HELO', 'foo.bar.com']. The actual method lookup name is taken from parts[0].

(The original method is also called state_COMMAND, because it uses the same pattern to implement a state machine, i.e. getattr(self, 'state_' + self.mode))

Body:
There's a pattern that I learned from Twisted Python code.

class SMTP:
    def lookupMethod(self, command):
        return getattr(self, 'do_' + command.upper(), None)
    def do_HELO(self, rest):
        return 'Howdy ' + rest
    def do_QUIT(self, rest):
        return 'Bye'

SMTP().lookupMethod('HELO')('foo.bar.com') # => 'Howdy foo.bar.com'
SMTP().lookupMethod('QUIT')('') # => 'Bye'

You can use it any time you need to dispatch on a token and execute extended piece of code. In a state machine you would have state_ methods, and dispatch on self.state. This switch can be cleanly extended by inheriting from base class and defining your own do_ methods. Often times you won't even have do_ methods in the base class.

Edit: how exactly is that used

In case of SMTP you will receive HELO from the wire. The relevant code (from twisted/mail/smtp.py, modified for our case) looks like this

class SMTP:
    # ...

    def do_UNKNOWN(self, rest):
        raise NotImplementedError, 'received unknown command'

    def state_COMMAND(self, line):
        line = line.strip()
        parts = line.split(None, 1)
        if parts:
            method = self.lookupMethod(parts[0]) or self.do_UNKNOWN
            if len(parts) == 2:
                return method(parts[1])
            else:
                return method('')
        else:
            raise SyntaxError, 'bad syntax'

SMTP().state_COMMAND('   HELO   foo.bar.com  ') # => Howdy foo.bar.com

You'll receive '  HELO   foo.bar.com ' (or you might get 'QUIT' or 'RCPT TO: foo'). This is tokenized into parts as ['HELO', 'foo.bar.com']. The actual method lookup name is taken from parts[0].

(The original method is also called state_COMMAND, because it uses the same pattern to implement a state machine, i.e. getattr(self, 'state_' + self.mode))

ContentLicense: CC BY-SA 2.5


问:
Array of Strings to an Array of Objects
Maybe there is a method that does this that I don't know about - I doubt it though - but I'm trying to convert an array of strings to an array of Objects. Here is the problem: I'm reading a file in from the command line. The file represents several classes of the following types each with their own data fields. Vehicle is the parent class of all who follow: Vehicle,Car,American Car, Foreign car, Truck, Bicycle.

I have no problem reading the file into a string array. However I need to create objects of all these types and store them in an array of type Vehicle[]. For example a portion of the file looks like this:

Vehicle

Kim Stanley Robinson

2344 court drive

(221)885-7777

stackoverflow@overflow.com

American Car

John Bunyon

1010 binary lane

(221)885-55643

bgt.com

convertable

made in detroit

 union plant

Where Class type is the first line followed by, Owner's Name, address, phone number, email address...Each type has fields particular to it. So a foreign car is not made in Detroit. Each of these fields appear on a separate line in the file. So what I've done is read the  entire file into a string array. However, I need to find my types in the array of strings,create objects of those types, and store them in a Vehicle array. My main problem is that each data field is on a separate line. How should I approach this problem?
This is java code by the way.

答:
I would use a Factory pattern that creates Adapters.  The factory would take the string (Vehicle, American Car) and the adapter would take the string array and current index.  The adapter would be responsible to knowing how many indices to read and return the concrete object (or an interface).

```<code>IAdapter adapter = AdapterFactory.Create( "American Car" );
Object concreteObject = adapter.Popluate( stringArray, currentIndex );
</code>```

Now, if you have control over how the data is stored, you might want to look into standard serialization, even JSON, to make processing easier.

OwnerDisplayName: BloodParrot

Title: Array of Strings to an Array of Objects

Body:
I would use a Factory pattern that creates Adapters.  The factory would take the string (Vehicle, American Car) and the adapter would take the string array and current index.  The adapter would be responsible to knowing how many indices to read and return the concrete object (or an interface).

IAdapter adapter = AdapterFactory.Create( "American Car" );
Object concreteObject = adapter.Popluate( stringArray, currentIndex );

Now, if you have control over how the data is stored, you might want to look into standard serialization, even JSON, to make processing easier.


问:
How does one get Browser (IE) toolbars in an HTA App?
I'm working on a web app that's embedded within an HTA.  Is it possible to enable browser toolbars so i can enable utilities like Development Toolbar, or IE8's built in Developer Tools?

I'm trying to do some firebug type things without using firebug or firebug lite and based on my googling it seems like it might not be possible!

Thank you!

答: You could use something like Appcelerator Titanium for Desktop which embeds a Webkit view and Webkit Inspector. It would also allow more HTML5 features to be used. </p>


问:
JQuery content editable div and text box on submit not sending POST
I have a website where you can edit and format text, then you can save it on to the server. I am using jquery to send the data to a PHP page where it will be saved. My site won't send the name of the file and the formatted text to PHP.

Here is my html code:

```<code><div id="editor" contenteditable="true">
    This is the editable text.
</div>

<input type="text" id="name" placeholder="File Name">
<input type="submit" id="save" value="Save">

<script>
    $(document).ready(function() {
        $("#save").on("click", function(event) {
            var formData = {text: $("#editor").html(), name: $("#name").val()};
            event.preventDefault();
            $.ajax({
                url: 'freewordsave.php',
                type:'POST',
                data: formData,
                success: function(msg)
                {
                    alert('Your file was saved!');
                }
            });
        });
    });
</script>
</code>```

Here is also my PHP code:

```<code>$name = $_POST['name'];
$text = $_POST['data'];
$file = fopen("./location/" . $name . ".html", "w") or die("<script> alert('Error'); </script>");
fwrite($file, $text);
fclose($file);
</code>```

My code won't even bring up the alert in javascript.

Thank you.

答:
I fixed my code after Simone Rossaini posted a comment.
I forget a } closing bracket at the end of formData.

Fixed JQuery Code.

```<code>$(document).ready(function() {
    $("#save").on("click", function(event) {
        var formData = {text: $("#editor").html(), name: $("#name").val()};
        event.preventDefault();
        $.ajax({
            url: 'freewordsave.php',
            type:'POST',
            data: formData,
            success: function(msg)
            {
                alert('Your file was saved!');
            }
        });
    });
});
</code>```

I know my PHP said $_POST['data'] but that was a mistake I made when I asked my question it wasn't actually like that in my PHP file.

Thank you

Body:
I have a website where you can edit and format text, then you can save it on to the server. I am using jquery to send the data to a PHP page where it will be saved. My site won't send the name of the file and the formatted text to PHP.

Here is my html code:

    This is the editable text.

<input type="text" id="name" placeholder="File Name">
<input type="submit" id="save" value="Save">

Here is also my PHP code:

$name = $_POST['name'];
$text = $_POST['data'];
$file = fopen("./location/" . $name . ".html", "w") or die("");
fwrite($file, $text);
fclose($file);

My code won't even bring up the alert in javascript.

Thank you.

Body:
I fixed my code after Simone Rossaini posted a comment.
I forget a } closing bracket at the end of formData.

Fixed JQuery Code.

$(document).ready(function() {
    $("#save").on("click", function(event) {
        var formData = {text: $("#editor").html(), name: $("#name").val()};
        event.preventDefault();
        $.ajax({
            url: 'freewordsave.php',
            type:'POST',
            data: formData,
            success: function(msg)
            {
                alert('Your file was saved!');
            }
        });
    });
});

I know my PHP said $_POST['data'] but that was a mistake I made when I asked my question it wasn't actually like that in my PHP file.

Thank you


问:
calculate average for group based on element value
I have a table with 2 columns: Model and Price

```<code>Model       Price
Pilot       30
Civic       20
Highlander  10
Corolla     40
Rav4        25
</code>```

I know that Pilot and Civic is Honda car while Highlander, Corolla, Rav4 is Toyota.
I want to calculate, say average price for Honda group (30+20)/2 and Toyota (10+40+25)/3.

Output table:

```<code>Mode    Average_price
Honda   25
Toyota  25
</code>```

My problem is that I am NOT allowed to create new table or new column in existing table.

Thus I think somewhere in the query I need to list all condition say

```<code>IF Model in ('Pilot','Civic') then Manufacturer='Honda' else if Model in ('Highlander','Corolla','Rav4') then Manufacturer='Toyota'
Then average by Manufacturer.
</code>```

Can anyone please help me to write a query?

Thank you,

Harry

答:
How about a common table expression?

```<code>;WITH hondaCTE AS (
    SELECT 'Honda' AS [make]
    ,   SUM(ct.Price) / COUNT(1) AS [avg_price]
    FROM car_table AS ct
    WHERE ct.Model IN ('pilot','civic')
)
, toyotaCTE AS (
    SELECT 'Toyota' AS [make]
    ,   SUM(ct.Price) / COUNT(1) AS [avg_price]
    FROM car_table AS ct
    WHERE ct.Model NOT IN ('pilot','civic') -- Exclude Honda models
)
-- Union results
SELECT * FROM hondaCTE
UNION
SELECT * FROM toyotaCTE
</code>```

Output:

```<code>make    avg_price
Honda   25
Toyota  25
</code>```

Body:
I have a table with 2 columns: Model and Price

Model       Price
Pilot       30
Civic       20
Highlander  10
Corolla     40
Rav4        25

I know that Pilot and Civic is Honda car while Highlander, Corolla, Rav4 is Toyota.
I want to calculate, say average price for Honda group (30+20)/2 and Toyota (10+40+25)/3.

Output table:

Mode    Average_price
Honda   25
Toyota  25

My problem is that I am NOT allowed to create new table or new column in existing table.

Thus I think somewhere in the query I need to list all condition say

IF Model in ('Pilot','Civic') then Manufacturer='Honda' else if Model in ('Highlander','Corolla','Rav4') then Manufacturer='Toyota'
Then average by Manufacturer.

Can anyone please help me to write a query?

Thank you,

Harry

Body:
How about a common table expression?

;WITH hondaCTE AS (
    SELECT 'Honda' AS [make]
    ,   SUM(ct.Price) / COUNT(1) AS [avg_price]
    FROM car_table AS ct
    WHERE ct.Model IN ('pilot','civic')
)
, toyotaCTE AS (
    SELECT 'Toyota' AS [make]
    ,   SUM(ct.Price) / COUNT(1) AS [avg_price]
    FROM car_table AS ct
    WHERE ct.Model NOT IN ('pilot','civic') -- Exclude Honda models
)
-- Union results
SELECT * FROM hondaCTE
UNION
SELECT * FROM toyotaCTE

Output:

make    avg_price
Honda   25
Toyota  25


问:
Static And Global Variables In Different Scopes
I'm a beginner programmer...Here I have a piece of code with two functions...one of them uses a global variable while the other one uses a local static variable...

So here is the code:

```<code>//Scope Rules
#include <iostream>
using namespace std;

int num {52};     //Global Variable - Declared outside any class or function

void globalExample();
void staticLocalExample();

void globalExample(){
    cout << "\nGlobal num in globalExample is: " << num << " - start" << endl;
    num *= 4;
    cout << "Global num in globalExample is: " << num << " - end" << endl;
}
void staticLocalExample(){
    static int num {5};      //local to staticLocalExample - retains it's value between calls
    cout << "\nLocal static num in staticLocalExample is: " << num << " - start" << endl;
    num += 20;
    cout << "Local static num in staticLocalExample is: " << num << " - end" << endl;
}

int main() {

    globalExample();
    globalExample();
    staticLocalExample();
    staticLocalExample();

    return 0;
}
</code>```

The reason I called these functions twice was for me to understand that the second time the function is called, changes will be stored to the variables so the results will be different.

What I don't understand is:

What's the difference between these two functions then?

What does the staticLocalExample function exactly do?(Because in comparison, they both have the same results)

Why and when do we use the keyword static?

Note1:I know the cause of changes is the assignments I have in both functions BUT... This is just an example and I don't quietly understand it

Note2:I checked the link you guys sent me and thank you so much for that...I understood the concepts behind it but still I couldn't find the answer to my third question :)

答:
I think I came to a conclusion...so please let me know if I'm wrong...

Global Varialble: You can change them and assign different numbers outside or inside of it's scope

Static Variable: You can only change it within it's scope not outside of it

So in conclusion lets modify this code a bit:

```<code>#include <iostream>
using namespace std;

int num {52};     //Global Variable - Declared outside any class or function

void globalExample();
void staticLocalExample(int x);

void globalExample(){
    cout << "\nGlobal num in globalExample is: " << num << " - start" << endl;
    num *= 4;
    cout << "Global num in globalExample is: " << num << " - end" << endl;
}
void staticLocalExample(int x){
    static int num {5};      //local to staticLocalExample - retains it's value between calls
    cout << "\nLocal static num in staticLocalExample is: " << num << " - start" << endl;
    num += 20;
    cout << "Local static num in staticLocalExample is: " << num << " - end" << endl;
}

int main() {

    globalExample();
    num = 20;
    globalExample();
    staticLocalExample(10);
    staticLocalExample(15);

    return 0;
}
</code>```

Output:

```<code>Global num in globalExample is: 52 - start
Global num in globalExample is: 208 - end

Global num in globalExample is: 20 - start     <-------
Global num in globalExample is: 80 - end

Local static num in staticLocalExample is: 5 - start
Local static num in staticLocalExample is: 25 - end

Local static num in staticLocalExample is: 25 - start
Local static num in staticLocalExample is: 45 - end
</code>```

As you can see The global variable changed but the static variable didn't...
All I had to do was to think outside the block of code not inside of it...

Thank you Cassio Renan

Body:
I'm a beginner programmer...Here I have a piece of code with two functions...one of them uses a global variable while the other one uses a local static variable...

So here is the code:

//Scope Rules
#include <iostream>
using namespace std;

int num {52};     //Global Variable - Declared outside any class or function

void globalExample();
void staticLocalExample();

void globalExample(){
    cout << "\nGlobal num in globalExample is: " << num << " - start" << endl;
    num *= 4;
    cout << "Global num in globalExample is: " << num << " - end" << endl;
}
void staticLocalExample(){
    static int num {5};      //local to staticLocalExample - retains it's value between calls
    cout << "\nLocal static num in staticLocalExample is: " << num << " - start" << endl;
    num += 20;
    cout << "Local static num in staticLocalExample is: " << num << " - end" << endl;
}

int main() {

    globalExample();
    globalExample();
    staticLocalExample();
    staticLocalExample();

    return 0;
}

The reason I called these functions twice was for me to understand that the second time the function is called, changes will be stored to the variables so the results will be different.

What I don't understand is:

What's the difference between these two functions then?

What does the staticLocalExample function exactly do?(Because in comparison, they both have the same results)

Why and when do we use the keyword static?

Note1:I know the cause of changes is the assignments I have in both functions BUT... This is just an example and I don't quietly understand it

Note2:I checked the link you guys sent me and thank you so much for that...I understood the concepts behind it but still I couldn't find the answer to my third question :)

Body:
I think I came to a conclusion...so please let me know if I'm wrong...

Global Varialble: You can change them and assign different numbers outside or inside of it's scope

Static Variable: You can only change it within it's scope not outside of it

So in conclusion lets modify this code a bit:

#include <iostream>
using namespace std;

int num {52};     //Global Variable - Declared outside any class or function

void globalExample();
void staticLocalExample(int x);

void globalExample(){
    cout << "\nGlobal num in globalExample is: " << num << " - start" << endl;
    num *= 4;
    cout << "Global num in globalExample is: " << num << " - end" << endl;
}
void staticLocalExample(int x){
    static int num {5};      //local to staticLocalExample - retains it's value between calls
    cout << "\nLocal static num in staticLocalExample is: " << num << " - start" << endl;
    num += 20;
    cout << "Local static num in staticLocalExample is: " << num << " - end" << endl;
}

int main() {

    globalExample();
    num = 20;
    globalExample();
    staticLocalExample(10);
    staticLocalExample(15);

    return 0;
}

Output:

Global num in globalExample is: 52 - start
Global num in globalExample is: 208 - end

Global num in globalExample is: 20 - start     <-------
Global num in globalExample is: 80 - end

Local static num in staticLocalExample is: 5 - start
Local static num in staticLocalExample is: 25 - end

Local static num in staticLocalExample is: 25 - start
Local static num in staticLocalExample is: 45 - end

As you can see The global variable changed but the static variable didn't...
All I had to do was to think outside the block of code not inside of it...

Thank you Cassio Renan


问:
Anchor link from html page to PHP page
I'm trying to anchor link from my HTML page to PHP. But when I click on whatever the links download window of the page will appear. If I leave the link as an HTML file, the link to another page works properly, but with PHP it starts to download.</p>

```<code> <ul class="netflix-list">
        <li><a href="index-en.php">Home</a></li>
        <li><a href="index-en.php#about">About</a></li>
        <li><a href="index-en.php#services">Services</a></li>
        <li>
          <ul>
            <li><a href="tattoo-en.html">Tattoo</a></li>
            <li><a href="beauty-en.html" class="gold">Beauty</a></li>
            <li><a href="piercing-en.html">Piercing</a></li>

          </ul>
        </li>
        <li><a href="index-en.php#contact">Contact</a></li>
        <li>
          <a href="beauty.html">Danish</a><img src="/images//denmark.svg" alt="danish-flag" class="flag" />
        </li>
</code>```

答:
To run PHP files you need to be on a server like Apache, if you try to access .php files without a server that accepts php it won't understand the request and will end up downloading the file.

You can Install WAMP or XAMPP(mac) and access your PHP files

Title: Anchor link from html page to PHP page

Body:
I'm trying to anchor link from my HTML page to PHP. But when I click on whatever the links download window of the page will appear. If I leave the link as an HTML file, the link to another page works properly, but with PHP it starts to download.

Home

About

Services

Tattoo

Beauty

Piercing

Contact

          Danish


问:
Reordering Boxplot in ggplot2
I have the following test data, and would like to plot them in descending order somehow my codes doesn't produce the desired plot

PAHs	Variable	Value

TB1	Nap	110

TB3	Nap	200

TB6	Nap	110

TB8	Nap	20

ND1	Nap	20

ND3	Nap	10

ND5	Nap	0

ND8	Nap	0

QT1	Nap	0

QT4	Nap	10

QT5	Nap	0

QT9	Nap	10

PT1	Nap	20

PT2	Nap	0

PT4	Nap	0

TB1	AcNP	20

TB3	AcNP	150

TB6	AcNP	70

TB8	AcNP	10

ND1	AcNP	0

ND3	AcNP	0

ND5	AcNP	0

ND8	AcNP	0

QT1	AcNP	0

QT4	AcNP	10

QT5	AcNP	0

QT9	AcNP	10

PT1	AcNP	30

PT2	AcNP	10

PT4	AcNP	0

TB1	AcN	130

TB3	AcN	110

TB6	AcN	150

TB8	AcN	10

ND1	AcN	40

ND3	AcN	0

ND5	AcN	0

ND8	AcN	10

QT1	AcN	0

QT4	AcN	10

QT5	AcN	0

QT9	AcN	10

PT1	AcN	150

PT2	AcN	10

PT4	AcN	10

TB1	Fl	70

TB3	Fl	80

TB6	Fl	0

TB8	Fl	0

ND1	Fl	0

ND3	Fl	10

ND5	Fl	0

ND8	Fl	10

QT1	Fl	0

QT4	Fl	30

QT5	Fl	0

QT9	Fl	0

PT1	Fl	0

PT2	Fl	10

PT4	Fl	0

TB1	An	100

TB3	An	230

TB6	An	110

TB8	An	110

ND1	An	130

ND3	An	10

ND5	An	10

ND8	An	40

QT1	An	10

QT4	An	60

QT5	An	0

QT9	An	110

PT1	An	150

PT2	An	30

PT4	An	30

TB1	PhA	100

TB3	PhA	240

TB6	PhA	200

TB8	PhA	110

ND1	PhA	130

ND3	PhA	40

ND5	PhA	10

ND8	PhA	40

QT1	PhA	0

QT4	PhA	70

QT5	PhA	0

QT9	PhA	130

PT1	PhA	150

PT2	PhA	30

PT4	PhA	40

TB1	FlA	20

TB3	FlA	20

TB6	FlA	60

TB8	FlA	30

ND1	FlA	30

ND3	FlA	0

ND5	FlA	0

ND8	FlA	0

QT1	FlA	0

QT4	FlA	20

QT5	FlA	0

QT9	FlA	30

PT1	FlA	30

PT2	FlA	0

PT4	FlA	20

TB1	Py	20

TB3	Py	20

TB6	Py	60

TB8	Py	30

ND1	Py	30

ND3	Py	0

ND5	Py	0

ND8	Py	0

QT1	Py	0

QT4	Py	20

QT5	Py	0

QT9	Py	30

PT1	Py	30

PT2	Py	0

PT4	Py	20

TB1	BaA	0

TB3	BaA	10

TB6	BaA	0

TB8	BaA	10

ND1	BaA	30

ND3	BaA	0

ND5	BaA	0

ND8	BaA	0

QT1	BaA	0

QT4	BaA	0

QT5	BaA	0

QT9	BaA	10

PT1	BaA	0

PT2	BaA	0

PT4	BaA	0

TB1	Chy	0

TB3	Chy	0

TB6	Chy	0

TB8	Chy	0

ND1	Chy	30

ND3	Chy	0

ND5	Chy	0

ND8	Chy	0

QT1	Chy	0

QT4	Chy	0

QT5	Chy	0

QT9	Chy	0

PT1	Chy	10

PT2	Chy	0

PT4	Chy	0

TB1	BpFlA	20

TB3	BpFlA	10

TB6	BpFlA	30

TB8	BpFlA	30

ND1	BpFlA	40

ND3	BpFlA	0

ND5	BpFlA	0

ND8	BpFlA	0

QT1	BpFlA	0

QT4	BpFlA	0

QT5	BpFlA	0

QT9	BpFlA	40

PT1	BpFlA	40

PT2	BpFlA	0

PT4	BpFlA	10

TB1	BkFlA	20

TB3	BkFlA	10

TB6	BkFlA	20

TB8	BkFlA	30

ND1	BkFlA	30

ND3	BkFlA	10

ND5	BkFlA	0

ND8	BkFlA	0

QT1	BkFlA	0

QT4	BkFlA	10

QT5	BkFlA	0

QT9	BkFlA	20

PT1	BkFlA	30

PT2	BkFlA	10

PT4	BkFlA	10

TB1	BaP	10

TB3	BaP	0

TB6	BaP	0

TB8	BaP	0

ND1	BaP	20

ND3	BaP	0

ND5	BaP	0

ND8	BaP	10

QT1	BaP	0

QT4	BaP	0

QT5	BaP	0

QT9	BaP	0

PT1	BaP	0

PT2	BaP	0

PT4	BaP	0

TB1	dBahA	40

TB3	dBahA	10

TB6	dBahA	20

TB8	dBahA	20

ND1	dBahA	20

ND3	dBahA	0

ND5	dBahA	0

ND8	dBahA	0

QT1	dBahA	0

QT4	dBahA	20

QT5	dBahA	0

QT9	dBahA	0

PT1	dBahA	0

PT2	dBahA	0

PT4	dBahA	10

TB1	IP	0

TB3	IP	0

TB6	IP	0

TB8	IP	0

ND1	IP	0

ND3	IP	0

ND5	IP	0

ND8	IP	0

QT1	IP	0

QT4	IP	0

QT5	IP	0

QT9	IP	0

PT1	IP	0

PT2	IP	0

PT4	IP	0

TB1	BghiP	0

TB3	BghiP	0

TB6	BghiP	0

TB8	BghiP	0

ND1	BghiP	10

ND3	BghiP	0

ND5	BghiP	0

ND8	BghiP	0

QT1	BghiP	0

QT4	BghiP	0

QT5	BghiP	0

QT9	BghiP	0

PT1	BghiP	0

PT2	BghiP	0

PT4	BghiP	0

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

```library(tidyverse)
library(cowplot)
library(scales)
scale_y_log2 <- function (...)
{scale_y_continuous(..., trans = log2_trans())
}
alexa<-read.csv(file.choose(),header=T, sep=",")
require(reshape2)

alexa.m<-melt(alexa,id_var="PAHs")
alexa.m$PAHs<-factor(alexa.m$PAHs,rev(unique(alexa.m$PAHs)),ordered=TRUE)
ggplot(alexa.m, aes(x=reorder(variable,-value),y=value))+scale_y_log2()+
 stat_boxplot(geom ='errorbar') +
 geom_boxplot()+xlab(" ")+ ylab("PAHs concentration(µg/L)") +
  theme(axis.text.y   = element_text(size=11),
        axis.text.x   = element_text(size=11),
        axis.title.y  = element_text(size=11),panel.background = element_blank(), panel.border = element_rect(colour = "black", fill=NA, size=1))
```

答:
Your plot is already in descending order - in means.

If you check ?reorder, the default is to order by mean.
You can specify how you want function you want to use to reorder the values of interest by FUN.

For example:
The line below reorders by median of value in an ascending manner.

```<code>aes(reorder(variable, value, FUN = median), value)
</code>```

The line below reorders by max value in an ascending manner.

```<code>aes(reorder(variable, value, FUN = max), value)
</code>```

For descending order, add a minus sign like you already did

```<code>aes(reorder(variable, -value, FUN = median), value)
aes(reorder(variable, -value, FUN = min), value)
</code>```

Title: Reordering Boxplot in ggplot2

Body:
I have the following test data, and would like to plot them in descending order somehow my codes doesn't produce the desired plot

PAHs	Variable	Value

TB1	Nap	110

TB3	Nap	200

TB6	Nap	110

TB8	Nap	20

ND1	Nap	20

ND3	Nap	10

ND5	Nap	0

ND8	Nap	0

QT1	Nap	0

QT4	Nap	10

QT5	Nap	0

QT9	Nap	10

PT1	Nap	20

PT2	Nap	0

PT4	Nap	0

TB1	AcNP	20

TB3	AcNP	150

TB6	AcNP	70

TB8	AcNP	10

ND1	AcNP	0

ND3	AcNP	0

ND5	AcNP	0

ND8	AcNP	0

QT1	AcNP	0

QT4	AcNP	10

QT5	AcNP	0

QT9	AcNP	10

PT1	AcNP	30

PT2	AcNP	10

PT4	AcNP	0

TB1	AcN	130

TB3	AcN	110

TB6	AcN	150

TB8	AcN	10

ND1	AcN	40

ND3	AcN	0

ND5	AcN	0

ND8	AcN	10

QT1	AcN	0

QT4	AcN	10

QT5	AcN	0

QT9	AcN	10

PT1	AcN	150

PT2	AcN	10

PT4	AcN	10

TB1	Fl	70

TB3	Fl	80

TB6	Fl	0

TB8	Fl	0

ND1	Fl	0

ND3	Fl	10

ND5	Fl	0

ND8	Fl	10

QT1	Fl	0

QT4	Fl	30

QT5	Fl	0

QT9	Fl	0

PT1	Fl	0

PT2	Fl	10

PT4	Fl	0

TB1	An	100

TB3	An	230

TB6	An	110

TB8	An	110

ND1	An	130

ND3	An	10

ND5	An	10

ND8	An	40

QT1	An	10

QT4	An	60

QT5	An	0

QT9	An	110

PT1	An	150

PT2	An	30

PT4	An	30

TB1	PhA	100

TB3	PhA	240

TB6	PhA	200

TB8	PhA	110

ND1	PhA	130

ND3	PhA	40

ND5	PhA	10

ND8	PhA	40

QT1	PhA	0

QT4	PhA	70

QT5	PhA	0

QT9	PhA	130

PT1	PhA	150

PT2	PhA	30

PT4	PhA	40

TB1	FlA	20

TB3	FlA	20

TB6	FlA	60

TB8	FlA	30

ND1	FlA	30

ND3	FlA	0

ND5	FlA	0

ND8	FlA	0

QT1	FlA	0

QT4	FlA	20

QT5	FlA	0

QT9	FlA	30

PT1	FlA	30

PT2	FlA	0

PT4	FlA	20

TB1	Py	20

TB3	Py	20

TB6	Py	60

TB8	Py	30

ND1	Py	30

ND3	Py	0

ND5	Py	0

ND8	Py	0

QT1	Py	0

QT4	Py	20

QT5	Py	0

QT9	Py	30

PT1	Py	30

PT2	Py	0

PT4	Py	20

TB1	BaA	0

TB3	BaA	10

TB6	BaA	0

TB8	BaA	10

ND1	BaA	30

ND3	BaA	0

ND5	BaA	0

ND8	BaA	0

QT1	BaA	0

QT4	BaA	0

QT5	BaA	0

QT9	BaA	10

PT1	BaA	0

PT2	BaA	0

PT4	BaA	0

TB1	Chy	0

TB3	Chy	0

TB6	Chy	0

TB8	Chy	0

ND1	Chy	30

ND3	Chy	0

ND5	Chy	0

ND8	Chy	0

QT1	Chy	0

QT4	Chy	0

QT5	Chy	0

QT9	Chy	0

PT1	Chy	10

PT2	Chy	0

PT4	Chy	0

TB1	BpFlA	20

TB3	BpFlA	10

TB6	BpFlA	30

TB8	BpFlA	30

ND1	BpFlA	40

ND3	BpFlA	0

ND5	BpFlA	0

ND8	BpFlA	0

QT1	BpFlA	0

QT4	BpFlA	0

QT5	BpFlA	0

QT9	BpFlA	40

PT1	BpFlA	40

PT2	BpFlA	0

PT4	BpFlA	10

TB1	BkFlA	20

TB3	BkFlA	10

TB6	BkFlA	20

TB8	BkFlA	30

ND1	BkFlA	30

ND3	BkFlA	10

ND5	BkFlA	0

ND8	BkFlA	0

QT1	BkFlA	0

QT4	BkFlA	10

QT5	BkFlA	0

QT9	BkFlA	20

PT1	BkFlA	30

PT2	BkFlA	10

PT4	BkFlA	10

TB1	BaP	10

TB3	BaP	0

TB6	BaP	0

TB8	BaP	0

ND1	BaP	20

ND3	BaP	0

ND5	BaP	0

ND8	BaP	10

QT1	BaP	0

QT4	BaP	0

QT5	BaP	0

QT9	BaP	0

PT1	BaP	0

PT2	BaP	0

PT4	BaP	0

TB1	dBahA	40

TB3	dBahA	10

TB6	dBahA	20

TB8	dBahA	20

ND1	dBahA	20

ND3	dBahA	0

ND5	dBahA	0

ND8	dBahA	0

QT1	dBahA	0

QT4	dBahA	20

QT5	dBahA	0

QT9	dBahA	0

PT1	dBahA	0

PT2	dBahA	0

PT4	dBahA	10

TB1	IP	0

TB3	IP	0

TB6	IP	0

TB8	IP	0

ND1	IP	0

ND3	IP	0

ND5	IP	0

ND8	IP	0

QT1	IP	0

QT4	IP	0

QT5	IP	0

QT9	IP	0

PT1	IP	0

PT2	IP	0

PT4	IP	0

TB1	BghiP	0

TB3	BghiP	0

TB6	BghiP	0

TB8	BghiP	0

ND1	BghiP	10

ND3	BghiP	0

ND5	BghiP	0

ND8	BghiP	0

QT1	BghiP	0

QT4	BghiP	0

QT5	BghiP	0

QT9	BghiP	0

PT1	BghiP	0

PT2	BghiP	0

PT4	BghiP	0

library(tidyverse)
library(cowplot)
library(scales)
scale_y_log2 <- function (...)
{scale_y_continuous(..., trans = log2_trans())
}
alexa<-read.csv(file.choose(),header=T, sep=",")
require(reshape2)

alexa.m<-melt(alexa,id_var="PAHs")
alexa.m$PAHs<-factor(alexa.m$PAHs,rev(unique(alexa.m$PAHs)),ordered=TRUE)
ggplot(alexa.m, aes(x=reorder(variable,-value),y=value))+scale_y_log2()+
 stat_boxplot(geom ='errorbar') +
 geom_boxplot()+xlab(" ")+ ylab("PAHs concentration(µg/L)") +
  theme(axis.text.y   = element_text(size=11),
        axis.text.x   = element_text(size=11),
        axis.title.y  = element_text(size=11),panel.background = element_blank(), panel.border = element_rect(colour = "black", fill=NA, size=1))

Body:
Your plot is already in descending order - in means.

If you check ?reorder, the default is to order by mean.
You can specify how you want function you want to use to reorder the values of interest by FUN.

For example:
The line below reorders by median of value in an ascending manner.

aes(reorder(variable, value, FUN = median), value)

The line below reorders by max value in an ascending manner.

aes(reorder(variable, value, FUN = max), value)

For descending order, add a minus sign like you already did

aes(reorder(variable, -value, FUN = median), value)
aes(reorder(variable, -value, FUN = min), value)


问:
Default OOBX EditForm disappeared for a SharePoint document library
Default OOBX EditForm disappeared for a SharePoint document library. We tried to create a new edit form in SharePoint designer but got an error that Could not save the List Changes to Server.
Then tried another approach, go to All files/Documentlibrary/Forms -- here got list view threshold error. We have more than 10 thousands items in the library, can't open up forms folder.

Please advise how to get the default edit form back.

答:
You'll need to do it through PowerShell:

```<code>$webpartTemplate = @"
<WebPart xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/WebPart/v2">
    <Assembly>Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
    <TypeName>Microsoft.SharePoint.WebPartPages.ListFormWebPart</TypeName>
    <ListName xmlns="http://schemas.microsoft.com/WebPart/v2/ListForm">{{{LIST_ID}}}</ListName>
    <ListId xmlns="http://schemas.microsoft.com/WebPart/v2/ListForm">{{LIST_ID}}</ListId>
    <PageType xmlns="http://schemas.microsoft.com/WebPart/v2/ListForm">{{PAGE_TYPE}}</PageType>
    <FormType xmlns="http://schemas.microsoft.com/WebPart/v2/ListForm">{{FORM_TYPE}}</FormType>
    <ControlMode xmlns="http://schemas.microsoft.com/WebPart/v2/ListForm">{{CONTROL_MODE}}</ControlMode>
    <ViewFlag xmlns="http://schemas.microsoft.com/WebPart/v2/ListForm">1048576</ViewFlag>
    <ViewFlags xmlns="http://schemas.microsoft.com/WebPart/v2/ListForm">Default</ViewFlags>
    <ListItemId xmlns="http://schemas.microsoft.com/WebPart/v2/ListForm">0</ListItemId>
</WebPart>
"@

Function Create-DefaultListForm
{
    param(
        [parameter(Mandatory=$true)]$List,
        [parameter(Mandatory=$true)][string]$FormUrl,
        [parameter(Mandatory=$true)][ValidateSet("Display", "Edit", "New")]$FormType
    )

    begin { }
    process
    {

        $webpartXml = $webpartTemplate -replace "{{LIST_ID}}", $List.Id.ToString()

        switch ($FormType)
        {
            "Display" {
                $webpartXml = $webpartXml -replace "{{PAGE_TYPE}}", "PAGE_DISPLAYFORM"
                $webpartXml = $webpartXml -replace "{{FORM_TYPE}}", "4"
                $webpartXml = $webpartXml -replace "{{CONTROL_MODE}}", "Display"
                break;
            }
            "Edit" {
                $webpartXml = $webpartXml -replace "{{PAGE_TYPE}}", "PAGE_EDITFORM"
                $webpartXml = $webpartXml -replace "{{FORM_TYPE}}", "6"
                $webpartXml = $webpartXml -replace "{{CONTROL_MODE}}", "Edit"
                break;
            }
            "New" {
                $webpartXml = $webpartXml -replace "{{PAGE_TYPE}}", "PAGE_NEWFORM"
                $webpartXml = $webpartXml -replace "{{FORM_TYPE}}", "8"
                $webpartXml = $webpartXml -replace "{{CONTROL_MODE}}", "New"
                break;
            }
        }

        try
        {
            #Check if form page already exists
            $listPages = Get-PnPProperty -ClientObject $List.RootFolder -Property Files
            $formPage = $listPages | Where-Object { $_.ServerRelativeUrl.ToLower() -eq $FormUrl.ToLower() }

            if ($null -eq $formPage) {
                Write-Output "  [Creating Form Page] $FormUrl"

                #Create Form
                Remove-PnPFile -ServerRelativeUrl $FormUrl -Force
                $formPage = $List.RootFolder.Files.AddTemplateFile($FormUrl, [Microsoft.SharePoint.Client.TemplateFileType]::FormPage)
            }
            else {
                #Form page exists, check if form is recognized by list (i.e. form page has a form webpart on it)
                $listForms = Get-PnPProperty -ClientObject $List -Property Forms

                if ($null -ne $listForms -and $listForms.Count -gt 0) {
                    $existingForm = $list.Forms | Where-Object { $_.ServerRelativeUrl.ToLower() -eq $FormUrl.ToLower() }
                    if ($null -ne $existingForm) {
                        Write-Warning "  [Form Already Exists] $FormUrl"
                        return;
                    }
                }
            }

            Write-Output "  [Adding Form Webpart] $FormUrl"
            #Get Webpart Manager for Form
            $wpm = $formPage.GetLimitedWebPartManager([Microsoft.SharePoint.Client.WebParts.PersonalizationScope]::Shared)

            #Import Webpart on page
            $wp = $wpm.ImportWebPart($webpartXml)

            #Add webpart to Form
            $wpm.AddWebPart($wp.WebPart, "Main", 1) | Out-Null

            #Execute changes
            $List.Context.ExecuteQuery()
        }
        catch
        {
            Write-Error "Error creating form $FormType at $FormUrl. Error: $($_.Exception)"
        }
    }
    end { }
}
</code>```

Use the script something like this.  If you only need to restore the EditForm, then you obviously you can skip the Upload, New, and DispForms below:

```<code>    Connect-PnPOnline -Url $problemSiteUrl -UseWebLogin
    $list = Get-PnPList $problemlistTitle
    $listUrl = $list.RootFolder.ServerRelativeUrl

    # Handle Document Library Types
    if ($list.BaseType -eq [Microsoft.SharePoint.Client.BaseType]::DocumentLibrary) {
        Write-Host " > Processing Library: $listUrl"
        Create-DefaultListForm -List $list -FormUrl "$listUrl/Forms/Upload.aspx"   -FormType New
        Create-DefaultListForm -List $list -FormUrl "$listUrl/Forms/DispForm.aspx" -FormType Display
        Create-DefaultListForm -List $list -FormUrl "$listUrl/Forms/EditForm.aspx" -FormType Edit
    }

    # Handle Generic List Types
    else {
        Write-Host " > Processing List: $listUrl"
        Create-DefaultListForm -List $list -FormUrl "$listUrl/NewForm.aspx"  -FormType New
        Create-DefaultListForm -List $list -FormUrl "$listUrl/DispForm.aspx" -FormType Display
        Create-DefaultListForm -List $list -FormUrl "$listUrl/EditForm.aspx" -FormType Edit
    }
</code>```

If you only need the Edit form, use the Create-DefaultListForm function like this:

```<code>    Connect-PnPOnline -Url 'UrlOfProblemSite' -UseWebLogin
    $list = Get-PnPList 'TitleOfTheProblemLibraryHere'
    $listUrl = $list.RootFolder.ServerRelativeUrl

    Create-DefaultListForm -List $list -FormUrl "$listUrl/Forms/EditForm.aspx" -FormType Edit
</code>```

Body:
You'll need to do it through PowerShell:

$webpartTemplate = @"
<WebPart xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/WebPart/v2">
    <Assembly>Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
    <TypeName>Microsoft.SharePoint.WebPartPages.ListFormWebPart</TypeName>
    <ListName xmlns="http://schemas.microsoft.com/WebPart/v2/ListForm">{{{LIST_ID}}}</ListName>
    <ListId xmlns="http://schemas.microsoft.com/WebPart/v2/ListForm">{{LIST_ID}}</ListId>
    <PageType xmlns="http://schemas.microsoft.com/WebPart/v2/ListForm">{{PAGE_TYPE}}</PageType>
    <FormType xmlns="http://schemas.microsoft.com/WebPart/v2/ListForm">{{FORM_TYPE}}</FormType>
    <ControlMode xmlns="http://schemas.microsoft.com/WebPart/v2/ListForm">{{CONTROL_MODE}}</ControlMode>
    <ViewFlag xmlns="http://schemas.microsoft.com/WebPart/v2/ListForm">1048576</ViewFlag>
    <ViewFlags xmlns="http://schemas.microsoft.com/WebPart/v2/ListForm">Default</ViewFlags>
    <ListItemId xmlns="http://schemas.microsoft.com/WebPart/v2/ListForm">0</ListItemId>
</WebPart>
"@

Function Create-DefaultListForm
{
    param(
        [parameter(Mandatory=$true)]$List,
        [parameter(Mandatory=$true)][string]$FormUrl,
        [parameter(Mandatory=$true)][ValidateSet("Display", "Edit", "New")]$FormType
    )

    begin { }
    process
    {

        $webpartXml = $webpartTemplate -replace "{{LIST_ID}}", $List.Id.ToString()

        switch ($FormType)
        {
            "Display" {
                $webpartXml = $webpartXml -replace "{{PAGE_TYPE}}", "PAGE_DISPLAYFORM"
                $webpartXml = $webpartXml -replace "{{FORM_TYPE}}", "4"
                $webpartXml = $webpartXml -replace "{{CONTROL_MODE}}", "Display"
                break;
            }
            "Edit" {
                $webpartXml = $webpartXml -replace "{{PAGE_TYPE}}", "PAGE_EDITFORM"
                $webpartXml = $webpartXml -replace "{{FORM_TYPE}}", "6"
                $webpartXml = $webpartXml -replace "{{CONTROL_MODE}}", "Edit"
                break;
            }
            "New" {
                $webpartXml = $webpartXml -replace "{{PAGE_TYPE}}", "PAGE_NEWFORM"
                $webpartXml = $webpartXml -replace "{{FORM_TYPE}}", "8"
                $webpartXml = $webpartXml -replace "{{CONTROL_MODE}}", "New"
                break;
            }
        }

        try
        {
            #Check if form page already exists
            $listPages = Get-PnPProperty -ClientObject $List.RootFolder -Property Files
            $formPage = $listPages | Where-Object { $_.ServerRelativeUrl.ToLower() -eq $FormUrl.ToLower() }

            if ($null -eq $formPage) {
                Write-Output "  [Creating Form Page] $FormUrl"

                #Create Form
                Remove-PnPFile -ServerRelativeUrl $FormUrl -Force
                $formPage = $List.RootFolder.Files.AddTemplateFile($FormUrl, [Microsoft.SharePoint.Client.TemplateFileType]::FormPage)
            }
            else {
                #Form page exists, check if form is recognized by list (i.e. form page has a form webpart on it)
                $listForms = Get-PnPProperty -ClientObject $List -Property Forms

                if ($null -ne $listForms -and $listForms.Count -gt 0) {
                    $existingForm = $list.Forms | Where-Object { $_.ServerRelativeUrl.ToLower() -eq $FormUrl.ToLower() }
                    if ($null -ne $existingForm) {
                        Write-Warning "  [Form Already Exists] $FormUrl"
                        return;
                    }
                }
            }

            Write-Output "  [Adding Form Webpart] $FormUrl"
            #Get Webpart Manager for Form
            $wpm = $formPage.GetLimitedWebPartManager([Microsoft.SharePoint.Client.WebParts.PersonalizationScope]::Shared)

            #Import Webpart on page
            $wp = $wpm.ImportWebPart($webpartXml)

            #Add webpart to Form
            $wpm.AddWebPart($wp.WebPart, "Main", 1) | Out-Null

            #Execute changes
            $List.Context.ExecuteQuery()
        }
        catch
        {
            Write-Error "Error creating form $FormType at $FormUrl. Error: $($_.Exception)"
        }
    }
    end { }
}

Use the script something like this.  If you only need to restore the EditForm, then you obviously you can skip the Upload, New, and DispForms below:

    Connect-PnPOnline -Url $problemSiteUrl -UseWebLogin
    $list = Get-PnPList $problemlistTitle
    $listUrl = $list.RootFolder.ServerRelativeUrl

    # Handle Document Library Types
    if ($list.BaseType -eq [Microsoft.SharePoint.Client.BaseType]::DocumentLibrary) {
        Write-Host " > Processing Library: $listUrl"
        Create-DefaultListForm -List $list -FormUrl "$listUrl/Forms/Upload.aspx"   -FormType New
        Create-DefaultListForm -List $list -FormUrl "$listUrl/Forms/DispForm.aspx" -FormType Display
        Create-DefaultListForm -List $list -FormUrl "$listUrl/Forms/EditForm.aspx" -FormType Edit
    }

    # Handle Generic List Types
    else {
        Write-Host " > Processing List: $listUrl"
        Create-DefaultListForm -List $list -FormUrl "$listUrl/NewForm.aspx"  -FormType New
        Create-DefaultListForm -List $list -FormUrl "$listUrl/DispForm.aspx" -FormType Display
        Create-DefaultListForm -List $list -FormUrl "$listUrl/EditForm.aspx" -FormType Edit
    }

If you only need the Edit form, use the Create-DefaultListForm function like this:

    Connect-PnPOnline -Url 'UrlOfProblemSite' -UseWebLogin
    $list = Get-PnPList 'TitleOfTheProblemLibraryHere'
    $listUrl = $list.RootFolder.ServerRelativeUrl

    Create-DefaultListForm -List $list -FormUrl "$listUrl/Forms/EditForm.aspx" -FormType Edit


问:
How to create a function to dynamically create list of tuples within a range?
Is there a way to create a function which creates a list of tuples with arguments for:

number of tuples

elements per tuple

beginning range

ending range

I believe I have most of it:

```<code>import random

def list_rand_num_tuples(num_of_tups, range_beg, range_end):
    list_tuples = [
        (random.randrange(range_beg, range_end),
         random.randrange(range_beg, range_end),
         random.randrange(range_beg, range_end))
        for i in range(num_of_tups)]
    return list_tuples

# test/display it
print(list_rand_num_tuples(3, 0, 51))
</code>```

but how can this portion be more dynamic?

```<code>(random.randrange(range_beg, range_end),
 random.randrange(range_beg, range_end),
 random.randrange(range_beg, range_end))
</code>```

For example, can the length of tuple / elements of tuple argument be provided to loop through this part the appropriate number of times?

答:
Do you mean adding an extra parameter for the elements per tuple? You can add another range</p>

```<code>def list_rand_num_of_tuples(num_tups, num_elements, range_beg, range_end):
    return [tuple(random.randrange(range_beg, range_end)
                  for _ in range(num_elements))
            for _ in range(num_tups)]
</code>```

Body:
Is there a way to create a function which creates a list of tuples with arguments for:

number of tuples

elements per tuple

beginning range

ending range

I believe I have most of it:

import random

def list_rand_num_tuples(num_of_tups, range_beg, range_end):
    list_tuples = [
        (random.randrange(range_beg, range_end),
         random.randrange(range_beg, range_end),
         random.randrange(range_beg, range_end))
        for i in range(num_of_tups)]
    return list_tuples

# test/display it
print(list_rand_num_tuples(3, 0, 51))

but how can this portion be more dynamic?

(random.randrange(range_beg, range_end),
 random.randrange(range_beg, range_end),
 random.randrange(range_beg, range_end))

For example, can the length of tuple / elements of tuple argument be provided to loop through this part the appropriate number of times?

Body:
Do you mean adding an extra parameter for the elements per tuple? You can add another range

def list_rand_num_of_tuples(num_tups, num_elements, range_beg, range_end):
    return [tuple(random.randrange(range_beg, range_end)
                  for _ in range(num_elements))
            for _ in range(num_tups)]


问:
Trailing zero's in Jekyll/Liquid
I have frontmatter that looks like this:

```<code>products:
- item: item name
  price: 39.50
- item: item number two
  price: 12.50
</code>```

How can I output these variables in liquid with trailing zero's?

Note that {{ products[0].price }} will output 39.5. I need it to output 39.50.

答:
I know this is an older question but you can create a custom filter for this.

```<code>module Jekyll
  module PrecisionFilter
    def precision(input, value=0)
      ("%.#{value}f" % input)
    end
  end
end

Liquid::Template.register_filter(Jekyll::PrecisionFilter)
</code>```

Save this as _plugins/precision_filter.rb and restart your jekyll server (if its running). It will give you the ability to set the precision on a number like so,

```<code>{{ price | precision: 2 }}
</code>```

Title: Trailing zero's in Jekyll/Liquid

Body:
I have frontmatter that looks like this:

products:
- item: item name
  price: 39.50
- item: item number two
  price: 12.50

How can I output these variables in liquid with trailing zero's?

Note that {{ products[0].price }} will output 39.5. I need it to output 39.50.

Body:
I know this is an older question but you can create a custom filter for this.

module Jekyll
  module PrecisionFilter
    def precision(input, value=0)
      ("%.#{value}f" % input)
    end
  end
end

Liquid::Template.register_filter(Jekyll::PrecisionFilter)

Save this as _plugins/precision_filter.rb and restart your jekyll server (if its running). It will give you the ability to set the precision on a number like so,

{{ price | precision: 2 }}


问:
Error: The dbplyr package is required to communicate with database backends
I am new to R and learning R from sources.

I am trying to use the dplyr package for connecting to the database.

I am trying out the following tutorial, and getting this error

https://github.com/ujjwalkarn/DataScienceR/blob/master/Intro%20to%20dplyr/7-databases.R

I am using RStudio for running the tutorials on Linux Platform.

```<code>> hflights_db <- src_sqlite("hflights.sqlite3", create = TRUE)
Error: The dbplyr package is required to communicate with database backends.
</code>```

答: Easy fix: install the dbplyr package.

Body:
I am new to R and learning R from sources.

I am trying to use the dplyr package for connecting to the database.

I am trying out the following tutorial, and getting this error

https://github.com/ujjwalkarn/DataScienceR/blob/master/Intro%20to%20dplyr/7-databases.R

I am using RStudio for running the tutorials on Linux Platform.

> hflights_db <- src_sqlite("hflights.sqlite3", create = TRUE)
Error: The dbplyr package is required to communicate with database backends.

Body: Easy fix: install the dbplyr package.


问:
List of dates from historic dates from a reference date
I am trying to create a list of weekday dates back from a reference date.  For example if my reference date was 2020-02-14 and I wanted a list of the last 10 weekdays I would like returned:

```<code>2020-02-14
2020-02-13
2020-02-12
2020-02-11
2020-02-10
2020-02-07
2020-02-06
2020-02-05
2020-02-04
2020-02-03
</code>```

I have tried:

```<code>dateList = pd.bdate_range(end='2020-02-14',periods=10)
</code>```

without success (I won't hard code in my actual code this is just for example).

Body:
I am trying to create a list of weekday dates back from a reference date.  For example if my reference date was 2020-02-14 and I wanted a list of the last 10 weekdays I would like returned:

2020-02-14
2020-02-13
2020-02-12
2020-02-11
2020-02-10
2020-02-07
2020-02-06
2020-02-05
2020-02-04
2020-02-03

I have tried:

dateList = pd.bdate_range(end='2020-02-14',periods=10)

without success (I won't hard code in my actual code this is just for example).

Body:
Using pd.bdate_range with frequency B for business days and set the end argument the calculate backwards.

dates = pd.bdate_range(end='2020-02-14', periods=10, freq='B')
print(dates)

DatetimeIndex(['2020-02-03', '2020-02-04', '2020-02-05', '2020-02-06',
               '2020-02-07', '2020-02-10', '2020-02-11', '2020-02-12',
               '2020-02-13', '2020-02-14'],
              dtype='datetime64[ns]', freq='B')

pd.Series(dates[::-1])

0   2020-02-14
1   2020-02-13
2   2020-02-12
3   2020-02-11
4   2020-02-10
5   2020-02-07
6   2020-02-06
7   2020-02-05
8   2020-02-04
9   2020-02-03
dtype: datetime64[ns]


问:
Dynamically populating a static variable in PHP
I have two static values: "type" and "typeID".  Type is human readable and constant, and typeID needs to be looked up from the database, based on the value of type.  I need the lookup to happen once, when the class definition is first loaded

To illustrate, here is some code that doesn't work because you can't call functions in the declaration space.

```<code>MyClass extends BaseClass {
  protected static $type = "communities";
  protected static $typeID = MyClass::lookupTypeID(self::$type);
}
</code>```

Is there a magic method that is called exactly once when the class definition is loaded?  If there is something obvious I'm missing it.

答: Such a thing would normally be called a "static constructor", but PHP lacks such things. You might want to consider one of the workarounds suggested in the PHP manual comments, e.g. http://www.php.net/manual/en/language.oop5.static.php#95217</p>

Body:
I have two static values: "type" and "typeID".  Type is human readable and constant, and typeID needs to be looked up from the database, based on the value of type.  I need the lookup to happen once, when the class definition is first loaded

To illustrate, here is some code that doesn't work because you can't call functions in the declaration space.

MyClass extends BaseClass {
  protected static $type = "communities";
  protected static $typeID = MyClass::lookupTypeID(self::$type);
}

Is there a magic method that is called exactly once when the class definition is loaded?  If there is something obvious I'm missing it.


问:
Primeng - how to use styleClass?
I want to use the styleClass property of the Togglebutton component. As described in another post, I thought it is straight forward by using:

```<code>styleClass="test"
</code>```

In my css-file I then set some attributes, like

```<code>.test { background: red; }
</code>```

But this does not work. Working with style is perfectly clear by using [style]="{'background':'red'}" No problem with that. But styleClass does not work. Here is the component. Any idea how to use styleClass?

答:
You can try to override o PrimeNg component doing this, eg. I was using tabMenu and worked:

```<code><p-tabMenu styleClass="override-this"></p-tabMenu>
</code>```

I suppose it will work with any PrimeNg component that accepts styleClass.

In root style.css file you just use body and then the styleClass name.

```<code>body .override-this{
  font-size: 10px;
}
</code>```

I didn't test with other properties, probably if you need to change some deeper you will need to cascade like

body .override-this .ui-tabmenu .ui-tabmenu-nav and so on.

Title: Primeng - how to use styleClass?

Body:
I want to use the styleClass property of the Togglebutton component. As described in another post, I thought it is straight forward by using:

styleClass="test"

In my css-file I then set some attributes, like

.test { background: red; }

But this does not work. Working with style is perfectly clear by using [style]="{'background':'red'}" No problem with that. But styleClass does not work. Here is the component. Any idea how to use styleClass?

Body:
You can try to override o PrimeNg component doing this, eg. I was using tabMenu and worked:

<p-tabMenu styleClass="override-this"></p-tabMenu>

I suppose it will work with any PrimeNg component that accepts styleClass.

In root style.css file you just use body and then the styleClass name.

body .override-this{
  font-size: 10px;
}

I didn't test with other properties, probably if you need to change some deeper you will need to cascade like

body .override-this .ui-tabmenu .ui-tabmenu-nav and so on.


问:
Changing indentation settings in the Spyder editor for Python
I am using the Spyder editor for Python.
I need to change the indentation setting (e.g., let "tab" mean "4 spaces").

How do I accomplish this?

答:
On Mac w/ Spyder 4.0.1, it's

Python -> Preference -> Editor -> Source Code (tab) -> Indentation characters


答:
A possible implementation could use the starmap function from the itertools module:

```<code>import random
import itertools

def list_rand_num_tuples(num_of_tups, range_beg, range_end):
    """
    Generate `num_of_tups` tuples, each containing `num_of_tups` random
    numbers selected from the interval `range_beg..range_end`.
    """
    interval = (range_beg, range_end)
    return [
         tuple(itertools.starmap(random.randrange, [interval] * num_of_tups))
         for _ in range(num_of_tups)
    ]

</code>```

With this implementation,

```<code>>>> list_rand_num_tuples(3, 0, 10)
</code>```

outputs

```<code>[(2, 7, 5), (4, 1, 0), (1, 7, 0)]
</code>```

I personally find this much more readable than nested list comprehensions, and it makes use of standard library functionality designed precisely for this purpose.

Title: How to create a function to dynamically create list of tuples within a range?

Body:
A possible implementation could use the starmap function from the itertools module:

import random
import itertools

def list_rand_num_tuples(num_of_tups, range_beg, range_end):
    """
    Generate `num_of_tups` tuples, each containing `num_of_tups` random
    numbers selected from the interval `range_beg..range_end`.
    """
    interval = (range_beg, range_end)
    return [
         tuple(itertools.starmap(random.randrange, [interval] * num_of_tups))
         for _ in range(num_of_tups)
    ]

With this implementation,

>>> list_rand_num_tuples(3, 0, 10)

outputs

[(2, 7, 5), (4, 1, 0), (1, 7, 0)]

I personally find this much more readable than nested list comprehensions, and it makes use of standard library functionality designed precisely for this purpose.


问:
Exclude Preceding Commit> line from git rev-list formatting
I'm trying to work on a branch diff command, and I've got it all working... Except for the formatting. I can use --pretty=oneline to display just the information I want, except it displays the full hash, and doesn't colorize the output.

So it'd just output this:

```<code>fa73c05913292fbce940075fc8f454bad5066666 Example Commit Message
de4dbeffa249393dddebb7b13ae555cb97cad5be Another Example Commit Message
</code>```

If I try and do a custom format string, such as this: --pretty="format:%C(yellow)%h%C(reset) %s", it works, but it also displays an additional line above it.

E.g.

```<code>commit >fa73c05913292fbce940075fc8f454bad5066666
fa73c05 Example Commit Message
commit >de4dbeffa249393dddebb7b13ae555cb97cad5be
de4dbef Another Example Commit Message
</code>```

Is there a way to have git rev-list output a format without the preceding commit >abcdef3... lines?

答:
You can use sed after git rev-list to delete all the lines starting with commit.

git rev-list --pretty=format:"%C(yellow)%h%C(reset) %s" | sed '/^commit [0-9a-f]\{40\}$/d'.

Body:
I'm trying to work on a branch diff command, and I've got it all working... Except for the formatting. I can use --pretty=oneline to display just the information I want, except it displays the full hash, and doesn't colorize the output.

So it'd just output this:

fa73c05913292fbce940075fc8f454bad5066666 Example Commit Message
de4dbeffa249393dddebb7b13ae555cb97cad5be Another Example Commit Message

If I try and do a custom format string, such as this: --pretty="format:%C(yellow)%h%C(reset) %s", it works, but it also displays an additional line above it.

E.g.

commit >fa73c05913292fbce940075fc8f454bad5066666
fa73c05 Example Commit Message
commit >de4dbeffa249393dddebb7b13ae555cb97cad5be
de4dbef Another Example Commit Message

Is there a way to have git rev-list output a format without the preceding commit >abcdef3... lines?


问:
What does a sealed class do and explanation of the class below
I have been doing android development for a while but I always looking forward to learning new things.

I came across the code below on codelab for viewmodel unit testing. I really like the code base is arranged but do not understand some codes like the one below.

I will like some guidance on creating a class that has a type of map as below.

Basically I will like to know how Result<*> still relate to Result and why the class is just called/implemented as Success(it).

I will appreciate a kind guidance.

```<code>sealed class Result<out R> {

    data class Success<out T>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
    object Loading : Result<Nothing>()

    override fun toString(): String {
        return when (this) {
            is Success<*> -> "Success[data=$data]"
            is Error -> "Error[exception=$exception]"
            Loading -> "Loading"
        }
    }
}

/**
 * `true` if [Result] is of type [Success] & holds non-null [Success.data].
 */
val Result<*>.succeeded
    get() = this is Success && data != null

//implementation
 override fun observeTask(taskId: String): LiveData<Result<Task>> {
        return tasksDao.observeTaskById(taskId).map {
            Success(it)
        }
    }
</code>```

答:
Result<*>.succeeded is an extension property of the sealed class Result.

Check the guide on extensions in Kotlin:

https://kotlinlang.org/docs/reference/extensions.html

Body:
I have been doing android development for a while but I always looking forward to learning new things.

I came across the code below on codelab for viewmodel unit testing. I really like the code base is arranged but do not understand some codes like the one below.

I will like some guidance on creating a class that has a type of map as below.

Basically I will like to know how Result<*> still relate to Result and why the class is just called/implemented as Success(it).

I will appreciate a kind guidance.

sealed class Result<out R> {

    data class Success<out T>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
    object Loading : Result<Nothing>()

    override fun toString(): String {
        return when (this) {
            is Success<*> -> "Success[data=$data]"
            is Error -> "Error[exception=$exception]"
            Loading -> "Loading"
        }
    }
}

/**
 * `true` if [Result] is of type [Success] & holds non-null [Success.data].
 */
val Result<*>.succeeded
    get() = this is Success && data != null

//implementation
 override fun observeTask(taskId: String): LiveData<Result<Task>> {
        return tasksDao.observeTaskById(taskId).map {
            Success(it)
        }
    }


问:
Uncaught SyntaxError: Invalid or unexpected token in EXT JS
Hi I am retrieving some values from database in onReady function of JS it gives me error Uncaught SyntaxError: Invalid or unexpected token

Below is my onReady function

var clientId = getFieldValue('editForm:clientId');
               if (!clientId) {
                   if ('#{applicationObject.attributes['isProduction']}' == true || '#{applicationObject.attributes['isProduction']}'=='true') {
                       clientId = '#{applicationObject.attributes['productionClientId']}';
                   } else {
                       clientId = '#{applicationObject.attributes['nonProductionClientId']}';
                   }
               }

   Ext.getDom('editForm:clientId').value = clientId;
```

The expected value of clientId is

1:ACP:cSHnNw4v7MhdAGuQ1QF0PnuVOh1PFVBz0u2hlzx81uMR7GJMUBGe08XIKmb/SE7WvMpeprAPPSQw\ngQd+N+fOdA==

In Chrome debugger it shows as below

答: Since you are inserting a multi-line string the easiest here (if you cannot modify that string or do not want to split it and then concatenate using 'line1' + 'line2') is to use so called template literals as they support multi-lines. Please also have a look at this question as it's not supported everywhere.

Body:
Hi I am retrieving some values from database in onReady function of JS it gives me error Uncaught SyntaxError: Invalid or unexpected token

Below is my onReady function

var clientId = getFieldValue('editForm:clientId');
               if (!clientId) {
                   if ('#{applicationObject.attributes['isProduction']}' == true || '#{applicationObject.attributes['isProduction']}'=='true') {
                       clientId = '#{applicationObject.attributes['productionClientId']}';
                   } else {
                       clientId = '#{applicationObject.attributes['nonProductionClientId']}';
                   }
               }

   Ext.getDom('editForm:clientId').value = clientId;

The expected value of clientId is

1:ACP:cSHnNw4v7MhdAGuQ1QF0PnuVOh1PFVBz0u2hlzx81uMR7GJMUBGe08XIKmb/SE7WvMpeprAPPSQw
gQd+N+fOdA==

In Chrome debugger it shows as below


问:
Adding list item is not adding all innerHTML
for part of a learning project I'm making I've run into a weird javascript/html issue. The section in question is a simple to do list, which works perfectly fine except for one thing. The program will successfully grab the text the user enters, add it to a new list item and insert it into the unordered list, but only adds an X (for a remove function I haven't added yet) to the first element.

Additionally, if you check in the browser inspector, both new li's do have the 'a' element with the X inside of it, but on hovering over the a element in both li's (or more li's depending) they all "point" back to the one and only 'a' element on the first li.

Can anyone explain what I did wrong so that I can fix it and avoid this in the future? Why is it not adding the 'a' element individually to each new li?

I've included a jsfiddle link below:

```<code> const li = document.createElement('li');
  // add li class
  li.className = 'list-item';
  // append text node containing user input to li item
  li.appendChild(document.createTextNode(taskList.value));
  // create 'a' element to list and add classes/html
  const link = document.createElement('a');
  link.className = 'delete-item';
  link.innerHTML = '<i class="fa fa-remove"></i>';

  // append 'a' element to li
  li.appendChild(link);
  document.querySelector('.list-items').append(li);
</code>```

https://jsfiddle.net/Iahon/xocpb6n7/11/

答:
It works but your styles complicated that. Look here:
https://jsfiddle.net/kedao6xm/

I removed the position:absolute from .container .row2 .to-doList .list-items .list-item .delete-item

You need to careful with that css property. All of your elements were added correctly but they were placed in the exact same position :)

EDIT: Look at the above link please one more time:
X is now aligned without the float:right.

Your X is still positioned as absolute but the list item has position:relative which fixes the issue :)

Body:
for part of a learning project I'm making I've run into a weird javascript/html issue. The section in question is a simple to do list, which works perfectly fine except for one thing. The program will successfully grab the text the user enters, add it to a new list item and insert it into the unordered list, but only adds an X (for a remove function I haven't added yet) to the first element.

Additionally, if you check in the browser inspector, both new li's do have the 'a' element with the X inside of it, but on hovering over the a element in both li's (or more li's depending) they all "point" back to the one and only 'a' element on the first li.

Can anyone explain what I did wrong so that I can fix it and avoid this in the future? Why is it not adding the 'a' element individually to each new li?

I've included a jsfiddle link below:

 const li = document.createElement('li');
  // add li class
  li.className = 'list-item';
  // append text node containing user input to li item
  li.appendChild(document.createTextNode(taskList.value));
  // create 'a' element to list and add classes/html
  const link = document.createElement('a');
  link.className = 'delete-item';
  link.innerHTML = '';

  // append 'a' element to li
  li.appendChild(link);
  document.querySelector('.list-items').append(li);

https://jsfiddle.net/Iahon/xocpb6n7/11/


问:
bash script to rename files based on a calculation
I have a file system containing PNG images.  The layout of the filesystem is: ZOOM/X/Y.png where ZOOM, X, and Y are all integers.

I need to change the names of the PNG files.  Basically, I need to convert Y from its current value to 2^ZOOM-Y-1.  I've written a bash script to accomplish this task.  However, I suspect it can be optimized substantially.  (I also suspect that I may have been better off writing it in Perl, but that is another story.)

Here is the script.  Is this about as good as it gets?  Or can the performance be optimized?  Are there tools I can use that would profile the script for me and tell me where I'm spending all my execution time?

```<code>#!/bin/bash

tiles=`ls -d */*/*`

for oldPath in $tiles
do
   oldY=`basename -s .png $oldPath`
   zoomX=`dirname $oldPath`
   zoom=`echo $zoomX | sed 's#\([^\]\)/.*#\1#'`
   newY=`echo 2^$zoom-$oldY-1|bc`
   mv ${zoomX}/${oldY}.png ${zoomX}/${newY}.png
done
</code>```

答:
one precept of computing credited to Donald Knuth is, "don't optimize too early."  Scripts run pretty fast and 'mv' operations(as long as they're not going across filesystems where you're really copying it to another disk and then deleting the file) are pretty fast as well, as all the filesystem has to do in most cases is just rename the file or change its parentage.

   Probably where it's spending most of its time is in that intial 'ls' operation.  I suspect you have ALOT of files.  There isn't much that can be done there.  Doing it another language like perl or python is going to face the same hurdle.  However you might be able to get more INTELLIGENCE and not limit yourself to 3 levels(//*).

Body:
I have a file system containing PNG images.  The layout of the filesystem is: ZOOM/X/Y.png where ZOOM, X, and Y are all integers.

I need to change the names of the PNG files.  Basically, I need to convert Y from its current value to 2^ZOOM-Y-1.  I've written a bash script to accomplish this task.  However, I suspect it can be optimized substantially.  (I also suspect that I may have been better off writing it in Perl, but that is another story.)

Here is the script.  Is this about as good as it gets?  Or can the performance be optimized?  Are there tools I can use that would profile the script for me and tell me where I'm spending all my execution time?

#!/bin/bash

tiles=`ls -d */*/*`

for oldPath in $tiles
do
   oldY=`basename -s .png $oldPath`
   zoomX=`dirname $oldPath`
   zoom=`echo $zoomX | sed 's#\([^\]\)/.*#\1#'`
   newY=`echo 2^$zoom-$oldY-1|bc`
   mv ${zoomX}/${oldY}.png ${zoomX}/${newY}.png
done