问:
VB.net Printing Image to Zebra
I have a bitmap image in VB.net that I want to print to a Zebra printer, hopefully using the ZPLII code. I have seen the example here: Working with bitmaps to a ZPL label printer with no luck. Can anyone help with this? I have hit my head against the wall for days on this. Thanks in advance!</p>

答:
i have a solution

```<code>         Imports System.Drawing
        Imports System.Drawing.Imaging
        Imports System.IO
        Imports System.Runtime.InteropServices
        Imports System.Text

        Class CONVERTBITMAP

            ''' <summary>
            ''' Return codeZPL of an bitmap
            ''' </summary>
            ''' <param name="BMP2">BITMAP</param>
            ''' <returns></returns>
            Public Shared Function CreateGRF(BMP2 As Bitmap) As String
                'Dim bmp2 As Bitmap = Nothing
                Dim bmp As Bitmap = Nothing
                Dim imgData As BitmapData = Nothing
                Dim pixels As Byte()
                Dim x As Integer, y As Integer, width As Integer
                Dim sb As StringBuilder
                Dim ptr As IntPtr
                Try
                    bmp = CONVERTBITMAP.CopyToBpp(BMP2, 1)
                    imgData = bmp.LockBits(New Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.[ReadOnly], PixelFormat.Format1bppIndexed)
                    width = Math.Abs(imgData.Stride)
                    pixels = New Byte(width - 1) {}
                    sb = New StringBuilder(width * bmp.Height * 2)
                    ptr = imgData.Scan0
                    Dim PREVNUM As Integer = 0
                    For y = 0 To bmp.Height - 1
                        Marshal.Copy(ptr, pixels, 0, width)
                        For x = 0 To width - 1
                            If (x + 1) * 8 > bmp.Width Then
                                Dim DIF As Integer = ((x + 1) * 8) - bmp.Width
                                Dim NUM As Integer = (2 ^ (DIF - PREVNUM)) - 1
                                Dim BYTENOT As Byte = Not (CByte(NUM))
                                PREVNUM = DIF
                                If NUM < 255 Then
                                    Dim NOTPX As Byte = Not (pixels(x))
                                    Dim CBYTE2 As Byte = CByte(NUM)
                                    Dim STR As Byte = Format("{0:X2}", NOTPX - CBYTE2)
                                    sb.AppendFormat("{0:X2}", CByte(STR))
                                Else
                                    sb.AppendFormat("{0:X2}", CByte(0))
                                End If

                            Else
                                sb.AppendFormat("{0:X2}", CByte(Not pixels(x)))
                            End If

                        Next
                        PREVNUM = 0
                        ptr = ptr.ToInt64 + imgData.Stride    'DirectCast(ptr.ToInt64() + imgData.Stride), IntPtr)
                    Next
                Finally
                    If bmp IsNot Nothing Then
                        If imgData IsNot Nothing Then
                            bmp.UnlockBits(imgData)
                        End If
                        bmp.Dispose()
                    End If
                End Try
                Return [String].Format("^GFA,{0},{0},{1},", width * y, width) + sb.ToString()
            End Function
        End Class
</code>```

then, for use

```<code>    public function Create_ZPLImage(my_Image As Image) as string
        return CONVERTBITMAP.CreateGRF(_Image)
    End Sub
</code>```

work for me

Title: VB.net Printing Image to Zebra

Body:
i have a solution

         Imports System.Drawing
        Imports System.Drawing.Imaging
        Imports System.IO
        Imports System.Runtime.InteropServices
        Imports System.Text

        Class CONVERTBITMAP

            ''' <summary>
            ''' Return codeZPL of an bitmap
            ''' </summary>
            ''' <param name="BMP2">BITMAP</param>
            ''' <returns></returns>
            Public Shared Function CreateGRF(BMP2 As Bitmap) As String
                'Dim bmp2 As Bitmap = Nothing
                Dim bmp As Bitmap = Nothing
                Dim imgData As BitmapData = Nothing
                Dim pixels As Byte()
                Dim x As Integer, y As Integer, width As Integer
                Dim sb As StringBuilder
                Dim ptr As IntPtr
                Try
                    bmp = CONVERTBITMAP.CopyToBpp(BMP2, 1)
                    imgData = bmp.LockBits(New Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.[ReadOnly], PixelFormat.Format1bppIndexed)
                    width = Math.Abs(imgData.Stride)
                    pixels = New Byte(width - 1) {}
                    sb = New StringBuilder(width * bmp.Height * 2)
                    ptr = imgData.Scan0
                    Dim PREVNUM As Integer = 0
                    For y = 0 To bmp.Height - 1
                        Marshal.Copy(ptr, pixels, 0, width)
                        For x = 0 To width - 1
                            If (x + 1) * 8 > bmp.Width Then
                                Dim DIF As Integer = ((x + 1) * 8) - bmp.Width
                                Dim NUM As Integer = (2 ^ (DIF - PREVNUM)) - 1
                                Dim BYTENOT As Byte = Not (CByte(NUM))
                                PREVNUM = DIF
                                If NUM < 255 Then
                                    Dim NOTPX As Byte = Not (pixels(x))
                                    Dim CBYTE2 As Byte = CByte(NUM)
                                    Dim STR As Byte = Format("{0:X2}", NOTPX - CBYTE2)
                                    sb.AppendFormat("{0:X2}", CByte(STR))
                                Else
                                    sb.AppendFormat("{0:X2}", CByte(0))
                                End If

                            Else
                                sb.AppendFormat("{0:X2}", CByte(Not pixels(x)))
                            End If

                        Next
                        PREVNUM = 0
                        ptr = ptr.ToInt64 + imgData.Stride    'DirectCast(ptr.ToInt64() + imgData.Stride), IntPtr)
                    Next
                Finally
                    If bmp IsNot Nothing Then
                        If imgData IsNot Nothing Then
                            bmp.UnlockBits(imgData)
                        End If
                        bmp.Dispose()
                    End If
                End Try
                Return [String].Format("^GFA,{0},{0},{1},", width * y, width) + sb.ToString()
            End Function
        End Class

then, for use

    public function Create_ZPLImage(my_Image As Image) as string
        return CONVERTBITMAP.CreateGRF(_Image)
    End Sub

work for me


来源: stackexchange

问:
Changing a Qsys design to run latest version of uClinux
I'm using a design in Qsys to run uClinux v2.6.

I would like to run a newer Linx but I wa told that I must change the Qsys design and add another timer because newer Linux uses two timers. Is that correct and where can I find information about that?

The board I use is Altera DE2-115 and it works to run old linux 2.6 with the Qsys design.

答:
You can find the documentation here: https://rocketboards.org/foswiki/view/Documentation/NiosIILinuxUserManual

The information on the website confirms the two timers need, I have not tested with only one. I am using kernel 4.1 ltsi on DE2-115 and it works fine.

ContentLicense: CC BY-SA 3.0


问:
Async pipe does not fill object data into template
Can anyone help me see if there is a syntax error here in my template? It does not give error, but does not fill in data into the template either:

{{hero}}

{{hero.name}} details!

    _id: {{hero._id}}

    name:
    <input [(ngModel)]="hero.name" placeholder="name" />

  <button (click)="goBack()">Back</button>

```
<p>Component code</p>
<pre class="lang-js prettyprint-override"><code>export class HeroDetailComponent implements OnInit {
    errorMessage: string;

    @Input() hero: Observable<Hero>;

    constructor(
        private _heroService: HeroService,
        private _routeParams: RouteParams
    ) {}

    ngOnInit() {
        let _id = +this._routeParams.get('_id');
        this._heroService.loadHero(_id);
        this.hero = this._heroService.hero$;
        this.hero.subscribe(data =>
           console.log(data)
        );
    }
}
</code>```

The console.log(data) prints:

Object {_id: 11, name: "Mr. Nice"}

which means that the data is correctly retrieved.

The
 block also shows up, which mean *ngIf sees the object as non-empty.

{{hero}}
 shows [object Object].

But why the {{hero.name}} is not showing?

答:
This is now possible using the 'as' syntax, available in v4.0.0:

```<code><span *ngIf="user$ | async as user; else loadingUserInfo">
 {{user.firstName}} {{user.lastName}}
</span>
<ng-template #loadingUserInfo>
  Loading user information...
</ng-template>
</code>```

More details available in the RFC thread on github.

ContentLicense: CC BY-SA 4.0

Body:
Can anyone help me see if there is a syntax error here in my template? It does not give error, but does not fill in data into the template either:

{{hero}}

{{hero.name}} details!

    _id: {{hero._id}}

    name:
    <input [(ngModel)]="hero.name" placeholder="name" />

  <button (click)="goBack()">Back</button>

Component code

export class HeroDetailComponent implements OnInit {
    errorMessage: string;

    @Input() hero: Observable<Hero>;

    constructor(
        private _heroService: HeroService,
        private _routeParams: RouteParams
    ) {}

    ngOnInit() {
        let _id = +this._routeParams.get('_id');
        this._heroService.loadHero(_id);
        this.hero = this._heroService.hero$;
        this.hero.subscribe(data =>
           console.log(data)
        );
    }
}

The console.log(data) prints:

Object {_id: 11, name: "Mr. Nice"}

which means that the data is correctly retrieved.

The
 block also shows up, which mean *ngIf sees the object as non-empty.

{{hero}}
 shows [object Object].

But why the {{hero.name}} is not showing?

Body:
This is now possible using the 'as' syntax, available in v4.0.0:

<span *ngIf="user$ | async as user; else loadingUserInfo">
 {{user.firstName}} {{user.lastName}}
</span>
<ng-template #loadingUserInfo>
  Loading user information...
</ng-template>

More details available in the RFC thread on github.


问:
Animated GIF in IE stopping
Does anyone know a work around to make animated GIF's continue to be animated after you click a link or submit a form on the page your on in IE? This works fine in other browsers.

Thanks.

答:
A very easy way is to use jQuery and SimpleModal plugin.
Then when I need to show my "loading" gif on submit, I do:</p>

```<code>$('*').css('cursor','wait');
$.modal("<table style='white-space: nowrap'><tr><td style='white-space: nowrap'><b>Please wait...</b></td><td><img alt='Please wait' src='loader.gif' /></td></tr></table>", {escClose:false} );
</code>```

ContentLicense: CC BY-SA 2.5

Title: Animated GIF in IE stopping

Body:
A very easy way is to use jQuery and SimpleModal plugin.
Then when I need to show my "loading" gif on submit, I do:

$('*').css('cursor','wait');
$.modal("<table style='white-space: nowrap'><tr><td style='white-space: nowrap'><b>Please wait...</b></td><td><img alt='Please wait' src='loader.gif' /></td></tr></table>", {escClose:false} );


问:
How can I tell which classes Proguard warns me about?
I am trying to release my app and ProGuard is causing all sorts of errors with my server code so I went into the gradle console and see this:

```<code>Note: there were 2 references to unknown classes.
  You should check your configuration for typos.
  (http://proguard.sourceforge.net/manual/troubleshooting.html#unknownclass)
Note: there were 26 unkept descriptor classes in kept class members.
  You should consider explicitly keeping the mentioned classes
  (using '-keep').
  (http://proguard.sourceforge.net/manual/troubleshooting.html#descriptorclass)
Note: there were 22 unresolved dynamic references to classes or interfaces.
  You should check if you need to specify additional program jars.
  (http://proguard.sourceforge.net/manual/troubleshooting.html#dynamicalclass)
Note: there were 15 accesses to class members by means of introspection.
  You should consider explicitly keeping the mentioned class members
  (using '-keep' or '-keepclassmembers').
  (http://proguard.sourceforge.net/manual/troubleshooting.html#dynamicalclassmember)
</code>```

That's all fine and dandy, but how the heck do I know which specific references ProGuard is talking about? Surely they don't expect me to find/remember these references independently?

答:
you need to add the verbose switch into the ProGuard configuration file:

```<code>-verbose
</code>```

while the ProGuard Manual explains these notices - and how to fix them.

Body:
I am trying to release my app and ProGuard is causing all sorts of errors with my server code so I went into the gradle console and see this:

Note: there were 2 references to unknown classes.
  You should check your configuration for typos.
  (http://proguard.sourceforge.net/manual/troubleshooting.html#unknownclass)
Note: there were 26 unkept descriptor classes in kept class members.
  You should consider explicitly keeping the mentioned classes
  (using '-keep').
  (http://proguard.sourceforge.net/manual/troubleshooting.html#descriptorclass)
Note: there were 22 unresolved dynamic references to classes or interfaces.
  You should check if you need to specify additional program jars.
  (http://proguard.sourceforge.net/manual/troubleshooting.html#dynamicalclass)
Note: there were 15 accesses to class members by means of introspection.
  You should consider explicitly keeping the mentioned class members
  (using '-keep' or '-keepclassmembers').
  (http://proguard.sourceforge.net/manual/troubleshooting.html#dynamicalclassmember)

That's all fine and dandy, but how the heck do I know which specific references ProGuard is talking about? Surely they don't expect me to find/remember these references independently?

Body:
you need to add the verbose switch into the ProGuard configuration file:

-verbose

while the ProGuard Manual explains these notices - and how to fix them.


问:
Publish Web Site (Precompilation) stalls/hangs in Visual Studio
I'm working on an ASP.NET Web Forms application (.NET 4.0 VS 2010). Lately we've been experiencing problems which have halted our release process.

Specifically, we have found ourselves unable to publish our website (to precompile it). Across all of our developer environments (3 developers), the build process appears to be stalling/hanging - without any report of error. Sometimes, it appears to succeed but only a couple of the compiled DLL's and .compiled files appear (less than 10 out of ~350 files).

I've loaded in various revisions of our projects from our source repository, both latest and very old versions which previously worked. The fact that it's happening across developer environments suggested that the problem was due to some change we committed, but the fact that the problem is occurring across latest and old revisions of the application perhaps suggest otherwise.

Internet searches for this issue reveal nothing significant. Things I've tried include the following:

Building and rebuilding

Clean solution

Deleting the .suo files for the solution

Deleting the contents of the ASP.NET Temporary Files solution and deleting the target location folder prior to publishing

Tried selecting the 'Allow this precompiled site to be updateable' option (produces an object reference error without a file or line number)

Restarting Visual Studio and PC

On examination of CPU usage during the build, the CPU usage for the devenv.exe process is in the sub 0.10% area for most of it (a few spikes at the beginning just).

I appreciate any assistance anyone can provide with this

UPDATE: We have found that eventually, the publish succeeds, but sometimes we get a long series of failures before it succeeds. There's no consistency at all... it seems random.

答: I had this same issue with Visual Studio 2015 on Server 2016. The issue was partially resolved by running VS as administrator. However the apparent root cause was virus scan - in this case ESET- installed not as a File Security but as workstation. This I discovered when every entry of the license codes for ESET appeared to work - then ESET reported it still required verification. Uninstalled the badly chosen ESET and reinstalled the correct license product and, presto, with or without pre-completion, the publish works! Thanks to the previous virus scan tip!</p>


问:
How to create multiselect dropdown on bootstrap?
I'm coding js app that parse some data and show it to users in table that generated by js. So i need to give to user dropdown list or something like that to choose fields that will be used to generate this table.
Are there any simple way to make this? I've only found
http://davidstutz.github.io/bootstrap-multiselect/
https://silviomoreto.github.io/bootstrap-select/examples/

But it's just dropdown select list! why i have to include jquery and thousand another scripts?

So, tell me pls simplest way to create multiselect tool. I cant imagine, that simpliest way - ugly checkbox :)

答:
selfanswere.

```<code><input type="checkbox" id="bla"><label for="bla">
</code>```

css - checbox visible false

Body:
selfanswere.

<input type="checkbox" id="bla"><label for="bla">

css - checbox visible false


问:
splitting bash string by delimiter (last line with delimiter) into array
I'm having a hard time splitting a string like this:

```<code>444,555,text with, separator
</code>```

into this:

```<code>444
555
text with, separator
</code>```

i.e. into a 3-element array (last element may contain comma)

I tried sed but I end up having 4 elements due to the last comma.

Any ideas?

Thanks,

答:
With bash and array:

```<code>s='444,555,text with, separator'
IFS=, read -r a b c <<< "$s"
array=("$a" "$b" "$c")
declare -p array
</code>```

Output:

```
declare -a array='([0]="444" [1]="555" [2]="text with, separator")'
```

Body:
I'm having a hard time splitting a string like this:

444,555,text with, separator

into this:

444
555
text with, separator

i.e. into a 3-element array (last element may contain comma)

I tried sed but I end up having 4 elements due to the last comma.

Any ideas?

Thanks,

Body:
With bash and array:

s='444,555,text with, separator'
IFS=, read -r a b c <<< "$s"
array=("$a" "$b" "$c")
declare -p array

Output:

declare -a array='([0]="444" [1]="555" [2]="text with, separator")'


问:
Segmentation Fault in template operator overload
I am currently trying to get to grips with templates and operator overloading in C++. I've written a class which is basically a wrapper of a vector. I am trying to add operator overloading to the template class so I can iterate over the list but I keep receiving a segmentation fault with the overloaded operator.

Here is the template code.

```<code>template <class T> class List {
private:
    std::list<T *> *objects;
    int count;
    uint currentIndex;
    typename std::list<T*>::iterator item_iter;

public:
    T *currentItem;
    T *get(int idx);
    void add(T *obj);
    void start();
    bool empty();
    void next();
    List<T>& operator++();

    List() {
        this->currentItem = NULL;
        this->currentIndex = 0;
        this->count = 0;
        this->objects = new std::list<T *>;
    }

    ~List() {
        delete this->objects;
    }
};

template <class T>
void List<T>::add(T *obj) {
    this->objects->push_back(obj);
}

template <class T>
T *List<T>::get(int idx) {
    if (idx < this->objects->size()) {
      typename std::list<T*>::iterator it = this->objects->begin();
      std::advance(it, idx);
      return *it;
    } else {
      return NULL;
    }
}

template <class T>
void List<T>::start() {
    this->currentIndex = 0;
    if (this->objects->size() > 0) {
      this->item_iter = this->objects->begin();
      this->currentItem = *(this->item_iter);
    } else {
      this->currentItem = NULL;
    }
}

template <class T>
void List<T>::next() {
     if (!this->empty() && (this->currentIndex == 0) && (this->currentItem == NULL)) {
      this->start();
    } else if (this->currentIndex < this->objects->size() - 1) {
      this->currentIndex++;
      std::advance(item_iter, 1);
      this->currentItem = *item_iter;
    } else {
      this->currentItem = NULL;
    }
}

template <class T>
bool List<T>::empty() {
    return !this->objects->size();
}

template <class T>
List<T>& List<T>::operator++() {
    // Note: We don't get this far
    this->next();
    return *this;
}
</code>```

The following code works.

```<code>List<Item> *items = new List<Item>();
items->addItem(new Item(20));

for(items->start(); items->currentItem != NULL; items->next()) {
    // Can work with items->currentItem;
}
</code>```

The following code causes the segmentation fault.

```<code>List<Item> *items = new List<Item>();
items->addItem(new Item(20));

for(items->start(); items->currentItem != NULL; items++) {
    // Segmentation fault occurs before we get inside
}
</code>```

答:
@FrançoisAndrieux was correct.

I needed to dereference the items pointer.

```<code>for(items.start(); items.currentItem != NULL; ++items) {
    // Can now use current item
}
</code>```

I also changed the return type.

```<code>template <class T>
List<T> List<T>::operator++() {
    this->next();
    return *this;
}
</code>```

Body:
I am currently trying to get to grips with templates and operator overloading in C++. I've written a class which is basically a wrapper of a vector. I am trying to add operator overloading to the template class so I can iterate over the list but I keep receiving a segmentation fault with the overloaded operator.

Here is the template code.

template <class T> class List {
private:
    std::list<T *> *objects;
    int count;
    uint currentIndex;
    typename std::list<T*>::iterator item_iter;

public:
    T *currentItem;
    T *get(int idx);
    void add(T *obj);
    void start();
    bool empty();
    void next();
    List<T>& operator++();

    List() {
        this->currentItem = NULL;
        this->currentIndex = 0;
        this->count = 0;
        this->objects = new std::list<T *>;
    }

    ~List() {
        delete this->objects;
    }
};

template <class T>
void List<T>::add(T *obj) {
    this->objects->push_back(obj);
}

template <class T>
T *List<T>::get(int idx) {
    if (idx < this->objects->size()) {
      typename std::list<T*>::iterator it = this->objects->begin();
      std::advance(it, idx);
      return *it;
    } else {
      return NULL;
    }
}

template <class T>
void List<T>::start() {
    this->currentIndex = 0;
    if (this->objects->size() > 0) {
      this->item_iter = this->objects->begin();
      this->currentItem = *(this->item_iter);
    } else {
      this->currentItem = NULL;
    }
}

template <class T>
void List<T>::next() {
     if (!this->empty() && (this->currentIndex == 0) && (this->currentItem == NULL)) {
      this->start();
    } else if (this->currentIndex < this->objects->size() - 1) {
      this->currentIndex++;
      std::advance(item_iter, 1);
      this->currentItem = *item_iter;
    } else {
      this->currentItem = NULL;
    }
}

template <class T>
bool List<T>::empty() {
    return !this->objects->size();
}

template <class T>
List<T>& List<T>::operator++() {
    // Note: We don't get this far
    this->next();
    return *this;
}

The following code works.

List<Item> *items = new List<Item>();
items->addItem(new Item(20));

for(items->start(); items->currentItem != NULL; items->next()) {
    // Can work with items->currentItem;
}

The following code causes the segmentation fault.

List<Item> *items = new List<Item>();
items->addItem(new Item(20));

for(items->start(); items->currentItem != NULL; items++) {
    // Segmentation fault occurs before we get inside
}

Body:
@FrançoisAndrieux was correct.

I needed to dereference the items pointer.

for(items.start(); items.currentItem != NULL; ++items) {
    // Can now use current item
}

I also changed the return type.

template <class T>
List<T> List<T>::operator++() {
    this->next();
    return *this;
}


问:
Rewriting Dynamic SQL Stored Procedure
I am trying to rewrite a Dynamic SQL Stored Procedure to avoid treating the SQL statement as a string

The original stored procedure

```<code>select @sql = 'select AM.AUTHNO, '
        select @sql = @sql + 'AST.DESCR, '
        select @sql = @sql + 'AM.MEMBID_DISP as ''MEMBID'', '
        select @sql = @sql + 'convert(varchar(25),isnull(AM.MEMBNAME,'''')) as member_name, '
        select @sql = @sql + 'isnull(MM.SEX,'''') as member_sex, '
        select @sql = @sql + 'isnull(MM.BIRTH,'''') as member_birth, '
        select @sql = @sql + 'convert(varchar(25),isnull(HC.HPNAME,'''')) as member_healthplan, '
        select @sql = @sql + 'convert(varchar(25),isnull(PM.lastname,'''') + isnull('', '' + PM.firstname,'''')) as provider_name, '
        select @sql = @sql + 'PM.PROVID_DISP as ''PROVID'', '
        select @sql = @sql + '''1'' as ''SORT_ORDER'', AM.MEMBID as ''MEMB_KEYID'', AM.AUTHPCP as ''PROV_KEYID'' '
        select @sql = @sql + ', AM.DBKEY as ''DBKEY'' '
        select @sql = @sql + ', (select DESCR from DB where [KEY] = AM.DBKEY) as ''IPA'' '
        select @sql = @sql + ', AM.AUTHDATE, AM.REQDATE '
        select @sql = @sql + 'from Z_AUTH_MASTERS AM, Z_AUTH_STATUS AST, Z_PROV_MASTERS PM, Z_MEMB_MASTERS MM, Z_HP_CONTRACTS HC '
        select @sql = @sql + 'where AM.DBKEY in (' + DBO.C_SP_AUTH_SEARCH_DBKEY(@DB_KEY,@GUID) + ') '  -- **** CUSTOM
        select @sql = @sql + 'and AM.DBKEY = PM.DBKEY '
        select @sql = @sql + 'and AM.AUTHPCP = PM.PROVID '
        select @sql = @sql + 'and AM.DBKEY = AST.DBKEY '
        select @sql = @sql + 'and AM.STATUS = AST.CODE '
        select @sql = @sql + 'and AM.DBKEY = MM.DBKEY '
        select @sql = @sql + 'and AM.MEMBID = MM.MEMBID '
        select @sql = @sql + 'and AM.DBKEY = HC.DBKEY '
        select @sql = @sql + 'and AM.HPCODE = HC.HPCODE '
        if @REFPROV <> '%'
            select @sql = @sql + 'and AM.AUTHPCP_DISP = ''' + @REFPROV + ''' '
        if @AUTHNO <> '%'
            select @sql = @sql + 'and AM.AUTHNO like ''' + @AUTHNO + ''' '
        if @STATUS <> '%'
            select @sql = @sql + 'and AM.STATUS = ''' + @STATUS + ''' '
        if @REQPROV_FIRST <> '%'
            select @sql = @sql + 'and PM.FIRSTNAME like ''' + @REQPROV_FIRST + ''' '
        if @REQPROV_LAST <> '%'
            select @sql = @sql + 'and PM.LASTNAME like ''' + @REQPROV_LAST + ''' '
        if @MEMB_FIRST <> '%'
            select @sql = @sql + 'and MM.FIRSTNM like ''' + @MEMB_FIRST + ''' '
        if @MEMB_LAST <> '%'
            select @sql = @sql + 'and MM.LASTNM like ''' + @MEMB_LAST + ''' '
        if @MEMB_ID <> '%'
            select @sql = @sql + 'and AM.MEMBID_DISP like ''' + @MEMB_ID + ''' '
        if @REQDATE_OP = 'E'
            select @sql = @sql + 'and AM.REQDATE = ''' + @REQDATE_BEGIN + ''' '
        if @REQDATE_OP = 'B'
            select @sql = @sql + 'and (AM.REQDATE >= ''' + @REQDATE_BEGIN + ''' and AM.REQDATE <= ''' + @REQDATE_END + ''') '
        if @AUTDATE_OP = 'E'
            select @sql = @sql + 'and AM.AUTHDATE = ''' + @AUTDATE_BEGIN + ''' '
        if @AUTDATE_OP = 'B'
            select @sql = @sql + 'and (AM.AUTHDATE >= ''' + @AUTDATE_BEGIN + ''' and AM.AUTHDATE <= ''' + @AUTDATE_END + ''') '
        if @EXPDATE_OP = 'E'
            select @sql = @sql + 'and AM.EXPRDATE = ''' + @EXPDATE_BEGIN + ''' '
        if @EXPDATE_OP = 'B'
            select @sql = @sql + 'and (AM.EXPRDATE >= ''' + @EXPDATE_BEGIN + ''' and AM.EXPRDATE <= ''' + @EXPDATE_END + ''') '
        if @FILTER <> '%'
            select @sql = @sql + 'and ' + @FILTER + ' '

        -- only show auths where the Authpcp or reqprov are providers that are linked to this user
        if @IS_SUPER=0
            begin
            select @sql = @sql + 'and ((AM.AUTHPCP in (SELECT PROVID from USER_PROVIDERS where USER_ID = ' + convert(varchar(10),@USER_ID) + ' and DBKEY in (' + DBO.C_SP_AUTH_SEARCH_DBKEY(@DB_KEY,@GUID) + '))) '
            select @sql = @sql + 'or (AM.REQPROV in (SELECT PROVID from USER_PROVIDERS where USER_ID = ' + convert(varchar(10),@USER_ID) + ' and DBKEY in (' + DBO.C_SP_AUTH_SEARCH_DBKEY(@DB_KEY,@GUID) + ')))) '
            end

        -- add sort code here
        select @sql = @sql + 'order by SORT_ORDER asc, '
        if @SORT_COLUMN = 1
            select @sql = @sql + 'AM.AUTHNO desc, '
        if @SORT_COLUMN = 2
            select @sql = @sql + 'AM.STATUS asc, '
        if @SORT_COLUMN = 3
            select @sql = @sql + 'AM.MEMBID_DISP asc, '
        if @SORT_COLUMN = 4
            select @sql = @sql + 'MM.LASTNM asc, '
        if @SORT_COLUMN = 5
            select @sql = @sql + 'MM.SEX asc, '
        if @SORT_COLUMN = 6
            select @sql = @sql + 'MM.BIRTH asc, '
        if @SORT_COLUMN = 7
            select @sql = @sql + 'HC.HPNAME asc, '
        if @SORT_COLUMN = 8
            select @sql = @sql + 'PM.LASTNAME asc, '
        if @SORT_COLUMN = 9
            select @sql = @sql + '''IPA'' asc, '

        -- trim off last ', '
        select @sql = left(@SQL,len(@SQL)-1)
        exec sp_executesql @sql
</code>```

This is what I have so far

```<code>        SELECT
            AM.AUTHNO as Auth_No,
            AST.DESCR as Descr,
            AM.MEMBID_DISP as Memb_Id,
            CONVERT(varchar(25), ISNULL(AM.MEMBNAME,'')) as Member_Name,
            ISNULL(MM.SEX,'') as Member_Sex,
            ISNULL(MM.BIRTH,'') as Member_Dob,
            CONVERT(varchar(25), ISNULL(HC.HPNAME,'')) as Member_Hp,
            CONVERT(varchar(25), ISNULL(PM.LASTNAME,'') + ISNULL(', ' + PM.FIRSTNAME, '')) as Provider_Name,
            PM.PROVID_DISP as Prov_Id,
            '1' as SORT_ORDER,
            AM.DBKEY as Db_Key,
            (SELECT DESCR FROM DB WHERE [KEY] = AM.DBKEY) as Ipa,
            AM.AUTHDATE,
            AM.REQDATE
        FROM
            Z_AUTH_MASTERS AM,
            Z_AUTH_STATUS AST,
            Z_PROV_MASTERS PM,
            Z_MEMB_MASTERS MM,
            Z_HP_CONTRACTS HC
        WHERE
            AM.DBKEY IN ( DBO.C_SP_AUTH_SEARCH_DBKEY(@DB_KEY, @GUID))
            AND AM.DBKEY = PM.DBKEY
            AND AM.AUTHPCP = PM.PROVID
            AND AM.DBKEY = AST.DBKEY
            AND AM.STATUS = AST.CODE
            AND AM.DBKEY = MM.DBKEY
            AND AM.MEMBID = MM.MEMBID
            AND AM.DBKEY = HC.DBKEY
            AND AM.HPCODE = HC.HPCODE
            AND (@STATUS IS NULL OR (AM.STATUS = @STATUS))
            AND (@REFPROV IS NULL OR (AM.AUTHPCP_DISP = @REFPROV))
            AND (@AUTHNO IS NULL OR (AM.AUTHNO like @AUTHNO))
            AND (@REQPROV_FIRST IS NULL OR (PM.FIRSTNAME like @REQPROV_FIRST))
            AND (@REQPROV_LAST IS NULL OR (PM.LASTNAME like @REQPROV_LAST))
            AND (@MEMB_FIRST IS NULL OR (MM.FIRSTNM like @MEMB_FIRST))
            AND (@MEMB_LAST IS NULL OR (MM.LASTNM like @MEMB_LAST))
            AND (@MEMB_ID IS NULL OR (AM.MEMBID_DISP like @MEMB_ID))
</code>```

I am having a difficult time coverting the following snippet of code

```<code>        if @REQDATE_OP = 'E'
            select @sql = @sql + 'and AM.REQDATE = ''' + @REQDATE_BEGIN + ''' '
        if @REQDATE_OP = 'B'
            select @sql = @sql + 'and (AM.REQDATE >= ''' + @REQDATE_BEGIN + ''' and AM.REQDATE <= ''' + @REQDATE_END + ''') '
        if @AUTDATE_OP = 'E'
            select @sql = @sql + 'and AM.AUTHDATE = ''' + @AUTDATE_BEGIN + ''' '
        if @AUTDATE_OP = 'B'
            select @sql = @sql + 'and (AM.AUTHDATE >= ''' + @AUTDATE_BEGIN + ''' and AM.AUTHDATE <= ''' + @AUTDATE_END + ''') '
        if @EXPDATE_OP = 'E'
            select @sql = @sql + 'and AM.EXPRDATE = ''' + @EXPDATE_BEGIN + ''' '
        if @EXPDATE_OP = 'B'
            select @sql = @sql + 'and (AM.EXPRDATE >= ''' + @EXPDATE_BEGIN + ''' and AM.EXPRDATE <= ''' + @EXPDATE_END + ''') '
        if @FILTER <> '%'
            select @sql = @sql + 'and ' + @FILTER + ' '
</code>```

I've tried implementing a CASE statement, but the syntax is incorrect

```<code> WHERE
    CASE
        WHEN @REQDATE_OP = 'E' THEN AM.REQDATE = @REQDATE_BEGIN
        WHEN @REQDATE_OP = 'B' THEN (AM.REQDATE >= @REQDATE_BEGIN AND AM.REQDATE <= @REQDATE_END)
        ....
        ....

    AM.DBKEY IN ( DBO.C_SP_AUTH_SEARCH_DBKEY(@DB_KEY, @GUID))
    AND AM.DBKEY = PM.DBKEY
    AND AM.AUTHPCP = PM.PROVID
</code>```

Is a CASE statement the correct approach? If so, how should the CASE
  statement be re-written? Are there other alternative approaches?

答:
You can improve the construction of this code, but with the @FILTER condition, it is unlikely that you can rid yourself of dynamic code without redefining the entire process. Here is the entire block in a single SELECT:

```<code>select @sql = 'select AM.AUTHNO,
    AST.DESCR,
    AM.MEMBID_DISP as ''MEMBID'',
    convert(varchar(25),isnull(AM.MEMBNAME,'''')) as member_name,
    isnull(MM.SEX,'''') as member_sex,
    isnull(MM.BIRTH,'''') as member_birth,
    convert(varchar(25),isnull(HC.HPNAME,'''')) as member_healthplan,
    convert(varchar(25),isnull(PM.lastname,'''') + isnull('', '' + PM.firstname,'''')) as provider_name,
    PM.PROVID_DISP as ''PROVID'',
    ''1'' as ''SORT_ORDER'', AM.MEMBID as ''MEMB_KEYID'', AM.AUTHPCP as ''PROV_KEYID''
    , AM.DBKEY as ''DBKEY''
    , (select DESCR from DB where [KEY] = AM.DBKEY) as ''IPA''
    , AM.AUTHDATE, AM.REQDATE
    from Z_AUTH_MASTERS AM
    INNER JOIN Z_AUTH_STATUS AST
        ON AM.DBKEY = AST.DBKEY
        and AM.STATUS = AST.CODE
    INNER JOIN Z_PROV_MASTERS PM
        ON AM.DBKEY = PM.DBKEY
        and AM.AUTHPCP = PM.PROVID
    INNER JOIN Z_MEMB_MASTERS MM
        ON AM.DBKEY = MM.DBKEY
        and AM.MEMBID = MM.MEMBID
    INNER JOIN Z_HP_CONTRACTS HC
        ON AM.DBKEY = HC.DBKEY
        and AM.HPCODE = HC.HPCODE
    where AM.DBKEY in (' + DBO.C_SP_AUTH_SEARCH_DBKEY(@DB_KEY,@GUID) + ') ' +   -- **** CUSTOM
    CASE
        WHEN @REFPROV <> '%'
            THEN 'and AM.AUTHPCP_DISP = ''' + @REFPROV + ''' '
        ELSE ''
    END + CASE
        WHEN @AUTHNO <> '%'
            THEN 'and AM.AUTHNO like ''' + @AUTHNO + ''' '
        ELSE ''
    END + CASE
        WHEN @STATUS <> '%'
            THEN 'and AM.STATUS = ''' + @STATUS + ''' '
        ELSE ''
    END + CASE
        WHEN @REQPROV_FIRST <> '%'
            THEN 'and PM.FIRSTNAME like ''' + @REQPROV_FIRST + ''' '
        ELSE ''
    END + CASE
        WHEN @REQPROV_LAST <> '%'
            THEN 'and PM.LASTNAME like ''' + @REQPROV_LAST + ''' '
        ELSE ''
    END + CASE
        WHEN @MEMB_FIRST <> '%'
            THEN 'and MM.FIRSTNM like ''' + @MEMB_FIRST + ''' '
        ELSE ''
    END + CASE
        WHEN @MEMB_LAST <> '%'
            THEN 'and MM.LASTNM like ''' + @MEMB_LAST + ''' '
        ELSE ''
    END + CASE
        WHEN @MEMB_ID <> '%'
            THEN 'and AM.MEMBID_DISP like ''' + @MEMB_ID + ''' '
        ELSE ''
    END + CASE @REQDATE_OP
        WHEN 'E'
            THEN 'and AM.REQDATE = ''' + @REQDATE_BEGIN + ''' '
        WHEN 'B'
            THEN 'and (AM.REQDATE >= ''' + @REQDATE_BEGIN + ''' and AM.REQDATE <= ''' + @REQDATE_END + ''') '
    END + CASE @AUTDATE_OP
        WHEN 'E'
            THEN 'and AM.AUTHDATE = ''' + @AUTDATE_BEGIN + ''' '
        WHEN 'B'
            THEN 'and (AM.AUTHDATE >= ''' + @AUTDATE_BEGIN + ''' and AM.AUTHDATE <= ''' + @AUTDATE_END + ''') '
    END + CASE @EXPDATE_OP
        WHEN 'E'
            THEN 'and AM.EXPRDATE = ''' + @EXPDATE_BEGIN + ''' '
        WHEN 'B'
            THEN 'and (AM.EXPRDATE >= ''' + @EXPDATE_BEGIN + ''' and AM.EXPRDATE <= ''' + @EXPDATE_END + ''') '
    END + CASE
        WHEN @FILTER <> '%'
            THEN 'and ' + @FILTER + ' '
        ELSE ''
    END + CASE        -- only show auths where the Authpcp or reqprov are providers that are linked to this user
        WHEN @IS_SUPER=0
            THEN 'and ((AM.AUTHPCP in (SELECT PROVID from USER_PROVIDERS where USER_ID = ' + convert(varchar(10),@USER_ID) + ' and DBKEY in (' + DBO.C_SP_AUTH_SEARCH_DBKEY(@DB_KEY,@GUID) + ')))
        or (AM.REQPROV in (SELECT PROVID from USER_PROVIDERS where USER_ID = ' + convert(varchar(10),@USER_ID) + ' and DBKEY in (' + DBO.C_SP_AUTH_SEARCH_DBKEY(@DB_KEY,@GUID) + ')))) '
    END + 'order by SORT_ORDER asc' +
    CASE @SORT_COLUMN
        WHEN 1
            THEN ', AM.AUTHNO desc'
        WHEN 2
            THEN ', AM.STATUS asc'
        WHEN 3
            THEN ', AM.MEMBID_DISP asc'
        WHEN 4
            THEN ', MM.LASTNM asc'
        WHEN 5
            THEN ', MM.SEX asc'
        WHEN 6
            THEN ', MM.BIRTH asc'
        WHEN 7
            THEN ', HC.HPNAME asc'
        WHEN 8
            THEN ', PM.LASTNAME asc'
        WHEN 9
            THEN ', ''IPA'' asc'
    END

exec sp_executesql @sql
</code>```

Also, one note: Why is there a sort on a constant? (the WHEN 9 condition). Just remove that, as it will not change the order of the sort at all.

Title: Rewriting Dynamic SQL Stored Procedure

Body:
I am trying to rewrite a Dynamic SQL Stored Procedure to avoid treating the SQL statement as a string

The original stored procedure

select @sql = 'select AM.AUTHNO, '
        select @sql = @sql + 'AST.DESCR, '
        select @sql = @sql + 'AM.MEMBID_DISP as ''MEMBID'', '
        select @sql = @sql + 'convert(varchar(25),isnull(AM.MEMBNAME,'''')) as member_name, '
        select @sql = @sql + 'isnull(MM.SEX,'''') as member_sex, '
        select @sql = @sql + 'isnull(MM.BIRTH,'''') as member_birth, '
        select @sql = @sql + 'convert(varchar(25),isnull(HC.HPNAME,'''')) as member_healthplan, '
        select @sql = @sql + 'convert(varchar(25),isnull(PM.lastname,'''') + isnull('', '' + PM.firstname,'''')) as provider_name, '
        select @sql = @sql + 'PM.PROVID_DISP as ''PROVID'', '
        select @sql = @sql + '''1'' as ''SORT_ORDER'', AM.MEMBID as ''MEMB_KEYID'', AM.AUTHPCP as ''PROV_KEYID'' '
        select @sql = @sql + ', AM.DBKEY as ''DBKEY'' '
        select @sql = @sql + ', (select DESCR from DB where [KEY] = AM.DBKEY) as ''IPA'' '
        select @sql = @sql + ', AM.AUTHDATE, AM.REQDATE '
        select @sql = @sql + 'from Z_AUTH_MASTERS AM, Z_AUTH_STATUS AST, Z_PROV_MASTERS PM, Z_MEMB_MASTERS MM, Z_HP_CONTRACTS HC '
        select @sql = @sql + 'where AM.DBKEY in (' + DBO.C_SP_AUTH_SEARCH_DBKEY(@DB_KEY,@GUID) + ') '  -- **** CUSTOM
        select @sql = @sql + 'and AM.DBKEY = PM.DBKEY '
        select @sql = @sql + 'and AM.AUTHPCP = PM.PROVID '
        select @sql = @sql + 'and AM.DBKEY = AST.DBKEY '
        select @sql = @sql + 'and AM.STATUS = AST.CODE '
        select @sql = @sql + 'and AM.DBKEY = MM.DBKEY '
        select @sql = @sql + 'and AM.MEMBID = MM.MEMBID '
        select @sql = @sql + 'and AM.DBKEY = HC.DBKEY '
        select @sql = @sql + 'and AM.HPCODE = HC.HPCODE '
        if @REFPROV <> '%'
            select @sql = @sql + 'and AM.AUTHPCP_DISP = ''' + @REFPROV + ''' '
        if @AUTHNO <> '%'
            select @sql = @sql + 'and AM.AUTHNO like ''' + @AUTHNO + ''' '
        if @STATUS <> '%'
            select @sql = @sql + 'and AM.STATUS = ''' + @STATUS + ''' '
        if @REQPROV_FIRST <> '%'
            select @sql = @sql + 'and PM.FIRSTNAME like ''' + @REQPROV_FIRST + ''' '
        if @REQPROV_LAST <> '%'
            select @sql = @sql + 'and PM.LASTNAME like ''' + @REQPROV_LAST + ''' '
        if @MEMB_FIRST <> '%'
            select @sql = @sql + 'and MM.FIRSTNM like ''' + @MEMB_FIRST + ''' '
        if @MEMB_LAST <> '%'
            select @sql = @sql + 'and MM.LASTNM like ''' + @MEMB_LAST + ''' '
        if @MEMB_ID <> '%'
            select @sql = @sql + 'and AM.MEMBID_DISP like ''' + @MEMB_ID + ''' '
        if @REQDATE_OP = 'E'
            select @sql = @sql + 'and AM.REQDATE = ''' + @REQDATE_BEGIN + ''' '
        if @REQDATE_OP = 'B'
            select @sql = @sql + 'and (AM.REQDATE >= ''' + @REQDATE_BEGIN + ''' and AM.REQDATE <= ''' + @REQDATE_END + ''') '
        if @AUTDATE_OP = 'E'
            select @sql = @sql + 'and AM.AUTHDATE = ''' + @AUTDATE_BEGIN + ''' '
        if @AUTDATE_OP = 'B'
            select @sql = @sql + 'and (AM.AUTHDATE >= ''' + @AUTDATE_BEGIN + ''' and AM.AUTHDATE <= ''' + @AUTDATE_END + ''') '
        if @EXPDATE_OP = 'E'
            select @sql = @sql + 'and AM.EXPRDATE = ''' + @EXPDATE_BEGIN + ''' '
        if @EXPDATE_OP = 'B'
            select @sql = @sql + 'and (AM.EXPRDATE >= ''' + @EXPDATE_BEGIN + ''' and AM.EXPRDATE <= ''' + @EXPDATE_END + ''') '
        if @FILTER <> '%'
            select @sql = @sql + 'and ' + @FILTER + ' '

        -- only show auths where the Authpcp or reqprov are providers that are linked to this user
        if @IS_SUPER=0
            begin
            select @sql = @sql + 'and ((AM.AUTHPCP in (SELECT PROVID from USER_PROVIDERS where USER_ID = ' + convert(varchar(10),@USER_ID) + ' and DBKEY in (' + DBO.C_SP_AUTH_SEARCH_DBKEY(@DB_KEY,@GUID) + '))) '
            select @sql = @sql + 'or (AM.REQPROV in (SELECT PROVID from USER_PROVIDERS where USER_ID = ' + convert(varchar(10),@USER_ID) + ' and DBKEY in (' + DBO.C_SP_AUTH_SEARCH_DBKEY(@DB_KEY,@GUID) + ')))) '
            end

        -- add sort code here
        select @sql = @sql + 'order by SORT_ORDER asc, '
        if @SORT_COLUMN = 1
            select @sql = @sql + 'AM.AUTHNO desc, '
        if @SORT_COLUMN = 2
            select @sql = @sql + 'AM.STATUS asc, '
        if @SORT_COLUMN = 3
            select @sql = @sql + 'AM.MEMBID_DISP asc, '
        if @SORT_COLUMN = 4
            select @sql = @sql + 'MM.LASTNM asc, '
        if @SORT_COLUMN = 5
            select @sql = @sql + 'MM.SEX asc, '
        if @SORT_COLUMN = 6
            select @sql = @sql + 'MM.BIRTH asc, '
        if @SORT_COLUMN = 7
            select @sql = @sql + 'HC.HPNAME asc, '
        if @SORT_COLUMN = 8
            select @sql = @sql + 'PM.LASTNAME asc, '
        if @SORT_COLUMN = 9
            select @sql = @sql + '''IPA'' asc, '

        -- trim off last ', '
        select @sql = left(@SQL,len(@SQL)-1)
        exec sp_executesql @sql

This is what I have so far

        SELECT
            AM.AUTHNO as Auth_No,
            AST.DESCR as Descr,
            AM.MEMBID_DISP as Memb_Id,
            CONVERT(varchar(25), ISNULL(AM.MEMBNAME,'')) as Member_Name,
            ISNULL(MM.SEX,'') as Member_Sex,
            ISNULL(MM.BIRTH,'') as Member_Dob,
            CONVERT(varchar(25), ISNULL(HC.HPNAME,'')) as Member_Hp,
            CONVERT(varchar(25), ISNULL(PM.LASTNAME,'') + ISNULL(', ' + PM.FIRSTNAME, '')) as Provider_Name,
            PM.PROVID_DISP as Prov_Id,
            '1' as SORT_ORDER,
            AM.DBKEY as Db_Key,
            (SELECT DESCR FROM DB WHERE [KEY] = AM.DBKEY) as Ipa,
            AM.AUTHDATE,
            AM.REQDATE
        FROM
            Z_AUTH_MASTERS AM,
            Z_AUTH_STATUS AST,
            Z_PROV_MASTERS PM,
            Z_MEMB_MASTERS MM,
            Z_HP_CONTRACTS HC
        WHERE
            AM.DBKEY IN ( DBO.C_SP_AUTH_SEARCH_DBKEY(@DB_KEY, @GUID))
            AND AM.DBKEY = PM.DBKEY
            AND AM.AUTHPCP = PM.PROVID
            AND AM.DBKEY = AST.DBKEY
            AND AM.STATUS = AST.CODE
            AND AM.DBKEY = MM.DBKEY
            AND AM.MEMBID = MM.MEMBID
            AND AM.DBKEY = HC.DBKEY
            AND AM.HPCODE = HC.HPCODE
            AND (@STATUS IS NULL OR (AM.STATUS = @STATUS))
            AND (@REFPROV IS NULL OR (AM.AUTHPCP_DISP = @REFPROV))
            AND (@AUTHNO IS NULL OR (AM.AUTHNO like @AUTHNO))
            AND (@REQPROV_FIRST IS NULL OR (PM.FIRSTNAME like @REQPROV_FIRST))
            AND (@REQPROV_LAST IS NULL OR (PM.LASTNAME like @REQPROV_LAST))
            AND (@MEMB_FIRST IS NULL OR (MM.FIRSTNM like @MEMB_FIRST))
            AND (@MEMB_LAST IS NULL OR (MM.LASTNM like @MEMB_LAST))
            AND (@MEMB_ID IS NULL OR (AM.MEMBID_DISP like @MEMB_ID))

I am having a difficult time coverting the following snippet of code

        if @REQDATE_OP = 'E'
            select @sql = @sql + 'and AM.REQDATE = ''' + @REQDATE_BEGIN + ''' '
        if @REQDATE_OP = 'B'
            select @sql = @sql + 'and (AM.REQDATE >= ''' + @REQDATE_BEGIN + ''' and AM.REQDATE <= ''' + @REQDATE_END + ''') '
        if @AUTDATE_OP = 'E'
            select @sql = @sql + 'and AM.AUTHDATE = ''' + @AUTDATE_BEGIN + ''' '
        if @AUTDATE_OP = 'B'
            select @sql = @sql + 'and (AM.AUTHDATE >= ''' + @AUTDATE_BEGIN + ''' and AM.AUTHDATE <= ''' + @AUTDATE_END + ''') '
        if @EXPDATE_OP = 'E'
            select @sql = @sql + 'and AM.EXPRDATE = ''' + @EXPDATE_BEGIN + ''' '
        if @EXPDATE_OP = 'B'
            select @sql = @sql + 'and (AM.EXPRDATE >= ''' + @EXPDATE_BEGIN + ''' and AM.EXPRDATE <= ''' + @EXPDATE_END + ''') '
        if @FILTER <> '%'
            select @sql = @sql + 'and ' + @FILTER + ' '

I've tried implementing a CASE statement, but the syntax is incorrect

 WHERE
    CASE
        WHEN @REQDATE_OP = 'E' THEN AM.REQDATE = @REQDATE_BEGIN
        WHEN @REQDATE_OP = 'B' THEN (AM.REQDATE >= @REQDATE_BEGIN AND AM.REQDATE <= @REQDATE_END)
        ....
        ....

    AM.DBKEY IN ( DBO.C_SP_AUTH_SEARCH_DBKEY(@DB_KEY, @GUID))
    AND AM.DBKEY = PM.DBKEY
    AND AM.AUTHPCP = PM.PROVID

Is a CASE statement the correct approach? If so, how should the CASE
  statement be re-written? Are there other alternative approaches?

Body:
You can improve the construction of this code, but with the @FILTER condition, it is unlikely that you can rid yourself of dynamic code without redefining the entire process. Here is the entire block in a single SELECT:

select @sql = 'select AM.AUTHNO,
    AST.DESCR,
    AM.MEMBID_DISP as ''MEMBID'',
    convert(varchar(25),isnull(AM.MEMBNAME,'''')) as member_name,
    isnull(MM.SEX,'''') as member_sex,
    isnull(MM.BIRTH,'''') as member_birth,
    convert(varchar(25),isnull(HC.HPNAME,'''')) as member_healthplan,
    convert(varchar(25),isnull(PM.lastname,'''') + isnull('', '' + PM.firstname,'''')) as provider_name,
    PM.PROVID_DISP as ''PROVID'',
    ''1'' as ''SORT_ORDER'', AM.MEMBID as ''MEMB_KEYID'', AM.AUTHPCP as ''PROV_KEYID''
    , AM.DBKEY as ''DBKEY''
    , (select DESCR from DB where [KEY] = AM.DBKEY) as ''IPA''
    , AM.AUTHDATE, AM.REQDATE
    from Z_AUTH_MASTERS AM
    INNER JOIN Z_AUTH_STATUS AST
        ON AM.DBKEY = AST.DBKEY
        and AM.STATUS = AST.CODE
    INNER JOIN Z_PROV_MASTERS PM
        ON AM.DBKEY = PM.DBKEY
        and AM.AUTHPCP = PM.PROVID
    INNER JOIN Z_MEMB_MASTERS MM
        ON AM.DBKEY = MM.DBKEY
        and AM.MEMBID = MM.MEMBID
    INNER JOIN Z_HP_CONTRACTS HC
        ON AM.DBKEY = HC.DBKEY
        and AM.HPCODE = HC.HPCODE
    where AM.DBKEY in (' + DBO.C_SP_AUTH_SEARCH_DBKEY(@DB_KEY,@GUID) + ') ' +   -- **** CUSTOM
    CASE
        WHEN @REFPROV <> '%'
            THEN 'and AM.AUTHPCP_DISP = ''' + @REFPROV + ''' '
        ELSE ''
    END + CASE
        WHEN @AUTHNO <> '%'
            THEN 'and AM.AUTHNO like ''' + @AUTHNO + ''' '
        ELSE ''
    END + CASE
        WHEN @STATUS <> '%'
            THEN 'and AM.STATUS = ''' + @STATUS + ''' '
        ELSE ''
    END + CASE
        WHEN @REQPROV_FIRST <> '%'
            THEN 'and PM.FIRSTNAME like ''' + @REQPROV_FIRST + ''' '
        ELSE ''
    END + CASE
        WHEN @REQPROV_LAST <> '%'
            THEN 'and PM.LASTNAME like ''' + @REQPROV_LAST + ''' '
        ELSE ''
    END + CASE
        WHEN @MEMB_FIRST <> '%'
            THEN 'and MM.FIRSTNM like ''' + @MEMB_FIRST + ''' '
        ELSE ''
    END + CASE
        WHEN @MEMB_LAST <> '%'
            THEN 'and MM.LASTNM like ''' + @MEMB_LAST + ''' '
        ELSE ''
    END + CASE
        WHEN @MEMB_ID <> '%'
            THEN 'and AM.MEMBID_DISP like ''' + @MEMB_ID + ''' '
        ELSE ''
    END + CASE @REQDATE_OP
        WHEN 'E'
            THEN 'and AM.REQDATE = ''' + @REQDATE_BEGIN + ''' '
        WHEN 'B'
            THEN 'and (AM.REQDATE >= ''' + @REQDATE_BEGIN + ''' and AM.REQDATE <= ''' + @REQDATE_END + ''') '
    END + CASE @AUTDATE_OP
        WHEN 'E'
            THEN 'and AM.AUTHDATE = ''' + @AUTDATE_BEGIN + ''' '
        WHEN 'B'
            THEN 'and (AM.AUTHDATE >= ''' + @AUTDATE_BEGIN + ''' and AM.AUTHDATE <= ''' + @AUTDATE_END + ''') '
    END + CASE @EXPDATE_OP
        WHEN 'E'
            THEN 'and AM.EXPRDATE = ''' + @EXPDATE_BEGIN + ''' '
        WHEN 'B'
            THEN 'and (AM.EXPRDATE >= ''' + @EXPDATE_BEGIN + ''' and AM.EXPRDATE <= ''' + @EXPDATE_END + ''') '
    END + CASE
        WHEN @FILTER <> '%'
            THEN 'and ' + @FILTER + ' '
        ELSE ''
    END + CASE        -- only show auths where the Authpcp or reqprov are providers that are linked to this user
        WHEN @IS_SUPER=0
            THEN 'and ((AM.AUTHPCP in (SELECT PROVID from USER_PROVIDERS where USER_ID = ' + convert(varchar(10),@USER_ID) + ' and DBKEY in (' + DBO.C_SP_AUTH_SEARCH_DBKEY(@DB_KEY,@GUID) + ')))
        or (AM.REQPROV in (SELECT PROVID from USER_PROVIDERS where USER_ID = ' + convert(varchar(10),@USER_ID) + ' and DBKEY in (' + DBO.C_SP_AUTH_SEARCH_DBKEY(@DB_KEY,@GUID) + ')))) '
    END + 'order by SORT_ORDER asc' +
    CASE @SORT_COLUMN
        WHEN 1
            THEN ', AM.AUTHNO desc'
        WHEN 2
            THEN ', AM.STATUS asc'
        WHEN 3
            THEN ', AM.MEMBID_DISP asc'
        WHEN 4
            THEN ', MM.LASTNM asc'
        WHEN 5
            THEN ', MM.SEX asc'
        WHEN 6
            THEN ', MM.BIRTH asc'
        WHEN 7
            THEN ', HC.HPNAME asc'
        WHEN 8
            THEN ', PM.LASTNAME asc'
        WHEN 9
            THEN ', ''IPA'' asc'
    END

exec sp_executesql @sql

Also, one note: Why is there a sort on a constant? (the WHEN 9 condition). Just remove that, as it will not change the order of the sort at all.


问:
git export from github remote repository
I'd like to export from github remote repository, not cloning it. Similar to svn export, I do not want to get .git folder with it. I can work around it by cloning and removing .git folder. I wonder if there is a cleaner way?

I read it somewhere you can use git archive to achieve this.

However I got the following errors..

```<code>$ git archive --format=tar --remote=git@github.com:xxx/yyy.git master | tar -xf -

Invalid command: 'git-upload-archive 'xxx/yyy.git''
You appear to be using ssh to clone a git:// URL.
Make sure your core.gitProxy config option and the
GIT_PROXY_COMMAND environment variable are NOT set.
fatal: The remote end hung up unexpectedly
</code>```

Any help would be great. Thanks.

答:
For unknown (to me at least) reasons GitHub doesn't support this.

```<code>We don’t support people running git-archive against our servers.
</code>```

Seems silly, since via SVN you can, but... I upvoted @Janos' answer.

Body:
I'd like to export from github remote repository, not cloning it. Similar to svn export, I do not want to get .git folder with it. I can work around it by cloning and removing .git folder. I wonder if there is a cleaner way?

I read it somewhere you can use git archive to achieve this.

However I got the following errors..

$ git archive --format=tar --remote=git@github.com:xxx/yyy.git master | tar -xf -

Invalid command: 'git-upload-archive 'xxx/yyy.git''
You appear to be using ssh to clone a git:// URL.
Make sure your core.gitProxy config option and the
GIT_PROXY_COMMAND environment variable are NOT set.
fatal: The remote end hung up unexpectedly

Any help would be great. Thanks.

Body:
For unknown (to me at least) reasons GitHub doesn't support this.

We don’t support people running git-archive against our servers.

Seems silly, since via SVN you can, but... I upvoted @Janos' answer.


问:
Date converter in python
```<code>def main():
    print "Welcome To the Date Converter"
    print "Please Enjoy Your Stay"
    print
    date_string = raw_input("Please enter a date in MM/DD/YYYY format:  ")
    date_list = date_string.split('/')
    import datetime
    d = datetime.date
    d.strftime('%B %d, %Y')

main()
</code>```

<p>That's what I have so far I keep getting a 0 for an output in help would be appreciated I am trying to have someone input a numerical date  and the program convert it to a date like November 15, 2010 </p>

答:
```<code>import datetime
def main():
    print "Welcome To the Date Converter"
    print "Please Enjoy Your Stay"
    print
    date_string = raw_input("Please enter a date in MM/DD/YYYY format:  ")
    d=datetime.datetime.strptime(date_string,'%m/%d/%Y')
    print(d.strftime('%B %d, %Y'))

if __name__=='__main__':
    main()
</code>```

If you try to split date_string
with date_string.split('/'), then
you have to convert the list of
strings into a list of ints. It's
possible, but more work than
necessary. Use
datetime.datetime.strptime
instead.

Put all imports at the top of the
script. It makes it easier to understand the dependencies of the script.

In general, it's a good habit to use
if __name__=='__main__' so that
your scripts are importable (without
inadvertently running code). This
makes your scripts double-purposed
-- you can run them as scripts from the command line, and also import
them to reuse functions.

You might also want to check out the
third-party module dateutil --
it has a fuzzy date parser which can
handle many formats.

Title: Date converter in python

Body:
def main():
    print "Welcome To the Date Converter"
    print "Please Enjoy Your Stay"
    print
    date_string = raw_input("Please enter a date in MM/DD/YYYY format:  ")
    date_list = date_string.split('/')
    import datetime
    d = datetime.date
    d.strftime('%B %d, %Y')

main()

That's what I have so far I keep getting a 0 for an output in help would be appreciated I am trying to have someone input a numerical date  and the program convert it to a date like November 15, 2010

Body:
import datetime
def main():
    print "Welcome To the Date Converter"
    print "Please Enjoy Your Stay"
    print
    date_string = raw_input("Please enter a date in MM/DD/YYYY format:  ")
    d=datetime.datetime.strptime(date_string,'%m/%d/%Y')
    print(d.strftime('%B %d, %Y'))

if __name__=='__main__':
    main()

If you try to split date_string
with date_string.split('/'), then
you have to convert the list of
strings into a list of ints. It's
possible, but more work than
necessary. Use
datetime.datetime.strptime
instead.

Put all imports at the top of the
script. It makes it easier to understand the dependencies of the script.

In general, it's a good habit to use
if __name__=='__main__' so that
your scripts are importable (without
inadvertently running code). This
makes your scripts double-purposed
-- you can run them as scripts from the command line, and also import
them to reuse functions.

You might also want to check out the
third-party module dateutil --
it has a fuzzy date parser which can
handle many formats.


问:
Why do these sum operations not "add up" as they should?
Note: This is a follow[on,up] to this question and this question and this question.

The responses all moved me forward, but even that last one, although it improved matters, did not completely solve this issue.

This query:

```<code>select monthlysales, MemberNo from ReportingMonthlySales
where unit = 'Abuelos' and CYear = 2017 and cmonth = 3
</code>```

...returns a bunch of rows, where the Monthly Sales total is $364,121.69

However, when I try to compartmentalize these monthly sales into four categories, although the sum of them all should be the same, the sum is actually astronomically "huger" - the following code returns the vastly inflated value of 23,924,211.30

24 millions of dollars is almost 70 times as much as the 364 thousand that is the actual sum total. Why is this "crazy" inflation occurring?

Here is the fancy pants but apparently bamboozled code:

```<code>declare @Unit varchar(30);
declare @Year int = 2017;
declare @Month int = 3;
declare @paramdate datetime;
set @paramdate = convert(datetime,convert(char(4),@Year)
                +right('0'+convert(varchar(2),@month),2)
                +'01')

IF OBJECT_ID('tempdb.dbo.#Units', 'U') IS NOT NULL
DROP TABLE #Units

select distinct unit
into #Units
from ReportingMonthlySales;

select
    u.Unit
  , New      = sum(case when ccl.Subcategory = 'New'      then rms.MonthlySales else 0 end)
  , Assumed  = sum(case when ccl.Subcategory = 'Assumed'  then rms.MonthlySales else 0 end)
  , Existing = sum(case when ccl.Subcategory = 'Existing' then rms.MonthlySales else 0 end)
  , Organic  = sum(case when ccl.Subcategory = 'Organic'  then rms.MonthlySales else 0 end)
from #Units u
  left join CustomerCategoryLog ccl
    on u.Unit = ccl.Unit
   and @paramdate >= ccl.begindate and
   (@paramdate <= ccl.enddate OR ccl.enddate is null)
  left join ReportingMonthlySales rms
    on u.Unit = rms.Unit
   and rms.cyear  = @year
   and rms.cmonth = @month
group by u.unit;

The two tables queried are:

CustomerCategoryLog
-------------------
MemberNo (VarChar)
Unit (VarChar)
Custno (VarChar)
Category (VarChar)
Subcategory (VarChar)
BeginDate (DateTime)
EndDate (DateTime)
ChangedBy (VarChar)
ChangedOn (DateTime)

ReportingMonthlySales
---------------------
AutoID (Int)
Unit (VarChar)
MemberNo (VarChar)
NumUnits (Int)
MonthlySales (Money)
CYear (Int)
Cmonth (Int)
CreateDate (DateTime)
</code>```

Is there something faulty in the fancy-pants sql, or ... ?!?

答: You are doing a join between the RMS table and these other tables.  Your code assumes it will find one record for each record in the RMS table.  This is not true.  This is the cause of getting multiple rows reported and summed.  I would think it is most likely that for a particular unit and @paramdate, there is multiple CCL entries.</p>

Body:
Note: This is a follow[on,up] to this question and this question and this question.

The responses all moved me forward, but even that last one, although it improved matters, did not completely solve this issue.

This query:

select monthlysales, MemberNo from ReportingMonthlySales
where unit = 'Abuelos' and CYear = 2017 and cmonth = 3

...returns a bunch of rows, where the Monthly Sales total is $364,121.69

However, when I try to compartmentalize these monthly sales into four categories, although the sum of them all should be the same, the sum is actually astronomically "huger" - the following code returns the vastly inflated value of 23,924,211.30

24 millions of dollars is almost 70 times as much as the 364 thousand that is the actual sum total. Why is this "crazy" inflation occurring?

Here is the fancy pants but apparently bamboozled code:

declare @Unit varchar(30);
declare @Year int = 2017;
declare @Month int = 3;
declare @paramdate datetime;
set @paramdate = convert(datetime,convert(char(4),@Year)
                +right('0'+convert(varchar(2),@month),2)
                +'01')

IF OBJECT_ID('tempdb.dbo.#Units', 'U') IS NOT NULL
DROP TABLE #Units

select distinct unit
into #Units
from ReportingMonthlySales;

select
    u.Unit
  , New      = sum(case when ccl.Subcategory = 'New'      then rms.MonthlySales else 0 end)
  , Assumed  = sum(case when ccl.Subcategory = 'Assumed'  then rms.MonthlySales else 0 end)
  , Existing = sum(case when ccl.Subcategory = 'Existing' then rms.MonthlySales else 0 end)
  , Organic  = sum(case when ccl.Subcategory = 'Organic'  then rms.MonthlySales else 0 end)
from #Units u
  left join CustomerCategoryLog ccl
    on u.Unit = ccl.Unit
   and @paramdate >= ccl.begindate and
   (@paramdate <= ccl.enddate OR ccl.enddate is null)
  left join ReportingMonthlySales rms
    on u.Unit = rms.Unit
   and rms.cyear  = @year
   and rms.cmonth = @month
group by u.unit;

The two tables queried are:

CustomerCategoryLog
-------------------
MemberNo (VarChar)
Unit (VarChar)
Custno (VarChar)
Category (VarChar)
Subcategory (VarChar)
BeginDate (DateTime)
EndDate (DateTime)
ChangedBy (VarChar)
ChangedOn (DateTime)

ReportingMonthlySales
---------------------
AutoID (Int)
Unit (VarChar)
MemberNo (VarChar)
NumUnits (Int)
MonthlySales (Money)
CYear (Int)
Cmonth (Int)
CreateDate (DateTime)

Is there something faulty in the fancy-pants sql, or ... ?!?


问:
Why is select button in App Maker Drive Picker not enabled?
I have a Drive Picker widget in Google App Maker that pops up and lets me select a folder.  However, the Select button is greyed out.

I have entries for selectedDocUrl, selectedDocName, and onDocumentSelect, but I cannot get the button to be clickable.  My views is set to FOLDERS and my security is set to run as the user's account.  I see this but since I am using App Maker I don't see how to apply it.

Any idea how to enable this button?

Thanks

答: Google has confirmed they have fixed the problem and it now works fine.</p>


问:
Javascript filter deep array in array while maintaining original array
I'm wanting to filter an array without changing the original array that I've sliced from. You can see that the first thing I do within the filterChange function is to splice from the original array. The original array still ends up changed as well and I don't understand why.</p>

```<code>var MenuDisplayModule = (function ($, window, document, Handlebars) {

    var module = {};
    module.menuItems = [];
    module.init = function () {
        console.info('BreadcrumbDisplayModule Init');

    };
    module.template = function (array) {
        module.menuItems = array;
        var filteredMenuItems = array.slice(0);
        _template(filteredMenuItems);
    }
    module.filterChange = function (filterText) {

        var filteredMenuItems = module.menuItems.slice(0);

        filteredMenuItems.forEach(function (item, index) {
            var filteredItems = item.MenuItems.filter(function (el) {
                return (el.MenuText.includes(filterText));
            });
            filteredMenuItems[index].MenuItems = filteredItems;
        })
        _template(filteredMenuItems);
    }
    function _template(filteredMenuItems) {
        var menu_items_source = $("#menu-items-template").html();
        var menu_items_template = Handlebars.compile(menu_items_source);
        $("#menu-items-placeholder").empty().html(menu_items_template({ menuItems: filteredMenuItems }));
    }
    return module;
}(window.jQuery, window, document, window.Handlebars));
</code>```

答:
If you want to filter the Array and create a new one with the filtered contents and leave the old one unchanged I suggest

```<code>newArray = oldArray.filter(function(item) { return item.wantThis === true; })
</code>```

Now you have newArray consisting of only those Objects which have property

```<code>item.wantThis === true
</code>```

In you example you are using slice() which in my experience looks very much like splice() (which will can mutate the Array).

I suggest you simply stick to using filter().

But why are you making so many slice copies?

It would help if you posted an example of an Object in the array you receive.

Form looking at you example it seems that filteredItems is a private var to the previous ForEach loop, if you change that active part of your code to....

```<code>   module.filterChange = function (filterText) {

    var filteredMenuItems = module.menuItems.slice(0);

    var filteredItems; // declare the var outside of the .forEach

        filteredMenuItems.forEach(function (item, index) {
            filteredItems = item.MenuItems.filter(function (el) {
            return (el.MenuText.includes(filterText));
        });
        filteredMenuItems[index].MenuItems = filteredItems;
    })
    _template(filteredMenuItems);
}
</code>```

It might work.

The effect of your filteredItems is..

```<code>   filteredMenuItems.forEach(function(item) {
    item.MenuItems = item.MenuItems
                            .filter(function(el) { return (el.MenuText.includes(filterText)); });
    })
</code>```

So your item.MenuItems will get smaller with each filter.

Body:
I'm wanting to filter an array without changing the original array that I've sliced from. You can see that the first thing I do within the filterChange function is to splice from the original array. The original array still ends up changed as well and I don't understand why.

var MenuDisplayModule = (function ($, window, document, Handlebars) {

    var module = {};
    module.menuItems = [];
    module.init = function () {
        console.info('BreadcrumbDisplayModule Init');

    };
    module.template = function (array) {
        module.menuItems = array;
        var filteredMenuItems = array.slice(0);
        _template(filteredMenuItems);
    }
    module.filterChange = function (filterText) {

        var filteredMenuItems = module.menuItems.slice(0);

        filteredMenuItems.forEach(function (item, index) {
            var filteredItems = item.MenuItems.filter(function (el) {
                return (el.MenuText.includes(filterText));
            });
            filteredMenuItems[index].MenuItems = filteredItems;
        })
        _template(filteredMenuItems);
    }
    function _template(filteredMenuItems) {
        var menu_items_source = $("#menu-items-template").html();
        var menu_items_template = Handlebars.compile(menu_items_source);
        $("#menu-items-placeholder").empty().html(menu_items_template({ menuItems: filteredMenuItems }));
    }
    return module;
}(window.jQuery, window, document, window.Handlebars));

Body:
If you want to filter the Array and create a new one with the filtered contents and leave the old one unchanged I suggest

newArray = oldArray.filter(function(item) { return item.wantThis === true; })

Now you have newArray consisting of only those Objects which have property

item.wantThis === true

In you example you are using slice() which in my experience looks very much like splice() (which will can mutate the Array).

I suggest you simply stick to using filter().

But why are you making so many slice copies?

It would help if you posted an example of an Object in the array you receive.

Form looking at you example it seems that filteredItems is a private var to the previous ForEach loop, if you change that active part of your code to....

   module.filterChange = function (filterText) {

    var filteredMenuItems = module.menuItems.slice(0);

    var filteredItems; // declare the var outside of the .forEach

        filteredMenuItems.forEach(function (item, index) {
            filteredItems = item.MenuItems.filter(function (el) {
            return (el.MenuText.includes(filterText));
        });
        filteredMenuItems[index].MenuItems = filteredItems;
    })
    _template(filteredMenuItems);
}

It might work.

The effect of your filteredItems is..

   filteredMenuItems.forEach(function(item) {
    item.MenuItems = item.MenuItems
                            .filter(function(el) { return (el.MenuText.includes(filterText)); });
    })

So your item.MenuItems will get smaller with each filter.


问:
Cannot find module 'meteor-promise'
I am using Meteor 1.4.3.2 on a windows7 dev environment.
I've ran into a problem with an application after attempting to remove a failed demeteorizer attempt. After removal of demeteorizer folders/files now receiving error:

```<code>module.js:327
    throw err;
    ^
Error: Cannot find module 'meteor-promise'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (C:\Users\muser\AppData\Local\.meteor\packages\meteor-
tool\1.4.0-1\mt-os.windows.x86_32\tools\tool-env\install-promise.js:6:1)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
</code>```

I believe this meteor-promise is related to the Fibers module used in demeteorizer.
Seems that files were inadvertently removed from outside of application folders due to sym-link to somewhere in \AppData\Local.meteor....  I think.

My other applications are still working fine, so a meteor reinstall seems unlikely to fix issue.

Adding to the excitement none of my saved versions (including fresh clones from repo) will work either. This I think adds evidence to the sym-link theory.

Any suggestions on best approach to fix the application?

Thanks very much for your time and expertise.

答:
It sounds like quite a mess, hopefully this fixes your issue.

Delete the meteor-tool folder within the version of meteor your app is using.  You mentioned you are using 1.4.3.2 so the folder to delete is probably...

```<code>C:\Users\<username>\AppData\Local\.meteor\packages\meteor-tool\1.4.3_2
</code>```

You can double check by looking at the release file in your project's .meteor folder.

Once that is deleted, startup your meteor app using meteor run and it will detect that the meteor-tool version is missing and re-download it.  The promise package is installed inside this folder...so re-downloading will replace it.

Title: Cannot find module 'meteor-promise'

Body:
I am using Meteor 1.4.3.2 on a windows7 dev environment.
I've ran into a problem with an application after attempting to remove a failed demeteorizer attempt. After removal of demeteorizer folders/files now receiving error:

module.js:327
    throw err;
    ^
Error: Cannot find module 'meteor-promise'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (C:\Users\muser\AppData\Local\.meteor\packages\meteor-
tool\1.4.0-1\mt-os.windows.x86_32\tools\tool-env\install-promise.js:6:1)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)

I believe this meteor-promise is related to the Fibers module used in demeteorizer.
Seems that files were inadvertently removed from outside of application folders due to sym-link to somewhere in \AppData\Local.meteor....  I think.

My other applications are still working fine, so a meteor reinstall seems unlikely to fix issue.

Adding to the excitement none of my saved versions (including fresh clones from repo) will work either. This I think adds evidence to the sym-link theory.

Any suggestions on best approach to fix the application?

Thanks very much for your time and expertise.

Body:
It sounds like quite a mess, hopefully this fixes your issue.

Delete the meteor-tool folder within the version of meteor your app is using.  You mentioned you are using 1.4.3.2 so the folder to delete is probably...

C:\Users\<username>\AppData\Local\.meteor\packages\meteor-tool\1.4.3_2

You can double check by looking at the release file in your project's .meteor folder.

Once that is deleted, startup your meteor app using meteor run and it will detect that the meteor-tool version is missing and re-download it.  The promise package is installed inside this folder...so re-downloading will replace it.


问:
How can I make a Python 3.x program allow the user control what the program does?
The program is supposed to do the described functions on the numbers given, but I get an error after I give the second number.

code

```<code>num1=int(input("Give me a number: "))
num2=int(input("Give me another number: "))

add=int(("For addition, press [1]."))
time.sleep(2)
sub=int(print("For subtraction, press [2]."))
time.sleep(2)
div=int(("For division, press [3]."))
time.sleep(2)
multi=int(("For multiplication, press [4]."))
time.sleep(2)
print("Please input an option and press [RETURN].")

if input == 1:
    ans=num1+num2
if input == 2:
    ans=num1+num2
</code>```

Any ideas on how I can improve on my code?

答:
More simplified version:</p>

```<code>print "Basic calculator"

num1=int(input("Enter number 1: "))
num2=int(input("Enter the other number: "))

choice=int(input("For addition, press [1].\n"
    "For subtraction, press [2].\n"
    "....\n"
    "Please input the operation and press [RETURN]."))
time.sleep(2)

if choice == 1:
    ans=num1+num2
elif choice == 2:
    ans=num1-num2
    ...

print "Answer is {}".format(ans)
</code>```

Body:
The program is supposed to do the described functions on the numbers given, but I get an error after I give the second number.

code

num1=int(input("Give me a number: "))
num2=int(input("Give me another number: "))

add=int(("For addition, press [1]."))
time.sleep(2)
sub=int(print("For subtraction, press [2]."))
time.sleep(2)
div=int(("For division, press [3]."))
time.sleep(2)
multi=int(("For multiplication, press [4]."))
time.sleep(2)
print("Please input an option and press [RETURN].")

if input == 1:
    ans=num1+num2
if input == 2:
    ans=num1+num2

Any ideas on how I can improve on my code?

Body:
More simplified version:

print "Basic calculator"

num1=int(input("Enter number 1: "))
num2=int(input("Enter the other number: "))

choice=int(input("For addition, press [1].\n"
    "For subtraction, press [2].\n"
    "....\n"
    "Please input the operation and press [RETURN]."))
time.sleep(2)

if choice == 1:
    ans=num1+num2
elif choice == 2:
    ans=num1-num2
    ...

print "Answer is {}".format(ans)


问:
How to clear the form after submitting in model-driven form? (Angular 2)
How can I clear the form after submitting in model-driven form? Do I have to use ngModel? Thanks

```<code><form [ngFormModel]="myForm" (ngSubmit)="onSubmit()">
    <input type="text" [ngFormControl]="name">
    <button type="submit">Submit</button>
</form>
</code>```

.

```<code>myForm: ControlGroup;
name: AbstractControl;

ngOnInit()
{
    this.myForm = this._formBuilder.group({
        'name': [""]
    });
    this.name = this.myForm.controls['name'];
}

onSubmit() {
    this.name.value = ""; // This is not working.
}
</code>```

答:
Another way useful if you have some server validation is to do this:

```<code><form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
    ...
</form>
</code>```

and

```<code>import { NgForm } from '@angular/forms';
onSubmit(myForm: NgForm) {
    // do something and if no error
    myForm.reset();
}
</code>```

Body:
How can I clear the form after submitting in model-driven form? Do I have to use ngModel? Thanks

<form [ngFormModel]="myForm" (ngSubmit)="onSubmit()">
    <input type="text" [ngFormControl]="name">
    <button type="submit">Submit</button>
</form>

.

myForm: ControlGroup;
name: AbstractControl;

ngOnInit()
{
    this.myForm = this._formBuilder.group({
        'name': [""]
    });
    this.name = this.myForm.controls['name'];
}

onSubmit() {
    this.name.value = ""; // This is not working.
}

Body:
Another way useful if you have some server validation is to do this:

<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
    ...
</form>

and

import { NgForm } from '@angular/forms';
onSubmit(myForm: NgForm) {
    // do something and if no error
    myForm.reset();
}


问:
R Data Frame remove rows with max values from all columns
Hello I have the data frame and I need to remove all the rows with max values from each columns.
Example

```<code>   A B C
1  2 3 5
2  4 1 1
3  1 4 3
4  2 1 1
</code>```

So the output is:

```<code>   A B C
4  2 1 1
</code>```

Is there any quick way to do this?

答:
```<code>df[-sapply(df, which.max),]
#  A B C
#4 2 1 1
</code>```

DATA

```<code>df = structure(list(A = c(2L, 4L, 1L, 2L), B = c(3L, 1L, 4L, 1L),
    C = c(5L, 1L, 3L, 1L)), .Names = c("A", "B", "C"),
    class = "data.frame", row.names = c(NA,-4L))
</code>```

Body:
Hello I have the data frame and I need to remove all the rows with max values from each columns.
Example

   A B C
1  2 3 5
2  4 1 1
3  1 4 3
4  2 1 1

So the output is:

   A B C
4  2 1 1

Is there any quick way to do this?

Body:
df[-sapply(df, which.max),]
#  A B C
#4 2 1 1

DATA

df = structure(list(A = c(2L, 4L, 1L, 2L), B = c(3L, 1L, 4L, 1L),
    C = c(5L, 1L, 3L, 1L)), .Names = c("A", "B", "C"),
    class = "data.frame", row.names = c(NA,-4L))


问:
Replace array item with another one without mutating state
This is how example of my state looks:

```<code>const INITIAL_STATE = {
 contents: [ {}, {}, {}, etc.. ],
 meta: {}
}
</code>```

I need to be able and somehow replace an item inside contents array knowing its index, I have tried:

```<code>      return {
        ...state,
        contents: [
          ...state.contents[action.meta.index],
          {
            content_type: 7,
            content_body: {
              album_artwork_url: action.payload.data.album.images[1].url,
              preview_url: action.payload.data.preview_url,
              title: action.payload.data.name,
              subtitle: action.payload.data.artists[0].name,
              spotify_link: action.payload.data.external_urls.spotify
            }
          }
        ]
      }
</code>```

where action.meta.index is index of array item I want to replace with another contents object, but I believe this just replaces whole array to this one object I'm passing. I also thought of using .splice() but that would just mutate the array?

答:
Note that Array.prototype.map() (docs) does not mutate the original array so it provides another option:

```<code> const INITIAL_STATE = {
   contents: [ {}, {}, {}, etc.. ],
   meta: {}
 }

 // Assuming this action object design
 {
   type: MY_ACTION,
   data: {
     // new content to replace
   },
   meta: {
     index: /* the array index in state */,
   }
 }

 function myReducer(state = INITIAL_STATE, action) {
   switch (action.type) {
     case MY_ACTION:
       return {
         ...state,
         // optional 2nd arg in callback is the array index
         contents: state.contents.map((content, index) => {
           if (index === action.meta.index) {
             return action.data
           }

           return content
         })
       }
   }
 }
</code>```

Body:
This is how example of my state looks:

const INITIAL_STATE = {
 contents: [ {}, {}, {}, etc.. ],
 meta: {}
}

I need to be able and somehow replace an item inside contents array knowing its index, I have tried:

      return {
        ...state,
        contents: [
          ...state.contents[action.meta.index],
          {
            content_type: 7,
            content_body: {
              album_artwork_url: action.payload.data.album.images[1].url,
              preview_url: action.payload.data.preview_url,
              title: action.payload.data.name,
              subtitle: action.payload.data.artists[0].name,
              spotify_link: action.payload.data.external_urls.spotify
            }
          }
        ]
      }

where action.meta.index is index of array item I want to replace with another contents object, but I believe this just replaces whole array to this one object I'm passing. I also thought of using .splice() but that would just mutate the array?

Body:
Note that Array.prototype.map() (docs) does not mutate the original array so it provides another option:

 const INITIAL_STATE = {
   contents: [ {}, {}, {}, etc.. ],
   meta: {}
 }

 // Assuming this action object design
 {
   type: MY_ACTION,
   data: {
     // new content to replace
   },
   meta: {
     index: /* the array index in state */,
   }
 }

 function myReducer(state = INITIAL_STATE, action) {
   switch (action.type) {
     case MY_ACTION:
       return {
         ...state,
         // optional 2nd arg in callback is the array index
         contents: state.contents.map((content, index) => {
           if (index === action.meta.index) {
             return action.data
           }

           return content
         })
       }
   }
 }


问:
Why geoEvent returns a list instead of single GeoFence
I have implemented GeoFence in my project. When geoFence event occur. It returns a GeoEvent object which has a method name getTriggeringGeofences (Returns a list of geofences that triggered this geofence transition alert.).

Why it is returning a list instead of single geoFence?

GeofenceReceiver.java

```<code>    public class GeofenceReceiver extends BroadcastReceiver {

    public static final String TAG = GeofenceReceiver.class.getSimpleName();
    private Context mContext;

    @Override
    public void onReceive(Context context, Intent intent) {

        mContext = context;
        GeofencingEvent geoEvent = GeofencingEvent.fromIntent(intent);

        Location triggredLocation = geoEvent.getTriggeringLocation();

        if (geoEvent.hasError()) {
            Log.d(TAG, "Error GeofenceReceiver.onHandleIntent");
        } else {
            Log.d(TAG, "GeofenceReceiver : Transition -> "
                    + geoEvent.getGeofenceTransition());

            int transitionType = geoEvent.getGeofenceTransition();

            if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER
                    || transitionType == Geofence.GEOFENCE_TRANSITION_DWELL
                    || transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
                //why it is a list of GeoFence
                List<Geofence> triggerList = geoEvent.getTriggeringGeofences();
            }
        }
    }
}
</code>```

答:
Typically geofences are used as a power efficient way of knowing when a device enters or leaves a region. On mobile devices, this is accomplished by polling for network locations occasionally, meaning you can travel a some distance into/away from the geofence before it triggers.

With that in mind, consider this Venn diagram.

Consider the top of the image as North. If you come in from the West into Geofence "A", you'll most likely trigger the ENTER only at that geofence. Same if you come from the East. However, if you were to come from the North or South between "A" and "B", you'll be inside of both geofences. At this point, you have triggered the ENTER event on both, so instead of calling your receiver twice in a row, it'll just give you the list of geofences that were triggered with this event, at which point you should iterate through them and perform whatever action is needed for the event on each geofence.

Looking at the docs, it seems that the broadcasts are separated by triggering events, meaning each broadcast will either be ENTER, EXIT, or DWELL events, so if you EXIT "B" and ENTER "A", you should get two different broadcasts, each with a list of 1 geofence.

Body:
I have implemented GeoFence in my project. When geoFence event occur. It returns a GeoEvent object which has a method name getTriggeringGeofences (Returns a list of geofences that triggered this geofence transition alert.).

Why it is returning a list instead of single geoFence?

GeofenceReceiver.java

    public class GeofenceReceiver extends BroadcastReceiver {

    public static final String TAG = GeofenceReceiver.class.getSimpleName();
    private Context mContext;

    @Override
    public void onReceive(Context context, Intent intent) {

        mContext = context;
        GeofencingEvent geoEvent = GeofencingEvent.fromIntent(intent);

        Location triggredLocation = geoEvent.getTriggeringLocation();

        if (geoEvent.hasError()) {
            Log.d(TAG, "Error GeofenceReceiver.onHandleIntent");
        } else {
            Log.d(TAG, "GeofenceReceiver : Transition -> "
                    + geoEvent.getGeofenceTransition());

            int transitionType = geoEvent.getGeofenceTransition();

            if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER
                    || transitionType == Geofence.GEOFENCE_TRANSITION_DWELL
                    || transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
                //why it is a list of GeoFence
                List<Geofence> triggerList = geoEvent.getTriggeringGeofences();
            }
        }
    }
}


问:
C# application unable to establish SSL/TLS connection
I have a c# application that generates an error "The request was aborted: Could not create SSL/TLS secure channel" when it tries to save a file to a remote SharePoint server.  This happens on a Windows 2012 server, but the application runs successfully from my desktop windows machine.

Also, from the dev server, I am able to connect to the SharePoint server with IE11, with only TLS 1.1 enabled.

The application has all security protocols enabled.

I also know that the application never calls the certificatevalidationcallback function.

Given these symptoms, does anyone have any idea what could be going wrong?

答:
After quite a bit of experimentation, I found the solution, but I'm still puzzled.  The solution turned out to be the use of

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls11;

which is not surprising.  What is surprising is that when I was getting the error, I was using

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;

I specified both protocols because I wasn't sure which was being used by the remote server, and I thought there was no downside to allowing either protocol.

Now I'm wondering why allowing a second protocol causes the application to be unable to establish the secure channel.


问:
How do I substitute one word in a string variable in Python?
I know people have asked about how to substitute words in strings, but I'd like to replace a specific word in a variable string, and leave the rest untouched.

For example: if the user enters "My family does not like chicken", I'd like the computer to output back to them "Your family does not like chicken". The word being replaced is "My", and the word replacing it is "Your". I'm using Python 2.7.13.

答:
The other answers do not deal with storing user input, you can do so by using raw_input in python 2:

```<code>#Store users input into a variable
user_input = raw_input("Please enter a sentence: ")

#Use str.replace to replace ALL occurrences of the word "My" with "Your" and output using print
print user_input.replace("My", "Your")
</code>```

Example Usage:

```<code>Please enter a sentence:  My family does not like chicken
Your family does not like chicken
</code>```

Try it here!

Link to python documentation for: str.replace

Body:
The other answers do not deal with storing user input, you can do so by using raw_input in python 2:

#Store users input into a variable
user_input = raw_input("Please enter a sentence: ")

#Use str.replace to replace ALL occurrences of the word "My" with "Your" and output using print
print user_input.replace("My", "Your")

Example Usage:

Please enter a sentence:  My family does not like chicken
Your family does not like chicken

Try it here!

Link to python documentation for: str.replace


问:
Using variable outside of ajax callback function
What is the best to use global variables outside of a callback function?</p>

```<code>    var icon;
    $(function(){

      $.get('data.xml', function(xml){

           icon = xml.documentElement.getElementsByTagName("icon");
           //this outputs a value
           console.log(icon);
       });
       //this is null
       //How can this maintain the value set above?
       console.log(icon);
    });
</code>```

答:
It can help to visualize the code like this.

```<code>    var icon;
    $(function(){
        $.get('data.xml', callback); // sends ajax request
        // next line happens immediately unless ajax request is set to synchronous
        console.log(icon); // logs undefined
    });
    function callback(xml){ // onsuccess callback happens
        icon = xml.documentElement.getElementsByTagName("icon");
        console.log(icon); // logs Array
    }
</code>```

I removed the anonymous function and placed the callback after the console.log. Like others have pointed out the ajax callback happens asynchronously, while javascript continues to execute.

Body:
What is the best to use global variables outside of a callback function?

    var icon;
    $(function(){

      $.get('data.xml', function(xml){

           icon = xml.documentElement.getElementsByTagName("icon");
           //this outputs a value
           console.log(icon);
       });
       //this is null
       //How can this maintain the value set above?
       console.log(icon);
    });

Body:
It can help to visualize the code like this.

    var icon;
    $(function(){
        $.get('data.xml', callback); // sends ajax request
        // next line happens immediately unless ajax request is set to synchronous
        console.log(icon); // logs undefined
    });
    function callback(xml){ // onsuccess callback happens
        icon = xml.documentElement.getElementsByTagName("icon");
        console.log(icon); // logs Array
    }

I removed the anonymous function and placed the callback after the console.log. Like others have pointed out the ajax callback happens asynchronously, while javascript continues to execute.


问:
Testing component in Android App SDLC?
"Automated testing is an integral part of the development lifecycle."

In android app proejcts we've implemented MVP, Rx with Retrofit and Content Provider/SQLite, dagger. Every android apps will always have server communication, storing data in local database,  complex ui like naviagtion drawer and recycler view etc, and difficult navigation flow of application.

What we want to achieve?

Few test cases which should be tested every time before we deliver the apk to client or release on play store?(20-30% automate testing)

List of test cases of business logic, which can not be auto tested because whatever reason like complex ui, navigation flow etc (40-60% manual testing)

Continuous Integration

Based on above, there are few questions,

What to test in auto and manual, how to decide that?

In automate testing, where to test in MVP - Model-View-Presenter layers?

What kind of general business logic should auto test for mobile apps - like registration, login, forgot password, update profile etc?

What type of testing should perform for android apps - unit testing, functional testing, integration testing, manual testing, performance testing, regression testing

Which tool to use - android testing support library, espresso, uiautomator, Robotium, roboelectric, appium, selendroid, mockito, JUnit

(Feel free to improve check list as we don't know best practices for testing module in SDLC for android mobile app.) originally asked, here.

答:
Some answers to your questions:

Auto vs. manual: once design/dev cycles have settled, automated tests should be part of the code delivery before releasing. A good trigger here is simply include UI testing in Definition of Done on stories before they're shipped. For Android, this could be as simple as some Espresso tests that cover new functionality.

MVP layer testing...unit test your presenters and UI test your views. that covers almost anything in models that doesn't work because model changes are rarely done in isolation of those two layers. high unit coverage in the presenter helps to balance how much UI test are written. see this article for in-depth tutorial.

business logic: at the very least, ALL tasks on the critical paths that users take to accomplish key goals (i.e. your revenue stream, basic adoption). So yes, this includes registration, login, and password features...but might not cover all preferences/configurations and their effects.

type of testing: each type tests different layers/aspects of your application, so ask yourself "what details in the layers of my app should I care about"?

unit is for basic code validation, so yes to that, always. that's just basic dev efficiency 101 there. high code coverage helps you catch bugs early.

integration: yes, and depends on how complicated your app is, but testing the app with/without dependencies helps isolate who's at fault when test fails.

functional tests (UI tests): yes, simple interactions or complete workflow, but it's about how your users work with your app. some functions of the app can't be tested without going through a set of other steps. again, align with actual usage and business expectations. map your amount of work here to reality, usage metrics, impact on revenue, etc.

performance: this is hard, and there are different schools of thought. what we see is that performance 'checks' along the way are necessary, but full performance testing cycles often impede development unless there's a high degree of maturity and process in the team/org.

regression: don't leave regression to a huge task towards the end! smaller sets of regression informed by the changes you've made help to reduce the number of defects caught in late-cycle regression testing. earlier means smaller, and don't forget that we're dealing with a very fragmented Android ecosystem so multiple devices/platforms/conditions needs to be included in regression strategy!

tools: you've pretty much nailed the current toolchain. for Android UI testing, Espresso/Dagger/mockito is a huge win. keep these types of tests small and focused. for end-to-end testing, Appium is still your best friend, but there are things that even it can't do (like visual validation and certain popups) that you'll need to seek beyond them to automate.

Also, while I completely understand your statement "can not be auto tested because whatever reason", I think that's a big red flag and the details matter a lot. The choice of auto vs. manual should be business decision about how to achieve velocity goals, not about technical limitations and shortfalls. I hear this all the time from customers until they realize that the right tech enables them to achieve the level of automation that's right for them.

There are two pieces of research I assisted with this year that I think will help this conversation:

Expanding Quality into the Build Cycle

Improving App Quality at Build-time

Hope this and my research above helps your work.

Title: Testing component in Android App SDLC?


问:
Angular 2: How do I access a custom Component's FormControl instance within that Component?
So I've been reading how to construct custom FormControls in Angular2, but I can't get what I'm trying to do working fully with validation.  I have a normal input control that I want to wrap up in a custom Component so that I can do this:

```<code><my-control name="something" [(ngModel)]="model.something" required></my-control>
</code>```

Rather than repeating this every time:

```<code><div class="form-group has-feedback" [ngClass]="{'has-success': someInput.valid, 'has-error': someInput.invalid && someInput.dirty}">
    <label class="control-label" for="someId">{{label || 'Some Input'}}</label>
    <input type="test" class="form-control" id="someId" placeholder="Some Input" [ngModel]="value" (ngModel)="onChange($event)" name="someInput" required #someInput="ngModel" minlength="8"/>
    <span class="glyphicon form-control-feedback" aria-hidden="true" [ngClass]="{'glyphicon-ok': someInput.valid, 'glyphicon-remove': someInput.invalid && someInput.dirty}"></span>
    <div [hidden]="someInput.valid || someInput.pristine || !someInput.errors.required" class="text-danger">Some Input is required</div>
    <div [hidden]="someInput.valid || someInput.pristine || !someInput.errors.minlength" class="text-danger">Some Input must be at least 8 characters</div>
</div>
</code>```

So I've implemented by custom Component following articles about how to create custom components online:

https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

What's missing is the ability to move the validation out of the component, but allow the custom component to handle the display of that validation.  So if you look above what I'm going for is to allow validation to be specified by the user of the component rather than have the component impose specific validations (note some validation would be inherent to a component, for example an email address component would validate it's an email without the user specifying that).  Notice that required is placed on the usage of that customer component.

So how do I get a reference to the custom component's FormControl within that component's definition?  NOTE: I understand how to access the input field within the template's FormControl instance as my code above demonstrates that exactly.  What I'm asking for is the FormControl instance for the custom control that template is within.  In the article I reference it would be the FormControl for the CounterInputComponent.

答:
Adding this seems to work:

```<code>@ViewChild(NgModel) model: NgModel;
</code>```

Then you can get to your FormControl through:

```<code>this.model.control
</code>```

Body:
So I've been reading how to construct custom FormControls in Angular2, but I can't get what I'm trying to do working fully with validation.  I have a normal input control that I want to wrap up in a custom Component so that I can do this:

<my-control name="something" [(ngModel)]="model.something" required></my-control>

Rather than repeating this every time:

    {{label || 'Some Input'}}
    <input type="test" class="form-control" id="someId" placeholder="Some Input" [ngModel]="value" (ngModel)="onChange($event)" name="someInput" required #someInput="ngModel" minlength="8"/>

Some Input is required

Some Input must be at least 8 characters

So I've implemented by custom Component following articles about how to create custom components online:

https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

What's missing is the ability to move the validation out of the component, but allow the custom component to handle the display of that validation.  So if you look above what I'm going for is to allow validation to be specified by the user of the component rather than have the component impose specific validations (note some validation would be inherent to a component, for example an email address component would validate it's an email without the user specifying that).  Notice that required is placed on the usage of that customer component.

So how do I get a reference to the custom component's FormControl within that component's definition?  NOTE: I understand how to access the input field within the template's FormControl instance as my code above demonstrates that exactly.  What I'm asking for is the FormControl instance for the custom control that template is within.  In the article I reference it would be the FormControl for the CounterInputComponent.

Body:
Adding this seems to work:

@ViewChild(NgModel) model: NgModel;

Then you can get to your FormControl through:

this.model.control