问:
How can I display FireMonkey modal form from a DLL?
I would like to load a DLL (from an VCL application <s>but that should't be important</s> [that is not true as both VCL and FMX contain a message loop]) and display a FireMonkey modal form created in that DLL. Showing the form works OK but I have problems cleaning after it ...

I can only find only articles on that topic from years 2011/2012 and they mostly refer to XE2. These solutions sadly don't work anymore. (Or I'm doing something wrong.)

All sample files are here: https://github.com/gabr42/GpDelphiCode/tree/master/FMX%20from%20DLL

My DLL just exports ShowMainForm.

```<code>library FMXDLL;

uses
  System.SysUtils,
  System.Classes,
  FMXMain in 'FMXMain.pas' {FormMain};

{$R *.res}

exports
  ShowMainForm;

begin
end.
</code>```

ShowMainForm initializes GDI+ and then shows the form. Afterwards, it tries to clean up but fails at that.

```<code>uses
  Winapi.GDIPAPI,
  Winapi.GDIPOBJ;

procedure InitGDIP;
begin
  // Initialize StartupInput structure
  StartupInput.DebugEventCallback := nil;
  StartupInput.SuppressBackgroundThread := False;
  StartupInput.SuppressExternalCodecs   := False;
  StartupInput.GdiplusVersion := 1;

  GdiplusStartup(gdiplusToken, @StartupInput, nil);
end;

procedure FreeGDIP;
begin
  if Assigned(GenericSansSerifFontFamily) then
    GenericSansSerifFontFamily.Free;
  if Assigned(GenericSerifFontFamily) then
    GenericSerifFontFamily.Free;
  if Assigned(GenericMonospaceFontFamily) then
    GenericMonospaceFontFamily.Free;
  if Assigned(GenericTypographicStringFormatBuffer) then
    GenericTypographicStringFormatBuffer.free;
  if Assigned(GenericDefaultStringFormatBuffer) then
    GenericDefaultStringFormatBuffer.Free;

  GdiplusShutdown(gdiplusToken);
end;

procedure ShowMainForm; stdcall;
var
  FormMain: TFormMain;
begin
  InitGDIP;
  Application.Title := 'DLL Form';
  FormMain := TFormMain.Create(Application);
  FormMain.ShowModal;
  FormMain.Free;
  Application.Terminate;
  Application.ProcessMessages;
  FreeGDIP;
end;
</code>```

Form contains a button which closes the form.

```<code>procedure TFormMain.btnCloseClick(Sender: TObject);
begin
  Close;
end;
</code>```

Host application loads this DLL when its main form is created

```<code>procedure TFormHost.FormCreate(Sender: TObject);
begin
  FLibHandle := LoadLibrary('FMXDLL');
  if FLibHandle = 0 then begin
    ShowMessage('Cannot load FMXDLL.DLL');
    Application.Terminate;
  end
  else begin
    FShowMain := GetProcAddress(FLibHandle, 'ShowMainForm');
    if not assigned(FShowMain) then begin
      ShowMessage('Missing export: ShowMainForm');
      Application.Terminate;
    end;
  end;
end;
</code>```

It has a button which shows FireMonkey form.

```<code>procedure TFormHost.Button1Click(Sender: TObject);
begin
  FShowMain();
end;
</code>```

DLL is unloaded when form is destroyed.

```<code>procedure TFormHost.FormDestroy(Sender: TObject);
begin
  if FLibHandle <> 0 then begin
    FreeLibrary(FLibHandle);
    FLibHandle := 0;
  end;
end;
</code>```

This is observed behaviour (Delphi 10.1 Berlin running on Windows 10 Creators Edition):

I start my host program. An icon with name "DLL Host" appears in the taskbar. [OK]

When I click the button, FireMonkey form appears. [OK].

This new form also has a taskbar button with a name "DLL Form". [OK]

When I click Close button on the FireMonkey form, it closes. [OK]

However, its taskbar button is still visible on screen! [Definitely NOT OK!]

I can click and close FireMonkey form multiple times. It will always show correctly but its taskbar button will never disappear.

When I close my VCL form, it disappears from the taskbar. [OK]

The FireMonkey form is, however, still visible and program hangs. [Definitely NOT OK!] Stack shows that the code is somewhere inside d3d11.dll, if that can be trusted.

I tried different ways of creating and destroying the FMX form but nothing seems to be working correctly.

答:
Short answer: FMX to FMX using packages is fine. Outside of that your first issue is solvable, without source code changes, however the crashing one isn't, if GDI+ is really needed.

Longer answer: you can fix the extraneous taskbar button easily enough by calling RegisterApplicationHWNDProc from FMX.Platform.Win, and providing a callback function; this function should then return a HWND sourced from the host. Best way to do this is probably to export an explicit initialisation function:

```<code>var
  _AppHandle: HWND;

function GetAppHandle: HWND;
begin
  Result := _AppHandle;
end;

function InitializeDLL(AppHandle: HWND): HRESULT; stdcall;
begin
  try
    if AppHandle = 0 then Exit(E_HANDLE);
    if _AppHandle <> 0 then Exit(E_FAIL);
    InitGDIP; //reuse what you've taken from WinApi.GDIOBJ.pas
    _AppHandle := AppHandle;
    RegisterApplicationHWNDProc(GetAppHandle);
    Result := S_OK;
  except
    Result := E_UNEXPECTED;
  end;
end;
</code>```

You'd then have a FinalizeDLL export or somesuch for cleanup:

```<code>procedure FinalizeDLL; stdcall;
begin
  FreeGDIP;
end;
</code>```

The host would call InitializeDLL on first-time use; were the application itself use FMX, then it should pass ApplicationHWND from FMX.Platform.Win for this.

However, this doesn't resolve the crashes on close. More exactly: I don't get them when the DLL is using the Direct2D backend, only when I force GDI+. The problem is the existence of resources held globally, e.g. by the style manager. You might think you could clean things up explicitly before finalising GDI+ by doing what the private FinalizeForms procedure in FMX.Forms.pas does (while FinalizeForms itself is private, what it calls is not):

```<code>//from FMX.Forms
procedure FinalizeForms;
begin
  FreeControls;
  TStyleManager.UnInitialize;
  TFilterManager.UnInitialize;
  TBitmapCodecManager.UnInitialize;
  TTextLayoutManager.UnInitialize;
  TCanvasManager.UnInitialize;
  TContextManager.UnInitialize;
  TShaderManager.UnInitialize;
end;

procedure FinalizeDLL; stdcall;
begin
  FinalizeForms;
  FreeGDIP;
end;
</code>```

This workaround however still fails eventually because TStyleManager.UnInitialize uses a plain Free for its first two disposals (the third gets the FreeAndNil treatment), which obviously then leads to access violations when the 'real' FinalizeForms is called from the finalisation section of FMX.Forms.

Body:
I would like to load a DLL (from an VCL application <s>but that should't be important</s> [that is not true as both VCL and FMX contain a message loop]) and display a FireMonkey modal form created in that DLL. Showing the form works OK but I have problems cleaning after it ...

I can only find only articles on that topic from years 2011/2012 and they mostly refer to XE2. These solutions sadly don't work anymore. (Or I'm doing something wrong.)

All sample files are here: https://github.com/gabr42/GpDelphiCode/tree/master/FMX%20from%20DLL

My DLL just exports ShowMainForm.

library FMXDLL;

uses
  System.SysUtils,
  System.Classes,
  FMXMain in 'FMXMain.pas' {FormMain};

{$R *.res}

exports
  ShowMainForm;

begin
end.

ShowMainForm initializes GDI+ and then shows the form. Afterwards, it tries to clean up but fails at that.

uses
  Winapi.GDIPAPI,
  Winapi.GDIPOBJ;

procedure InitGDIP;
begin
  // Initialize StartupInput structure
  StartupInput.DebugEventCallback := nil;
  StartupInput.SuppressBackgroundThread := False;
  StartupInput.SuppressExternalCodecs   := False;
  StartupInput.GdiplusVersion := 1;

  GdiplusStartup(gdiplusToken, @StartupInput, nil);
end;

procedure FreeGDIP;
begin
  if Assigned(GenericSansSerifFontFamily) then
    GenericSansSerifFontFamily.Free;
  if Assigned(GenericSerifFontFamily) then
    GenericSerifFontFamily.Free;
  if Assigned(GenericMonospaceFontFamily) then
    GenericMonospaceFontFamily.Free;
  if Assigned(GenericTypographicStringFormatBuffer) then
    GenericTypographicStringFormatBuffer.free;
  if Assigned(GenericDefaultStringFormatBuffer) then
    GenericDefaultStringFormatBuffer.Free;

  GdiplusShutdown(gdiplusToken);
end;

procedure ShowMainForm; stdcall;
var
  FormMain: TFormMain;
begin
  InitGDIP;
  Application.Title := 'DLL Form';
  FormMain := TFormMain.Create(Application);
  FormMain.ShowModal;
  FormMain.Free;
  Application.Terminate;
  Application.ProcessMessages;
  FreeGDIP;
end;

Form contains a button which closes the form.

procedure TFormMain.btnCloseClick(Sender: TObject);
begin
  Close;
end;

Host application loads this DLL when its main form is created

procedure TFormHost.FormCreate(Sender: TObject);
begin
  FLibHandle := LoadLibrary('FMXDLL');
  if FLibHandle = 0 then begin
    ShowMessage('Cannot load FMXDLL.DLL');
    Application.Terminate;
  end
  else begin
    FShowMain := GetProcAddress(FLibHandle, 'ShowMainForm');
    if not assigned(FShowMain) then begin
      ShowMessage('Missing export: ShowMainForm');
      Application.Terminate;
    end;
  end;
end;

It has a button which shows FireMonkey form.

procedure TFormHost.Button1Click(Sender: TObject);
begin
  FShowMain();
end;

DLL is unloaded when form is destroyed.

procedure TFormHost.FormDestroy(Sender: TObject);
begin
  if FLibHandle <> 0 then begin
    FreeLibrary(FLibHandle);
    FLibHandle := 0;
  end;
end;

This is observed behaviour (Delphi 10.1 Berlin running on Windows 10 Creators Edition):

I start my host program. An icon with name "DLL Host" appears in the taskbar. [OK]

When I click the button, FireMonkey form appears. [OK].

This new form also has a taskbar button with a name "DLL Form". [OK]

When I click Close button on the FireMonkey form, it closes. [OK]

However, its taskbar button is still visible on screen! [Definitely NOT OK!]

I can click and close FireMonkey form multiple times. It will always show correctly but its taskbar button will never disappear.

When I close my VCL form, it disappears from the taskbar. [OK]

The FireMonkey form is, however, still visible and program hangs. [Definitely NOT OK!] Stack shows that the code is somewhere inside d3d11.dll, if that can be trusted.

I tried different ways of creating and destroying the FMX form but nothing seems to be working correctly.

Body:
Short answer: FMX to FMX using packages is fine. Outside of that your first issue is solvable, without source code changes, however the crashing one isn't, if GDI+ is really needed.

Longer answer: you can fix the extraneous taskbar button easily enough by calling RegisterApplicationHWNDProc from FMX.Platform.Win, and providing a callback function; this function should then return a HWND sourced from the host. Best way to do this is probably to export an explicit initialisation function:

var
  _AppHandle: HWND;

function GetAppHandle: HWND;
begin
  Result := _AppHandle;
end;

function InitializeDLL(AppHandle: HWND): HRESULT; stdcall;
begin
  try
    if AppHandle = 0 then Exit(E_HANDLE);
    if _AppHandle <> 0 then Exit(E_FAIL);
    InitGDIP; //reuse what you've taken from WinApi.GDIOBJ.pas
    _AppHandle := AppHandle;
    RegisterApplicationHWNDProc(GetAppHandle);
    Result := S_OK;
  except
    Result := E_UNEXPECTED;
  end;
end;

You'd then have a FinalizeDLL export or somesuch for cleanup:

procedure FinalizeDLL; stdcall;
begin
  FreeGDIP;
end;

The host would call InitializeDLL on first-time use; were the application itself use FMX, then it should pass ApplicationHWND from FMX.Platform.Win for this.

However, this doesn't resolve the crashes on close. More exactly: I don't get them when the DLL is using the Direct2D backend, only when I force GDI+. The problem is the existence of resources held globally, e.g. by the style manager. You might think you could clean things up explicitly before finalising GDI+ by doing what the private FinalizeForms procedure in FMX.Forms.pas does (while FinalizeForms itself is private, what it calls is not):

//from FMX.Forms
procedure FinalizeForms;
begin
  FreeControls;
  TStyleManager.UnInitialize;
  TFilterManager.UnInitialize;
  TBitmapCodecManager.UnInitialize;
  TTextLayoutManager.UnInitialize;
  TCanvasManager.UnInitialize;
  TContextManager.UnInitialize;
  TShaderManager.UnInitialize;
end;

procedure FinalizeDLL; stdcall;
begin
  FinalizeForms;
  FreeGDIP;
end;

This workaround however still fails eventually because TStyleManager.UnInitialize uses a plain Free for its first two disposals (the third gets the FreeAndNil treatment), which obviously then leads to access violations when the 'real' FinalizeForms is called from the finalisation section of FMX.Forms.


来源: stackexchange

问:
Unable to register a COM object for usage in a scheduled task
I'm trying to create a set of C# classes that I can schedule to run at a future time. The intention is to programmatically schedule these via other parts of my code.

This is the current class I'm trying to call via COM.

```<code>using System;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.Win32.TaskScheduler;

namespace SchedulableTasks
{
    [Guid("F5CAE94C-BCC7-4304-BEFB-FE1E5D56309A")]
    public class TaskRegistry : ITaskHandler
    {
        private ITaskHandler _taskHandler;
        public void Start(object pHandlerServices, string data)
        {
            var arguments = data.Split('|');
            var taskTypeName = arguments.FirstOrDefault();
            var taskArguments = arguments.Skip(1).FirstOrDefault();
            var taskType = Type.GetType(taskTypeName);
            _taskHandler = (ITaskHandler) Activator.CreateInstance(taskType);
            _taskHandler.Start(pHandlerServices, taskArguments);
        }

        public void Stop(out int pRetCode)
        {
            var retCode = 1;
            _taskHandler?.Stop(out retCode);
            pRetCode = retCode;
        }

        public void Pause()
        {
            _taskHandler.Pause();
        }

        public void Resume()
        {
            _taskHandler.Resume();
        }
    }
}
</code>```

Here's how I'm attempting to schedule the task

```<code>using System;
using Microsoft.Win32.TaskScheduler;
using Newtonsoft.Json;
using Action = Microsoft.Win32.TaskScheduler.Action;

namespace MyProject.Service
{
    public static class SchedulingService
    {
        public enum ScheduledTask
        {
            BillingQuery
        }
        private static readonly Guid RegistryGUI = new Guid("F5CAE94C-BCC7-4304-BEFB-FE1E5D56309A");
        public static void ScheduleAction(string name, string description, Trigger trigger, Action action)
        {
            using (var taskService = new TaskService())
            {
                var task = taskService.NewTask();
                task.RegistrationInfo.Description = description;
                task.Triggers.Add(trigger);
                task.Actions.Add(action);
                taskService.RootFolder.RegisterTaskDefinition(name, task);
            }
        }

        public static Action CreateCSharpAction(ScheduledTask task, object data)
        {
            var taskData = $"{task.ToString()}|{JsonConvert.SerializeObject(data)}";
            return new ComHandlerAction(RegistryGUI, taskData);
        }
    }
}
</code>```

Microsoft.Win32.TaskScheduler is version 2.7.2 of this library

I can create the scheduled task no problem, but when I attempt to run it, I get a Class not registered (0x80040154).

In my .csproj I'm registering the assembly as a COM object.
For the PlatformTarget attribute, I've tried all of AnyCPU, x86, and x64 with the corresponding regasm.exe.

```<code>  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <RegisterForComInterop>true</RegisterForComInterop>
    <PlatformTarget>x86</PlatformTarget>
  </PropertyGroup>
</code>```

I'm using the following post-build event to register the .dll.

```<code>powershell C:\Windows\Microsoft.Net\Framework64\v4*\RegAsm.exe /codebase '$(ProjectDir)$(OutDir)SchedulableTasks.dll'
</code>```

As near as I can tell, it's properly registered.

Procmon.exe seems to report the same. The thing I'm worried about is the "NAME NOT FOUND" for \TreatAs, \InprocHandler and \InprocServer32\InprocServer32

答:
I think I see your problem:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">

Try targeting x86. Please see this answer for an in depth description: How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

Edit:

I couldn't repro it, I added a few things:

The Attribute [ComVisible(true)]

A Parameterless Constructor

Signed the Assembly

Had to run the powershell command once manually.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a set of C# classes that I can schedule to run at a future time. The intention is to programmatically schedule these via other parts of my code.

This is the current class I'm trying to call via COM.

using System;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.Win32.TaskScheduler;

namespace SchedulableTasks
{
    [Guid("F5CAE94C-BCC7-4304-BEFB-FE1E5D56309A")]
    public class TaskRegistry : ITaskHandler
    {
        private ITaskHandler _taskHandler;
        public void Start(object pHandlerServices, string data)
        {
            var arguments = data.Split('|');
            var taskTypeName = arguments.FirstOrDefault();
            var taskArguments = arguments.Skip(1).FirstOrDefault();
            var taskType = Type.GetType(taskTypeName);
            _taskHandler = (ITaskHandler) Activator.CreateInstance(taskType);
            _taskHandler.Start(pHandlerServices, taskArguments);
        }

        public void Stop(out int pRetCode)
        {
            var retCode = 1;
            _taskHandler?.Stop(out retCode);
            pRetCode = retCode;
        }

        public void Pause()
        {
            _taskHandler.Pause();
        }

        public void Resume()
        {
            _taskHandler.Resume();
        }
    }
}

Here's how I'm attempting to schedule the task

using System;
using Microsoft.Win32.TaskScheduler;
using Newtonsoft.Json;
using Action = Microsoft.Win32.TaskScheduler.Action;

namespace MyProject.Service
{
    public static class SchedulingService
    {
        public enum ScheduledTask
        {
            BillingQuery
        }
        private static readonly Guid RegistryGUI = new Guid("F5CAE94C-BCC7-4304-BEFB-FE1E5D56309A");
        public static void ScheduleAction(string name, string description, Trigger trigger, Action action)
        {
            using (var taskService = new TaskService())
            {
                var task = taskService.NewTask();
                task.RegistrationInfo.Description = description;
                task.Triggers.Add(trigger);
                task.Actions.Add(action);
                taskService.RootFolder.RegisterTaskDefinition(name, task);
            }
        }

        public static Action CreateCSharpAction(ScheduledTask task, object data)
        {
            var taskData = $"{task.ToString()}|{JsonConvert.SerializeObject(data)}";
            return new ComHandlerAction(RegistryGUI, taskData);
        }
    }
}

Microsoft.Win32.TaskScheduler is version 2.7.2 of this library

I can create the scheduled task no problem, but when I attempt to run it, I get a Class not registered (0x80040154).

In my .csproj I'm registering the assembly as a COM object.
For the PlatformTarget attribute, I've tried all of AnyCPU, x86, and x64 with the corresponding regasm.exe.

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <RegisterForComInterop>true</RegisterForComInterop>
    <PlatformTarget>x86</PlatformTarget>
  </PropertyGroup>

I'm using the following post-build event to register the .dll.

powershell C:\Windows\Microsoft.Net\Framework64\v4*\RegAsm.exe /codebase '$(ProjectDir)$(OutDir)SchedulableTasks.dll'

As near as I can tell, it's properly registered.

Procmon.exe seems to report the same. The thing I'm worried about is the "NAME NOT FOUND" for \TreatAs, \InprocHandler and \InprocServer32\InprocServer32


问:
Two way client server network communication
I am looking at building a client server application in C# using winforms or WPF.  The client application must be a local application because it has to interact with specialised hardware.

The architecture I'm looking for is the client connects to a server port using TCP/IP.  The client will then make requests to the server and the server will send responses to the client.  The client wills stay connected to the server while the user is logged in.

I have looked at web services and as far as I can figure out, WCF extends web services which means there is no way for the server to send a message to the client.

Am I incorrect about WCF?  If not what is the best way to accomplish this?

答:
I know WCF is the bee's knees and all - but I'd probably just do a TcpServer and TcpClient pair. Then again, perhaps I'm the only one who thinks WCF is way too complicated for the 80% case.

Then again, if you have disparate clients or servers or something - you may want to look into WCF. But, for simple network socket stuff - well, we've been doing socket programming for years without WCF and have done pretty well with it.

OwnerDisplayName: John Oxley

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Mark Brackett


问:
How to ignore deprecation warnings in Python
I keep getting this :

```<code>DeprecationWarning: integer argument expected, got float
</code>```

How do I make this message go away? Is there a way to avoid warnings in Python?

答:
When you want to ignore warnings only in functions you can do the following.

```<code>import warnings
from functools import wraps

def ignore_warnings(f):
    @wraps(f)
    def inner(*args, **kwargs):
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("ignore")
            response = f(*args, **kwargs)
        return response
    return inner

@ignore_warnings
def foo(arg1, arg2):
    ...
    write your code here without warnings
    ...

@ignore_warnings
def foo2(arg1, arg2, arg3):
    ...
    write your code here without warnings
    ...
</code>```

Just add the @ignore_warnings decorator on the function you want to ignore all warnings

Body:
I keep getting this :

DeprecationWarning: integer argument expected, got float

How do I make this message go away? Is there a way to avoid warnings in Python?

Body:
When you want to ignore warnings only in functions you can do the following.

import warnings
from functools import wraps

def ignore_warnings(f):
    @wraps(f)
    def inner(*args, **kwargs):
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("ignore")
            response = f(*args, **kwargs)
        return response
    return inner

@ignore_warnings
def foo(arg1, arg2):
    ...
    write your code here without warnings
    ...

@ignore_warnings
def foo2(arg1, arg2, arg3):
    ...
    write your code here without warnings
    ...

Just add the @ignore_warnings decorator on the function you want to ignore all warnings


问:
how to identify "unused" Azure SQL database
We have approximately 2 dozen SQL Database in our Azure portal.  I have been asked to evaluate these and see if any are no longer being used and can be dropped.  I know how to query their original Quotas and current sizes but I am baffled as to how to query DTUs.

How can I query each DB and see when someone last logged into or initiated any queries?

Thank you!

答:
The following query should give you an idea if the database has been used based on resource consumption over the last 7 days:</p>

```<code>SELECT *
FROM sys.dm_db_resource_stats
WHERE --database_name = 'AdventureWorksLT' AND
    end_time > DATEADD(day, -7, GETDATE())
ORDER BY end_time DESC;
</code>```

Body:
The following query should give you an idea if the database has been used based on resource consumption over the last 7 days:

SELECT *
FROM sys.dm_db_resource_stats
WHERE --database_name = 'AdventureWorksLT' AND
    end_time > DATEADD(day, -7, GETDATE())
ORDER BY end_time DESC;


问:
How can I set up a reverse DNS for a private subnet using route 53?
I have websites running in a private subnet that communicates to the outside world using NAT.

Our mails are going straight to spam folder, even though AWS has unlocked our full account.

How do you create a reverse dns for our website using route 53?  Do we have to use the nat ip address?

Thanks!

Edit: What goes into "Name", "Type", "Alias", "TTLS", and "Value"?

答:
If you have an Elastic IP for your NAT gateway, you can ask AWS to set a reverse record for you. Just fill out this form.

There may be other reasons why your emails are marked as spam. Check your EIP via http://multirbl.valli.org to see who may be blacklisting you.


问:
Disable all dates except a list of specific dates using MultiDatesPicker
I'm using MultiDatesPicker for jQuery UI.

I have a list of dates and I want to enable only those dates and disable all others.

```<code>var a = ['11.11.11', '11.12.12', '11.12.13'];

$('.dates').multiDatesPicker({
    dateFormat: "dd.mm.y",
    beforeShowDay: function(a){
        _.each(a, function(date){
            return date ? [true, ''] : [false, '']
        })
    },
    separator: '.',
    maxPicks: 1,
});
</code>```

This is not working. How can I accomplished this?

答:
Did you tried the example in the doc ?

http://dubrox.github.io/Multiple-Dates-Picker-for-jQuery-UI/#demo-disable-dates

It seems that you have to pass an array of dates and not an array of strings.

Body:
I'm using MultiDatesPicker for jQuery UI.

I have a list of dates and I want to enable only those dates and disable all others.

var a = ['11.11.11', '11.12.12', '11.12.13'];

$('.dates').multiDatesPicker({
    dateFormat: "dd.mm.y",
    beforeShowDay: function(a){
        _.each(a, function(date){
            return date ? [true, ''] : [false, '']
        })
    },
    separator: '.',
    maxPicks: 1,
});

This is not working. How can I accomplished this?


问:
Pygame - Issues with button rendering
Basically, I want to create a button and write text on it with pygame and I succeed.

But the last button (named leaderboardButton) doesn't change image to "./image/mouseOnButton.png" when the cursor is on the button.

I really wonder why is this happening. The rest of button is fine.

```<code>import pygame
from pygame.locals import *
import sys

FPS = 60
clock = pygame.time.Clock()
screen = pygame.display.set_mode((800, 700))
screen.fill((255, 255, 255))
pygame.font.init()
pygame.init()

class Button():
    def __init__(self, msg, font, x , y, w, h, color):
        self.msg = msg
        self.font = font
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.color = color

    def createButton(self):
        (mouseX, mouseY) = pygame.mouse.get_pos()
        if((mouseX >= self.x and mouseY <= self.x + self.w) and (mouseY >= self.y and mouseY <= self.y + self.h)):
            button = pygame.image.load("./image/mouseOnButton.png")
        else:
            button = pygame.image.load("./image/button.png")
        screen.blit(button, (self.x, self.y))
        text = pygame.font.SysFont(self.font, 32)
        textSurface = text.render(self.msg.encode("utf-8"), True, self.color)
        screen.blit(textSurface, (self.x + self.w / len(self.msg), self.y + self.h / 2))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == KEYDOWN:
            if(event.key == pygame.K_F4 and pygame.KMOD_ALT):
                sys.exit()

    localButton = Button("Local Play", "./font/NanumSquareRoundEB.ttf", 325, 200, 150, 75, (255, 255, 255)).createButton()
    socketButton = Button("Socket Play", "./font/NanumSquareRoundEB.ttf", 325, 325, 150, 75, (255, 255, 255)).createButton()
    howtoButton = Button("How to Play", "./font/NanumSquareRoundEB.ttf", 325, 450, 150, 75, (255, 255, 255)).createButton()
    leaderboardButton = Button("Leaderboard", "./font/NanumSquareRoundEB.ttf", 325, 575, 150, 75, (255, 255, 255)).createButton()
    pygame.display.update()
    clock.tick(FPS)
</code>```

答:
The problem was caused by a typo in the second line of your createButton method (it would be better to use pygame.Rects and their collision detection methods):

```<code>if((mouseX >= self.x and mouseY <= self.x + self.w) and (mouseY >= self.y and mouseY <= self.y + self.h)):
# Should be:
if((mouseX >= self.x and mouseX <= self.x + self.w) and (mouseY >= self.y and mouseY <= self.y + self.h)):
</code>```

I suggest to create instances of your Button before the while loop and also give them a draw and a handle_event method, so that you can just call button.draw(screen) inside of the while loop. I've already modified the Button in the following example. Note that you can simplify your code by using pygame.Rects as the blit position and for the collision detection. You can also put the buttons into a list and draw them and handle the events in a for loop, e.g. for button in button_list: button.draw(screen).

```<code>import sys
import pygame

pygame.init()
FPS = 60
clock = pygame.time.Clock()
screen = pygame.display.set_mode((800, 700))

class Button():
    def __init__(self, msg, font, x, y, w, h, color):
        self.msg = msg
        self.color = color
        self.font = pygame.font.SysFont(font, 32)
        self.text_surf = self.font.render(self.msg, True, self.color)
        self.image_normal = pygame.Surface((w, h))
        self.image_normal.fill(pygame.Color('dodgerblue1'))
        self.image_hover = pygame.Surface((w, h))
        self.image_hover.fill(pygame.Color('lightskyblue'))

        self.image = self.image_normal
        self.rect = self.image.get_rect(topleft=(x, y))
        # To center the text rect.
        self.text_rect = self.text_surf.get_rect(center=self.rect.center)

    def handle_event(self, event):
        if event.type == pygame.MOUSEMOTION:
            if self.rect.collidepoint(event.pos):
                self.image = self.image_hover
            else:
                self.image = self.image_normal

    def draw(self, screen):
        screen.blit(self.image, self.rect)
        screen.blit(self.text_surf, self.text_rect)

local_button = Button(
    "Local Play", "Comic Sans MS", 325, 200, 150, 75, (255, 255, 255))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        local_button.handle_event(event)

    screen.fill((30, 30, 30))
    local_button.draw(screen)

    pygame.display.update()
    clock.tick(FPS)
</code>```

Title: Pygame - Issues with button rendering

Body:
Basically, I want to create a button and write text on it with pygame and I succeed.

But the last button (named leaderboardButton) doesn't change image to "./image/mouseOnButton.png" when the cursor is on the button.

I really wonder why is this happening. The rest of button is fine.

import pygame
from pygame.locals import *
import sys

FPS = 60
clock = pygame.time.Clock()
screen = pygame.display.set_mode((800, 700))
screen.fill((255, 255, 255))
pygame.font.init()
pygame.init()

class Button():
    def __init__(self, msg, font, x , y, w, h, color):
        self.msg = msg
        self.font = font
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.color = color

    def createButton(self):
        (mouseX, mouseY) = pygame.mouse.get_pos()
        if((mouseX >= self.x and mouseY <= self.x + self.w) and (mouseY >= self.y and mouseY <= self.y + self.h)):
            button = pygame.image.load("./image/mouseOnButton.png")
        else:
            button = pygame.image.load("./image/button.png")
        screen.blit(button, (self.x, self.y))
        text = pygame.font.SysFont(self.font, 32)
        textSurface = text.render(self.msg.encode("utf-8"), True, self.color)
        screen.blit(textSurface, (self.x + self.w / len(self.msg), self.y + self.h / 2))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == KEYDOWN:
            if(event.key == pygame.K_F4 and pygame.KMOD_ALT):
                sys.exit()

    localButton = Button("Local Play", "./font/NanumSquareRoundEB.ttf", 325, 200, 150, 75, (255, 255, 255)).createButton()
    socketButton = Button("Socket Play", "./font/NanumSquareRoundEB.ttf", 325, 325, 150, 75, (255, 255, 255)).createButton()
    howtoButton = Button("How to Play", "./font/NanumSquareRoundEB.ttf", 325, 450, 150, 75, (255, 255, 255)).createButton()
    leaderboardButton = Button("Leaderboard", "./font/NanumSquareRoundEB.ttf", 325, 575, 150, 75, (255, 255, 255)).createButton()
    pygame.display.update()
    clock.tick(FPS)

Body:
The problem was caused by a typo in the second line of your createButton method (it would be better to use pygame.Rects and their collision detection methods):

if((mouseX >= self.x and mouseY <= self.x + self.w) and (mouseY >= self.y and mouseY <= self.y + self.h)):
# Should be:
if((mouseX >= self.x and mouseX <= self.x + self.w) and (mouseY >= self.y and mouseY <= self.y + self.h)):

I suggest to create instances of your Button before the while loop and also give them a draw and a handle_event method, so that you can just call button.draw(screen) inside of the while loop. I've already modified the Button in the following example. Note that you can simplify your code by using pygame.Rects as the blit position and for the collision detection. You can also put the buttons into a list and draw them and handle the events in a for loop, e.g. for button in button_list: button.draw(screen).

import sys
import pygame

pygame.init()
FPS = 60
clock = pygame.time.Clock()
screen = pygame.display.set_mode((800, 700))

class Button():
    def __init__(self, msg, font, x, y, w, h, color):
        self.msg = msg
        self.color = color
        self.font = pygame.font.SysFont(font, 32)
        self.text_surf = self.font.render(self.msg, True, self.color)
        self.image_normal = pygame.Surface((w, h))
        self.image_normal.fill(pygame.Color('dodgerblue1'))
        self.image_hover = pygame.Surface((w, h))
        self.image_hover.fill(pygame.Color('lightskyblue'))

        self.image = self.image_normal
        self.rect = self.image.get_rect(topleft=(x, y))
        # To center the text rect.
        self.text_rect = self.text_surf.get_rect(center=self.rect.center)

    def handle_event(self, event):
        if event.type == pygame.MOUSEMOTION:
            if self.rect.collidepoint(event.pos):
                self.image = self.image_hover
            else:
                self.image = self.image_normal

    def draw(self, screen):
        screen.blit(self.image, self.rect)
        screen.blit(self.text_surf, self.text_rect)

local_button = Button(
    "Local Play", "Comic Sans MS", 325, 200, 150, 75, (255, 255, 255))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        local_button.handle_event(event)

    screen.fill((30, 30, 30))
    local_button.draw(screen)

    pygame.display.update()
    clock.tick(FPS)


问:
In SQL Server 2005 emulating autonomous transaction
I have needs to keep some of log data in different tables even my transaction is rolled back.

I already learned that in SQL Server it is impossible do something like this

```<code>begin tran t1
insert ...
insert ...
select ...
       begin tran t2
         insert into log
       commit tran t2
rollback tran t1
select * from log -- IS EMPTY ALWAYS
</code>```

So I try hacking SQL Server that I madded CLR which is going to export data need for LOG to local server disk in XML format. CLR Code is simple as it can be:

```<code>File.WriteAllText(fileName, xmlLog.Value.ToString());
</code>```

Before I release this in production bases Ill love to hear your toughs about this technique.

Here are few questions:

Is there other better way to accomplish autonomous transaction in SQL Server 2005

How can be bad holding my transaction uncommitted while SQL Server is executing CLR (amount of data written by SQL is relative small about 50 - 60 records of 3 integers and 4 floats)

答:
I would suggest using a Table Variable as it is not affected by the Transaction (this is one of the methods listed in the blog noted by Martin below the question).  Consider doing this, which will work in SQL Server 2005:

```<code>DECLARE @TempLog TABLE (FieldList...)

BEGIN TRY

    BEGIN TRAN

    INSERT...

    INSERT INTO @TempLog (FieldList...) VALUES (@Variables or StaticValues...)

    INSERT...

    INSERT INTO @TempLog (FieldList...) VALUES (@Variables or StaticValues...)

    COMMIT TRAN

END TRY
BEGIN CATCH

    IF (@@TRANCOUNT > 0)
    BEGIN
        ROLLBACK TRAN
    END

    /* Maybe add a Log message to note that we ran into an error */
    INSERT INTO @TempLog (FieldList...) VALUES (@Variables or StaticValues...)

END CATCH

INSERT INTO RealLogTable (FieldList...)
    SELECT FieldsList
    FROM @TempLog
</code>```

Please note that while we are making use of the fact that Table Variables are not part of the transaction, that does create a potential situation where this code does a COMMIT but errors (or server crashes) before the INSERT INTO RealLogTable and you will have lost the logging for the data that did make it in.  At this point there would be a disconnect as there is data but no record of it being inserted as far as RealLogTable is concerned.  But this is just the obvious trade-off for being able to bypass the Transaction.

Body:
I have needs to keep some of log data in different tables even my transaction is rolled back.

I already learned that in SQL Server it is impossible do something like this

begin tran t1
insert ...
insert ...
select ...
       begin tran t2
         insert into log
       commit tran t2
rollback tran t1
select * from log -- IS EMPTY ALWAYS

So I try hacking SQL Server that I madded CLR which is going to export data need for LOG to local server disk in XML format. CLR Code is simple as it can be:

File.WriteAllText(fileName, xmlLog.Value.ToString());

Before I release this in production bases Ill love to hear your toughs about this technique.

Here are few questions:

Is there other better way to accomplish autonomous transaction in SQL Server 2005

How can be bad holding my transaction uncommitted while SQL Server is executing CLR (amount of data written by SQL is relative small about 50 - 60 records of 3 integers and 4 floats)

Body:
I would suggest using a Table Variable as it is not affected by the Transaction (this is one of the methods listed in the blog noted by Martin below the question).  Consider doing this, which will work in SQL Server 2005:

DECLARE @TempLog TABLE (FieldList...)

BEGIN TRY

    BEGIN TRAN

    INSERT...

    INSERT INTO @TempLog (FieldList...) VALUES (@Variables or StaticValues...)

    INSERT...

    INSERT INTO @TempLog (FieldList...) VALUES (@Variables or StaticValues...)

    COMMIT TRAN

END TRY
BEGIN CATCH

    IF (@@TRANCOUNT > 0)
    BEGIN
        ROLLBACK TRAN
    END

    /* Maybe add a Log message to note that we ran into an error */
    INSERT INTO @TempLog (FieldList...) VALUES (@Variables or StaticValues...)

END CATCH

INSERT INTO RealLogTable (FieldList...)
    SELECT FieldsList
    FROM @TempLog

Please note that while we are making use of the fact that Table Variables are not part of the transaction, that does create a potential situation where this code does a COMMIT but errors (or server crashes) before the INSERT INTO RealLogTable and you will have lost the logging for the data that did make it in.  At this point there would be a disconnect as there is data but no record of it being inserted as far as RealLogTable is concerned.  But this is just the obvious trade-off for being able to bypass the Transaction.


问:
Searching for video titles on YouTube with Node.js
I'm creating a bot for Discord and I stumbled upon this. How do you (using a given string) search for a video on youtube and get its URL?

I'd prefer if you gave me some lite library on NPMJS.

Sorry if I'm being a little uninformative but tl;dr.

答: You can use youtube-node NPM package. You'll need to get your API key from Youtube before you can start using this package.</p>

ContentLicense: CC BY-SA 4.0


问:
How to Run Code on Android Generated by AndoirdViewClient?
Through the CulebraTester application on my device, I generated some python to simply open the settings application. When I went to run the script, I was greeted with

pkg_resources.DistributionNotFound: The 'androidviewclient<12.4.0' distribution was not found and is required by the application

So then I realized that I didn't have the environment variable set, so I downloaded the project from Github and ran the command

export ANDROID_VIEW_CLIENT_HOME=/path/to/androidviewclient/

I'm confident I did this correctly because I can cd to $ANDROID_VIEW_CLIENT_HOME and view the contents. Now when I go back to run the script this same error appears, so I commented out pkg_resources.require('androidviewclient>=12.4.0') and was then presented with this error

ImportError: No module named com.dtmilano.android.viewclient

Right now I'm clueless about what to do, I tried googling, but I've found nothing to fix the problem. Some-what related I saw a video on youtube where curl was used to run javascript generated by CulebraTester so maybe the same can be done with Python?

答:
CulebraTester can generate tests in a variety of languages:

Python

Java

Kotlin

Javascript

etc.

see Code-Generation-language for details.

Each language has its own dependencies in order to run, for example, if you generate UiAutomator tests in Java you will need the corresponding dependencies in your build.gradle.

In your specific case, as you have generated Python tests you need androidviewclient. To install it, follow the instructions on AndroidViewClient: Installation


问:
Mysql - speed up select query from 2 million rows
I have a table like below,

```<code>Field    Type      Null Key Default               Extra

id       bigint(11) NO  PRI NULL                  auto_increment
deviceId bigint(11) NO  MUL NULL
value    double     NO      NULL
time    timestamp   YES MUL 0000-00-00 00:00:00
</code>```

It has more than 2 million rows. When I run select * from tableName; It takes more than 15 mins.

When I run select value,time from sensor_value where time > '2017-05-21 04:47:48' and deviceId>=812; It takes more than 45 sec to load.

Note :  512 has more than 92514 rows.
Even I have added index for column like below,

```<code>ALTER TABLE `sensor_value`
 ADD INDEX `IDX_FIELDS1_2` (`time`, `deviceId`) ;
</code>```

How do I make select query fast?(load in 1sec) Am I doing indexing wrong?

答:
When using combined index usually you must use equality operator on first column and then you can use range criteria on second column. So I recommend you change the order of columns in your index like this:

```<code>ALTER TABLE `sensor_value`
 ADD INDEX `IDX_FIELDS1_2` (`deviceId`, `time`) ;
</code>```

then change to use equal sign for deviceId(use deviceId=812 not deviceId>=812):

```<code>select value,time from sensor_value where time > '2017-05-21 04:47:48' and deviceId=812;
</code>```

I hope it could help.

2 million records is not much for Mysql and it is normal to get result in less than 1 sec for 1 billion records if you do the right things.

Body:
I have a table like below,

Field    Type      Null Key Default               Extra

id       bigint(11) NO  PRI NULL                  auto_increment
deviceId bigint(11) NO  MUL NULL
value    double     NO      NULL
time    timestamp   YES MUL 0000-00-00 00:00:00

It has more than 2 million rows. When I run select * from tableName; It takes more than 15 mins.

When I run select value,time from sensor_value where time > '2017-05-21 04:47:48' and deviceId>=812; It takes more than 45 sec to load.

Note :  512 has more than 92514 rows.
Even I have added index for column like below,

ALTER TABLE `sensor_value`
 ADD INDEX `IDX_FIELDS1_2` (`time`, `deviceId`) ;

How do I make select query fast?(load in 1sec) Am I doing indexing wrong?

Body:
When using combined index usually you must use equality operator on first column and then you can use range criteria on second column. So I recommend you change the order of columns in your index like this:

ALTER TABLE `sensor_value`
 ADD INDEX `IDX_FIELDS1_2` (`deviceId`, `time`) ;

then change to use equal sign for deviceId(use deviceId=812 not deviceId>=812):

select value,time from sensor_value where time > '2017-05-21 04:47:48' and deviceId=812;

I hope it could help.

2 million records is not much for Mysql and it is normal to get result in less than 1 sec for 1 billion records if you do the right things.


问:
Scala List function for grouping consecutive identical elements
Given e.g.:

```<code>List(5, 2, 3, 3, 3, 5, 5, 3, 3, 2, 2, 2)
</code>```

I'd like to get to:

```<code>List(List(5), List(2), List(3, 3, 3), List(5, 5), List(3, 3), List(2, 2, 2))
</code>```

I would assume there is a simple List function that does this, but am unable to find it.

答:
Damn Rex Kerr, for writing the answer I'd go for. Since there are minor stylistic differences, here's my take:

```<code>list.tail.foldLeft(List(list take 1)) {
    case (acc @ (lst @ hd :: _) :: tl, el) =>
        if (el == hd) (el :: lst) :: tl
        else (el :: Nil) :: acc
}
</code>```

Since the elements are identical, I didn't bother reversing the sublists.

Body:
Given e.g.:

List(5, 2, 3, 3, 3, 5, 5, 3, 3, 2, 2, 2)

I'd like to get to:

List(List(5), List(2), List(3, 3, 3), List(5, 5), List(3, 3), List(2, 2, 2))

I would assume there is a simple List function that does this, but am unable to find it.

Body:
Damn Rex Kerr, for writing the answer I'd go for. Since there are minor stylistic differences, here's my take:

list.tail.foldLeft(List(list take 1)) {
    case (acc @ (lst @ hd :: _) :: tl, el) =>
        if (el == hd) (el :: lst) :: tl
        else (el :: Nil) :: acc
}

Since the elements are identical, I didn't bother reversing the sublists.


问:
SQL join on columns of same table with MAX on another column
Have this table (top row is column names):

```<code>security    quote_type      price     round
sec_1       bid             3.4       1
sec_1       ask             3.6       1
sec_1       bid             3.5       2
sec_1       ask             3.7       2
sec_2       bid             5.2       1
sec_2       ask             5.4       1
sec_3       bid             2.3       1
sec_4       ask             7.8       1
sec_4       ask             7.9       2
</code>```

Need to achieve these results:

```<code>security    bid     ask      round
sec_1       3.5     3.7      2
sec_2       5.2     5.4      1
sec_3       2.3     null     1
sec_4       null    7.9      2
</code>```

Have this much working, which does not yet take into account the "round" column:

```<code>select security,
   max(case when quote_type = 'bid' then price end) as bid,
   max(case when quote_type = 'ask' then price end) as ask
from t
group by security;
</code>```

There will always be at most one bid and one ask price per security, per round.

Using SQL Server.

Thanks for any help!

答:
You seem to want the maximum round for each security.  Here is one method:</p>

```<code>select security,
       max(case when quote_type = 'bid' then price end) as bid,
       max(case when quote_type = 'ask' then price end) as ask
from (select t.*, max(round) over (partition by security) as max_round
      from t
     ) t
where round = max_round
group by security;
</code>```

Body:
Have this table (top row is column names):

security    quote_type      price     round
sec_1       bid             3.4       1
sec_1       ask             3.6       1
sec_1       bid             3.5       2
sec_1       ask             3.7       2
sec_2       bid             5.2       1
sec_2       ask             5.4       1
sec_3       bid             2.3       1
sec_4       ask             7.8       1
sec_4       ask             7.9       2

Need to achieve these results:

security    bid     ask      round
sec_1       3.5     3.7      2
sec_2       5.2     5.4      1
sec_3       2.3     null     1
sec_4       null    7.9      2

Have this much working, which does not yet take into account the "round" column:

select security,
   max(case when quote_type = 'bid' then price end) as bid,
   max(case when quote_type = 'ask' then price end) as ask
from t
group by security;

There will always be at most one bid and one ask price per security, per round.

Using SQL Server.

Thanks for any help!

Body:
You seem to want the maximum round for each security.  Here is one method:

select security,
       max(case when quote_type = 'bid' then price end) as bid,
       max(case when quote_type = 'ask' then price end) as ask
from (select t.*, max(round) over (partition by security) as max_round
      from t
     ) t
where round = max_round
group by security;


问:
WHERE inside CASE statement
I have seen lots of posts about putting CASE statements inside WHERE clauses.  However, in my case, I want to put a WHERE statement inside a CASE statement, which I don't think can be done.

My situation is that I have a view that is going on many, many databases.  In half of them, I need to have a WHERE clause.  In the other half, I don't need the WHERE clause.  Leaving it in isn't harmful, in that I don't get bad data, but it slows the query down considerably given that it has to read and sort a large table when it is unnecessary.

```<code>Status_Table
ID    Status
1     Active
2     Inactive
3     Unknown    --this row of data will not exist in some DBs

Item_table
Item_ID    Status    value1    value2
1001          3      .....     .....
1002          1      .....     .....
</code>```

What I want to do is something like this.

```<code>-- big nasty ugly query with various CTEs, selects, and joins
CASE    WHEN (SELECT MAX(ID) FROM Status_table) = 3
        THEN WHERE Item_Table.Status != 3
        ELSE WHERE 1=1
END
</code>```

Ultimately, I can probably swing this by constructing the query using dynamic SQL, but I was hoping for a more elegant solution.

答:
SQL Fiddle

MS SQL Server 2014 Schema Setup:

```<code>CREATE TABLE Status_Table ( ID int, [Status] varchar(30) ) ;
INSERT INTO Status_Table ( ID, [Status] )
VALUES
  ( 1,'Active' ), (2,'Inactive'), (3,'Unknown')
;

CREATE TABLE Item_table ( Item_ID int, [Status] int, value1 varchar(10), value2 varchar(10) ) ;
/* NOTE: Item_table.[Status] should be a descriptive name, like [StatusID], or something not the same name as a different datatype column in the relation table. */
INSERT INTO Item_Table ( Item_ID, [Status], value1, value2 )
VALUES (1001,3,'Bill','Exclude')
  ,(1002,1,'Ted','Include')
  ,(1003,3,'Rufus','Exclude')
  ,(1004,2,'Jay','Include')
  ,(1005,5,'Bob','BadRecord')
;
</code>```

Query 1:

```<code>SELECT s1.Item_ID, s1.Status, s1.Value1, s1.Value2
FROM (
  SELECT i.Item_ID, i.Status, i.Value1, i.Value2
    , RANK() OVER (ORDER BY s.ID DESC) AS rn
  FROM Item_Table i
  RIGHT OUTER JOIN Status_Table s ON i.[Status] = s.ID
) s1
WHERE s1.rn <> 1
</code>```

Results:

```<code>| Item_ID | Status | Value1 |  Value2 |
|---------|--------|--------|---------|
|    1004 |      2 |    Jay | Include |
|    1002 |      1 |    Ted | Include |
</code>```

Title: WHERE inside CASE statement

Body:
I have seen lots of posts about putting CASE statements inside WHERE clauses.  However, in my case, I want to put a WHERE statement inside a CASE statement, which I don't think can be done.

My situation is that I have a view that is going on many, many databases.  In half of them, I need to have a WHERE clause.  In the other half, I don't need the WHERE clause.  Leaving it in isn't harmful, in that I don't get bad data, but it slows the query down considerably given that it has to read and sort a large table when it is unnecessary.

Status_Table
ID    Status
1     Active
2     Inactive
3     Unknown    --this row of data will not exist in some DBs

Item_table
Item_ID    Status    value1    value2
1001          3      .....     .....
1002          1      .....     .....

What I want to do is something like this.

-- big nasty ugly query with various CTEs, selects, and joins
CASE    WHEN (SELECT MAX(ID) FROM Status_table) = 3
        THEN WHERE Item_Table.Status != 3
        ELSE WHERE 1=1
END

Ultimately, I can probably swing this by constructing the query using dynamic SQL, but I was hoping for a more elegant solution.

Body:
SQL Fiddle

MS SQL Server 2014 Schema Setup:

CREATE TABLE Status_Table ( ID int, [Status] varchar(30) ) ;
INSERT INTO Status_Table ( ID, [Status] )
VALUES
  ( 1,'Active' ), (2,'Inactive'), (3,'Unknown')
;

CREATE TABLE Item_table ( Item_ID int, [Status] int, value1 varchar(10), value2 varchar(10) ) ;
/* NOTE: Item_table.[Status] should be a descriptive name, like [StatusID], or something not the same name as a different datatype column in the relation table. */
INSERT INTO Item_Table ( Item_ID, [Status], value1, value2 )
VALUES (1001,3,'Bill','Exclude')
  ,(1002,1,'Ted','Include')
  ,(1003,3,'Rufus','Exclude')
  ,(1004,2,'Jay','Include')
  ,(1005,5,'Bob','BadRecord')
;

Query 1:

SELECT s1.Item_ID, s1.Status, s1.Value1, s1.Value2
FROM (
  SELECT i.Item_ID, i.Status, i.Value1, i.Value2
    , RANK() OVER (ORDER BY s.ID DESC) AS rn
  FROM Item_Table i
  RIGHT OUTER JOIN Status_Table s ON i.[Status] = s.ID
) s1
WHERE s1.rn <> 1

Results:

| Item_ID | Status | Value1 |  Value2 |
|---------|--------|--------|---------|
|    1004 |      2 |    Jay | Include |
|    1002 |      1 |    Ted | Include |


问:
EF Core 2.0 - Filtering data by user best practice
There seem to be many ways to achieve this, but im trying to figure out what the best practice would be with .net Core 2 / EF core 2.0.

I have objects such as

public class Company {
    public Guid CompanyID {get; set;}
    public ICollection<Order> Orders {get; set;}
    ...
    public ICollection<UserLocation> UserLocations { get; set; }
}

public class Order {
    public Guid CompanyID { get; set; }
    public Company Company { get; set; }
    public DateTime OrderDate {get; set;}
}

public class UserLocation {
    public Guid CompanyID { get; set; }
    public Company Company { get; set; }

    public String UserId { get; set; }
    public ApplicationUser ApplicationUser { get; set; }
}
```

For my company Index page I only want companies that the user has access to to be displayed. Could a global filter be used for this or does that not work for this situation?

Thank you

答: It depends, if the user should not have access to the companies a global filter is a good solution. When the requirement only applies to the index page, you can best make a specific query for the index page.</p>

Body:
There seem to be many ways to achieve this, but im trying to figure out what the best practice would be with .net Core 2 / EF core 2.0.

I have objects such as

public class Company {
    public Guid CompanyID {get; set;}
    public ICollection<Order> Orders {get; set;}
    ...
    public ICollection<UserLocation> UserLocations { get; set; }
}

public class Order {
    public Guid CompanyID { get; set; }
    public Company Company { get; set; }
    public DateTime OrderDate {get; set;}
}

public class UserLocation {
    public Guid CompanyID { get; set; }
    public Company Company { get; set; }

    public String UserId { get; set; }
    public ApplicationUser ApplicationUser { get; set; }
}

For my company Index page I only want companies that the user has access to to be displayed. Could a global filter be used for this or does that not work for this situation?

Thank you


问:
RxJava Combine Sequence Of Requests

The Problem

I have two Apis. Api 1 gives me a List of Items and Api 2 gives me more detailed Information for each of the items I got from Api 1. The way I solved it so far results in bad Performance.

The Question

Efficent and fast solution to this Problem with the help of Retrofit and RxJava.

My Approach

At the Moment my Solution Looks like this:

Step 1: Retrofit executes Single<ArrayList<Information>> from Api 1.

Step 2: I iterate through this Items and make a request for each to Api 2.

Step 3: Retrofit Returns Sequentially executes Single<ExtendedInformation> for
each item

Step 4: After all calls form Api 2 completely executed I create a new Object for all Items combining the Information and Extended Information.

My Code

```<code> public void addExtendedInformations(final Information[] informations) {
        final ArrayList<InformationDetail> informationDetailArrayList = new ArrayList<>();
        final JSONRequestRatingHelper.RatingRequestListener ratingRequestListener = new JSONRequestRatingHelper.RatingRequestListener() {
            @Override
            public void onDownloadFinished(Information baseInformation, ExtendedInformation extendedInformation) {
                informationDetailArrayList.add(new InformationDetail(baseInformation, extendedInformation));
                if (informationDetailArrayList.size() >= informations.length){
                    listener.onAllExtendedInformationLoadedAndCombined(informationDetailArrayList);
                }
            }
        };

        for (Information information : informations) {
            getExtendedInformation(ratingRequestListener, information);
        }
    }

    public void getRatingsByTitle(final JSONRequestRatingHelper.RatingRequestListener ratingRequestListener, final Information information) {
        Single<ExtendedInformation> repos = service.findForTitle(information.title);
        disposable.add(repos.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribeWith(new DisposableSingleObserver<ExtendedInformation>() {
            @Override
            public void onSuccess(ExtendedInformation extendedInformation) {
                    ratingRequestListener.onDownloadFinished(information, extendedInformation);
            }

            @Override
            public void onError(Throwable e) {
                ExtendedInformation extendedInformation = new ExtendedInformation();
                ratingRequestListener.onDownloadFinished(extendedInformation, information);
            }
        }));
    }

    public interface RatingRequestListener {

        void onDownloadFinished(Information information, ExtendedInformation extendedInformation);

    }
</code>```

答:
the flatMap operator is designed to cater to these types of workflows.

i'll outline the broad strokes with a simple five step example. hopefully you can easily reconstruct the same principles in your code:

```<code>@Test fun flatMapExample() {
    // (1) constructing a fake stream that emits a list of values
    Observable.just(listOf(1, 2, 3, 4, 5))
            // (2) convert our List emission into a stream of its constituent values
            .flatMap { numbers -> Observable.fromIterable(numbers) }
            // (3) subsequently convert each individual value emission into an Observable of some
            //     newly calculated type
            .flatMap { number ->
                when(number) {
                       1 -> Observable.just("A1")
                       2 -> Observable.just("B2")
                       3 -> Observable.just("C3")
                       4 -> Observable.just("D4")
                       5 -> Observable.just("E5")
                    else -> throw RuntimeException("Unexpected value for number [$number]")
                }
            }
            // (4) collect all the final emissions into a list
            .toList()
            .subscribeBy(
                    onSuccess = {
                        // (5) handle all the combined results (in list form) here
                        println("## onNext($it)")
                    },
                    onError = { error ->
                        println("## onError(${error.message})")
                    }
            )
}
</code>```

(incidentally, if the order of the emissions matter, look at using concatMap instead).

i hope that helps.

Title: RxJava Combine Sequence Of Requests

Body:
The Problem

I have two Apis. Api 1 gives me a List of Items and Api 2 gives me more detailed Information for each of the items I got from Api 1. The way I solved it so far results in bad Performance.

The Question

Efficent and fast solution to this Problem with the help of Retrofit and RxJava.

My Approach

At the Moment my Solution Looks like this:

Step 1: Retrofit executes Single<ArrayList<Information>> from Api 1.

Step 2: I iterate through this Items and make a request for each to Api 2.

Step 3: Retrofit Returns Sequentially executes Single<ExtendedInformation> for
each item

Step 4: After all calls form Api 2 completely executed I create a new Object for all Items combining the Information and Extended Information.

My Code

 public void addExtendedInformations(final Information[] informations) {
        final ArrayList<InformationDetail> informationDetailArrayList = new ArrayList<>();
        final JSONRequestRatingHelper.RatingRequestListener ratingRequestListener = new JSONRequestRatingHelper.RatingRequestListener() {
            @Override
            public void onDownloadFinished(Information baseInformation, ExtendedInformation extendedInformation) {
                informationDetailArrayList.add(new InformationDetail(baseInformation, extendedInformation));
                if (informationDetailArrayList.size() >= informations.length){
                    listener.onAllExtendedInformationLoadedAndCombined(informationDetailArrayList);
                }
            }
        };

        for (Information information : informations) {
            getExtendedInformation(ratingRequestListener, information);
        }
    }

    public void getRatingsByTitle(final JSONRequestRatingHelper.RatingRequestListener ratingRequestListener, final Information information) {
        Single<ExtendedInformation> repos = service.findForTitle(information.title);
        disposable.add(repos.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribeWith(new DisposableSingleObserver<ExtendedInformation>() {
            @Override
            public void onSuccess(ExtendedInformation extendedInformation) {
                    ratingRequestListener.onDownloadFinished(information, extendedInformation);
            }

            @Override
            public void onError(Throwable e) {
                ExtendedInformation extendedInformation = new ExtendedInformation();
                ratingRequestListener.onDownloadFinished(extendedInformation, information);
            }
        }));
    }

    public interface RatingRequestListener {

        void onDownloadFinished(Information information, ExtendedInformation extendedInformation);

    }

Body:
the flatMap operator is designed to cater to these types of workflows.

i'll outline the broad strokes with a simple five step example. hopefully you can easily reconstruct the same principles in your code:

@Test fun flatMapExample() {
    // (1) constructing a fake stream that emits a list of values
    Observable.just(listOf(1, 2, 3, 4, 5))
            // (2) convert our List emission into a stream of its constituent values
            .flatMap { numbers -> Observable.fromIterable(numbers) }
            // (3) subsequently convert each individual value emission into an Observable of some
            //     newly calculated type
            .flatMap { number ->
                when(number) {
                       1 -> Observable.just("A1")
                       2 -> Observable.just("B2")
                       3 -> Observable.just("C3")
                       4 -> Observable.just("D4")
                       5 -> Observable.just("E5")
                    else -> throw RuntimeException("Unexpected value for number [$number]")
                }
            }
            // (4) collect all the final emissions into a list
            .toList()
            .subscribeBy(
                    onSuccess = {
                        // (5) handle all the combined results (in list form) here
                        println("## onNext($it)")
                    },
                    onError = { error ->
                        println("## onError(${error.message})")
                    }
            )
}

(incidentally, if the order of the emissions matter, look at using concatMap instead).

i hope that helps.


问:
Protractor jasmine2-html-reporterHTML verify element was clicked
My jasmine-spec-reporter verifies that an element was clicked I see the check marks in the console view however in my protractor-jasmine2-html-reporter shows that the spec was skipped when it was actually clicked. How can I correct this?

I Know this has something to do with an expect statement for example this visually shows passed expect(browser.getCurrentUrl()).toEqual('https://adp.com');

However I am stomped on how to write and expect statement to show an element was clicked so that the protractor-jasmine2-html-reporter shows passed. Any Help would be appreciated. this is my code below

```<code> it('Load WFN home page - completed', function() {
        browser.get('https://wfn-iat.adp.com/public/index.htm');
        expect(browser.getCurrentUrl()).toEqual('https://wfn-iat.adp.com/public/index.htm');
    });

    it('click admin login - completed', function () {
        var adminlogin;
         adminlogin = ($('#adminLogin'));
        browser.wait(EC.elementToBeClickable(adminlogin), 5000).then(function() {
        adminlogin.click();
          // browser.sleep(10000);
        });
</code>```

答:
You can try with expect(EC.stalenessOf($('#adminLogin'),1000)).toBeTruthy(), so you check, if the Button is no longer present in the DOM.

That way the test would fail on invalid credentials, because in those case you'd probably stay on the page and show some error.

Also using .not seems an option, so something like:  expect($('#adminLogin')).not.toBePresent()

Body:
My jasmine-spec-reporter verifies that an element was clicked I see the check marks in the console view however in my protractor-jasmine2-html-reporter shows that the spec was skipped when it was actually clicked. How can I correct this?

I Know this has something to do with an expect statement for example this visually shows passed expect(browser.getCurrentUrl()).toEqual('https://adp.com');

However I am stomped on how to write and expect statement to show an element was clicked so that the protractor-jasmine2-html-reporter shows passed. Any Help would be appreciated. this is my code below

 it('Load WFN home page - completed', function() {
        browser.get('https://wfn-iat.adp.com/public/index.htm');
        expect(browser.getCurrentUrl()).toEqual('https://wfn-iat.adp.com/public/index.htm');
    });

    it('click admin login - completed', function () {
        var adminlogin;
         adminlogin = ($('#adminLogin'));
        browser.wait(EC.elementToBeClickable(adminlogin), 5000).then(function() {
        adminlogin.click();
          // browser.sleep(10000);
        });


问:
Extract rows from dataframe inside list inside dataframe in R
I'm using package RISmed in R in order to obtain information from PubMed. The 'Mesh' package function allows me to obtain the MeSH terms of each citation. Nevertheless it is a List, containing a Data Frame.
I want to list each MeSH term besides its corresponding citation id (PMID).
For example, I can construct a table containing both values:

```<code>table = cbind(ArticleId(MedlineObject),Mesh(MedlineObject))
</code>```

The first column is a char object but the second one is a list, containing a dataframe. If the value inside 1st column were "29145282" and the content of 2dnd column were "Cardiomyopathy, Hypertrophic", "Combined Modality Therapy" and "Diagnosis, Differential", I would want to obtain:

```<code>"29145282","Cardiomyopathy, Hypertrophic"
"29145282","Combined Modality Therapy"
"29145282","Diagnosis, Differential"
</code>```

How could I accomplish this?

答:
I would like to use myeloma as an example of medline object since I don't have your data. myeloma is a medline data within RISmed package.

First add the id to all dataframes in your list by mapply and cbind:

```<code>MedList = mapply(cbind, "ID"=ArticleId(myeloma),Mesh(myeloma),SIMPLIFY = FALSE)
</code>```

And then merge all list into one dataframe by do.call and rbind:

```<code>MedFrame = do.call("rbind",MedList)
</code>```

You just need to change 'myeloma' in the code to your own MedlineObject

Body:
I'm using package RISmed in R in order to obtain information from PubMed. The 'Mesh' package function allows me to obtain the MeSH terms of each citation. Nevertheless it is a List, containing a Data Frame.
I want to list each MeSH term besides its corresponding citation id (PMID).
For example, I can construct a table containing both values:

table = cbind(ArticleId(MedlineObject),Mesh(MedlineObject))

The first column is a char object but the second one is a list, containing a dataframe. If the value inside 1st column were "29145282" and the content of 2dnd column were "Cardiomyopathy, Hypertrophic", "Combined Modality Therapy" and "Diagnosis, Differential", I would want to obtain:

"29145282","Cardiomyopathy, Hypertrophic"
"29145282","Combined Modality Therapy"
"29145282","Diagnosis, Differential"

How could I accomplish this?

Body:
I would like to use myeloma as an example of medline object since I don't have your data. myeloma is a medline data within RISmed package.

First add the id to all dataframes in your list by mapply and cbind:

MedList = mapply(cbind, "ID"=ArticleId(myeloma),Mesh(myeloma),SIMPLIFY = FALSE)

And then merge all list into one dataframe by do.call and rbind:

MedFrame = do.call("rbind",MedList)

You just need to change 'myeloma' in the code to your own MedlineObject


问:
WebLogic stuck thread protection
By default WebLogic kills stuck threads after 15 min (600 s), this is controlled by StuckThreadMaxTime parameter.  However, I cannot find more details on how exactly "stuckness" is defined.  Specifically:

What is the point at which 15 min countdown begins.  Request processing start?  Last wait()-like method?  Something else?

Does this apply only to request-processing threads or to all threads?  I.e. can a request-processing thread "escape" this protection by spawning a worker thread for a long task?  Especially, can it delegate response writing to such a worker without 15 min countdown?

My usecase is download of huge files through a permission system.  Since a user needs to be authenticated and have permissions to view a file, I cannot (or at least don't know how) leave this to a simple HTTP server, e.g. Apache.  And because files can be huge, download could (at least in theory) take more than 15 minutes.

答:
The WLS10 WorkManager documentation can cause some real headscratching.  See http://blogs.oracle.com/jamesbayer/2010/01/work_manager_leash_for_slow_js.html for a step by step example of how to define a WorkManager for a webapp in weblogic.xml and assign a specific servlet to use it.

Adding to that example, you can add <ignore-stuck-threads>true</ignore-stuck-threads> to the <work-manager> definition which should prevent threads working for that WorkManager from being counted against a failed server state.

Title: WebLogic stuck thread protection


问:
replacement of words in strings
I have a list of phrases, in which I want to replace certain words with a similar word, in case it is misspelled.

How can I search a string, a word that matches and replace it?

The expected result is the following example:

```<code>a1<- c(" the classroom is ful ")
a2<- c(" full")
</code>```

In this case I would be replacing ful for full in a1

答:
Create a list of the corrections then replace them using gsubfn which is a generalization of gsub that can also take list, function and proto object replacement objects.  The regular expression matches a word boundary, one or more word characters and another word boundary.  Each time it finds a match it looks up the match in the list names and if found replaces it with the corresponding list value.

```<code>library(gsubfn)

L <- list(ful = "full")  # can add more words to this list if desired

gsubfn("\\b\\w+\\b", L, a1, perl = TRUE)
## [1] " the classroom is full "
</code>```

Title: replacement of words in strings

Body:
I have a list of phrases, in which I want to replace certain words with a similar word, in case it is misspelled.

How can I search a string, a word that matches and replace it?

The expected result is the following example:

a1<- c(" the classroom is ful ")
a2<- c(" full")

In this case I would be replacing ful for full in a1

Body:
Create a list of the corrections then replace them using gsubfn which is a generalization of gsub that can also take list, function and proto object replacement objects.  The regular expression matches a word boundary, one or more word characters and another word boundary.  Each time it finds a match it looks up the match in the list names and if found replaces it with the corresponding list value.

library(gsubfn)

L <- list(ful = "full")  # can add more words to this list if desired

gsubfn("\\b\\w+\\b", L, a1, perl = TRUE)
## [1] " the classroom is full "


问:
Very slow cursor SQL Server
I don't know why this is so slow

```<code>DECLARE kursor CURSOR FOR
    SELECT mediatime, ShortDate, MediaDateID, TimeID
    FROM DateTimeMCross

DECLARE @mediatime INT, @ShortDate DATE, @MediaDateID INT, @TimeID INT, @tmpDate DATE

SET @mediatime = 0;

OPEN kursor

FETCH NEXT FROM kursor INTO @mediatime, @ShortDate, @MediaDateID, @TimeID

WHILE @@FETCH_STATUS = 0
BEGIN
    /*SET @tmpDate = (select DATEADD(day,-1,@shortDate))*/
    IF @mediatime >= 2400
    BEGIN
        UPDATE DateTimeMCross
        SET DateTimeMCross.newMediaDateID = 2/*(SELECT     YEAR(@tmpDate) * 10000 + MONTH(@tmpDate) * 100 + DAY(@tmpDate))*/
        WHERE DateTimeMCross.MediaDateID = @MediaDateID
          AND DateTimeMCross.TimeID = @TimeID
    END
    ELSE IF @mediatime < 2400 AND @mediatime >= 0
    BEGIN
        UPDATE DateTimeMCross
        SET DateTimeMCross.newMediaDateID = @MediaDateID
        WHERE DateTimeMCross.MediaDateID = @MediaDateID
          AND DateTimeMCross.TimeID = @TimeID
    END

    FETCH NEXT FROM kursor INTO @mediatime, @ShortDate, @MediaDateID, @TimeID
END

CLOSE kursor
DEALLOCATE kursor
</code>```

I make before one statement with cursor and it was fast and this is really really slow.

I thought at the beginning it was caused by DATEADD() and other function but no. After comment out it is as slow as before

答:
You just need an UPDATE, not a cursor:

```<code>UPDATE d
SET d.newMediaDateID = CASE
                        WHEN mediatime>=2400 THEN 2
                        WHEN mediatime <2400 AND mediatime >=0 THEN MediaDateID
                        END
FROM DateTimeMCross d
</code>```

Title: Very slow cursor SQL Server

Body:
I don't know why this is so slow

DECLARE kursor CURSOR FOR
    SELECT mediatime, ShortDate, MediaDateID, TimeID
    FROM DateTimeMCross

DECLARE @mediatime INT, @ShortDate DATE, @MediaDateID INT, @TimeID INT, @tmpDate DATE

SET @mediatime = 0;

OPEN kursor

FETCH NEXT FROM kursor INTO @mediatime, @ShortDate, @MediaDateID, @TimeID

WHILE @@FETCH_STATUS = 0
BEGIN
    /*SET @tmpDate = (select DATEADD(day,-1,@shortDate))*/
    IF @mediatime >= 2400
    BEGIN
        UPDATE DateTimeMCross
        SET DateTimeMCross.newMediaDateID = 2/*(SELECT     YEAR(@tmpDate) * 10000 + MONTH(@tmpDate) * 100 + DAY(@tmpDate))*/
        WHERE DateTimeMCross.MediaDateID = @MediaDateID
          AND DateTimeMCross.TimeID = @TimeID
    END
    ELSE IF @mediatime < 2400 AND @mediatime >= 0
    BEGIN
        UPDATE DateTimeMCross
        SET DateTimeMCross.newMediaDateID = @MediaDateID
        WHERE DateTimeMCross.MediaDateID = @MediaDateID
          AND DateTimeMCross.TimeID = @TimeID
    END

    FETCH NEXT FROM kursor INTO @mediatime, @ShortDate, @MediaDateID, @TimeID
END

CLOSE kursor
DEALLOCATE kursor

I make before one statement with cursor and it was fast and this is really really slow.

I thought at the beginning it was caused by DATEADD() and other function but no. After comment out it is as slow as before

Body:
You just need an UPDATE, not a cursor:

UPDATE d
SET d.newMediaDateID = CASE
                        WHEN mediatime>=2400 THEN 2
                        WHEN mediatime <2400 AND mediatime >=0 THEN MediaDateID
                        END
FROM DateTimeMCross d


问:
enum returning spring beans dynamically
Is it possible for an enum to return different spring beans for different values?

If possible, we can create an enum holding different values, and we can return different type of spring component for a different value.

I wanted to achieve something like this:

```<code>public enum MyFactory {
    BEAN1 {
        @Autowired
        Bean1 bean1;

       @Override
       public MyBean getMyBean() {
           return bean1;
       }
    },
    BEAN2 {
        @Autowired
        Bean1 bean2;

       @Override
       public MyBean getMyBean() {
           return bean2;
       }
    };

    public abstract MyBean getMyBean();
}
</code>```

Thanks,

答:
Java enums are designed to be constant values.

But to achieve you requirement, you should set the enum states after their creation or passing as parameter the ApplicationContext to the enum method or to an enum method initialization.

It defeats the enum purpose : constant values.

I think that it is make more sense to define a bean class that provides beans defined once and without way to change them.

```<code>@Component
public class MyEnumClass{

   @Autowired
   private Value valueA;

   @Autowired
   private Value valueB;

   public Value getValueA(){
       return valueA;
   }

   public Value getValueB(){
       return valueB;
   }
   ...

}
</code>```

Where Value class is preferably not mutable.

Title: enum returning spring beans dynamically

Body:
Is it possible for an enum to return different spring beans for different values?

If possible, we can create an enum holding different values, and we can return different type of spring component for a different value.

I wanted to achieve something like this:

public enum MyFactory {
    BEAN1 {
        @Autowired
        Bean1 bean1;

       @Override
       public MyBean getMyBean() {
           return bean1;
       }
    },
    BEAN2 {
        @Autowired
        Bean1 bean2;

       @Override
       public MyBean getMyBean() {
           return bean2;
       }
    };

    public abstract MyBean getMyBean();
}

Thanks,

Body:
Java enums are designed to be constant values.

But to achieve you requirement, you should set the enum states after their creation or passing as parameter the ApplicationContext to the enum method or to an enum method initialization.

It defeats the enum purpose : constant values.

I think that it is make more sense to define a bean class that provides beans defined once and without way to change them.

@Component
public class MyEnumClass{

   @Autowired
   private Value valueA;

   @Autowired
   private Value valueB;

   public Value getValueA(){
       return valueA;
   }

   public Value getValueB(){
       return valueB;
   }
   ...

}

Where Value class is preferably not mutable.


问:
Input value not changed when clicking div
I want to change the value of a input and submit it after clicking.
For some reason it is not submited.

The value inside the input increase or decrease when clicking the div, but it is not submitting.

When I change the value inside the input and offocus, it does save.

What am I missing here?

```<code><div class="reduced items item-<?php echo $this->getQty() ?>" onclick="
var result_<?php echo $item->getId() ?> = document.getElementById('qty_<?php echo $item->getId() ?>');
var qty_<?php echo $item->getId() ?> = result_<?php echo $item->getId() ?>.value;
if( !isNaN( qty_<?php echo $item->getId() ?> ) && qty_<?php echo $item->getId() ?> > 1 ) result_<?php echo $item->getId() ?>.value--;
$(location.href='save').submit();
return false;">-</div>

<input type="text" name="quote_request[<?php echo $item->getId() ?>][qty][]" id="qty_<?php echo $item->getId() ?>" value="<?php echo $item->getQty()*1; ?>" size="4" title="<?php echo $this->__('Qty') ?>" onchange="location.href='save'" class="required-entry validate-zero-or-greater input-text" maxlength="12" />

<div class="increase items" onclick="
var result_<?php echo $item->getId() ?> = document.getElementById('qty_<?php echo $item->getId() ?>');
var qty_<?php echo $item->getId() ?> = result_<?php echo $item->getId() ?>.value;
if( !isNaN( qty_<?php echo $item->getId() ?> )) result_<?php echo $item->getId() ?>.value++;
$(location.href='save').submit();
return false;">+</div>
</code>```

答:
Well,
First you should not mix your php/html/javascript code like in the way that you did.

Second, avoid put the id, or whatever another code value in the variable name, instead use an Array's with the key value equivalent to id.

Third, use functions, the easily way to see the problem that is occuring, is cleaning your code.

Your problem is because you are using location.href inside the jquery seletor, I dont know what is your form, but the correctly way to submit a form  is something like this:

```<code>function click_function_down(item_id) {
    var result[item_id] = document.getElementById('qty_' + item_id);
    var qty[item_id] = result[item_id].value;
    if( !isNaN( qty[item_id] )
        && qty[item_id] > 1 ) {
            result[item_id].value--;
        }

    $('#yourform').submit();
    return false;
}

function click_function_up(item_id) {
    var result[item_id] = document.getElementById('qty_' + item_id);
    var qty[item_id] = result[item_id].value;
    if( !isNaN( qty[item_id] ) ) {
            result[item_id].value--;
        }

    $('#yourform').submit();
    return false;
}
</code>```

And the html code:

```<code><form id="yourform" action="save">
<div
class="reduced items item-<?php echo $this->getQty() ?>"
onclick="click_function_up(<?php echo $item->getId() ?>)">
-
</div>

<input
type="text"
name="quote_request[<?php echo $item->getId() ?>][qty][]"
id="qty_<?php echo $item->getId() ?>" value="<?php echo $item->getQty()*1; ?>"
size="4"
title="<?php echo $this->__('Qty') ?>"
onchange="location.href='save'"
class="required-entry validate-zero-or-greater input-text"
 maxlength="12" />

<div
class="reduced items item-<?php echo $this->getQty() ?>"
onclick="click_function_up(<?php echo $item->getId() ?>)">
-
</div>
</code>```

try this, and let me know if you could fix the problem.

Body:
I want to change the value of a input and submit it after clicking.
For some reason it is not submited.

The value inside the input increase or decrease when clicking the div, but it is not submitting.

When I change the value inside the input and offocus, it does save.

What am I missing here?

<div class="reduced items item-<?php echo $this->getQty() ?>" onclick="
var result_<?php echo $item->getId() ?> = document.getElementById('qty_<?php echo $item->getId() ?>');
var qty_<?php echo $item->getId() ?> = result_<?php echo $item->getId() ?>.value;
if( !isNaN( qty_<?php echo $item->getId() ?> ) && qty_<?php echo $item->getId() ?> > 1 ) result_<?php echo $item->getId() ?>.value--;
$(location.href='save').submit();
return false;">-

<input type="text" name="quote_request[<?php echo $item->getId() ?>][qty][]" id="qty_<?php echo $item->getId() ?>" value="<?php echo $item->getQty()*1; ?>" size="4" title="<?php echo $this->__('Qty') ?>" onchange="location.href='save'" class="required-entry validate-zero-or-greater input-text" maxlength="12" />

<div class="increase items" onclick="
var result_<?php echo $item->getId() ?> = document.getElementById('qty_<?php echo $item->getId() ?>');
var qty_<?php echo $item->getId() ?> = result_<?php echo $item->getId() ?>.value;
if( !isNaN( qty_<?php echo $item->getId() ?> )) result_<?php echo $item->getId() ?>.value++;
$(location.href='save').submit();
return false;">+

Body:
Well,
First you should not mix your php/html/javascript code like in the way that you did.

Second, avoid put the id, or whatever another code value in the variable name, instead use an Array's with the key value equivalent to id.

Third, use functions, the easily way to see the problem that is occuring, is cleaning your code.

Your problem is because you are using location.href inside the jquery seletor, I dont know what is your form, but the correctly way to submit a form  is something like this:

function click_function_down(item_id) {
    var result[item_id] = document.getElementById('qty_' + item_id);
    var qty[item_id] = result[item_id].value;
    if( !isNaN( qty[item_id] )
        && qty[item_id] > 1 ) {
            result[item_id].value--;
        }

    $('#yourform').submit();
    return false;
}

function click_function_up(item_id) {
    var result[item_id] = document.getElementById('qty_' + item_id);
    var qty[item_id] = result[item_id].value;
    if( !isNaN( qty[item_id] ) ) {
            result[item_id].value--;
        }

    $('#yourform').submit();
    return false;
}

And the html code:

<form id="yourform" action="save">
<div
class="reduced items item-<?php echo $this->getQty() ?>"
onclick="click_function_up(<?php echo $item->getId() ?>)">
-
</div>

<input
type="text"
name="quote_request[<?php echo $item->getId() ?>][qty][]"
id="qty_<?php echo $item->getId() ?>" value="<?php echo $item->getQty()*1; ?>"
size="4"
title="<?php echo $this->__('Qty') ?>"
onchange="location.href='save'"
class="required-entry validate-zero-or-greater input-text"
 maxlength="12" />

<div
class="reduced items item-<?php echo $this->getQty() ?>"
onclick="click_function_up(<?php echo $item->getId() ?>)">
-
</div>

try this, and let me know if you could fix the problem.


问:
Dynamic table design (common lookup table), need a nice query to get the values
sql2005

This is my simplified example:
(in reality there are 40+ tables in here, I only showed 2)

I got a table called tb_modules, with 3 columns (id, description, tablename as varchar):

```<code> 1, UserType, tb_usertype
 2, Religion, tb_religion
</code>```

(Last column is actually the name of a different table)

I got an other table that looks like this:
tb_value (columns:id, tb_modules_ID, usertype_OR_religion_ID)
values:

```<code> 1111, 1, 45
 1112, 1, 55
 1113, 2, 123
 1114, 2, 234
</code>```

so, I mean 45, 55, 123, 234 are usertype OR religion ID's
(45, 55 usertype, 123, 234 religion ID`s)

Don't judge, I didn't design the database

Question
How can I make a select, showing * from tb_value, plus one column
That one column would be TITLE from the tb_usertype or RELIGIONNAME from the tb_religion table

I would like to make a general thing.
Was thinking initially about maybe a SQL function that returns a string, but I think I would need dynamic SQL, which is not ok in a function.

Anyone a better idea ?

答:
I think it's intended to be used with dynamic sql.

Maybe break out each tb_value.tb_modules_ID row into its own temp table, named with the tb_modules.tablename.

Then have an sp iterate through the temp tables matching your naming convention (by prefix or suffix) building the sql and doing your join.

Body:
sql2005

This is my simplified example:
(in reality there are 40+ tables in here, I only showed 2)

I got a table called tb_modules, with 3 columns (id, description, tablename as varchar):

 1, UserType, tb_usertype
 2, Religion, tb_religion

(Last column is actually the name of a different table)

I got an other table that looks like this:
tb_value (columns:id, tb_modules_ID, usertype_OR_religion_ID)
values:

 1111, 1, 45
 1112, 1, 55
 1113, 2, 123
 1114, 2, 234

so, I mean 45, 55, 123, 234 are usertype OR religion ID's
(45, 55 usertype, 123, 234 religion ID`s)

Don't judge, I didn't design the database

Question
How can I make a select, showing * from tb_value, plus one column
That one column would be TITLE from the tb_usertype or RELIGIONNAME from the tb_religion table

I would like to make a general thing.
Was thinking initially about maybe a SQL function that returns a string, but I think I would need dynamic SQL, which is not ok in a function.

Anyone a better idea ?


问:
Extracting superset list from pandas dataframe
In the foll. dataframe, I have a collection of year and month values as tuples in a list:

```<code>state
alabama           [(2017.0, 10.0), (2017.0, 11.0), (2017.0, 12.0), (2018.0, 1.0)]
arkansas          [(2017.0, 10.0), (2017.0, 11.0), (2017.0, 12.0)]
colorado          [(2017.0, 9.0), (2017.0, 10.0), (2017.0, 11.0)]
</code>```

How can I extract a superset list of year and month combinations? In this case, the soln would be:

```<code>[(2017.0, 9.0), (2017.0, 10.0), (2017.0, 11.0), (2017.0, 12.0), (2018.0, 1.0)]
</code>```

I could potentially do it using a for loop but that would be slow, anything more pythonic?

Here is what I tried:

```<code>for row in df:
    if all(y in row for x, y in df):
        tmp = row
</code>```

but I get this error:

```<code>ValueError: too many values to unpack (expected 2)
</code>```

Body:
In the foll. dataframe, I have a collection of year and month values as tuples in a list:

state
alabama           [(2017.0, 10.0), (2017.0, 11.0), (2017.0, 12.0), (2018.0, 1.0)]
arkansas          [(2017.0, 10.0), (2017.0, 11.0), (2017.0, 12.0)]
colorado          [(2017.0, 9.0), (2017.0, 10.0), (2017.0, 11.0)]

How can I extract a superset list of year and month combinations? In this case, the soln would be:

[(2017.0, 9.0), (2017.0, 10.0), (2017.0, 11.0), (2017.0, 12.0), (2018.0, 1.0)]

I could potentially do it using a for loop but that would be slow, anything more pythonic?

Here is what I tried:

for row in df:
    if all(y in row for x, y in df):
        tmp = row

but I get this error:

ValueError: too many values to unpack (expected 2)

Body:
Using a sample DF from your previous question:

In [109]: df[['Year','Month']].sort_values(['Year','Month']).drop_duplicates().values.tolist()
Out[109]:
[[2017.0, 10.0],
 [2017.0, 11.0],
 [2017.0, 12.0],
 [2018.0, 1.0],
 [2018.0, 2.0],
 [2018.0, 3.0],
 [2018.0, 4.0],
 [2018.0, 5.0],
 [2018.0, 6.0],
 [2018.0, 7.0]]


问:
django creating generic class to validate User authentication
I am trying to replace the generic View class with a custom class so that the user authentication happens automatically when i make a reference to this class.

The Base Class

```<code>class CustomView(View):

    def __init__(self, request):
        if not request.user.is_authenticated:
            redirect('register.registerForm')
</code>```

The sub class

class DashboardPage(CustomView):

```<code>def get(self, request):
    user_object = User.objects.get(username=request.user)
    all_files = user_object.files_set.all()
    return render(request, 'dashboard/dashboard.html', {'all_files': all_files})
</code>```

I expected the user authentication happened automatically when the CustomView class is called. And also wanted to know if this is the best way to generalize user authentication for all the pages in my application which require authentication.

I am getting the below error:

```<code>TypeError at /dashboard/
__init__() missing 1 required positional argument: 'request'
Request Method: GET
Request URL:    http://127.0.0.1:8000/dashboard/
Django Version: 1.11.7
Exception Type: TypeError
Exception Value:
__init__() missing 1 required positional argument: 'request'
Exception Location: C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.7-py3.6.egg\django\views\generic\base.py in view, line 62
Python Executable:  C:\Program Files (x86)\Python36-32\python.exe
Python Version: 3.6.3
Python Path:
['C:\\Users\\Varun\\Desktop\\newsite',
 'C:\\Program Files (x86)\\Python36-32\\python36.zip',
 'C:\\Program Files (x86)\\Python36-32\\DLLs',
 'C:\\Program Files (x86)\\Python36-32\\lib',
 'C:\\Program Files (x86)\\Python36-32',
 'C:\\Program Files (x86)\\Python36-32\\lib\\site-packages',
 'C:\\Program Files '
 '(x86)\\Python36-32\\lib\\site-packages\\django-1.11.7-py3.6.egg',
 'C:\\Program Files '
 '(x86)\\Python36-32\\lib\\site-packages\\pytz-2017.3-py3.6.egg']
Server time:    Mon, 4 Dec 2017 20:43:12 +0000
</code>```

答:
You should not override __init__ in a view class.

However, there is no need to do any of this. Django already includes a LoginRequired mixin which does exactly what you want.

Body:
I am trying to replace the generic View class with a custom class so that the user authentication happens automatically when i make a reference to this class.

The Base Class

class CustomView(View):

    def __init__(self, request):
        if not request.user.is_authenticated:
            redirect('register.registerForm')

The sub class

class DashboardPage(CustomView):

def get(self, request):
    user_object = User.objects.get(username=request.user)
    all_files = user_object.files_set.all()
    return render(request, 'dashboard/dashboard.html', {'all_files': all_files})

I expected the user authentication happened automatically when the CustomView class is called. And also wanted to know if this is the best way to generalize user authentication for all the pages in my application which require authentication.

I am getting the below error:

TypeError at /dashboard/
__init__() missing 1 required positional argument: 'request'
Request Method: GET
Request URL:    http://127.0.0.1:8000/dashboard/
Django Version: 1.11.7
Exception Type: TypeError
Exception Value:
__init__() missing 1 required positional argument: 'request'
Exception Location: C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.7-py3.6.egg\django\views\generic\base.py in view, line 62
Python Executable:  C:\Program Files (x86)\Python36-32\python.exe
Python Version: 3.6.3
Python Path:
['C:\\Users\\Varun\\Desktop\\newsite',
 'C:\\Program Files (x86)\\Python36-32\\python36.zip',
 'C:\\Program Files (x86)\\Python36-32\\DLLs',
 'C:\\Program Files (x86)\\Python36-32\\lib',
 'C:\\Program Files (x86)\\Python36-32',
 'C:\\Program Files (x86)\\Python36-32\\lib\\site-packages',
 'C:\\Program Files '
 '(x86)\\Python36-32\\lib\\site-packages\\django-1.11.7-py3.6.egg',
 'C:\\Program Files '
 '(x86)\\Python36-32\\lib\\site-packages\\pytz-2017.3-py3.6.egg']
Server time:    Mon, 4 Dec 2017 20:43:12 +0000


问:
Tensorflow variable scope: reuse if variable exists
I want a piece of code that creates a variable within a scope if it doesn't exist, and access the variable if it already exists. I need it to be the same code since it will be called multiple times.

However, Tensorflow needs me to specify whether I want to create or reuse the variable, like this:

```<code>with tf.variable_scope("foo"): #create the first time
    v = tf.get_variable("v", [1])

with tf.variable_scope("foo", reuse=True): #reuse the second time
    v = tf.get_variable("v", [1])
</code>```

How can I get it to figure out whether to create or reuse it automatically? I.e., I want the above two blocks of code to be the same and have the program run.

答:
New AUTO_REUSE option does the trick.

From the tf.variable_scope API docs: if reuse=tf.AUTO_REUSE, we create variables if they do not exist, and return them otherwise.

Basic example of sharing a variable AUTO_REUSE:

```<code>def foo():
  with tf.variable_scope("foo", reuse=tf.AUTO_REUSE):
    v = tf.get_variable("v", [1])
  return v

v1 = foo()  # Creates v.
v2 = foo()  # Gets the same, existing v.
assert v1 == v2
</code>```

Body:
I want a piece of code that creates a variable within a scope if it doesn't exist, and access the variable if it already exists. I need it to be the same code since it will be called multiple times.

However, Tensorflow needs me to specify whether I want to create or reuse the variable, like this:

with tf.variable_scope("foo"): #create the first time
    v = tf.get_variable("v", [1])

with tf.variable_scope("foo", reuse=True): #reuse the second time
    v = tf.get_variable("v", [1])

How can I get it to figure out whether to create or reuse it automatically? I.e., I want the above two blocks of code to be the same and have the program run.

Body:
New AUTO_REUSE option does the trick.

From the tf.variable_scope API docs: if reuse=tf.AUTO_REUSE, we create variables if they do not exist, and return them otherwise.

Basic example of sharing a variable AUTO_REUSE:

def foo():
  with tf.variable_scope("foo", reuse=tf.AUTO_REUSE):
    v = tf.get_variable("v", [1])
  return v

v1 = foo()  # Creates v.
v2 = foo()  # Gets the same, existing v.
assert v1 == v2


问:
How to Assign values to a List of Lists in scala using loops?
I am new to scala so finding difficulty. can some one please guide me about how to initialize a list of lists using for loop?? I tried this:

for(i <- 1 to N)
  {
    for(D <- 1 to Dimensions)
    {
  Population=List(List(D,i))
    }```

but it is not working well

答:
You don't want to assign values to an existing List. That's not what the List type is good for and it would be very poor Scala style. What you can and should do, however, is create a new List[List[Int]] with all the needed elements.

```<code>val population:List[List[Int]] = for {
  i <- (1 to n).toList
  d <- 1 to dimension
} yield List(d,i)
</code>```

The 1st Range (1 to n) is cast to List so that the result will be List[List[Int]]. Without it the result is Seq[List[Int]].

Body:
I am new to scala so finding difficulty. can some one please guide me about how to initialize a list of lists using for loop?? I tried this:

for(i <- 1 to N)
  {
    for(D <- 1 to Dimensions)
    {
  Population=List(List(D,i))
    }

but it is not working well

Body:
You don't want to assign values to an existing List. That's not what the List type is good for and it would be very poor Scala style. What you can and should do, however, is create a new List[List[Int]] with all the needed elements.

val population:List[List[Int]] = for {
  i <- (1 to n).toList
  d <- 1 to dimension
} yield List(d,i)

The 1st Range (1 to n) is cast to List so that the result will be List[List[Int]]. Without it the result is Seq[List[Int]].