问:
Using Topshelf and Quartz.NET
I'm having problems setting up a basic Quartz.NET and Topshelf integration.

Errors appear when accessing ScheduleQuartzJob:

```<code>Error   1   Delegate 'System.Func<ServiceTest.MyService>' does not take 1 arguments
Error   2   Not all code paths return a value in lambda expression of type 'System.Func<Topshelf.Runtime.HostSettings,ServiceTest.MyService>'
Error   3   'Topshelf.Runtime.HostSettings' does not contain a definition for 'ConstructUsing' and the best extension method overload 'Topshelf.ServiceConfiguratorExtensions.ConstructUsing<T>(Topshelf.ServiceConfigurators.ServiceConfigurator<T>, System.Func<T>)' has some invalid arguments
Error   4   Instance argument: cannot convert from 'Topshelf.Runtime.HostSettings' to 'Topshelf.ServiceConfigurators.ServiceConfigurator<ServiceTest.MyService>'
Error   5   'Topshelf.Runtime.HostSettings' does not contain a definition for 'WhenStarted' and no extension method 'WhenStarted' accepting a first argument of type 'Topshelf.Runtime.HostSettings' could be found (are you missing a using directive or an assembly reference?)
Error   6   'Topshelf.Runtime.HostSettings' does not contain a definition for 'WhenStopped' and no extension method 'WhenStopped' accepting a first argument of type 'Topshelf.Runtime.HostSettings' could be found (are you missing a using directive or an assembly reference?)
Error   7   'Topshelf.ServiceConfigurators.ServiceConfigurator<ServiceTest.MyService>' does not contain a definition for 'ScheduleQuartzJob' and no extension method 'ScheduleQuartzJob' accepting a first argument of type 'Topshelf.ServiceConfigurators.ServiceConfigurator<ServiceTest.MyService>' could be found (are you missing a using directive or an assembly reference?)
</code>```

I think I am missing something obvious here...

Side question: Is there a simpler way to set up a Quartz/Topshelf configuration?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using NLog;
using Quartz;
using Quartz.Impl;
using Common.Logging.Configuration;
using Common.Logging.NLog;
using Topshelf;

namespace ServiceTest
{
    public class MyService
    {
        public bool Start(HostControl control)
        {
            return true;
        }

        public bool Stop(HostControl control)
        {
            return true;
        }
    }

    public class Program
    {
        private static Logger log = LogManager.GetCurrentClassLogger();

        public static void Main(string[] args)
        {
            var config = new NameValueCollection();
            var adaptor = new NLogLoggerFactoryAdapter(config);
            Common.Logging.LogManager.Adapter = adaptor;

            HostFactory.Run(x =>
            {
                x.Service<MyService>(sc =>
                {
                    sc.ConstructUsing(() => new MyService());
                    sc.WhenStarted((service, control) => service.Start(control));
                    sc.WhenStopped((service, control) => service.Stop(control));

                    sc.ScheduleQuartzJob(q =>
                        q.WithJob(() =>
                            JobBuilder.Create<MyJob>().Build())
                            .AddTrigger(() => TriggerBuilder.Create()
                                .WithSimpleSchedule(b => b
                                    .WithIntervalInSeconds(10)
                                    .RepeatForever())
                                .Build()));
                });
                x.RunAsLocalSystem()
                    .DependsOnEventLog()
                    .StartAutomatically()
                    .EnableServiceRecovery(rc => rc.RestartService(1));

                x.SetDescription("Checker Service");
                x.SetDisplayName("Checker Service");
                x.SetServiceName("CheckerService");
                x.UseNLog();
            });

        }
    }

    public class MyJob : IJob
    {
        private static Logger log = LogManager.GetCurrentClassLogger();

        public void Execute(IJobExecutionContext context)
        {
            log.Info("It is {0} and all is well", DateTime.UtcNow);
        }
    }
}```

答:
Needed to add a reference to Topshelf.Quartz!

I knew it was something stupid and simple.

Title: Using Topshelf and Quartz.NET

Body:
I'm having problems setting up a basic Quartz.NET and Topshelf integration.

Errors appear when accessing ScheduleQuartzJob:

Error   1   Delegate 'System.Func<ServiceTest.MyService>' does not take 1 arguments
Error   2   Not all code paths return a value in lambda expression of type 'System.Func<Topshelf.Runtime.HostSettings,ServiceTest.MyService>'
Error   3   'Topshelf.Runtime.HostSettings' does not contain a definition for 'ConstructUsing' and the best extension method overload 'Topshelf.ServiceConfiguratorExtensions.ConstructUsing<T>(Topshelf.ServiceConfigurators.ServiceConfigurator<T>, System.Func<T>)' has some invalid arguments
Error   4   Instance argument: cannot convert from 'Topshelf.Runtime.HostSettings' to 'Topshelf.ServiceConfigurators.ServiceConfigurator<ServiceTest.MyService>'
Error   5   'Topshelf.Runtime.HostSettings' does not contain a definition for 'WhenStarted' and no extension method 'WhenStarted' accepting a first argument of type 'Topshelf.Runtime.HostSettings' could be found (are you missing a using directive or an assembly reference?)
Error   6   'Topshelf.Runtime.HostSettings' does not contain a definition for 'WhenStopped' and no extension method 'WhenStopped' accepting a first argument of type 'Topshelf.Runtime.HostSettings' could be found (are you missing a using directive or an assembly reference?)
Error   7   'Topshelf.ServiceConfigurators.ServiceConfigurator<ServiceTest.MyService>' does not contain a definition for 'ScheduleQuartzJob' and no extension method 'ScheduleQuartzJob' accepting a first argument of type 'Topshelf.ServiceConfigurators.ServiceConfigurator<ServiceTest.MyService>' could be found (are you missing a using directive or an assembly reference?)

I think I am missing something obvious here...

Side question: Is there a simpler way to set up a Quartz/Topshelf configuration?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using NLog;
using Quartz;
using Quartz.Impl;
using Common.Logging.Configuration;
using Common.Logging.NLog;
using Topshelf;

namespace ServiceTest
{
    public class MyService
    {
        public bool Start(HostControl control)
        {
            return true;
        }

        public bool Stop(HostControl control)
        {
            return true;
        }
    }

    public class Program
    {
        private static Logger log = LogManager.GetCurrentClassLogger();

        public static void Main(string[] args)
        {
            var config = new NameValueCollection();
            var adaptor = new NLogLoggerFactoryAdapter(config);
            Common.Logging.LogManager.Adapter = adaptor;

            HostFactory.Run(x =>
            {
                x.Service<MyService>(sc =>
                {
                    sc.ConstructUsing(() => new MyService());
                    sc.WhenStarted((service, control) => service.Start(control));
                    sc.WhenStopped((service, control) => service.Stop(control));

                    sc.ScheduleQuartzJob(q =>
                        q.WithJob(() =>
                            JobBuilder.Create<MyJob>().Build())
                            .AddTrigger(() => TriggerBuilder.Create()
                                .WithSimpleSchedule(b => b
                                    .WithIntervalInSeconds(10)
                                    .RepeatForever())
                                .Build()));
                });
                x.RunAsLocalSystem()
                    .DependsOnEventLog()
                    .StartAutomatically()
                    .EnableServiceRecovery(rc => rc.RestartService(1));

                x.SetDescription("Checker Service");
                x.SetDisplayName("Checker Service");
                x.SetServiceName("CheckerService");
                x.UseNLog();
            });

        }
    }

    public class MyJob : IJob
    {
        private static Logger log = LogManager.GetCurrentClassLogger();

        public void Execute(IJobExecutionContext context)
        {
            log.Info("It is {0} and all is well", DateTime.UtcNow);
        }
    }
}


来源: stackexchange

问:
File.getCanonicalPath() failure examples
Does anyone have an experience or know when the method File.getCanonicalPath() will throw an IOException

I have tried to look up from the Internet and the best answer is in File API which says

"IOException - If an I/O error occurs, which is possible because the construction of the canonical pathname may require filesystem queries"

However, it is not clear to me because I still cannot think of a case which this might fail. Can anyone give me concrete examples which can happen on Linux, Windows and other OS (optional)?

I reason I want to know is because I want to handle this exception accordingly. Thus, it will be best if I know all the possible failures that can happen.

答:
Seen here in the Sun Bug Database.

For JRE 1.4.2_06, File.getCanonicalPath() wasn't working on Windows for a removable drive when there is no media present in the drive.

It was corrected in Java 1.5, but you can see there can be OS-based problems with this method.

I don't know of any problem in the current time, but it can happen, that's exactly what the Javadoc says. Usually it's quickly fixed in the newest Java version.

ContentLicense: CC BY-SA 2.5


问:
Add NSTableView To SpriteKit app
I finally created a NSTableView programmatically. I added an NSScrollView to it, but for some reason it doesn't show the scroll. If I add more and more objects to the table it grows in height and I want it to remain the same height. How can this be done? Here's the code below that I've cobbled together.

```<code>#import "GameScene.h"

@interface GameScene()

@property NSMutableArray *data;

@end

@implementation GameScene

- (void)didMoveToView:(SKView *)view {
    _data = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", nil];

    NSRect rect = NSMakeRect(300, 200, 400, 100);
    _tableView = [[NSTableView alloc] initWithFrame:rect];
    [_tableView addTableColumn:[[NSTableColumn alloc] initWithIdentifier:@"column 1"]];
    _tableView.dataSource = self;
    _tableView.delegate = self;

    NSScrollView *scrollView = [[NSScrollView alloc] init];
    [scrollView setHasVerticalScroller:YES];
    [scrollView setDocumentView:self.tableView];

    [self.view addSubview:_tableView];
}

-(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    return [_data count];
}

-(NSView*)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    NSTextView *textView = [[NSTextView alloc] init];
    textView.string = [_data objectAtIndex:row];
    return textView;
}

-(void)update:(CFTimeInterval)currentTime {
    // Called before each frame is rendered
}

-(void)removeUIViews{
    [_tableView removeFromSuperview];
}

@end
</code>```

Here's what it looks like with 8 elements in the data array:

Here's what it looks like with 16 elements in the data array (taller table):

答:
[self.view addSubview:_tableView]; moves the table view from the scrollview/clipview to self.view.

[self.view addSubview:scrollView]; adds the scroll view with the table view to self.view.

ContentLicense: CC BY-SA 3.0

Title: Add NSTableView To SpriteKit app

Body:
I finally created a NSTableView programmatically. I added an NSScrollView to it, but for some reason it doesn't show the scroll. If I add more and more objects to the table it grows in height and I want it to remain the same height. How can this be done? Here's the code below that I've cobbled together.

#import "GameScene.h"

@interface GameScene()

@property NSMutableArray *data;

@end

@implementation GameScene

- (void)didMoveToView:(SKView *)view {
    _data = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", nil];

    NSRect rect = NSMakeRect(300, 200, 400, 100);
    _tableView = [[NSTableView alloc] initWithFrame:rect];
    [_tableView addTableColumn:[[NSTableColumn alloc] initWithIdentifier:@"column 1"]];
    _tableView.dataSource = self;
    _tableView.delegate = self;

    NSScrollView *scrollView = [[NSScrollView alloc] init];
    [scrollView setHasVerticalScroller:YES];
    [scrollView setDocumentView:self.tableView];

    [self.view addSubview:_tableView];
}

-(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    return [_data count];
}

-(NSView*)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    NSTextView *textView = [[NSTextView alloc] init];
    textView.string = [_data objectAtIndex:row];
    return textView;
}

-(void)update:(CFTimeInterval)currentTime {
    // Called before each frame is rendered
}

-(void)removeUIViews{
    [_tableView removeFromSuperview];
}

@end

Here's what it looks like with 8 elements in the data array:

Here's what it looks like with 16 elements in the data array (taller table):


问:
Using ASP.NET MVC or Web API 2 backend + Angular for dashboard platform
I am trying to create a web-based dashboard platform and framework. The techniques I think about using is either ASP.NET MVC 5/6 (backend and frontend integrated) or a ASP.NET Web API 2 backend and an Angular frontend.

The application should function as an application (host), but also as a framework in which applications can be made. An application in this case is a small web application which can be shown on the dashboards.  One of the main bottlenecks I came across is figuring out a way to instantiate the same application multiple times on a dashboard. Since by default doing this introduces ID collision between multiple HTML elements on the web page.

I know Angular kind of 'solves' this problem for you since the scope of your application (looking at an application like it's a component) is maintained by the Angular framework. The reason I mention ASP.NET Web API is because I'd then like to use this as a backend where all the configurations of the applications is stored.

ASP.NET MVC does not (as far as I know) allows you nice ways to handle this, except for rendering the HTML on the server and replacing all HTML ID's to something unique. But even when you manage to do that, you still have the issue of your js files referring to the old not-unique HTML elements. This could then maybe be fixed by using a JS framework that allows you to do such thing.

The reason I ask this question is because I have a lot of experience in the .NET framework and very little experience using Angular. The choice for Angular seems more suited for this use case, but due to my lack of experience in Angular, I am not able to make an arguable choice. I have some experience in ASP.NET MVC specifically, but not enough to also think of a nice way of handling the ID collision issue.

Therefore my question to you, the StackOverflow community, is do you have any experience using any of these frameworks? And if so, what would you choose and why do you think the choice is better suited for the job?

答: Use angular 2 (or 4) and webapi. Through use of components and parameterized directives, that can solve it. If you need good authentication, that will have to be dealt separately.</p>


问:
Run winform application with terminal command, with the configuration xml file given as command argument
The batch testing requires calling existing winforms application (say MyApp.exe) from the terminal, using the configuration stored in the .xml file in the same directory as .exe (say MyAppConfig.xml). Which changes should I make on the application in order to be able to call start /realtime c:\MyApp.exe /config="MyAppConfig.xml" from terminal. Would anyone be able to point me in the right direction on how to implement this feature? Help appreciated.

答:
When building a console or forms application the Main method usually serves as the entrypoint for the code. It takes an array of strings as a parameter that gets passed down from the CLI.

```<code>public static void Main(string[] args)
{
   for(int i = 0; i < args.Length; i++)
   {
       Console.WriteLine("Argument #{0} = {1}", i, args[i]);
   }
}
</code>```

So running program.exe FOO BAR would result in :

```<code>Argument #0 = FOO
Argument #1 = BAR
</code>```

You could also use program.exe config="MyAppConfig.xml" notation to make the arguments order-independant, but you would have to do some parsing yourself.

Body:
When building a console or forms application the Main method usually serves as the entrypoint for the code. It takes an array of strings as a parameter that gets passed down from the CLI.

public static void Main(string[] args)
{
   for(int i = 0; i < args.Length; i++)
   {
       Console.WriteLine("Argument #{0} = {1}", i, args[i]);
   }
}

So running program.exe FOO BAR would result in :

Argument #0 = FOO
Argument #1 = BAR

You could also use program.exe config="MyAppConfig.xml" notation to make the arguments order-independant, but you would have to do some parsing yourself.


问:
Getting bus error while adding ascii values to array characters. Why? (C)
```<code>#include <stdio.h>

char    *ft_strupcase(char *str);

char    *ft_strupcase(char *str)
{
    int i;

    i = 0;
    while (str[i])
    {
        if (str[i] >= 'a' && str[i] <= 'z')
        {
             str[i] -= 32;
        }
        i++;
    }
    return (str);
}

int main(void)
{
    char *test = ft_strupcase("fdfFEhk");
    for (int k = 0; test[k] != '\0'; k++)
    {
        printf("%c", test[k]);
    }
    return (0);
}
</code>```

The expected result is to print the string passed to the function, all in capital letters. Instead, I get a bus error. Why and how can I fix this?

答:
This is undefined behaviour as you are modifying string literal using ft_strupcase function

Rewrite your code to:

```<code>char source[] = "fdfFEhk";
char *test = ft_strupcase(source);
</code>```

Now your string is not string literal anymore and is copied to RAM everytime source variable is initialized. Therefore, you have defined behaviour.

Body:
#include <stdio.h>

char    *ft_strupcase(char *str);

char    *ft_strupcase(char *str)
{
    int i;

    i = 0;
    while (str[i])
    {
        if (str[i] >= 'a' && str[i] <= 'z')
        {
             str[i] -= 32;
        }
        i++;
    }
    return (str);
}

int main(void)
{
    char *test = ft_strupcase("fdfFEhk");
    for (int k = 0; test[k] != '\0'; k++)
    {
        printf("%c", test[k]);
    }
    return (0);
}

The expected result is to print the string passed to the function, all in capital letters. Instead, I get a bus error. Why and how can I fix this?

Body:
This is undefined behaviour as you are modifying string literal using ft_strupcase function

Rewrite your code to:

char source[] = "fdfFEhk";
char *test = ft_strupcase(source);

Now your string is not string literal anymore and is copied to RAM everytime source variable is initialized. Therefore, you have defined behaviour.


问:
DOM XML Public Doctype not appearing in result xml file
I have written a code to generate XML files. I am stuck at defining doctype for the XML as it should be public. I am able to get SYSTEM doctype successfully but somehow not able to get public doctype written in XML. Below code for SYSTEM doctype is working but same snippet for PUBLIC doctype is not working : </p>

```<code>String xmldestpath = "C:/failed/tester.xml";
        doctype2 = CreateDoctypeString();

        StreamResult result =  new StreamResult(new File(xmldestpath ));
          try {
              transformer = transformerFactory.newTransformer();
              transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"TEST");
              transformer.transform(source, result);
    //        logger.debug("COMPLETED Copying xml files /....!!");

            System.out.println("COMPLETED Copying xml files to bulk import....!!");
</code>```

<p>Not working snippet. Its not giving error but no doctype is appearing in resultant xml: </p>

```<code> String xmldestpath = "C:/failed/tester.xml";
    doctype2 = CreateDoctypeString();

    StreamResult result =  new StreamResult(new File(xmldestpath ));
      try {
          transformer = transformerFactory.newTransformer();
          transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"TEST");
          transformer.transform(source, result);
//        //logger.debug("COMPLETED Copying xml files /....!!");

        System.out.println("COMPLETED Copying xml files to bulk import....!!");
</code>```

答:
If you know you need/want PUBLIC, perhaps you should know that a public literal cannot exist without a system literal.

The XML specification shows:

```<code>ExternalID  ::=  'SYSTEM' S SystemLiteral
                 | 'PUBLIC' S PubidLiteral S SystemLiteral
</code>```

So it should be easy to conclude that you need to specify both in order to get it to work, as demonstrated by this MCVE:

```<code>TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "TEST1");
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "TEST2");
transformer.transform(new StreamSource(new StringReader("<Root></Root>")),
                      new StreamResult(System.out));
</code>```

Output

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE Root PUBLIC "TEST1" "TEST2">
<Root/>
```

Body:
I have written a code to generate XML files. I am stuck at defining doctype for the XML as it should be public. I am able to get SYSTEM doctype successfully but somehow not able to get public doctype written in XML. Below code for SYSTEM doctype is working but same snippet for PUBLIC doctype is not working :

String xmldestpath = "C:/failed/tester.xml";
        doctype2 = CreateDoctypeString();

        StreamResult result =  new StreamResult(new File(xmldestpath ));
          try {
              transformer = transformerFactory.newTransformer();
              transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"TEST");
              transformer.transform(source, result);
    //        logger.debug("COMPLETED Copying xml files /....!!");

            System.out.println("COMPLETED Copying xml files to bulk import....!!");

Not working snippet. Its not giving error but no doctype is appearing in resultant xml:

 String xmldestpath = "C:/failed/tester.xml";
    doctype2 = CreateDoctypeString();

    StreamResult result =  new StreamResult(new File(xmldestpath ));
      try {
          transformer = transformerFactory.newTransformer();
          transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"TEST");
          transformer.transform(source, result);
//        //logger.debug("COMPLETED Copying xml files /....!!");

        System.out.println("COMPLETED Copying xml files to bulk import....!!");

Body:
If you know you need/want PUBLIC, perhaps you should know that a public literal cannot exist without a system literal.

The XML specification shows:

ExternalID  ::=  'SYSTEM' S SystemLiteral
                 | 'PUBLIC' S PubidLiteral S SystemLiteral

So it should be easy to conclude that you need to specify both in order to get it to work, as demonstrated by this MCVE:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "TEST1");
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "TEST2");
transformer.transform(new StreamSource(new StringReader("<Root></Root>")),
                      new StreamResult(System.out));

Output

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE Root PUBLIC "TEST1" "TEST2">
<Root/>


问:
Python home directory in Windows / Problem with multiple versions
I'm using Python 3 for developing and CollabNet Subversion Edge as versioning software. Subversion Edge comes with a little program called ViewVC which is written in Python 2, which is also directly bundled with it. There is a system environment variable called PYTHONHOME.

If it is set to the Python 2 distribution from Subversion Edge, my Python 3 won't start (not even IDLE), instead giving a runtime error messagebox.

If it is set to Python 3, ViewVC doesn't work.

Is there a way to make both work at the same time?

答: You shouldn't need to set PYTHONHOME at all. Python uses it (if set) to locate its installation. Typically, it should be able to locate it without this variable, as well: by looking at the path name of the python executable, and, failing that, by looking into the registry.</p>


答:
In your application's Program.cs file you'll find your applications entry point, Main() method. Change its signature and add string array which will hold parameters. Then, check for parameters and implement your logic.

Something like this:

```<code>static void Main(string[] startArgs)
{
    if (startArgs.Length == 0)
    {
        //show messagebox stating that there's no parameters or something else
    }
    else
    {
        var configArg = startArgs.FirstOrDefault(s => s.StartsWith("config"));
        if (configArg == null)
        {
            //config parameter is missing
        }
        else
        {
            string xml = configArg.Split('=')[1];
            //xml holds your path to your xml file.
            //Now you can pass it to form, or load it here

            //XmlDocument doc = new XmlDocument();
            //doc.Load(xml);
            //etc...
        }

    }

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}
</code>```

If you plan to have multiple command line parameters, you should look for NET CLI library which is .net port of the apache commons cli API, used for parsing command line arguments...

Title: Run winform application with terminal command, with the configuration xml file given as command argument

Body: The batch testing requires calling existing winforms application (say MyApp.exe) from the terminal, using the configuration stored in the .xml file in the same directory as .exe (say MyAppConfig.xml). Which changes should I make on the application in order to be able to call start /realtime c:\MyApp.exe /config="MyAppConfig.xml" from terminal. Would anyone be able to point me in the right direction on how to implement this feature? Help appreciated.

Body:
In your application's Program.cs file you'll find your applications entry point, Main() method. Change its signature and add string array which will hold parameters. Then, check for parameters and implement your logic.

Something like this:

static void Main(string[] startArgs)
{
    if (startArgs.Length == 0)
    {
        //show messagebox stating that there's no parameters or something else
    }
    else
    {
        var configArg = startArgs.FirstOrDefault(s => s.StartsWith("config"));
        if (configArg == null)
        {
            //config parameter is missing
        }
        else
        {
            string xml = configArg.Split('=')[1];
            //xml holds your path to your xml file.
            //Now you can pass it to form, or load it here

            //XmlDocument doc = new XmlDocument();
            //doc.Load(xml);
            //etc...
        }

    }

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}

If you plan to have multiple command line parameters, you should look for NET CLI library which is .net port of the apache commons cli API, used for parsing command line arguments...


问:
MS SQL variable add value from count in the same statement
I have this Select statement

```<code>select Id, UserName, from UserTable where Department= @DepartmentInput
</code>```

and a variable to calculate how many users from the department

```<code>@UserCounter
</code>```

Is there a way to add count(the number of users from the department) into @UserCounter from the select statement should the statement runs in a while loop?

答:
Presuming sql-server:

```<code>select Id, UserName, @UserCounter = Count(*) OVER (Partition By Department)
from UserTable
where Department= @DepartmentInput
</code>```

Otherwise a simple sub-query should work too:

```<code>select Id, UserName, @UserCounter = (select count(*) from UserTable
                                     where Department= @DepartmentInput)
from UserTable
where Department= @DepartmentInput
</code>```

The database should be clever enough to optimize that query so that the subquery doesn't need to be avaulated for every (matching) row.

Body:
I have this Select statement

select Id, UserName, from UserTable where Department= @DepartmentInput

and a variable to calculate how many users from the department

@UserCounter

Is there a way to add count(the number of users from the department) into @UserCounter from the select statement should the statement runs in a while loop?

Body:
Presuming sql-server:

select Id, UserName, @UserCounter = Count(*) OVER (Partition By Department)
from UserTable
where Department= @DepartmentInput

Otherwise a simple sub-query should work too:

select Id, UserName, @UserCounter = (select count(*) from UserTable
                                     where Department= @DepartmentInput)
from UserTable
where Department= @DepartmentInput

The database should be clever enough to optimize that query so that the subquery doesn't need to be avaulated for every (matching) row.


问:
How can I parse this JSON object using Swift 3.0
I'm trying to parse a JSON string returned from a new API. The returned JSON string looks like this.

```<code>QuerySearchResult":{
"StartAt":"1",
"Count":"40",
"TotalAvailable":"500",
"Items":[
    {"TITLE":"OST420 Generation",
    "PATH":"http:\\Test.pdf",
    "WRITE":"2016-12-12T15:47:42",
    "RANK":"32286574",
    "SIZE":"145091",
    "ISDOCUMENT":"true",
    "ID":"18548",
    "WPTASK":"Onsite Generation",
    "WPDOCTYPE":"Local Operating Procedure",
    "WPDOCREFID":"304580",
    "WPCONTENTTYPE":"Document"},
    {"TITLE":"OST420 Measurement",
    "PATH":"http:\Test33.pdf",
    .
    .
</code>```

I'm using the code below which accepts the JSON variable but fails when I try to load item. I've tried using Array around Dictionary but it still fails. What declaration do I need to read in Items?

```<code>if let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as? Dictionary<String, AnyObject> {
   for item in json {
      if let dict = item as? Dictionary<String, AnyObject> {
         if let items = json["Items"] as? Array<Dictionary<String, AnyObject>> {
            for rec in items {
               if let title = rec["TITLE"] as? String {
                  let xx = title
               }
            }
        }
   }
}
</code>```

答:
In Swift 3.1 :-

```<code>func parseJson(anyObj:AnyObject) {

            if  let anyObj = anyObj as? Array<Dictionary<String,AnyObject>> {
                self.yourArrayName = anyObj.flatMap({yourModelName(json:$0) })
            }
        }
</code>```

Body:
I'm trying to parse a JSON string returned from a new API. The returned JSON string looks like this.

QuerySearchResult":{
"StartAt":"1",
"Count":"40",
"TotalAvailable":"500",
"Items":[
    {"TITLE":"OST420 Generation",
    "PATH":"http:\\Test.pdf",
    "WRITE":"2016-12-12T15:47:42",
    "RANK":"32286574",
    "SIZE":"145091",
    "ISDOCUMENT":"true",
    "ID":"18548",
    "WPTASK":"Onsite Generation",
    "WPDOCTYPE":"Local Operating Procedure",
    "WPDOCREFID":"304580",
    "WPCONTENTTYPE":"Document"},
    {"TITLE":"OST420 Measurement",
    "PATH":"http:\Test33.pdf",
    .
    .

I'm using the code below which accepts the JSON variable but fails when I try to load item. I've tried using Array around Dictionary but it still fails. What declaration do I need to read in Items?

if let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as? Dictionary<String, AnyObject> {
   for item in json {
      if let dict = item as? Dictionary<String, AnyObject> {
         if let items = json["Items"] as? Array<Dictionary<String, AnyObject>> {
            for rec in items {
               if let title = rec["TITLE"] as? String {
                  let xx = title
               }
            }
        }
   }
}

Body:
In Swift 3.1 :-

func parseJson(anyObj:AnyObject) {

            if  let anyObj = anyObj as? Array<Dictionary<String,AnyObject>> {
                self.yourArrayName = anyObj.flatMap({yourModelName(json:$0) })
            }
        }


问:
OBIEE 12.2.1.2 - Custom Data Format for numeric values
I am facing problems with the custom data format in the latest OBI release.

The following format is used and I have problems in dealing with null values - in this case significant digits, which I still want to be displayed:

```<code>+$#0,#.0,,M;-$#0,#.0,,M
</code>```

Resulting in (picture 1):

Removing the first '0' results in (picture 2):

Is there another -global- option (without adding an extra calculation in criteria tab) for this display? Ideas and suggestions are much appreciated!

答:
If I understand this correctly, the format string should look like

```<code>+$#,#0.0,,M;-$#,#0.0,,M
</code>```

to get the result you want.

Explanation

The dot will be replaced with the separator from your locale. So if you are using e.g. the german locale, a number like

```<code>123,00
</code>```

with a formatting like this

```<code>#0.0
</code>```

would be written like

```<code>123,0
</code>```

The comma in the string is the thousands separator. This will also be replaced by the separator of your locale. Again, with the german example the comma would be replaced.

Body:
I am facing problems with the custom data format in the latest OBI release.

The following format is used and I have problems in dealing with null values - in this case significant digits, which I still want to be displayed:

+$#0,#.0,,M;-$#0,#.0,,M

Resulting in (picture 1):

Removing the first '0' results in (picture 2):

Is there another -global- option (without adding an extra calculation in criteria tab) for this display? Ideas and suggestions are much appreciated!

Body:
If I understand this correctly, the format string should look like

+$#,#0.0,,M;-$#,#0.0,,M

to get the result you want.

Explanation

The dot will be replaced with the separator from your locale. So if you are using e.g. the german locale, a number like

123,00

with a formatting like this

#0.0

would be written like

123,0

The comma in the string is the thousands separator. This will also be replaced by the separator of your locale. Again, with the german example the comma would be replaced.


问:
Internet permission
I have app gradle like that

```<code>apply plugin: 'com.android.application'

android {

    compileSdkVersion 24
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.ahmed.bigovenrecipes"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {

        release {

            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {

        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
    compile 'com.squareup.picasso:picasso:2.3.3'
    testCompile 'junit:junit:4.12'
}
</code>```

and I want to put Internet permission put I don't know in which part.

答:
Just add the following code in your AndroidManifest.xml file:

```<code><uses-permission android:name="android.permission.INTERNET" />
</code>```

Title: Internet permission

Body:
I have app gradle like that

apply plugin: 'com.android.application'

android {

    compileSdkVersion 24
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.ahmed.bigovenrecipes"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {

        release {

            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {

        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
    compile 'com.squareup.picasso:picasso:2.3.3'
    testCompile 'junit:junit:4.12'
}

and I want to put Internet permission put I don't know in which part.

Body:
Just add the following code in your AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET" />


问:
How can I create a PayPal link that will send money to a specific e-mail address?
This if for an internal CMS, so it's not public facing. I have my publishers that I need to pay via PayPal. I'd like to be able to click one link and it goes directly to a PayPal page with their email address filled in and a particular value.

Is this possible?

答:
For physical items

A basic setup for physical goods (with shipping):

```<code>https://www.paypal.com/cgi-bin/webscr?&cmd=_xclick&business=info@test.com&currency_code=EUR&amount=0.01&item_name=Test description
</code>```

It will add &item_name parameter that indicates to PayPal API that you are selling physical items that need to be shipped to the customer. A shipping address will be displayed on the payment screen and the items will be hidden behind a drop-down menu at the top/right corner (the shopping cart).

PayPal link generator (3rd party)

There is a pure JS lazy PayPal link generation tool over here:

http://www.itaynoy.com/sites/paypal_button_generator/

However, having shipping address displayed may be inconvenient if you sell services and the payment takes place afterwards.

For services

1) First option for a service would look like this:

```<code>https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=info@test.com&currency_code=EUR&amount=0.01&invoice=112233&custom=something
</code>```

Because you don't specify item_name or item_number, the buyer will be taken to a different checkout screen, more suitable for services. It will display company name and allow buyer to add description. You can use invoice and/or custom parameters to specify what the payment is for. However, I haven't found a way yet to make PayPal display invoice number, custom field, or pre-fill description input, so that the buyer would also see what he is paying for.

2) Second option for services is to combine item_name and no_shipping=1 parameters:

```<code>https://www.paypal.com/cgi-bin/webscr?&cmd=_xclick&business=info@test.com&currency_code=EUR&amount=0.01&item_name=Test description&no_shipping=1
</code>```

This will take the buyer to the physical items checkout screen, but without shipping address. It will not allow buyer to add description, but at least it will show the text from item_name parameter in cart (drop-down menu in top/right corner). It's not the best location to display services payment details, but it's something.

PayPal's documentation on the buttons/links:

https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/formbasics/
https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/

PayPal.me

PayPal.me is a relatively new service specially designed for payments through simple links. Unfortunately it doesn't allow (as of today) to specify what the payment is for. Not by the seller, nor by the buyer. You can't specify it as a parameter and there is no description field on the checkout page. Although PayPal.me has prettier URLs and checkout screen, for the above reason it is currently more suitable for exchanging money with family and friends than for sales.

Body:
For physical items

A basic setup for physical goods (with shipping):

https://www.paypal.com/cgi-bin/webscr?&cmd=_xclick&business=info@test.com&currency_code=EUR&amount=0.01&item_name=Test description

It will add &item_name parameter that indicates to PayPal API that you are selling physical items that need to be shipped to the customer. A shipping address will be displayed on the payment screen and the items will be hidden behind a drop-down menu at the top/right corner (the shopping cart).

PayPal link generator (3rd party)

There is a pure JS lazy PayPal link generation tool over here:

http://www.itaynoy.com/sites/paypal_button_generator/

However, having shipping address displayed may be inconvenient if you sell services and the payment takes place afterwards.

For services

1) First option for a service would look like this:

https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=info@test.com&currency_code=EUR&amount=0.01&invoice=112233&custom=something

Because you don't specify item_name or item_number, the buyer will be taken to a different checkout screen, more suitable for services. It will display company name and allow buyer to add description. You can use invoice and/or custom parameters to specify what the payment is for. However, I haven't found a way yet to make PayPal display invoice number, custom field, or pre-fill description input, so that the buyer would also see what he is paying for.

2) Second option for services is to combine item_name and no_shipping=1 parameters:

https://www.paypal.com/cgi-bin/webscr?&cmd=_xclick&business=info@test.com&currency_code=EUR&amount=0.01&item_name=Test description&no_shipping=1

This will take the buyer to the physical items checkout screen, but without shipping address. It will not allow buyer to add description, but at least it will show the text from item_name parameter in cart (drop-down menu in top/right corner). It's not the best location to display services payment details, but it's something.

PayPal's documentation on the buttons/links:

https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/formbasics/
https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/

PayPal.me

PayPal.me is a relatively new service specially designed for payments through simple links. Unfortunately it doesn't allow (as of today) to specify what the payment is for. Not by the seller, nor by the buyer. You can't specify it as a parameter and there is no description field on the checkout page. Although PayPal.me has prettier URLs and checkout screen, for the above reason it is currently more suitable for exchanging money with family and friends than for sales.


问:
Magrittr forward pipe fails to forward values into openXL::addWorksheet - "Error ...: First argument must be a Workbook"
magrittr appears to be failing to pipe 'workbook' class objects into the addWorkbook function from the package openxlsx.

(Never mind why I need to use excel...eugh yuk)

For example, to write the InsectSprays dataset to an excel file in 'base' syntax:

```<code>library("openxlsx")
insect.wb <- createWorkbook()
addWorksheet(wb = insect.wb,
             sheetName = "Insect Spray")
writeData(wb = insect.wb,
          sheet = "Insect Spray",
          x= InsectSprays)

openXL(insect.wb)
</code>```

Opens a temp excel file with the data.

So magrittr should

pipe a value forward into an expression or function call; something
  along the lines of x %>% f, rather than f(x)

But e.g.

```<code>library("openxlsx")
library("magrittr")
insect.wb <- createWorkbook()
insect.wb %>%
  addWorksheet(sheetName = "Insect Spray") %>%
  writeData(sheet = "Insect Spray",
            x= InsectSprays)
</code>```

Returns

```<code>Error in writeData(., sheet = "Insect Spray", x = InsectSprays) :
First argument must be a Workbook.
</code>```

But insect.wb is a workbook object:

```<code> > insect.wb <- createWorkbook()
 > class(insect.wb)

[1] "Workbook"
attr(,"package")
[1] "openxlsx"
</code>```

Which suggests that the issue is that the object isn't getting piped in...

Am I just buggering up the syntax, or is there a more interesting explanation for why this is failing?

For interest, there is no issue with forward pipe and writeData –- if we shift the use of forward-pipes until after addWorksheet, it also works fine:

```<code>insect.wb <- createWorkbook()
addWorksheet(wb = insect.wb,
             sheetName = "Insect Spray")

insect.wb %>%
  writeData(sheet = "Insect Spray",
            x= InsectSprays)

openXL(insect.wb)
</code>```

答:
In your command chain, writeData takes as a first input the output of insect.wb %>% addWorksheet(sheetName = "Insect Spray")

addWorksheet modifies directly the object, and doesn't return the object, so whatever you're passing to writeData is NOT a worksheet (from your comment, it's probably the number of sheets after the add).

You may use the operator %T>% and write

```<code>insect.wb %T>%
  addWorksheet(sheetName = "Insect Spray") %>%
  writeData(sheet = "Insect Spray", x= InsectSprays)
</code>```

%T>%starts a new chain in the sense that the ouput of the rhs is not returned, but the lhs is returned, so then writeData takes it where %T>% left, except that insect.wb has now been modified by addWorksheet.

Body:
magrittr appears to be failing to pipe 'workbook' class objects into the addWorkbook function from the package openxlsx.

(Never mind why I need to use excel...eugh yuk)

For example, to write the InsectSprays dataset to an excel file in 'base' syntax:

library("openxlsx")
insect.wb <- createWorkbook()
addWorksheet(wb = insect.wb,
             sheetName = "Insect Spray")
writeData(wb = insect.wb,
          sheet = "Insect Spray",
          x= InsectSprays)

openXL(insect.wb)

Opens a temp excel file with the data.

So magrittr should

pipe a value forward into an expression or function call; something
  along the lines of x %>% f, rather than f(x)

But e.g.

library("openxlsx")
library("magrittr")
insect.wb <- createWorkbook()
insect.wb %>%
  addWorksheet(sheetName = "Insect Spray") %>%
  writeData(sheet = "Insect Spray",
            x= InsectSprays)

Returns

Error in writeData(., sheet = "Insect Spray", x = InsectSprays) :
First argument must be a Workbook.

But insect.wb is a workbook object:

 > insect.wb <- createWorkbook()
 > class(insect.wb)

[1] "Workbook"
attr(,"package")
[1] "openxlsx"

Which suggests that the issue is that the object isn't getting piped in...

Am I just buggering up the syntax, or is there a more interesting explanation for why this is failing?

For interest, there is no issue with forward pipe and writeData –- if we shift the use of forward-pipes until after addWorksheet, it also works fine:

insect.wb <- createWorkbook()
addWorksheet(wb = insect.wb,
             sheetName = "Insect Spray")

insect.wb %>%
  writeData(sheet = "Insect Spray",
            x= InsectSprays)

openXL(insect.wb)

Body:
In your command chain, writeData takes as a first input the output of insect.wb %>% addWorksheet(sheetName = "Insect Spray")

addWorksheet modifies directly the object, and doesn't return the object, so whatever you're passing to writeData is NOT a worksheet (from your comment, it's probably the number of sheets after the add).

You may use the operator %T>% and write

insect.wb %T>%
  addWorksheet(sheetName = "Insect Spray") %>%
  writeData(sheet = "Insect Spray", x= InsectSprays)

%T>%starts a new chain in the sense that the ouput of the rhs is not returned, but the lhs is returned, so then writeData takes it where %T>% left, except that insect.wb has now been modified by addWorksheet.


问:
IOS Swift: Animating TableviewCell changes do not work correctly
I have a quite strange behaviour when updating a TableViews cells.

The easiest way to describe is a video:
https://drive.google.com/open?id=0B67InGf2FEPaODFLUEhLZ29LWTg

Here you can see, that the first time i try to expand(or collapse) the View, it sor of does something, but not really. The views that i wanted to show are not there, but it flickers.

Here is my Code:

```<code>class StylingTableViewController: UITableViewController {

//MARK: properties
var articles = [Article]()

override func viewDidLoad() {
    super.viewDidLoad()

    articles.append(contentsOf: [Article(id: "Artikel 1"), Article(id: "Artikel 2")])

    //Let table auto layout in height
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 100

    // Use the edit button item provided by the table view controller.
    navigationItem.rightBarButtonItem = editButtonItem
}

// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return articles.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // Table view cells are reused and should be dequeued using a cell identifier.
    let cellIdentifier = "ArticleDetailCell"

    guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? StylingDetailTableViewCell  else {
        fatalError("The dequeued cell is not an instance of StylingDetailTableViewCell.")
    }

    let article = articles[indexPath.row]
    cell.articleName.text = article.id

    //Scrollview
    let width:CGFloat = 90;
    var xPos:CGFloat = 0;
    var scrollViewContentSize:CGFloat=0;
    for _ in 0...10{
        let myView:CFPictureView = CFPictureView()
        myView.frame.size.width = 80
        myView.frame.size.height = 120
        myView.frame.origin.x = CGFloat(xPos)
        xPos += width
        cell.pictures_scrollView.addSubview(myView)
        scrollViewContentSize += width
        cell.pictures_scrollView.contentSize = CGSize(width: scrollViewContentSize, height: 120)
    }

    return cell
}

// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        // Delete the row from the data source
        articles.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
    } else if editingStyle == .insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}

//MARK: Actions
@IBAction func favButtonPressed(_ sender: UIButton) {
    sender.isSelected = !sender.isSelected
}
@IBAction func expandCell(_ sender: UIButton) {

    if let cell = sender.superview?.superview?.superview?.superview?.superview as? StylingDetailTableViewCell {
        cell.fieldDescriptorStackView.isHidden = false;
        cell.articleBarcode.isHidden = false;
        cell.articleCustomerNumber.isHidden = false;
        cell.articleStyle.isHidden = false;
        cell.expandCellButton.isHidden = true;
        cell.collapseCellButton.isHidden = false;
        cell.pictures_order.isHidden = false;
        cell.pictures_amount.isHidden = false;
        cell.pictures_scrollView.isHidden = false;
        cell.pictures_title.isHidden = false;

        let indexPath = tableView.indexPath(for: cell)
        self.tableView.reloadRows(at: [indexPath!], with: UITableViewRowAnimation.automatic)
        (self.parent as? StylingViewController)?.topStackView.isHidden = true;
    }

}
@IBAction func collapseCell(_ sender: UIButton) {

    if let cell = sender.superview?.superview?.superview as? StylingDetailTableViewCell {
        cell.fieldDescriptorStackView.isHidden = true;
        cell.articleBarcode.isHidden = true;
        cell.articleCustomerNumber.isHidden = true;
        cell.articleStyle.isHidden = true;
        cell.expandCellButton.isHidden = false;
        cell.collapseCellButton.isHidden = true;
        cell.pictures_order.isHidden = true;
        cell.pictures_amount.isHidden = true;
        cell.pictures_scrollView.isHidden = true;
        cell.pictures_title.isHidden = true;

        let indexPath = tableView.indexPath(for: cell)
        self.tableView.reloadRows(at: [indexPath!], with: UITableViewRowAnimation.automatic)
        (self.parent as? StylingViewController)?.topStackView.isHidden = false;
    }
}
func undoAction() {
    print("undo")

}
</code>```

}

It seems like something is wrong with tableView.reloadRows.
Help would be appreciated

答:
Could be the issue because the app still didint know the estimated height of the cell at first run.
A fix could be by adding this on viewDidLoad : </p>

```<code> tableView.estimatedRowHeight = 60
 tableView.rowHeight = UITableViewAutomaticDimension
</code>```

Body:
I have a quite strange behaviour when updating a TableViews cells.

The easiest way to describe is a video:
https://drive.google.com/open?id=0B67InGf2FEPaODFLUEhLZ29LWTg

Here you can see, that the first time i try to expand(or collapse) the View, it sor of does something, but not really. The views that i wanted to show are not there, but it flickers.

Here is my Code:

class StylingTableViewController: UITableViewController {

//MARK: properties
var articles = [Article]()

override func viewDidLoad() {
    super.viewDidLoad()

    articles.append(contentsOf: [Article(id: "Artikel 1"), Article(id: "Artikel 2")])

    //Let table auto layout in height
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 100

    // Use the edit button item provided by the table view controller.
    navigationItem.rightBarButtonItem = editButtonItem
}

// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return articles.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // Table view cells are reused and should be dequeued using a cell identifier.
    let cellIdentifier = "ArticleDetailCell"

    guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? StylingDetailTableViewCell  else {
        fatalError("The dequeued cell is not an instance of StylingDetailTableViewCell.")
    }

    let article = articles[indexPath.row]
    cell.articleName.text = article.id

    //Scrollview
    let width:CGFloat = 90;
    var xPos:CGFloat = 0;
    var scrollViewContentSize:CGFloat=0;
    for _ in 0...10{
        let myView:CFPictureView = CFPictureView()
        myView.frame.size.width = 80
        myView.frame.size.height = 120
        myView.frame.origin.x = CGFloat(xPos)
        xPos += width
        cell.pictures_scrollView.addSubview(myView)
        scrollViewContentSize += width
        cell.pictures_scrollView.contentSize = CGSize(width: scrollViewContentSize, height: 120)
    }

    return cell
}

// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        // Delete the row from the data source
        articles.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
    } else if editingStyle == .insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}

//MARK: Actions
@IBAction func favButtonPressed(_ sender: UIButton) {
    sender.isSelected = !sender.isSelected
}
@IBAction func expandCell(_ sender: UIButton) {

    if let cell = sender.superview?.superview?.superview?.superview?.superview as? StylingDetailTableViewCell {
        cell.fieldDescriptorStackView.isHidden = false;
        cell.articleBarcode.isHidden = false;
        cell.articleCustomerNumber.isHidden = false;
        cell.articleStyle.isHidden = false;
        cell.expandCellButton.isHidden = true;
        cell.collapseCellButton.isHidden = false;
        cell.pictures_order.isHidden = false;
        cell.pictures_amount.isHidden = false;
        cell.pictures_scrollView.isHidden = false;
        cell.pictures_title.isHidden = false;

        let indexPath = tableView.indexPath(for: cell)
        self.tableView.reloadRows(at: [indexPath!], with: UITableViewRowAnimation.automatic)
        (self.parent as? StylingViewController)?.topStackView.isHidden = true;
    }

}
@IBAction func collapseCell(_ sender: UIButton) {

    if let cell = sender.superview?.superview?.superview as? StylingDetailTableViewCell {
        cell.fieldDescriptorStackView.isHidden = true;
        cell.articleBarcode.isHidden = true;
        cell.articleCustomerNumber.isHidden = true;
        cell.articleStyle.isHidden = true;
        cell.expandCellButton.isHidden = false;
        cell.collapseCellButton.isHidden = true;
        cell.pictures_order.isHidden = true;
        cell.pictures_amount.isHidden = true;
        cell.pictures_scrollView.isHidden = true;
        cell.pictures_title.isHidden = true;

        let indexPath = tableView.indexPath(for: cell)
        self.tableView.reloadRows(at: [indexPath!], with: UITableViewRowAnimation.automatic)
        (self.parent as? StylingViewController)?.topStackView.isHidden = false;
    }
}
func undoAction() {
    print("undo")

}

}

It seems like something is wrong with tableView.reloadRows.
Help would be appreciated

Body:
Could be the issue because the app still didint know the estimated height of the cell at first run.
A fix could be by adding this on viewDidLoad :

 tableView.estimatedRowHeight = 60
 tableView.rowHeight = UITableViewAutomaticDimension


问:
why refresh html page is slow
For some reason the method display is being processed before location.reload(). Here is my syntax:

$(document).ready(function() {
  $("#refresh").click(function() {
    alert("before refresh")
    location.reload();
    display()
  })
})

function display() {
  alert("hello world")
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="refresh">
  refersh and continue
</button></code>```

My goal here is to refresh the page when the button is clicked then call display method.
The problem is that display method is being called before the page is refreshed.
First of all, is what I am trying to achieve achievable. If not, what other ways can go take in order to solve the problem?

答:
<!DOCTYPE html>

<button id="refresh">
refersh and continue
</button>

```

Try this, call the display method on loading the document and remove the reload(), if needed add display() in refresh.

Title: why refresh html page is slow

Body:
For some reason the method display is being processed before location.reload(). Here is my syntax:

$(document).ready(function() {
  $("#refresh").click(function() {
    alert("before refresh")
    location.reload();
    display()
  })
})

function display() {
  alert("hello world")
}

<button id="refresh">
  refersh and continue
</button>

My goal here is to refresh the page when the button is clicked then call display method.
The problem is that display method is being called before the page is refreshed.
First of all, is what I am trying to achieve achievable. If not, what other ways can go take in order to solve the problem?

Body:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

 <script>
$(document).ready(function(){
display();
  $("#refresh").click(function(){
    alert("before refresh")
    //location.reload();
  display();
  });
})

function display(){
    alert("hello world")
}

    </script>
<button id="refresh">
refersh and continue
</button>

</body>
</html>

Try this, call the display method on loading the document and remove the reload(), if needed add display() in refresh.


问:
xamarin form next back button fixed bar
I am newbie to Xamarin forms and I have to implement something like bellow.
where in very bottom of the page there is a next button and back button and in the middle of the page having some page indicator where current page is rely.

what my question is I need to change the page content upon click in next and back button ? how do I can start doing something like this ?

In simple term are there like xamarin form page where it having container to embedded view to that page dynamically.

答:
So you can use your carousel page that I showed you previous time. You make a renderer for the carousel page where your override all the gestures of that carouselpage ( do this on you viewdidload )

```<code>foreach (var g in this.View.GestureRecognizers)
            g.ShouldBegin = recognizer => false;
</code>```

Next you just add buttons in XAML code to your carousel page and swap to them programmatically. Here is some extra information on how to do that: http://www.patridgedev.com/2015/03/07/xamarin-forms-switching-tabbedpage-tabs-programmatically/

Note: this is for tabbed page, but should work the same way. (ps you are interested in switching tabs by index, since you want the back and forward button)

Good luck

Title: xamarin form next back button fixed bar

Body:
So you can use your carousel page that I showed you previous time. You make a renderer for the carousel page where your override all the gestures of that carouselpage ( do this on you viewdidload )

foreach (var g in this.View.GestureRecognizers)
            g.ShouldBegin = recognizer => false;

Next you just add buttons in XAML code to your carousel page and swap to them programmatically. Here is some extra information on how to do that: http://www.patridgedev.com/2015/03/07/xamarin-forms-switching-tabbedpage-tabs-programmatically/

Note: this is for tabbed page, but should work the same way. (ps you are interested in switching tabs by index, since you want the back and forward button)

Good luck


问:
Apache multiple rewrite rule
how to rewrite multiple rules in .htaccess file?

The following is my .htaccess:

```<code><IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_URI} ^/download(.*)$
    RewriteRule ^(.*)/download/(.*)$ download/$2 [L]

    RewriteCond %{REQUEST_URI} ^/file(.*)$
    RewriteRule ^(.*)/file/(.*)$ file/$2 [L]

    RewriteRule ^(.*)$ main/$1 [L]
</IfModule>
</code>```

If request url is http://localhost/{download}/foo.php then will run download/foo.php

If request url is http://localhost/{file}/foo/bar.php then will run file/foo/bar.php

If not in rules then will run main/index.php

答:
Here is example:</p>

```<code><IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_URI} ^/download/.*$ [NC]
    RewriteRule ^/download/(.*) download/$1 [L]

    RewriteCond %{REQUEST_URI} ^/file/.*$ [NC]
    RewriteRule ^/file/(.*) file/$1 [L]

    RewriteCond %{REQUEST_URI} !^(/download/(.*)|/file/(.*))$ [NC]
    RewriteRule ^(.*)$ main/$1 [L]

</IfModule>
</code>```

Title: Apache multiple rewrite rule

Body:
how to rewrite multiple rules in .htaccess file?

The following is my .htaccess:

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_URI} ^/download(.*)$
    RewriteRule ^(.*)/download/(.*)$ download/$2 [L]

    RewriteCond %{REQUEST_URI} ^/file(.*)$
    RewriteRule ^(.*)/file/(.*)$ file/$2 [L]

    RewriteRule ^(.*)$ main/$1 [L]
</IfModule>

If request url is http://localhost/{download}/foo.php then will run download/foo.php

If request url is http://localhost/{file}/foo/bar.php then will run file/foo/bar.php

If not in rules then will run main/index.php

Body:
Here is example:

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_URI} ^/download/.*$ [NC]
    RewriteRule ^/download/(.*) download/$1 [L]

    RewriteCond %{REQUEST_URI} ^/file/.*$ [NC]
    RewriteRule ^/file/(.*) file/$1 [L]

    RewriteCond %{REQUEST_URI} !^(/download/(.*)|/file/(.*))$ [NC]
    RewriteRule ^(.*)$ main/$1 [L]

</IfModule>


问:
How to upload image to php server from angular2 using PrimeNg?
my app.component.ts code

```<code>import { Http, Response } from '@angular/http';
//import the do function to be used with the http library.
import "rxjs/add/operator/do";
import {FileUploadModule} from 'primeng/primeng';
//import the map function to be used with the http library
import "rxjs/add/operator/map";
import {AccordionModule} from 'primeng/primeng';
import {MenuItem} from 'primeng/primeng';            //api
@Component({
  selector: 'my-app',
  template:  '<p-fileUpload name="myfile[]" url="./upload.php"> </p-fileUpload>'  ,
})
export class AppComponent   {
 name = 'Angular';
}
</code>```

my app.module.ts code

```<code>import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http'
import { AppComponent }  from './app.component';
import { FormSubmitionComponent } from "./components/form.component";
import {FormsModule} from "@angular/forms"
import {AccordionModule} from 'primeng/primeng';
import {MenuItem,FileUploadModule} from 'primeng/primeng';
@NgModule({<br>
  imports:      [ BrowserModule,FormsModule ,HttpModule,FileUploadModule],
  declarations: [ AppComponent ,FormSubmitionComponent],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
</code>```

code from
 https://www.primefaces.org/primeng/#/fileupload
when i run it showing

```<code>: XHR error (404 Not Found) loading http://localhost:3006/primeng/primeng
<br>
    Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:3006/primeng/primeng
    Error: XHR error (404 Not Found) loading http://localhost:3006/primeng/primeng
        at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (http://localhost:3006/node_modules/zone.js/dist/zone.js:1056:39)
        at ZoneDelegate.invokeTask (http://localhost:3006/node_modules/zone.js/dist/zone.js:424:31)
        at Zone.runTask (http://localhost:3006/node_modules/zone.js/dist/zone.js:191:47)
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:3006/node_modules/zone.js/dist/zone.js:486:38)
    Error loading http://localhost:3006/primeng/primeng as "primeng/primeng" from http://localhost:3006/app/app.module.js
        at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (http://localhost:3006/node_modules/zone.js/dist/zone.js:1056:39)
        at ZoneDelegate.invokeTask (http://localhost:3006/node_modules/zone.js/dist/zone.js:424:31)
        at Zone.runTask (http://localhost:3006/node_modules/zone.js/dist/zone.js:191:47)
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:3006/node_modules/zone.js/dist/zone.js:486:38)
    Error loading http://localhost:3006/primeng/primeng as "primeng/primeng" from http://localhost:3006/app/app.module.js
</code>```

答:
You need to update your module too :</p>

```<code>import {FileUploadModule} from 'primeng/primeng';

@Module({
    // ...
    imports: [FileUploadModule]
})
</code>```

Body:
my app.component.ts code

import { Http, Response } from '@angular/http';
//import the do function to be used with the http library.
import "rxjs/add/operator/do";
import {FileUploadModule} from 'primeng/primeng';
//import the map function to be used with the http library
import "rxjs/add/operator/map";
import {AccordionModule} from 'primeng/primeng';
import {MenuItem} from 'primeng/primeng';            //api
@Component({
  selector: 'my-app',
  template:  '

'  ,
})
export class AppComponent   {
 name = 'Angular';
}

my app.module.ts code

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http'
import { AppComponent }  from './app.component';
import { FormSubmitionComponent } from "./components/form.component";
import {FormsModule} from "@angular/forms"
import {AccordionModule} from 'primeng/primeng';
import {MenuItem,FileUploadModule} from 'primeng/primeng';
@NgModule({

  imports:      [ BrowserModule,FormsModule ,HttpModule,FileUploadModule],
  declarations: [ AppComponent ,FormSubmitionComponent],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

code from
 https://www.primefaces.org/primeng/#/fileupload
when i run it showing

: XHR error (404 Not Found) loading http://localhost:3006/primeng/primeng

    Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:3006/primeng/primeng
    Error: XHR error (404 Not Found) loading http://localhost:3006/primeng/primeng
        at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (http://localhost:3006/node_modules/zone.js/dist/zone.js:1056:39)
        at ZoneDelegate.invokeTask (http://localhost:3006/node_modules/zone.js/dist/zone.js:424:31)
        at Zone.runTask (http://localhost:3006/node_modules/zone.js/dist/zone.js:191:47)
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:3006/node_modules/zone.js/dist/zone.js:486:38)
    Error loading http://localhost:3006/primeng/primeng as "primeng/primeng" from http://localhost:3006/app/app.module.js
        at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (http://localhost:3006/node_modules/zone.js/dist/zone.js:1056:39)
        at ZoneDelegate.invokeTask (http://localhost:3006/node_modules/zone.js/dist/zone.js:424:31)
        at Zone.runTask (http://localhost:3006/node_modules/zone.js/dist/zone.js:191:47)
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:3006/node_modules/zone.js/dist/zone.js:486:38)
    Error loading http://localhost:3006/primeng/primeng as "primeng/primeng" from http://localhost:3006/app/app.module.js

Body:
You need to update your module too :

import {FileUploadModule} from 'primeng/primeng';

@Module({
    // ...
    imports: [FileUploadModule]
})


问:
How to add a NOT NULLABLE column with a foreign key to an existing table that already contains data?
An example for this problem:

Imagine you have a table projects. The table projects already
  contains data. Now you want to add a project_type_id column to the
  table, that can't be NULL and has a foreign key to the project_types
  table.

The database sees the project_type_id can't be NULL, so it inserts a
  0 in the column for all the existing rows. The 0 does not exist in
  the project_types table, so the foreign key constraint fails. This
  means you can't add the foreign key.

I thought about adding a first "default" row to the project_types table and link all the projects to that type. This isn't a good solution, because the user has to change all the types from "default" to the correct type.

What is your solution for this problem?

答:
You should have a valid foreign key that exists in DB, for example: 1

Then Create a new migration :

```<code>$table->integer('project_type_id')->unsigned()->default(1);
$table->foreignkey('project_type_id')->references('id')->on('project_types');
</code>```

Then user has to manually change every one of them or change them randomly (random valid ids) with foreach.

Body:
You should have a valid foreign key that exists in DB, for example: 1

Then Create a new migration :

$table->integer('project_type_id')->unsigned()->default(1);
$table->foreignkey('project_type_id')->references('id')->on('project_types');

Then user has to manually change every one of them or change them randomly (random valid ids) with foreach.


问:
Creating Java Calendar, basic parameters
I would like to send a Java Calendar object over a web service (soap). I notice that this kind of object is too complex and there should be a better method to send the same information.

What are the basic attributes that should be sended over the web service, so the client can create a Java Calendar out of this attributes?

I'm guessing: TimeZone, Date, and Time?

Also, how can the client recreate the Calendar based on those attributes?

Thanks!

答:
The easiest way is to use a long value.

```<code>java.util.Calendar.getInstance().getTimeInMillis()
</code>```

This returns the long value for the date. That value can be used to construct java.util.Date or a Calendar.

Body:
The easiest way is to use a long value.

java.util.Calendar.getInstance().getTimeInMillis()

This returns the long value for the date. That value can be used to construct java.util.Date or a Calendar.


问:
Filter and show AVAsset without completely processing
I would like to use only the native API (UIKit, AVFoundation, Core Image, etc.) to filter an AVAsset while showing it in an AVPlayerLayer or an equivalent UI component. I will not use GPUImage because it was extremely problematic for me.

In other words, can I filter each frame right before showing it (or a couple frames in advance) so that I do not have to completely process the entire movie every time I want to filter?

I would also accept an answer that describes how to set up a custom AVPlayerLayer with a frame buffer or something like that.

Also, is there a filter tag for this? All the ones I saw are for signals.

答:
AVPlayerItem has a property videoComposition

You can use this property to process each frame

First way

If You want to use CoreImage strating from iOS9 you can use init(asset:applyingCIFiltersWithHandler:) method.

To process video frames using Core Image filters—whether for display
  or export—create a composition with this method. AVFoundation calls
  your applier block once for each frame to be displayed (or processed
  for export) from the asset’s first enabled video track. In that block,
  you access the video frame and return a filtered result using the
  provided

See docs for more info.

Second way

AVVideoComposition has a property customVideoCompositorClass.
You need to set that property to an instance of AVVideoCompositing protocol.
Here is an example. (Its in Objective-C but I think that it wouldn't be hard to translate it to swift)


问:
regex remove  etc
In previous question (link needed) I try to remove hastags and comments from Twitter. My string is text like this:

```<code>@lien_ayy92 % Real Avail▶#Jakarta #Bekasi Excl/Incl Expo▶6-7 Juli #Cirebon Wajib DP Cek BIO https://local.com/
</code>```

I want try remove the icons and text that is not important.

My code from previus code

let clean = function (data) {
 data = data.replace(/(?:https?|ftp):\/\/[\n\S]+|\B[@#]\w+\b|\b\w+[@#]\B|\B[^\w\s]{2,}\B|\b[a-zA-Z]{1,3}\b|[0-9]+|[$&+,:;=?@#|'<>.^*()%!-/]|\ud83d[\ude00-\ude4f]/g, '');
 return data;
}
let stopwords = function (docs) {
   docs = clean(docs);
 docs = docs.trim();
    docs = docs.toLowerCase();
 docs = docs.split(' ');
  let wordsstop = ['about'];
 let docs1 = new Array;
  var x =  0;
  for(let i = 0; i < docs.length; i++){
       if(wordsstop.indexOf(docs[i]) !== -1 || docs[i] == ""){

      }else{
      docs1[x] = docs[i]
      x++;
      }
  }
  return docs1;
}

console.log(stopwords('@lien_ayy92 % Real Avail▶#Jakarta #Bekasi Excl/Incl Expo▶6-7 Juli #Cirebon Wajib DP Cek BIO https://local.com about data'));```
</div>
</div>
</p>

<p>I want result like this:</p>

```["real","juli","data"];
```

答:
You can use Array.prototype.filter to remove all items with special character.

let clean = function (data) {
 data = data.replace(/(?:https?|ftp):\/\/[\n\S]+|\B[@#]\w+\b|\b\w+[@#]\B|\B[^\w\s]{2,}\B|\b[a-zA-Z]{1,3}\b|[0-9]+|[$&+,:;=?@#|'<>.^*()%!-/]|\ud83d[\ude00-\ude4f]/g, '');
 return data;
}
let stopwords = function (docs) {
   docs = clean(docs);
 docs = docs.trim();
    docs = docs.toLowerCase();
 docs = docs.split(' ');
  let wordsstop = ['about'];
 let docs1 = new Array;
  var x =  0;
  for(let i = 0; i < docs.length; i++){
       if(wordsstop.indexOf(docs[i]) !== -1 || docs[i] == ""){

      }else{
      docs1[x] = docs[i]
      x++;
      }
  }

  // filter code below
  var resultDocs = docs1.filter(function(data) {
    var tmp = data.replace(/[a-zA-Z$&+,:;=?@#|'<>.^*()%!-/]/g, '');
    if (tmp.length === 0) {
      return true;
    }
  });

  return resultDocs;

}

console.log(stopwords('@lien_ayy92 % Real Avail▶#Jakarta #Bekasi Excl/Incl Expo▶6-7 Juli #Cirebon Wajib DP Cek BIO https://local.com about data'));```

Title: regex remove  etc

Body:
In previous question (link needed) I try to remove hastags and comments from Twitter. My string is text like this:

@lien_ayy92 % Real Avail▶#Jakarta #Bekasi Excl/Incl Expo▶6-7 Juli #Cirebon Wajib DP Cek BIO https://local.com/

I want try remove the icons and text that is not important.

My code from previus code

let clean = function (data) {
 data = data.replace(/(?:https?|ftp):\/\/[\n\S]+|\B[@#]\w+\b|\b\w+[@#]\B|\B[^\w\s]{2,}\B|\b[a-zA-Z]{1,3}\b|[0-9]+|[$&+,:;=?@#|'<>.^*()%!-/]|\ud83d[\ude00-\ude4f]/g, '');
 return data;
}
let stopwords = function (docs) {
   docs = clean(docs);
 docs = docs.trim();
    docs = docs.toLowerCase();
 docs = docs.split(' ');
  let wordsstop = ['about'];
 let docs1 = new Array;
  var x =  0;
  for(let i = 0; i < docs.length; i++){
       if(wordsstop.indexOf(docs[i]) !== -1 || docs[i] == ""){

      }else{
      docs1[x] = docs[i]
      x++;
      }
  }
  return docs1;
}

console.log(stopwords('@lien_ayy92 % Real Avail▶#Jakarta #Bekasi Excl/Incl Expo▶6-7 Juli #Cirebon Wajib DP Cek BIO https://local.com about data'));

I want result like this:

["real","juli","data"];


问:
Declaration of child method must be compatible with parent method
Here's my code :

I have a class A, with a method foo, that returns a Bar object.

```<code>class A {
    public function foo(): Bar {
        //some ops
        return $bar; //'Bar' object
    }
}
</code>```

I also have a class B, that extends class A, with an overridden method foo, that returns a BarX object.

```<code>class B extends A {
    public function foo(): BarX {
        //some ops
        return $barX; //'BarX' object
    }
}
</code>```

What is important is that the BarX class extends the Bar class.

When I run my code, I have an error on class B, saying :

Declaration of B::foo(): BarX must be compatible with A::foo(): Bar

How are they not compatible since BarX extends Bar ? And how could I fix this problem please ?

Thank you.

答:
Study the L in SOLID carefully and consider:

```<code>function (A $a) {
    $bar = $a->foo();
}
</code>```

Is $bar going to be a Bar or BarX? You don't know. Since $a can be injected either as an A or B (because B instanceof A, because B extends A), you can't predict what $a will be and hence what $bar will be.

That's why a uniform and predictable interface is important and that's what PHP complains about.

Body:
Here's my code :

I have a class A, with a method foo, that returns a Bar object.

class A {
    public function foo(): Bar {
        //some ops
        return $bar; //'Bar' object
    }
}

I also have a class B, that extends class A, with an overridden method foo, that returns a BarX object.

class B extends A {
    public function foo(): BarX {
        //some ops
        return $barX; //'BarX' object
    }
}

What is important is that the BarX class extends the Bar class.

When I run my code, I have an error on class B, saying :

Declaration of B::foo(): BarX must be compatible with A::foo(): Bar

How are they not compatible since BarX extends Bar ? And how could I fix this problem please ?

Thank you.

Body:
Study the L in SOLID carefully and consider:

function (A $a) {
    $bar = $a->foo();
}

Is $bar going to be a Bar or BarX? You don't know. Since $a can be injected either as an A or B (because B instanceof A, because B extends A), you can't predict what $a will be and hence what $bar will be.

That's why a uniform and predictable interface is important and that's what PHP complains about.


问:
How to return a viewEntryCollection in random order
I have the following code

```<code>var vec:ViewEntryCollection = database.getView("view").getAllEntriesByKey("Mykey",true)
</code>```

how can I make "vec" in random order using SSJS (or java) so that I get a new order every time?

答: For better performance, do NOT keep collection entries in memory. First, make list/array of UNIDs from your view. That will be the slowest part. Then pick any random number and pick desired number of UNIDs from the list/array. Call getDocumentByUnid or initialize (say 10) datasources.</p>

Body:
I have the following code

var vec:ViewEntryCollection = database.getView("view").getAllEntriesByKey("Mykey",true)

how can I make "vec" in random order using SSJS (or java) so that I get a new order every time?


问:
Maximum number of tasks supported in AUTOSAR
What is the maximum number of tasks supported in AUTOSAR compliant systems?

In Linux, I can check the maximum process IDs supported to get the maximum number of tasks supported.

However, I couldn't find any source that states the maximum number of tasks supported by AUTOSAR.

Thank you very much for your help!

答:
Formally you can have an infinite number of OsTasks. According to the spec. the configuration of the Os can have 0..* OsTask.
Apart from that the (OS) software uses data type TaskType for Task-Index variables. Therefore, if TaskType is of uint16 you could not have more than 65535 tasks.
Besides that, if you have a lot of tasks, you might re-think your design.</p>


问:
How do i create a CSV with a simple search on tweepy?
I'm trying to make a script that downloads a twitter search in a .CSV format, but, there a error with my code, any help???

```<code>import tweepy
import csv
import pandas as pd
####input your credentials here
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth,wait_on_rate_limit=True)
#####United Airlines
# Open/Create a file to append data
csvFile = open('test.csv', 'a')
#Use csv Writer
csvWriter = csv.writer(csvFile)

for tweet in tweepy.Cursor(api.search,q="petya",count=100,
                           since="2017-04-03").items():
        print ("ID:", tweet.id)
        print ("User ID:", tweet.user.id)
        print ("Text:", tweet.text)
        print ("Created:", tweet.created_at)
        print ("Geo:", tweet.geo)
        print ("Contributors:", tweet.contributors)
        print ("Coordinates:", tweet.coordinates)
        print ("Favorited:", tweet.favorited)
        print ("In reply to screen name:", tweet.in_reply_to_screen_name)
        print ("In reply to status ID:", tweet.in_reply_to_status_id)
        print ("In reply to status ID str:", tweet.in_reply_to_status_id_str)
        print ("In reply to user ID:", tweet.in_reply_to_user_id)
        print ("In reply to user ID str:", tweet.in_reply_to_user_id_str)
        print ("Place:", tweet.place)
        print ("Retweeted:", tweet.retweeted)
        print ("Retweet count:", tweet.retweet_count)
        print ("Source:", tweet.source)
        print ("Truncated:", tweet.truncated)

    # Write a row to the CSV file. I use encode UTF-8
    csvWriter.writerow([tweet.created_at, tweet.user.id, tweet.id, tweet.geo, tweet.text, tweet.contributors, tweet.favorited, tweet.source, tweet.retweeted, tweet.in_reply_to_screen_name, eet.in_reply_to_status_id_str('utf-8')])
    print tweet.created_at, tweet.user.id, tweet.id, tweet.geo, tweet.text, tweet.contributors, tweet.favorited, tweet.source, tweet.retweeted, tweet.in_reply_to_screen_name, eet.in_reply_to_status_id_str
csvFile.close()
</code>```

I think the problem is in the last part where the csvWriter is, maybe I put to much text in one line? As I said before I'm new at this and need tons of help.

答:
I think the easiest solution utilizes pandas (which, interestingly, you imported but didn't use).

A working solution may look something like this:

```<code>import tweepy
import pandas as pd
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth,wait_on_rate_limit=True)

# create list to append tweets to
tweets = []

# append all tweet data to list
for tweet in tweepy.Cursor(api.search,q="petya",count=100,
                       since="2017-04-03").items():
    tweets.append(tweet)

# convert 'tweets' list to pandas.DataFrame
tweets_df = pd.DataFrame(vars(tweets[i]) for i in range(len(tweets)))

# define file path (string) to save csv file to
FILE_PATH = </path/to/file.csv>

# use pandas to save dataframe to csv
tweets_df.to_csv(FILE_PATH)
</code>```

And boom, you're done!

Note, if you only want to select a particular set of tweets, you can just create a list and then subset the dataframe afterwards.

e.g. (after the step where you convert the tweets to a pandas.DataFrame):

```<code># define attributes you want
tweet_atts = [
'text', 'created_at', 'favorite_count',
'lang', 'retweet_count', 'source',
'in_reply_to_user_id_str', 'retweeted',
'id'
]

# subset dataframe
tweets_df = tweets_df[tweets_atts]

# save resulting df to csv
tweets_df.to_csv(FILE_PATH)
</code>```

Feel free to reply if you need any more help!

Body:
I'm trying to make a script that downloads a twitter search in a .CSV format, but, there a error with my code, any help???

import tweepy
import csv
import pandas as pd
####input your credentials here
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth,wait_on_rate_limit=True)
#####United Airlines
# Open/Create a file to append data
csvFile = open('test.csv', 'a')
#Use csv Writer
csvWriter = csv.writer(csvFile)

for tweet in tweepy.Cursor(api.search,q="petya",count=100,
                           since="2017-04-03").items():
        print ("ID:", tweet.id)
        print ("User ID:", tweet.user.id)
        print ("Text:", tweet.text)
        print ("Created:", tweet.created_at)
        print ("Geo:", tweet.geo)
        print ("Contributors:", tweet.contributors)
        print ("Coordinates:", tweet.coordinates)
        print ("Favorited:", tweet.favorited)
        print ("In reply to screen name:", tweet.in_reply_to_screen_name)
        print ("In reply to status ID:", tweet.in_reply_to_status_id)
        print ("In reply to status ID str:", tweet.in_reply_to_status_id_str)
        print ("In reply to user ID:", tweet.in_reply_to_user_id)
        print ("In reply to user ID str:", tweet.in_reply_to_user_id_str)
        print ("Place:", tweet.place)
        print ("Retweeted:", tweet.retweeted)
        print ("Retweet count:", tweet.retweet_count)
        print ("Source:", tweet.source)
        print ("Truncated:", tweet.truncated)

    # Write a row to the CSV file. I use encode UTF-8
    csvWriter.writerow([tweet.created_at, tweet.user.id, tweet.id, tweet.geo, tweet.text, tweet.contributors, tweet.favorited, tweet.source, tweet.retweeted, tweet.in_reply_to_screen_name, eet.in_reply_to_status_id_str('utf-8')])
    print tweet.created_at, tweet.user.id, tweet.id, tweet.geo, tweet.text, tweet.contributors, tweet.favorited, tweet.source, tweet.retweeted, tweet.in_reply_to_screen_name, eet.in_reply_to_status_id_str
csvFile.close()

I think the problem is in the last part where the csvWriter is, maybe I put to much text in one line? As I said before I'm new at this and need tons of help.

Body:
I think the easiest solution utilizes pandas (which, interestingly, you imported but didn't use).

A working solution may look something like this:

import tweepy
import pandas as pd
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth,wait_on_rate_limit=True)

# create list to append tweets to
tweets = []

# append all tweet data to list
for tweet in tweepy.Cursor(api.search,q="petya",count=100,
                       since="2017-04-03").items():
    tweets.append(tweet)

# convert 'tweets' list to pandas.DataFrame
tweets_df = pd.DataFrame(vars(tweets[i]) for i in range(len(tweets)))

# define file path (string) to save csv file to
FILE_PATH = </path/to/file.csv>

# use pandas to save dataframe to csv
tweets_df.to_csv(FILE_PATH)

And boom, you're done!

Note, if you only want to select a particular set of tweets, you can just create a list and then subset the dataframe afterwards.

e.g. (after the step where you convert the tweets to a pandas.DataFrame):

# define attributes you want
tweet_atts = [
'text', 'created_at', 'favorite_count',
'lang', 'retweet_count', 'source',
'in_reply_to_user_id_str', 'retweeted',
'id'
]

# subset dataframe
tweets_df = tweets_df[tweets_atts]

# save resulting df to csv
tweets_df.to_csv(FILE_PATH)

Feel free to reply if you need any more help!


问:
How to require characters after domain name and slash of a url?
This is the regex I've come up with:

```<code>^(https:\/\/|http:\/\/)?(www.)?example\.com
</code>```

It will match everything from example.com even this address: https://www.example.com/

I want the regex to match any url with something after the domain like: https://www.example.com/testing/proof.php

It shouldn't match on a url looking like this: https://www.example.com/.

How is this done?

答:
I think I understand your question, although mickmackusa explains it much better than I ever will:</p>

```<code>(http)s?:\/\/(www.)?example.com\/(.+)
</code>```

Body:
This is the regex I've come up with:

^(https:\/\/|http:\/\/)?(www.)?example\.com

It will match everything from example.com even this address: https://www.example.com/

I want the regex to match any url with something after the domain like: https://www.example.com/testing/proof.php

It shouldn't match on a url looking like this: https://www.example.com/.

How is this done?

Body:
I think I understand your question, although mickmackusa explains it much better than I ever will:

(http)s?:\/\/(www.)?example.com\/(.+)


问:
How to add preloader and success message on form submit using vue-resource
How to accomplish below task using vue-resource:

Include preloader text Loading... or gif image when fetching the data
from the server.

Show success message on form submit.

答:
This was questioned by me, with the help that I got from @Vamsi, here is my solution:

Component

```<code><loading-indicator v-if="loadingGroup" :bgAlpha="'.6'"></loading-indicator>

<script>
  import LoadingIndicator from '../partials/LoadingIndicator'

  export default {
    data () {
      return {
        loadingGroup: true,
      }
    },

    components: {LoadingIndicator},

    methods: {
      fetchGroup() {
        let _this = this;
        this.loadingGroup = true;

        api._get({url: 'api/group/' + _this.$route.params.id})
          .then(function (response) {
            _this.groupData = response.data;
            _this.loadingGroup = false;
          });
      }
    },

    mounted() {
      this.fetchGroup();
    }
  }
</script>
</code>```

My Template that's in: ../partials/LoadingIndicator.vue

```<code><template>
  <div class="pin pin-xy d-flex"
       :style="{ backgroundColor: 'rgba(255, 255 ,255,' + bgAlpha + ')'}">
    <div class="loading-indicator">
      <div class="loading-indicator-circle"></div>
    </div>
  </div>
</template>

<script>
  export default {
    props: {
      bgAlpha: String
    }
  }
</script>

<style lang="scss">
  .pin {
    position: absolute;

    &-xy {
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
    }
  }

  .d-flex {
    display: flex;
  }

  .loading-indicator {
    width: 32px;
    height: 32px;
    margin: auto;
    overflow: hidden;
    animation: animation-fadeIn 1s ease-in;
  }

  .loading-indicator-circle {
    animation: loading-indicator-rotation 0.67s linear infinite;
    background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAzMiAzMic+PGxpbmVhckdyYWRpZW50IGlkPSdGYXN0TG9hZGluZ0luZGljYXRvci1saW5lYXJHcmFkaWVudCcgZ3JhZGllbnRVbml0cz0ndXNlclNwYWNlT25Vc2UnIHgxPScxLjc4MDQnIHkxPScxNi4wMzc5JyB4Mj0nMzAuMTQzOScgeTI9JzE2LjAzNzknPjxzdG9wIG9mZnNldD0nMC40MTY5JyBzdG9wLWNvbG9yPScjQ0RDRkQyJy8+PHN0b3Agb2Zmc2V0PScwLjkzNzYnIHN0b3AtY29sb3I9J3JnYmEoMjQ4LDI0OCwyNDksMCknLz48L2xpbmVhckdyYWRpZW50PjxjaXJjbGUgY3g9JzE2JyBjeT0nMTYnIHI9JzEyLjcnIHN0eWxlPSdmaWxsOiBub25lOyBzdHJva2U6IHVybCgjRmFzdExvYWRpbmdJbmRpY2F0b3ItbGluZWFyR3JhZGllbnQpOyBzdHJva2Utd2lkdGg6IDI7Jz48L2NpcmNsZT48L3N2Zz4=");
    height: 100%;
    width: 100%
  }

  @keyframes loading-indicator-rotation {
    from {
      transform: rotate(0deg)
    }
    to {
      transform: rotate(360deg)
    }
  }
</style>
</code>```

Body:
This was questioned by me, with the help that I got from @Vamsi, here is my solution:

Component

<loading-indicator v-if="loadingGroup" :bgAlpha="'.6'"></loading-indicator>

<script>
  import LoadingIndicator from '../partials/LoadingIndicator'

  export default {
    data () {
      return {
        loadingGroup: true,
      }
    },

    components: {LoadingIndicator},

    methods: {
      fetchGroup() {
        let _this = this;
        this.loadingGroup = true;

        api._get({url: 'api/group/' + _this.$route.params.id})
          .then(function (response) {
            _this.groupData = response.data;
            _this.loadingGroup = false;
          });
      }
    },

    mounted() {
      this.fetchGroup();
    }
  }
</script>

My Template that's in: ../partials/LoadingIndicator.vue

<template>
  <div class="pin pin-xy d-flex"
       :style="{ backgroundColor: 'rgba(255, 255 ,255,' + bgAlpha + ')'}">
    <div class="loading-indicator">
      <div class="loading-indicator-circle"></div>
    </div>
  </div>
</template>

<script>
  export default {
    props: {
      bgAlpha: String
    }
  }
</script>

<style lang="scss">
  .pin {
    position: absolute;

    &-xy {
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
    }
  }

  .d-flex {
    display: flex;
  }

  .loading-indicator {
    width: 32px;
    height: 32px;
    margin: auto;
    overflow: hidden;
    animation: animation-fadeIn 1s ease-in;
  }

  .loading-indicator-circle {
    animation: loading-indicator-rotation 0.67s linear infinite;
    background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAzMiAzMic+PGxpbmVhckdyYWRpZW50IGlkPSdGYXN0TG9hZGluZ0luZGljYXRvci1saW5lYXJHcmFkaWVudCcgZ3JhZGllbnRVbml0cz0ndXNlclNwYWNlT25Vc2UnIHgxPScxLjc4MDQnIHkxPScxNi4wMzc5JyB4Mj0nMzAuMTQzOScgeTI9JzE2LjAzNzknPjxzdG9wIG9mZnNldD0nMC40MTY5JyBzdG9wLWNvbG9yPScjQ0RDRkQyJy8+PHN0b3Agb2Zmc2V0PScwLjkzNzYnIHN0b3AtY29sb3I9J3JnYmEoMjQ4LDI0OCwyNDksMCknLz48L2xpbmVhckdyYWRpZW50PjxjaXJjbGUgY3g9JzE2JyBjeT0nMTYnIHI9JzEyLjcnIHN0eWxlPSdmaWxsOiBub25lOyBzdHJva2U6IHVybCgjRmFzdExvYWRpbmdJbmRpY2F0b3ItbGluZWFyR3JhZGllbnQpOyBzdHJva2Utd2lkdGg6IDI7Jz48L2NpcmNsZT48L3N2Zz4=");
    height: 100%;
    width: 100%
  }

  @keyframes loading-indicator-rotation {
    from {
      transform: rotate(0deg)
    }
    to {
      transform: rotate(360deg)
    }
  }
</style>


问:
Clicking an href to our Github oAuth endpoint works, but an AJAX request to same endpoint gives a CORS error?
We are trying to implement Github oAuth in our app using Passport.js.  If the user hits the endpoint by clicking an anchor tag/href, it works fine, but if we use a click handler to initiate an ajax request instead, we receive a CORS error from the Github server. Why?

Server side code:

```<code>app.get('/auth/github',
  passport.authenticate('github', { scope: [ 'user:email' ] }));

app.get('/auth/github/callback',
  passport.authenticate('github', { failureRedirect: '/login' }),
   function(req, res) {
    console.log('Github authentication successful!');
    res.redirect('/');
 });
</code>```

Client side code (we are using React):

--> Works:

```<code><a href='/auth/github'>Contact</a>;
</code>```

--> Does Not Work - CORS error:

```<code>handleContactAuth(event) {
  $.ajax({
    url: '/auth/github',
    method: 'GET',
    success: data => console.log( 'Contact Auth response: ', data),
    error: err => console.log( 'Error connecting to GitHub.', err)
  });
}
</code>```

NOTE: This is a click handler on the React component and is functioning    fine, as the ajax request is being triggered. I'm aware we're not handling the response currently, apart from just a console.log.

--> CORS Error we see on the Client side when using AJAX method instead of href:

XMLHttpRequest cannot load https://github.com/login/oauth/authorize?      response_type=code&redirect_uri=ht…auth%2Fgithub%2Fcallback&scope=user%3Aemail&client_id=our_client_code. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

Any ideas? Would appreciate any insights - many thanks.

答:
I had the same problem and I found that at least in Google Chrome XMLHttpRequest object is restricted to same origin policy. So you may need to stick to using an anchor tag.

Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.

Link: https://developer.chrome.com/extensions/xhr

Body:
We are trying to implement Github oAuth in our app using Passport.js.  If the user hits the endpoint by clicking an anchor tag/href, it works fine, but if we use a click handler to initiate an ajax request instead, we receive a CORS error from the Github server. Why?

Server side code:

app.get('/auth/github',
  passport.authenticate('github', { scope: [ 'user:email' ] }));

app.get('/auth/github/callback',
  passport.authenticate('github', { failureRedirect: '/login' }),
   function(req, res) {
    console.log('Github authentication successful!');
    res.redirect('/');
 });

Client side code (we are using React):

--> Works:

Contact;

--> Does Not Work - CORS error:

handleContactAuth(event) {
  $.ajax({
    url: '/auth/github',
    method: 'GET',
    success: data => console.log( 'Contact Auth response: ', data),
    error: err => console.log( 'Error connecting to GitHub.', err)
  });
}

NOTE: This is a click handler on the React component and is functioning    fine, as the ajax request is being triggered. I'm aware we're not handling the response currently, apart from just a console.log.

--> CORS Error we see on the Client side when using AJAX method instead of href:

XMLHttpRequest cannot load https://github.com/login/oauth/authorize?      response_type=code&redirect_uri=ht…auth%2Fgithub%2Fcallback&scope=user%3Aemail&client_id=our_client_code. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

Any ideas? Would appreciate any insights - many thanks.