问:
Return a non empty string from range of cells in Access 2016
So I have inherited an Access 2016 DB that needs some tweaking, and I need help as I am familiar with Access, but I am not the best (not by far, or at all) :)

The db is setup as follows:
Data is linked to 4 SQL Server Databases that imports two tables from each db, one being Clients and One Being Prospective Clients (this is for lookup purposes as the client wants to do nothing manually). In the only table that is updated in Access, there are 8 columns, one being the Client and One being the Prospective Client from each SQL Database. Looking like this:

Highveld_Client | Highveld_Prospect | Eastern_Client | Eastern_Prospect | Northern_Client | Northern_Prospect | Africa_Client | Africa_Prospect

Each of these is a drop down box and looks up the right data. But this makes for a very tedious report (as you can well imagine). What I am thinking is to have a field update automatically based on which one of these fields is not empty.

What I need is, exactly, the following:

Of the 8 fields shown above, only 1 will ever bill filled.
I need to automatically update a new field with the data from whichever one of these fields is filled.

For the love of me, I cannot seem to find a place that will guide me properly on how to do this. I have spent days scouring tutorials and forums, and nada. I know that if i need this done, it will more than likely be a VBA Code, but then it's not going to happen, knowing me, I will end up deploying a nuclear missile or something disastrous.

Thank you in advance, you'll never know how much all your help on these forums helps, or is appreciated.

答:
You can solve this problem without touching VBA, using only the power of SQL. Try the following query:</p>

```<code>  SELECT Highveld_Client AS Client, Highveld_Prospect AS Prospect, "Highveld" As Region
  From MyTable
  WHERE Highveld_Client IS NOT NULL OR Highveld_Prospect IS NOT NULL
UNION ALL
  SELECT Eastern_Client AS Client, Eastern_Prospect AS Prospect, "Eastern" As Region
  From MyTable
  WHERE Eastern_Client IS NOT NULL OR Eastern_Prospect IS NOT NULL
UNION ALL
  SELECT Northern_Client AS Client, Northern_Prospect AS Prospect, "Northern" As Region
  From MyTable
  WHERE Northern_Client IS NOT NULL OR Northern_Prospect IS NOT NULL
UNION ALL
  SELECT Africa_Client AS Client, Africa_Prospect AS Prospect, "Africa" As Region
  From MyTable
  WHERE Africa_Client IS NOT NULL OR Africa_Prospect IS NOT NULL
</code>```

Body:
You can solve this problem without touching VBA, using only the power of SQL. Try the following query:

  SELECT Highveld_Client AS Client, Highveld_Prospect AS Prospect, "Highveld" As Region
  From MyTable
  WHERE Highveld_Client IS NOT NULL OR Highveld_Prospect IS NOT NULL
UNION ALL
  SELECT Eastern_Client AS Client, Eastern_Prospect AS Prospect, "Eastern" As Region
  From MyTable
  WHERE Eastern_Client IS NOT NULL OR Eastern_Prospect IS NOT NULL
UNION ALL
  SELECT Northern_Client AS Client, Northern_Prospect AS Prospect, "Northern" As Region
  From MyTable
  WHERE Northern_Client IS NOT NULL OR Northern_Prospect IS NOT NULL
UNION ALL
  SELECT Africa_Client AS Client, Africa_Prospect AS Prospect, "Africa" As Region
  From MyTable
  WHERE Africa_Client IS NOT NULL OR Africa_Prospect IS NOT NULL


来源: stackexchange

问:
Loading correct texture from Atlas with multiple pages
I have a big set of images saved in one atlas, but due to the 2048*2048 size limitation of a single page I had to split my packs in 12 pages.

My problem is that when I use  atlas.findRegion(imageName).getTexture() to load the texture, it loads the whole 2048*2048 page and not the single texture inside the page (the image pack contains the correct image though, so I know it's loading the correct file, I just don't understand why it's not cropping the texture around the image I pass as parameter to findRegion).

Thanks in advance, hope the question is detailed enough to receive an answer.

答: The problem was actually calling the getTexture() method, I just needed to load the Region. More info here loading regions of textureatlas in libgdx loads the entire file

ContentLicense: CC BY-SA 3.0


问:
Why i can not change text view value in fragment?
I'm new to android, I wrote a simple app to learn fragments. I created a text view:

```<code><TextView
        android:id="@+id/behzad"
        android:text="behzad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</code>```

In fragment I wrote this simple method:

```<code>public void setTest(){

        TextView text=(TextView) FiveView.findViewById(R.id.behzad);
        text.setText("hahaha");
        Toast.makeText(getActivity().getBaseContext(), "ok", Toast.LENGTH_SHORT).show();
    }
</code>```

I call that method in activity:

```<code>Fragment frag=adapter.getItem(4);
        ((FiveFragment)frag).setTest();
</code>```

I get the ok message from toast but the fragment's text view does not show hahaha

Why the text view's value has not changed? This is my code

答:
add notifyDataSetChanged() in your code:</p>

```<code>Fragment frag=adapter.getItem(4);
        ((FiveFragment)frag).setTest();
adapter.notifyDataSetChanged();
</code>```

Body:
I'm new to android, I wrote a simple app to learn fragments. I created a text view:

<TextView
        android:id="@+id/behzad"
        android:text="behzad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

In fragment I wrote this simple method:

public void setTest(){

        TextView text=(TextView) FiveView.findViewById(R.id.behzad);
        text.setText("hahaha");
        Toast.makeText(getActivity().getBaseContext(), "ok", Toast.LENGTH_SHORT).show();
    }

I call that method in activity:

Fragment frag=adapter.getItem(4);
        ((FiveFragment)frag).setTest();

I get the ok message from toast but the fragment's text view does not show hahaha

Why the text view's value has not changed? This is my code

Body:
add notifyDataSetChanged() in your code:

Fragment frag=adapter.getItem(4);
        ((FiveFragment)frag).setTest();
adapter.notifyDataSetChanged();


问:
Android Studio desgn mode for fullscreen app
I'm using AS 2.3.3 with a full screen app. I know how to put the app into full screen at run time but the design view still shows the status bar, a title and the nav buttons. How can I remove those from the preview so it looks as it will be when deployed?</p>

答:
Add NoActionBar theme to your application as:

```<code>android:theme="@style/AppTheme"
</code>```

and set theme in style.xml as:

```<code> <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</code>```

Body:
Add NoActionBar theme to your application as:

android:theme="@style/AppTheme"

and set theme in style.xml as:

 <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>


问:
in rx.js make source.subscribe await it's observer using async/await
I have an observer that goes like this.

```<code>var source = rx.Observable.fromEvent(eventAppeared.emitter, 'event')
      .filter(mAndF.isValidStreamType)
      .map(mAndF.transformEvent)
      .share();
</code>```

I then share it with a number of subscribers.  These subscribers all take the event and perform some async operations on them.
so my subscribers are like

```<code> source.subscribe(async function(x) {
  const func = handler[x.eventName];
  if (func) {
    await eventWorkflow(x, handler.handlerName, func.bind(handler));
  }
});
</code>```

There's a bit of extra stuff in there but I think the intent is clear.
I need every "handler" that handles this particular event to handle it and block till it gets back.  Then process the next event.

What I've found with the above code is that it's just calling the event with out awaiting it and my handlers are stepping on themselves.

I've read a fair number of posts, but I can't really see how to do it.  Most people are talking about making the observer awaitable.  But that's not what I need is it?  It seems like what I need is to make the observer awaitable.  I can't find anything on that which usually means it's either super easy or a super ridiculous thing to do.  I'm hoping for the former.

Please let me know if you need any further clarification.

---update---

what I have realized is that what I need is a fifo queue or buffer ( first in first out ), sometimes referred to as back pressure. I need all messages processed in order and only when the preceding message is done processing.

---end update---

at first I thought it was cuz I was using rx 2.5.3 but I just upgraded to 4.1.0 and it's still not synchronous.

答:
There's no way to tell a source observable to put events on hold from within a subscribe, it just lets us "observe" incoming events. Asynchronous things should be managed via Rx operators.

For example, to let your asynchronous handlers process events sequentially, you could try to use concatMap operator:

```<code>source
    .concatMap(x => {
        const func = handler[x.eventName];
        return func ?
            eventWorkflow(x, handler.handlerName, func.bind(handler)) :
            Rx.Observable.empty();
    })
    .subscribe();
</code>```

Note that in the example above await is not needed as concatMap knows how to deal with a promise which eventWorkflow returns: concatMap converts it to an observable and waits until the observable completes before proceeding with the next event.

Body:
I have an observer that goes like this.

var source = rx.Observable.fromEvent(eventAppeared.emitter, 'event')
      .filter(mAndF.isValidStreamType)
      .map(mAndF.transformEvent)
      .share();

I then share it with a number of subscribers.  These subscribers all take the event and perform some async operations on them.
so my subscribers are like

 source.subscribe(async function(x) {
  const func = handler[x.eventName];
  if (func) {
    await eventWorkflow(x, handler.handlerName, func.bind(handler));
  }
});

There's a bit of extra stuff in there but I think the intent is clear.
I need every "handler" that handles this particular event to handle it and block till it gets back.  Then process the next event.

What I've found with the above code is that it's just calling the event with out awaiting it and my handlers are stepping on themselves.

I've read a fair number of posts, but I can't really see how to do it.  Most people are talking about making the observer awaitable.  But that's not what I need is it?  It seems like what I need is to make the observer awaitable.  I can't find anything on that which usually means it's either super easy or a super ridiculous thing to do.  I'm hoping for the former.

Please let me know if you need any further clarification.

---update---

what I have realized is that what I need is a fifo queue or buffer ( first in first out ), sometimes referred to as back pressure. I need all messages processed in order and only when the preceding message is done processing.

---end update---

at first I thought it was cuz I was using rx 2.5.3 but I just upgraded to 4.1.0 and it's still not synchronous.

Body:
There's no way to tell a source observable to put events on hold from within a subscribe, it just lets us "observe" incoming events. Asynchronous things should be managed via Rx operators.

For example, to let your asynchronous handlers process events sequentially, you could try to use concatMap operator:

source
    .concatMap(x => {
        const func = handler[x.eventName];
        return func ?
            eventWorkflow(x, handler.handlerName, func.bind(handler)) :
            Rx.Observable.empty();
    })
    .subscribe();

Note that in the example above await is not needed as concatMap knows how to deal with a promise which eventWorkflow returns: concatMap converts it to an observable and waits until the observable completes before proceeding with the next event.


问:
Set Subject Alternative Names programmatically in Java
I am using something similar to this code. How can I add set the Subject Alternative Names in my certificate programmatically using sun.security?

答:
OK, it was a bit tricky to trace several sources but here it is the clue (in case it can help anyone in future as I have been helped other times):

```<code>CertificateExtensions ext = new CertificateExtensions();

ext.set(SubjectAlternativeNameExtension.NAME, new SubjectAlternativeNameExtension(....*));

// * a `GeneralNames` object including a `GeneralName` object including (for example) an `IPAddressName` object.
</code>```

And then pass the object ext to the constructor of the certificate.

Body:
OK, it was a bit tricky to trace several sources but here it is the clue (in case it can help anyone in future as I have been helped other times):

CertificateExtensions ext = new CertificateExtensions();

ext.set(SubjectAlternativeNameExtension.NAME, new SubjectAlternativeNameExtension(....*));

// * a `GeneralNames` object including a `GeneralName` object including (for example) an `IPAddressName` object.

And then pass the object ext to the constructor of the certificate.


问:
What is the difference between $a = $(Read-Host) and $a = (Read-Host)?
I have to review some scripts what my Ex-Colleague left behind and I am very curious why he is using $a = $(Read-Host -Prompt "Write something") in the Parameters section rather than $a = (Read-Host -Prompt "Write something").

I have tested it in a single script but haven't seen any difference so far.
I have searched thru the google and StackOverFlow but haven't find any clue so far what could be the difference.
Maybe my searching methods are bad.

答:
$() is for evaluating subexpressions in strings. It does nothing here.

You don't need () around read-host either, you can simply use $a = Read-Host -Prompt 'your input here'

(-Prompt needs a string as parameter).


问:
Using system icons for TreeView in C#
I'm making a file transfer app, and I need to use system icons so the icons will match different versions of Windows. They are remote files are distant so I can't just use SHFILEINFO.</p>

答:
So, I got it working by using this very good example from CodeProject:

```<code>public class IconReader
{
    /// <summary>
    /// Options to specify the size of icons to return.
    /// </summary>
    public enum IconSize
    {
        /// <summary>
        /// Specify large icon - 32 pixels by 32 pixels.
        /// </summary>
        Large = 0,
        /// <summary>
        /// Specify small icon - 16 pixels by 16 pixels.
        /// </summary>
        Small = 1
    }

    /// <summary>
    /// Options to specify whether folders should be in the open or closed state.
    /// </summary>
    public enum FolderType
    {
        /// <summary>
        /// Specify open folder.
        /// </summary>
        Open = 0,
        /// <summary>
        /// Specify closed folder.
        /// </summary>
        Closed = 1
    }

    /// <summary>
    /// Returns an icon for a given file - indicated by the name parameter.
    /// </summary>
    /// <param name="name">Pathname for file.</param>
    /// <param name="size">Large or small</param>
    /// <param name="linkOverlay">Whether to include the link icon</param>
    /// <returns>System.Drawing.Icon</returns>
    public static System.Drawing.Icon GetFileIcon(string name, IconSize size, bool linkOverlay)
    {
        Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
        uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;

        if (true == linkOverlay) flags += Shell32.SHGFI_LINKOVERLAY;

        /* Check the size specified for return. */
        if (IconSize.Small == size)
        {
            flags += Shell32.SHGFI_SMALLICON;
        }
        else
        {
            flags += Shell32.SHGFI_LARGEICON;
        }

        Shell32.SHGetFileInfo(name,
            Shell32.FILE_ATTRIBUTE_NORMAL,
            ref shfi,
            (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
            flags);

        // Copy (clone) the returned icon to a new object, thus allowing us to clean-up properly
        System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();
        User32.DestroyIcon(shfi.hIcon);     // Cleanup
        return icon;
    }

    /// <summary>
    /// Used to access system folder icons.
    /// </summary>
    /// <param name="size">Specify large or small icons.</param>
    /// <param name="folderType">Specify open or closed FolderType.</param>
    /// <returns>System.Drawing.Icon</returns>
    public static System.Drawing.Icon GetFolderIcon(IconSize size, FolderType folderType)
    {
        // Need to add size check, although errors generated at present!
        uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;

        if (FolderType.Open == folderType)
        {
            flags += Shell32.SHGFI_OPENICON;
        }

        if (IconSize.Small == size)
        {
            flags += Shell32.SHGFI_SMALLICON;
        }
        else
        {
            flags += Shell32.SHGFI_LARGEICON;
        }

        // Get the folder icon
        Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
        Shell32.SHGetFileInfo(@"Folder",
            Shell32.FILE_ATTRIBUTE_DIRECTORY,
            ref shfi,
            (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
            flags);

        System.Drawing.Icon.FromHandle(shfi.hIcon); // Load the icon from an HICON handle

        // Now clone the icon, so that it can be successfully stored in an ImageList
        System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();

        User32.DestroyIcon(shfi.hIcon);     // Cleanup
        return icon;
    }

    public static System.Drawing.Icon GetDriveIcon(IconSize size, FolderType folderType)
    {
        // Need to add size check, although errors generated at present!
        uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;

        if (FolderType.Open == folderType)
        {
            flags += Shell32.SHGFI_OPENICON;
        }

        if (IconSize.Small == size)
        {
            flags += Shell32.SHGFI_SMALLICON;
        }
        else
        {
            flags += Shell32.SHGFI_LARGEICON;
        }

        // Get the folder icon
        Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
        Shell32.SHGetFileInfo(null,
            Shell32.FILE_ATTRIBUTE_DIRECTORY,
            ref shfi,
            (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
            flags);

        System.Drawing.Icon.FromHandle(shfi.hIcon); // Load the icon from an HICON handle

        // Now clone the icon, so that it can be successfully stored in an ImageList
        System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();

        User32.DestroyIcon(shfi.hIcon);     // Cleanup
        return icon;
    }
}

/// <summary>
/// Wraps necessary Shell32.dll structures and functions required to retrieve Icon Handles using SHGetFileInfo. Code
/// courtesy of MSDN Cold Rooster Consulting case study.
/// </summary>
///

// This code has been left largely untouched from that in the CRC example. The main changes have been moving
// the icon reading code over to the IconReader type.
public class Shell32
{

    public const int MAX_PATH = 256;
    [StructLayout(LayoutKind.Sequential)]
    public struct SHITEMID
    {
        public ushort cb;
        [MarshalAs(UnmanagedType.LPArray)]
        public byte[] abID;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct ITEMIDLIST
    {
        public SHITEMID mkid;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct BROWSEINFO
    {
        public IntPtr hwndOwner;
        public IntPtr pidlRoot;
        public IntPtr pszDisplayName;
        [MarshalAs(UnmanagedType.LPTStr)]
        public string lpszTitle;
        public uint ulFlags;
        public IntPtr lpfn;
        public int lParam;
        public IntPtr iImage;
    }

    // Browsing for directory.
    public const uint BIF_RETURNONLYFSDIRS = 0x0001;
    public const uint BIF_DONTGOBELOWDOMAIN = 0x0002;
    public const uint BIF_STATUSTEXT = 0x0004;
    public const uint BIF_RETURNFSANCESTORS = 0x0008;
    public const uint BIF_EDITBOX = 0x0010;
    public const uint BIF_VALIDATE = 0x0020;
    public const uint BIF_NEWDIALOGSTYLE = 0x0040;
    public const uint BIF_USENEWUI = (BIF_NEWDIALOGSTYLE | BIF_EDITBOX);
    public const uint BIF_BROWSEINCLUDEURLS = 0x0080;
    public const uint BIF_BROWSEFORCOMPUTER = 0x1000;
    public const uint BIF_BROWSEFORPRINTER = 0x2000;
    public const uint BIF_BROWSEINCLUDEFILES = 0x4000;
    public const uint BIF_SHAREABLE = 0x8000;

    [StructLayout(LayoutKind.Sequential)]
    public struct SHFILEINFO
    {
        public const int NAMESIZE = 80;
        public IntPtr hIcon;
        public int iIcon;
        public uint dwAttributes;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
        public string szDisplayName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = NAMESIZE)]
        public string szTypeName;
    };

    public const uint SHGFI_ICON = 0x000000100;     // get icon
    public const uint SHGFI_DISPLAYNAME = 0x000000200;     // get display name
    public const uint SHGFI_TYPENAME = 0x000000400;     // get type name
    public const uint SHGFI_ATTRIBUTES = 0x000000800;     // get attributes
    public const uint SHGFI_ICONLOCATION = 0x000001000;     // get icon location
    public const uint SHGFI_EXETYPE = 0x000002000;     // return exe type
    public const uint SHGFI_SYSICONINDEX = 0x000004000;     // get system icon index
    public const uint SHGFI_LINKOVERLAY = 0x000008000;     // put a link overlay on icon
    public const uint SHGFI_SELECTED = 0x000010000;     // show icon in selected state
    public const uint SHGFI_ATTR_SPECIFIED = 0x000020000;     // get only specified attributes
    public const uint SHGFI_LARGEICON = 0x000000000;     // get large icon
    public const uint SHGFI_SMALLICON = 0x000000001;     // get small icon
    public const uint SHGFI_OPENICON = 0x000000002;     // get open icon
    public const uint SHGFI_SHELLICONSIZE = 0x000000004;     // get shell size icon
    public const uint SHGFI_PIDL = 0x000000008;     // pszPath is a pidl
    public const uint SHGFI_USEFILEATTRIBUTES = 0x000000010;     // use passed dwFileAttribute
    public const uint SHGFI_ADDOVERLAYS = 0x000000020;     // apply the appropriate overlays
    public const uint SHGFI_OVERLAYINDEX = 0x000000040;     // Get the index of the overlay

    public const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
    public const uint FILE_ATTRIBUTE_NORMAL = 0x00000080;

    [DllImport("Shell32.dll")]
    public static extern IntPtr SHGetFileInfo(
        string pszPath,
        uint dwFileAttributes,
        ref SHFILEINFO psfi,
        uint cbFileInfo,
        uint uFlags
        );
}

/// <summary>
/// Wraps necessary functions imported from User32.dll. Code courtesy of MSDN Cold Rooster Consulting example.
/// </summary>
public class User32
{
    /// <summary>
    /// Provides access to function required to delete handle. This method is used internally
    /// and is not required to be called separately.
    /// </summary>
    /// <param name="hIcon">Pointer to icon handle.</param>
    /// <returns>N/A</returns>
    [DllImport("User32.dll")]
    public static extern int DestroyIcon(IntPtr hIcon);
}
</code>```

But, There is still one problem: The icons look HORRIBLE ! Here is a screenshot:

Do someone know how I can solve this ?

ContentLicense: CC BY-SA 4.0

Title: Using system icons for TreeView in C#

Body:
So, I got it working by using this very good example from CodeProject:

public class IconReader
{
    /// <summary>
    /// Options to specify the size of icons to return.
    /// </summary>
    public enum IconSize
    {
        /// <summary>
        /// Specify large icon - 32 pixels by 32 pixels.
        /// </summary>
        Large = 0,
        /// <summary>
        /// Specify small icon - 16 pixels by 16 pixels.
        /// </summary>
        Small = 1
    }

    /// <summary>
    /// Options to specify whether folders should be in the open or closed state.
    /// </summary>
    public enum FolderType
    {
        /// <summary>
        /// Specify open folder.
        /// </summary>
        Open = 0,
        /// <summary>
        /// Specify closed folder.
        /// </summary>
        Closed = 1
    }

    /// <summary>
    /// Returns an icon for a given file - indicated by the name parameter.
    /// </summary>
    /// <param name="name">Pathname for file.</param>
    /// <param name="size">Large or small</param>
    /// <param name="linkOverlay">Whether to include the link icon</param>
    /// <returns>System.Drawing.Icon</returns>
    public static System.Drawing.Icon GetFileIcon(string name, IconSize size, bool linkOverlay)
    {
        Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
        uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;

        if (true == linkOverlay) flags += Shell32.SHGFI_LINKOVERLAY;

        /* Check the size specified for return. */
        if (IconSize.Small == size)
        {
            flags += Shell32.SHGFI_SMALLICON;
        }
        else
        {
            flags += Shell32.SHGFI_LARGEICON;
        }

        Shell32.SHGetFileInfo(name,
            Shell32.FILE_ATTRIBUTE_NORMAL,
            ref shfi,
            (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
            flags);

        // Copy (clone) the returned icon to a new object, thus allowing us to clean-up properly
        System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();
        User32.DestroyIcon(shfi.hIcon);     // Cleanup
        return icon;
    }

    /// <summary>
    /// Used to access system folder icons.
    /// </summary>
    /// <param name="size">Specify large or small icons.</param>
    /// <param name="folderType">Specify open or closed FolderType.</param>
    /// <returns>System.Drawing.Icon</returns>
    public static System.Drawing.Icon GetFolderIcon(IconSize size, FolderType folderType)
    {
        // Need to add size check, although errors generated at present!
        uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;

        if (FolderType.Open == folderType)
        {
            flags += Shell32.SHGFI_OPENICON;
        }

        if (IconSize.Small == size)
        {
            flags += Shell32.SHGFI_SMALLICON;
        }
        else
        {
            flags += Shell32.SHGFI_LARGEICON;
        }

        // Get the folder icon
        Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
        Shell32.SHGetFileInfo(@"Folder",
            Shell32.FILE_ATTRIBUTE_DIRECTORY,
            ref shfi,
            (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
            flags);

        System.Drawing.Icon.FromHandle(shfi.hIcon); // Load the icon from an HICON handle

        // Now clone the icon, so that it can be successfully stored in an ImageList
        System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();

        User32.DestroyIcon(shfi.hIcon);     // Cleanup
        return icon;
    }

    public static System.Drawing.Icon GetDriveIcon(IconSize size, FolderType folderType)
    {
        // Need to add size check, although errors generated at present!
        uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;

        if (FolderType.Open == folderType)
        {
            flags += Shell32.SHGFI_OPENICON;
        }

        if (IconSize.Small == size)
        {
            flags += Shell32.SHGFI_SMALLICON;
        }
        else
        {
            flags += Shell32.SHGFI_LARGEICON;
        }

        // Get the folder icon
        Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
        Shell32.SHGetFileInfo(null,
            Shell32.FILE_ATTRIBUTE_DIRECTORY,
            ref shfi,
            (uint)System.Runtime.InteropServices.Marshal.SizeOf(shfi),
            flags);

        System.Drawing.Icon.FromHandle(shfi.hIcon); // Load the icon from an HICON handle

        // Now clone the icon, so that it can be successfully stored in an ImageList
        System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();

        User32.DestroyIcon(shfi.hIcon);     // Cleanup
        return icon;
    }
}

/// <summary>
/// Wraps necessary Shell32.dll structures and functions required to retrieve Icon Handles using SHGetFileInfo. Code
/// courtesy of MSDN Cold Rooster Consulting case study.
/// </summary>
///

// This code has been left largely untouched from that in the CRC example. The main changes have been moving
// the icon reading code over to the IconReader type.
public class Shell32
{

    public const int MAX_PATH = 256;
    [StructLayout(LayoutKind.Sequential)]
    public struct SHITEMID
    {
        public ushort cb;
        [MarshalAs(UnmanagedType.LPArray)]
        public byte[] abID;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct ITEMIDLIST
    {
        public SHITEMID mkid;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct BROWSEINFO
    {
        public IntPtr hwndOwner;
        public IntPtr pidlRoot;
        public IntPtr pszDisplayName;
        [MarshalAs(UnmanagedType.LPTStr)]
        public string lpszTitle;
        public uint ulFlags;
        public IntPtr lpfn;
        public int lParam;
        public IntPtr iImage;
    }

    // Browsing for directory.
    public const uint BIF_RETURNONLYFSDIRS = 0x0001;
    public const uint BIF_DONTGOBELOWDOMAIN = 0x0002;
    public const uint BIF_STATUSTEXT = 0x0004;
    public const uint BIF_RETURNFSANCESTORS = 0x0008;
    public const uint BIF_EDITBOX = 0x0010;
    public const uint BIF_VALIDATE = 0x0020;
    public const uint BIF_NEWDIALOGSTYLE = 0x0040;
    public const uint BIF_USENEWUI = (BIF_NEWDIALOGSTYLE | BIF_EDITBOX);
    public const uint BIF_BROWSEINCLUDEURLS = 0x0080;
    public const uint BIF_BROWSEFORCOMPUTER = 0x1000;
    public const uint BIF_BROWSEFORPRINTER = 0x2000;
    public const uint BIF_BROWSEINCLUDEFILES = 0x4000;
    public const uint BIF_SHAREABLE = 0x8000;

    [StructLayout(LayoutKind.Sequential)]
    public struct SHFILEINFO
    {
        public const int NAMESIZE = 80;
        public IntPtr hIcon;
        public int iIcon;
        public uint dwAttributes;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
        public string szDisplayName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = NAMESIZE)]
        public string szTypeName;
    };

    public const uint SHGFI_ICON = 0x000000100;     // get icon
    public const uint SHGFI_DISPLAYNAME = 0x000000200;     // get display name
    public const uint SHGFI_TYPENAME = 0x000000400;     // get type name
    public const uint SHGFI_ATTRIBUTES = 0x000000800;     // get attributes
    public const uint SHGFI_ICONLOCATION = 0x000001000;     // get icon location
    public const uint SHGFI_EXETYPE = 0x000002000;     // return exe type
    public const uint SHGFI_SYSICONINDEX = 0x000004000;     // get system icon index
    public const uint SHGFI_LINKOVERLAY = 0x000008000;     // put a link overlay on icon
    public const uint SHGFI_SELECTED = 0x000010000;     // show icon in selected state
    public const uint SHGFI_ATTR_SPECIFIED = 0x000020000;     // get only specified attributes
    public const uint SHGFI_LARGEICON = 0x000000000;     // get large icon
    public const uint SHGFI_SMALLICON = 0x000000001;     // get small icon
    public const uint SHGFI_OPENICON = 0x000000002;     // get open icon
    public const uint SHGFI_SHELLICONSIZE = 0x000000004;     // get shell size icon
    public const uint SHGFI_PIDL = 0x000000008;     // pszPath is a pidl
    public const uint SHGFI_USEFILEATTRIBUTES = 0x000000010;     // use passed dwFileAttribute
    public const uint SHGFI_ADDOVERLAYS = 0x000000020;     // apply the appropriate overlays
    public const uint SHGFI_OVERLAYINDEX = 0x000000040;     // Get the index of the overlay

    public const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
    public const uint FILE_ATTRIBUTE_NORMAL = 0x00000080;

    [DllImport("Shell32.dll")]
    public static extern IntPtr SHGetFileInfo(
        string pszPath,
        uint dwFileAttributes,
        ref SHFILEINFO psfi,
        uint cbFileInfo,
        uint uFlags
        );
}

/// <summary>
/// Wraps necessary functions imported from User32.dll. Code courtesy of MSDN Cold Rooster Consulting example.
/// </summary>
public class User32
{
    /// <summary>
    /// Provides access to function required to delete handle. This method is used internally
    /// and is not required to be called separately.
    /// </summary>
    /// <param name="hIcon">Pointer to icon handle.</param>
    /// <returns>N/A</returns>
    [DllImport("User32.dll")]
    public static extern int DestroyIcon(IntPtr hIcon);
}

But, There is still one problem: The icons look HORRIBLE ! Here is a screenshot:

Do someone know how I can solve this ?


问:
Copy Connector while creating an instance of an element in Enterprise Architect
I tried to create an instance of a DataObject with the option 'Copy Connectors' checked. I expect EA to copy all my connections from the 'main' DataObject but EA creates an instance which is not connected to any element.
any idea what I'm probably doing wrong?
I#m using EA version 12.0.1207</p>

答:
Well, EAUI...

You need to drag/drop more than one element. That means you have multiple elements selected. Here you select the connected Class1 and Class2:

This results in:

If they have connectors, the instances will also be connected. Doing it one by one will not create connectors on the instances.


问:
AppCompatActivity.onCreate can only be called from within the same library group
After upgrading to appcompat 25.1.0 I've started getting weird errors.

In my code:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
</code>```

I get lint error:

AppCompatActivity.onCreate can only be called from within the same library group (groupId=com.android.support)

How to prevent such behavior?

答:
As previous responses highlighted, it is bug. I recommend not to disable the specific lint warning project-wide, but for that method only. Annotate your method as follows:</p>

```<code>@SuppressLint("RestrictedApi")
@Override
public void setupDialog(Dialog dialog, int style) {
    super.setupDialog(dialog, style);
    //your code here
}
</code>```

Body:
After upgrading to appcompat 25.1.0 I've started getting weird errors.

In my code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

I get lint error:

AppCompatActivity.onCreate can only be called from within the same library group (groupId=com.android.support)

How to prevent such behavior?

Body:
As previous responses highlighted, it is bug. I recommend not to disable the specific lint warning project-wide, but for that method only. Annotate your method as follows:

@SuppressLint("RestrictedApi")
@Override
public void setupDialog(Dialog dialog, int style) {
    super.setupDialog(dialog, style);
    //your code here
}


问:
Could you please suggest better design?
Following is the scenario.

I have something called as Domain which can have multiple States (Statekey-Statevalue pair) in it. The same StateKey can be present in multiple domains but with different StateValue.

e.g. StateKey named 'EconomicCapital' may be present in Domains like 'England', 'America' with values 'London', 'Washington' respectively.

Classes corresponding to these are in common library which can be consumed at client or service side as required.

I have a winform application in which I can select a specific domain. In any string, wherever I encounter any StateKey, I want to replace it by its StateValue for the selected domain.

I can think of following designs:

Establish composition relationship. Domain can be composed of the States. So when I want a StateValue of any StateKey, I can get the object of the required domain and can extract StateKey from the States collection composed in it.

But there can be large number of instances where StateKey would be used, I do not think this approach is quite good snce it requires finding Domain object from the collection of domains and iterating through its State collection to find particular key.

OR

Maintain a static collection which can hold all StateKeys in different domain. When I want particular StateKey I can simply lookup in this collection.

Could you please advice me which approach is more appropriate? Will there be any other approach/design?

(If the logic is implemented at service side; not just one winform application but many such applications can access it.)

答:
What about something like

```<code>Dictionary<domain, Dictionary<statekey, statevalue>()
</code>```

You could then find the key value pairs from the domain, and get the value from that.... Or am I missing something in your question?

ContentLicense: CC BY-SA 2.5

Title: Could you please suggest better design?

Body:
What about something like

Dictionary<domain, Dictionary<statekey, statevalue>()

You could then find the key value pairs from the domain, and get the value from that.... Or am I missing something in your question?


问:
Why some APIs implemented Serializable interface but did not declare serialVersionUID?
I'am confused when I look the source code of org.springframework.jdbc.datasource.DataSourceTransactionManager, why does it implement Serializable but no serialVersionUID was given in it?

[]

答:
It is recommended to declare it but you can omit declaring it, default mechanism take care it for you.

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value.


问:
Triggering a video autoplay based on scroll position
I am writing a script that uses the Wipe animation from the scrollorama.js script. I am hoping to be able to implement a video to autoplay at certain markers in the scroll depth: ie, when a video page has wiped out another, and is now fully viewable.  I have figured out how to measure scroll depth, i am successfully logging it in my console. I have figured out how to measure how deep i have scrolled, but maybe i am so tired, i don't know how to ask the video to play automatically at the scroll depth. I hope this is a legal question, and that I can get some assistance. Has anyone out there tried this before?  Here is the code thus far.

enter code here $(document).ready(function() {

$(window).scroll(function(e) {

```<code>  var scrollAmount = $('body').scrollTop();
  console.log(scrollAmount);
</code>```

});

```<code>    var controller = $.superscrollorama();
    var pinDur = 800;
    // create animation timeline for pinned element
var pinAnimations = new TimelineLite();

//pinAnimations.append([TweenMax.to($('#green'), .5, {css:{top:0}})], .5)
pinAnimations.append([TweenMax.to($('#intromovie'), .5, {css:{top:0}})], .5 )
pinAnimations.append([TweenMax.to($('#red'), .5, {css:{top:0}})], .5)
pinAnimations.append([TweenMax.to($('#blue'), .5, {css:{top:0}})], .5 )
pinAnimations.append([TweenMax.to($('#movie1'), .5, {css:{top:0}})], .5);
pinAnimations.append([TweenMax.to($('#history1'), .5, {css:{top:0}})], .5);
//pinAnimations.append(TweenMax.to($('#pin-frame-unpin'), .5, {css:{top:'100px'}}));

controller.pin($('#content_wrapper'), pinDur, {
    anim:pinAnimations,
    onPin: function() {
        $('#content_wrapper').css('height','100%');
    },
    onUnpin: function() {
        $('#content_wrapper').css('height','1000px');
    }

});

});
</code>```

答:
just add the script from below and add playonscroll param to your video tag anywhere on a page.

As well some times it's required to use different scroll container than body, sometimes its not obvious, so the following code works like a charm for me:

```<code>setInterval(function () {
    $('video[playonscroll]').each(function () {
        var videoElement = $(this)[0];
        var eTop = $(this).offset().top;
        var elementOffestY = (eTop - $(window).scrollTop());
        var videoOffset = [elementOffestY, elementOffestY+$(this).height()];
        if ((videoOffset[0] < 100) && (videoOffset[1] > 350)) {
            console.log('play');
            if (!videoElement.playing) {
                videoElement.play();
            }
        } else {
            if (videoElement.playing) {
                videoElement.pause();
            }
        }
    });
},300);
</code>```

in case if you always use body container for scroll just change setInterval to $(window).scroll

And don't forget to define property for Video tag element:

```<code>Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
    get: function(){
        return (this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
    }
})
</code>```

Body:
I am writing a script that uses the Wipe animation from the scrollorama.js script. I am hoping to be able to implement a video to autoplay at certain markers in the scroll depth: ie, when a video page has wiped out another, and is now fully viewable.  I have figured out how to measure scroll depth, i am successfully logging it in my console. I have figured out how to measure how deep i have scrolled, but maybe i am so tired, i don't know how to ask the video to play automatically at the scroll depth. I hope this is a legal question, and that I can get some assistance. Has anyone out there tried this before?  Here is the code thus far.

enter code here $(document).ready(function() {

$(window).scroll(function(e) {

  var scrollAmount = $('body').scrollTop();
  console.log(scrollAmount);

});

    var controller = $.superscrollorama();
    var pinDur = 800;
    // create animation timeline for pinned element
var pinAnimations = new TimelineLite();

//pinAnimations.append([TweenMax.to($('#green'), .5, {css:{top:0}})], .5)
pinAnimations.append([TweenMax.to($('#intromovie'), .5, {css:{top:0}})], .5 )
pinAnimations.append([TweenMax.to($('#red'), .5, {css:{top:0}})], .5)
pinAnimations.append([TweenMax.to($('#blue'), .5, {css:{top:0}})], .5 )
pinAnimations.append([TweenMax.to($('#movie1'), .5, {css:{top:0}})], .5);
pinAnimations.append([TweenMax.to($('#history1'), .5, {css:{top:0}})], .5);
//pinAnimations.append(TweenMax.to($('#pin-frame-unpin'), .5, {css:{top:'100px'}}));

controller.pin($('#content_wrapper'), pinDur, {
    anim:pinAnimations,
    onPin: function() {
        $('#content_wrapper').css('height','100%');
    },
    onUnpin: function() {
        $('#content_wrapper').css('height','1000px');
    }

});

});

Body:
just add the script from below and add playonscroll param to your video tag anywhere on a page.

As well some times it's required to use different scroll container than body, sometimes its not obvious, so the following code works like a charm for me:

setInterval(function () {
    $('video[playonscroll]').each(function () {
        var videoElement = $(this)[0];
        var eTop = $(this).offset().top;
        var elementOffestY = (eTop - $(window).scrollTop());
        var videoOffset = [elementOffestY, elementOffestY+$(this).height()];
        if ((videoOffset[0] < 100) && (videoOffset[1] > 350)) {
            console.log('play');
            if (!videoElement.playing) {
                videoElement.play();
            }
        } else {
            if (videoElement.playing) {
                videoElement.pause();
            }
        }
    });
},300);

in case if you always use body container for scroll just change setInterval to $(window).scroll

And don't forget to define property for Video tag element:

Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
    get: function(){
        return (this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
    }
})


问:
Proper handling of request_uri in double nginx reverse proxy?
So, essentially I am running Joomla in a Docker php7-fpm container, then I have an nginx container where a joomla.conf file is defined as follows:

```<code>#https://docs.joomla.org/nginx

server {
  listen 8081;

  error_log  /var/log/nginx/error.log;
  access_log /var/log/nginx/access.log;

  server_name php-docker.local;

  root /usr/src/joomla;
  index index.php index.html index.htm default.html default.htm;

  location / {
    try_files $uri $uri/ /index.php?$args;
  }

  # deny running scripts inside writable directories
  location ~* /(images|cache|media|logs|tmp)/.*\.(php|pl|py|jsp|asp|sh|cgi)$ {
    return 403;
    error_page 403 /403_error.html;
  }

  location ~ \.php$ {
    fastcgi_pass  joomla:9000;
    fastcgi_index index.php;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;

    include fastcgi_params;
    #include /etc/nginx/fastcgi.conf;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
  }
}
</code>```

And this works as expected... going to http://:8081 loads everything correctly.

Now, 8081 is just temporarily exposed in the nginx container, what I essentially want to do is setup a reverse proxy such that http:///joomla will be the final endpoint.

For this, I am struggling with the following conf file:

```<code>server{

  listen 80;
  server_name _;

  location /joomla/ {
    proxy_pass          http://localhost:8081/;

    proxy_set_header    Referer           $http_referer;
    proxy_set_header    X-Forwarded-Port  $server_port;
    proxy_set_header    X-Forwarded-Proto $http_x_forwarded_proto;
    proxy_set_header    Host              $host;
    proxy_set_header    X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Host  $host;
  }

}
</code>```

What happens is that the HTML is served correctly, however, none of the assets are. This is because the URLs in Joomla are generated by a JURI class, which seems to rely on $request_uri, which by when it appears to arrive to Joomla is already lost.

https://github.com/joomla/joomla-cms/blob/6ab2a6e9010e7e04c260b9eba17dc76e866dd3e6/libraries/joomla/uri/uri.php#L87

So every link or reference to a file, script, or css renders like this:

http://localhost/login

http://localhost/images/headers/maple.jpg

Instead of:

http://localhost/joomla/login

http://localhost/joomla/images/headers/maple.jpg

However, when I access the second set of URL, I can access the link/asset without a problem... but of course once again, no images, templates, js or links being rendered correctly.

I prefer not to touch joomla.conf unless something is wrong, as for site.conf I would only like to translate URI segments to map requests to other applications, e.g.:

```<code>/joomla -> localhost:8081
/phpbb -> localhost:8082
/someapp -> localhost:8083
</code>```

答:
You could try use sub_filter how it mentioned in this answer.

So in your case your nginx config should looks like this one:

```<code>server{

  listen 80;
  server_name _;

  location /joomla/ {
    proxy_pass          http://localhost:8081/;

    proxy_set_header    Referer           $http_referer;
    proxy_set_header    X-Forwarded-Port  $server_port;
    proxy_set_header    X-Forwarded-Proto $http_x_forwarded_proto;
    proxy_set_header    Host              $host;
    proxy_set_header    X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Host  $host;
    sub_filter "http://your_server/" "http://your_server/joomla/";
    sub_filter_once off;
  }

}
</code>```

Body:
So, essentially I am running Joomla in a Docker php7-fpm container, then I have an nginx container where a joomla.conf file is defined as follows:

#https://docs.joomla.org/nginx

server {
  listen 8081;

  error_log  /var/log/nginx/error.log;
  access_log /var/log/nginx/access.log;

  server_name php-docker.local;

  root /usr/src/joomla;
  index index.php index.html index.htm default.html default.htm;

  location / {
    try_files $uri $uri/ /index.php?$args;
  }

  # deny running scripts inside writable directories
  location ~* /(images|cache|media|logs|tmp)/.*\.(php|pl|py|jsp|asp|sh|cgi)$ {
    return 403;
    error_page 403 /403_error.html;
  }

  location ~ \.php$ {
    fastcgi_pass  joomla:9000;
    fastcgi_index index.php;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;

    include fastcgi_params;
    #include /etc/nginx/fastcgi.conf;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
  }
}

And this works as expected... going to http://:8081 loads everything correctly.

Now, 8081 is just temporarily exposed in the nginx container, what I essentially want to do is setup a reverse proxy such that http:///joomla will be the final endpoint.

For this, I am struggling with the following conf file:

server{

  listen 80;
  server_name _;

  location /joomla/ {
    proxy_pass          http://localhost:8081/;

    proxy_set_header    Referer           $http_referer;
    proxy_set_header    X-Forwarded-Port  $server_port;
    proxy_set_header    X-Forwarded-Proto $http_x_forwarded_proto;
    proxy_set_header    Host              $host;
    proxy_set_header    X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Host  $host;
  }

}

What happens is that the HTML is served correctly, however, none of the assets are. This is because the URLs in Joomla are generated by a JURI class, which seems to rely on $request_uri, which by when it appears to arrive to Joomla is already lost.

https://github.com/joomla/joomla-cms/blob/6ab2a6e9010e7e04c260b9eba17dc76e866dd3e6/libraries/joomla/uri/uri.php#L87

So every link or reference to a file, script, or css renders like this:

http://localhost/login

http://localhost/images/headers/maple.jpg

Instead of:

http://localhost/joomla/login

http://localhost/joomla/images/headers/maple.jpg

However, when I access the second set of URL, I can access the link/asset without a problem... but of course once again, no images, templates, js or links being rendered correctly.

I prefer not to touch joomla.conf unless something is wrong, as for site.conf I would only like to translate URI segments to map requests to other applications, e.g.:

/joomla -> localhost:8081
/phpbb -> localhost:8082
/someapp -> localhost:8083

Body:
You could try use sub_filter how it mentioned in this answer.

So in your case your nginx config should looks like this one:

server{

  listen 80;
  server_name _;

  location /joomla/ {
    proxy_pass          http://localhost:8081/;

    proxy_set_header    Referer           $http_referer;
    proxy_set_header    X-Forwarded-Port  $server_port;
    proxy_set_header    X-Forwarded-Proto $http_x_forwarded_proto;
    proxy_set_header    Host              $host;
    proxy_set_header    X-Forwarded-For   $proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Host  $host;
    sub_filter "http://your_server/" "http://your_server/joomla/";
    sub_filter_once off;
  }

}


答:
```<code>    Fragment fragment = adapter.getItem(viewPager.getCurrentItem());
    if (fragment instanceof FiveFragment) {
               fragment.setTest();
            }
</code>```

Title: Why i can not change text view value in fragment?


问:
Using ExcelDataReader to read Excel data starting from a particular cell
I am using ExcelDataReader to read data from my Excel workbook in C#.

But structure of my Excel sheet is such that data to be read can start from any particular cell and not necessarily A1.

Can any one Please suggest a way on how this can be achieved using ExcelDataReader?

答:
I found this useful to read from a specific column and row:        </p>

```<code>FileStream stream = File.Open(@"C:\Users\Desktop\ExcelDataReader.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.IsFirstRowAsColumnNames = true;
DataTable dt = result.Tables[0];
string text = dt.Rows[1][0].ToString();
</code>```

Body:
I found this useful to read from a specific column and row:

FileStream stream = File.Open(@"C:\Users\Desktop\ExcelDataReader.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.IsFirstRowAsColumnNames = true;
DataTable dt = result.Tables[0];
string text = dt.Rows[1][0].ToString();


问:
which is the best Camera API for image processing in Android
I am working on an Android project which should capture an image by the camera API and the do some image processing to classify the image and give result to user (I used opencv to process the image and classify result). My question is which is the best camera API? Shall I use Java camera view in opencv or use Camera API using intent or finally use camera 2 API which can give me control to manage some characteristics related to ambient conditions. </p>

<p>Please clear my confusion and suggest which is the best one to control the quality of the image and and other conditions that affect the image taken.  </p>

答:
try gpuImagePlus library  which is available for both android and ios.
here is the link for android version.
https://github.com/wysaid/android-gpuimage-plus</p>

Body:
I am working on an Android project which should capture an image by the camera API and the do some image processing to classify the image and give result to user (I used opencv to process the image and classify result). My question is which is the best camera API? Shall I use Java camera view in opencv or use Camera API using intent or finally use camera 2 API which can give me control to manage some characteristics related to ambient conditions.

Please clear my confusion and suggest which is the best one to control the quality of the image and and other conditions that affect the image taken.


问:
Jquery Ajax GET call different results
I've written a few lines of code to tackle the following problem:

Get the TwitchTV UserID based on the username. The usernames are in an arrray. After hitting a button a GET AJAX request will be called to GET the UserID and to push it in another array and the call to the API will made via AJAX after hitting a button.

My problem is that if I hit the button again the usersID are in wrong order.

If I set async: false, it works.

Is this problem because of Asynchronous AJAX? What would be the approach for a valid fix? Use callback? A hint in the right direction would be appreciated.

The comments in the code are for testing.

Code:

```<code><script>

        var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "spicyjewlive"];
            clientID = "?client_id=XXX";
            userID = [];
            userStatus = [];
for(var i=0; i<users.length; i++){
          idCall(users[i]);

        };
function idCall (data){
            $.ajax({
              type: "GET",
              url: "https://api.twitch.tv/kraken/users/" + data + clientID,
              async: false,
              cache: false,
              dataType: "jsonp",
              success: function (data){
                console.log(data._id);
              },
              error: function (data) {
                console.log("error");
              }});
        };
</script>
</code>```

答:
Use an array of request promises and update the dom after all those are resolved. The results will be in same order as original users array</p>

```<code>var requestPromises = users.map(idCall);

$.when.apply(null, requestPromises).then(function(){
   var dataArray = [].slice.call(arguments);
   // now loop over data array which is in same order as users
   dataArray.forEach(function(userData){
     // do something with each userData object
   });
}).fail(function(){
   console.log("Something went wrong in at least one request");
});

function idCall(user) {
  // return the ajax promise
  return $.ajax({
    url: "https://api.twitch.tv/kraken/users/" + user + clientID,
    dataType: "jsonp"
  }).then(function(data) {
    // return the data resolved by promise
    return data;
  });
};
</code>```

Title: Jquery Ajax GET call different results

Body:
Use an array of request promises and update the dom after all those are resolved. The results will be in same order as original users array

var requestPromises = users.map(idCall);

$.when.apply(null, requestPromises).then(function(){
   var dataArray = [].slice.call(arguments);
   // now loop over data array which is in same order as users
   dataArray.forEach(function(userData){
     // do something with each userData object
   });
}).fail(function(){
   console.log("Something went wrong in at least one request");
});

function idCall(user) {
  // return the ajax promise
  return $.ajax({
    url: "https://api.twitch.tv/kraken/users/" + user + clientID,
    dataType: "jsonp"
  }).then(function(data) {
    // return the data resolved by promise
    return data;
  });
};


问:
ANDROID How can I send result in a new Activity after scanning a QR Code?
Hello to everyone I'm trying to create an app that scan a QR Code.

In the main activity I want to make the scan of the QR Code and I want to send the result in a new Activity.

Here is my code

Main Activity.java:

```<code>public class MainActivity extends AppCompatActivity {

SurfaceView cameraView;
BarcodeDetector barcode;
CameraSource cameraSource;
SurfaceHolder holder;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
    }

    cameraView = (SurfaceView) findViewById(R.id.cameraView);
    cameraView.setZOrderMediaOverlay(true);
    holder = cameraView.getHolder();
    barcode = new BarcodeDetector.Builder(this)
            .setBarcodeFormats(Barcode.QR_CODE)
            .build();
    if(!barcode.isOperational()){
        Toast.makeText(getApplicationContext(), "Sorry, Couldn't setup the detector", Toast.LENGTH_LONG).show();
        this.finish();
    }
    cameraSource = new CameraSource.Builder(this, barcode)
            .setFacing(CameraSource.CAMERA_FACING_BACK)
            .setRequestedFps(24)
            .setAutoFocusEnabled(true)
            .setRequestedPreviewSize(1920,1024)
            .build();
    cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try{
                if(ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
                    cameraSource.start(cameraView.getHolder());
                }
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {

        }
    });
    barcode.setProcessor(new Detector.Processor<Barcode>() {
        @Override
        public void release() {

        }

        @Override
        public void receiveDetections(Detector.Detections<Barcode> detections) {
            final SparseArray<Barcode> barcodes =  detections.getDetectedItems();
            if(barcodes.size() > 0){

                Intent intent = new Intent(MainActivity.this, Result.class);
                startActivityForResult(intent, 100);
                intent.putExtra("barcode", barcodes.valueAt(0));
                setResult(RESULT_OK, intent);
                finish();
            }
        }
    });
}}
</code>```

Result.java:

```<code>public class Result extends AppCompatActivity {

TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_result);
    result = (TextView) findViewById(R.id.result);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == 100 && resultCode == RESULT_OK){
        if(data != null){
            final Barcode barcode = data.getParcelableExtra("barcode");
            result.post(new Runnable() {
                @Override
                public void run() {
                    result.setText(barcode.displayValue);
                }
            });
        }
    }
}}
</code>```

But when I try to test the app in the result activity i can't see the result.

What's wrong?

Thank you to everyone

答:
the code You wrote in your MainActivity

```<code>Intent intent = new Intent(MainActivity.this, Result.class);
            startActivityForResult(intent, 100);
            intent.putExtra("barcode", barcodes.valueAt(0));
            setResult(RESULT_OK, intent);
            finish();
</code>```

is wrong Actually it should be like the following and please do not ActivityForResult

```<code>Intent intent = new Intent(MainActivity.this, Result.class);
            intent.putExtra("barcode", barcodes.valueAt(0));
            startActivityForResult(intent, 100);
            finish();
</code>```

And for getting result from Your MainActivity in ResultActivity  onCreate() method use following code if you are going to show result then

```<code>TextView YourResult
YourResult = (TextView) findViewById(R.id.TextView_YourResult);
    final Barcode barcode = getIntent().getParcelableExtra("barcode");
    result.setText(barcode.displayValue);
</code>```

Body:
Hello to everyone I'm trying to create an app that scan a QR Code.

In the main activity I want to make the scan of the QR Code and I want to send the result in a new Activity.

Here is my code

Main Activity.java:

public class MainActivity extends AppCompatActivity {

SurfaceView cameraView;
BarcodeDetector barcode;
CameraSource cameraSource;
SurfaceHolder holder;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
    }

    cameraView = (SurfaceView) findViewById(R.id.cameraView);
    cameraView.setZOrderMediaOverlay(true);
    holder = cameraView.getHolder();
    barcode = new BarcodeDetector.Builder(this)
            .setBarcodeFormats(Barcode.QR_CODE)
            .build();
    if(!barcode.isOperational()){
        Toast.makeText(getApplicationContext(), "Sorry, Couldn't setup the detector", Toast.LENGTH_LONG).show();
        this.finish();
    }
    cameraSource = new CameraSource.Builder(this, barcode)
            .setFacing(CameraSource.CAMERA_FACING_BACK)
            .setRequestedFps(24)
            .setAutoFocusEnabled(true)
            .setRequestedPreviewSize(1920,1024)
            .build();
    cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try{
                if(ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
                    cameraSource.start(cameraView.getHolder());
                }
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {

        }
    });
    barcode.setProcessor(new Detector.Processor<Barcode>() {
        @Override
        public void release() {

        }

        @Override
        public void receiveDetections(Detector.Detections<Barcode> detections) {
            final SparseArray<Barcode> barcodes =  detections.getDetectedItems();
            if(barcodes.size() > 0){

                Intent intent = new Intent(MainActivity.this, Result.class);
                startActivityForResult(intent, 100);
                intent.putExtra("barcode", barcodes.valueAt(0));
                setResult(RESULT_OK, intent);
                finish();
            }
        }
    });
}}

Result.java:

public class Result extends AppCompatActivity {

TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_result);
    result = (TextView) findViewById(R.id.result);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == 100 && resultCode == RESULT_OK){
        if(data != null){
            final Barcode barcode = data.getParcelableExtra("barcode");
            result.post(new Runnable() {
                @Override
                public void run() {
                    result.setText(barcode.displayValue);
                }
            });
        }
    }
}}

But when I try to test the app in the result activity i can't see the result.

What's wrong?

Thank you to everyone

Body:
the code You wrote in your MainActivity

Intent intent = new Intent(MainActivity.this, Result.class);
            startActivityForResult(intent, 100);
            intent.putExtra("barcode", barcodes.valueAt(0));
            setResult(RESULT_OK, intent);
            finish();

is wrong Actually it should be like the following and please do not ActivityForResult

Intent intent = new Intent(MainActivity.this, Result.class);
            intent.putExtra("barcode", barcodes.valueAt(0));
            startActivityForResult(intent, 100);
            finish();

And for getting result from Your MainActivity in ResultActivity  onCreate() method use following code if you are going to show result then

TextView YourResult
YourResult = (TextView) findViewById(R.id.TextView_YourResult);
    final Barcode barcode = getIntent().getParcelableExtra("barcode");
    result.setText(barcode.displayValue);


问:
React webpack bundle for production
I need some help to bundle my output for production but I have no idea how. Here's my webpack.config.js

```<code>module.exports = {
    devtool: 'eval',
    context: __dirname,
    entry: "./js-source/index.jsx",
    output: {
        path: __dirname + "/scripts",
        filename: "bundle.js"
    },
    module: {
        loaders: [
            {
                test: /\.(js|jsx)$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            }
        ],
        resolve: {
            extensions: ['', '.js', '.jsx', '.json']
        }
    }
};
</code>```

Here's my package.json

```<code>{
  "name": "citygross-store-web",
  "version": "2.0.0",
  "dependencies": {
    "axios": "^0.14.0",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-redux": "^4.1.2",
    "react-responsive": "^1.3.0",
    "react-router": "^4.1.1",
    "react-router-dom": "^4.1.1",
    "react-transition-group": "^1.2.0",
    "redux": "^3.1.2",
    "redux-logger": "^2.6.1",
    "redux-promise-middleware": "^4.0.0",
    "redux-thunk": "^2.1.0"
  },
  "devDependencies": {
    "babel-core": "^6.21.0",
    "babel-loader": "^6.2.10",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-runtime": "^6.15.0",
    "babel-polyfill": "^6.3.14",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-latest": "^6.16.0",
    "babel-preset-react": "^6.16.0",
    "babel-preset-stage-0": "^6.24.1",
    "babel-preset-stage-1": "^6.24.1",
    "babel-preset-stage-2": "^6.13.0",
    "webpack": "^1.14.0",
    "webpack-hot-middleware": "^2.12.2"
  },
  "scripts": {
    "build": "webpack --colors",
    "dev": "webpack --watch --colors"
  },
  "-vs-binding": {
    "ProjectOpened": [
      "dev"
    ]
  }
}
</code>```

How do you usually bundle for production? By adding a command like "npm run build" and having the other settings in that setting?

I would appreciate if someone could help me out how to set this up. Right now I can do "npm run dev" and "npm run build", however there's no difference between using the two more than "run dev" creates a -watcher and build builds the bundle one time.

答:
Set the environment variable NODE_ENV to production when running your build script.  This will cause the production build of React to be included in the output.

Easiest way is to add another script to your package.json:

```<code>"scripts": {
    "build": "webpack --colors",
    "buildprod": "NODE_ENV=production webpack --colors",
    "dev": "webpack --watch --colors"
  },
</code>```

Now when you do npm run buildprod, you'll get a production build of your code.

Note: if you are on Windows, the above won't work right.  For proper cross-OS you should use cross-env:

Install cross-env:

```<code>npm install cross-env --save-dev
</code>```

or

```<code>yarn add cross-env --dev
</code>```

Then make your scripts section look like:

```<code>"scripts": {
    "build": "webpack --colors",
    "buildprod": "cross-env NODE_ENV=production webpack --colors",
    "dev": "webpack --watch --colors"
  },
</code>```

Title: React webpack bundle for production

Body:
I need some help to bundle my output for production but I have no idea how. Here's my webpack.config.js

module.exports = {
    devtool: 'eval',
    context: __dirname,
    entry: "./js-source/index.jsx",
    output: {
        path: __dirname + "/scripts",
        filename: "bundle.js"
    },
    module: {
        loaders: [
            {
                test: /\.(js|jsx)$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            }
        ],
        resolve: {
            extensions: ['', '.js', '.jsx', '.json']
        }
    }
};

Here's my package.json

{
  "name": "citygross-store-web",
  "version": "2.0.0",
  "dependencies": {
    "axios": "^0.14.0",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-redux": "^4.1.2",
    "react-responsive": "^1.3.0",
    "react-router": "^4.1.1",
    "react-router-dom": "^4.1.1",
    "react-transition-group": "^1.2.0",
    "redux": "^3.1.2",
    "redux-logger": "^2.6.1",
    "redux-promise-middleware": "^4.0.0",
    "redux-thunk": "^2.1.0"
  },
  "devDependencies": {
    "babel-core": "^6.21.0",
    "babel-loader": "^6.2.10",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-runtime": "^6.15.0",
    "babel-polyfill": "^6.3.14",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-latest": "^6.16.0",
    "babel-preset-react": "^6.16.0",
    "babel-preset-stage-0": "^6.24.1",
    "babel-preset-stage-1": "^6.24.1",
    "babel-preset-stage-2": "^6.13.0",
    "webpack": "^1.14.0",
    "webpack-hot-middleware": "^2.12.2"
  },
  "scripts": {
    "build": "webpack --colors",
    "dev": "webpack --watch --colors"
  },
  "-vs-binding": {
    "ProjectOpened": [
      "dev"
    ]
  }
}

How do you usually bundle for production? By adding a command like "npm run build" and having the other settings in that setting?

I would appreciate if someone could help me out how to set this up. Right now I can do "npm run dev" and "npm run build", however there's no difference between using the two more than "run dev" creates a -watcher and build builds the bundle one time.

Body:
Set the environment variable NODE_ENV to production when running your build script.  This will cause the production build of React to be included in the output.

Easiest way is to add another script to your package.json:

"scripts": {
    "build": "webpack --colors",
    "buildprod": "NODE_ENV=production webpack --colors",
    "dev": "webpack --watch --colors"
  },

Now when you do npm run buildprod, you'll get a production build of your code.

Note: if you are on Windows, the above won't work right.  For proper cross-OS you should use cross-env:

Install cross-env:

npm install cross-env --save-dev

or

yarn add cross-env --dev

Then make your scripts section look like:

"scripts": {
    "build": "webpack --colors",
    "buildprod": "cross-env NODE_ENV=production webpack --colors",
    "dev": "webpack --watch --colors"
  },


问:
Lombok not working with "Android room". Gives "error: Cannot find getter for field"
I'm using Lombok in android studio 3.0 preview with gradle 3.0.0-alpha1. I have following two annotation processor in my dependency:

```<code>annotationProcessor "android.arch.persistence.room:compiler:1.0.0-alpha1"
annotationProcessor "org.projectlombok:lombok:1.16.16"
</code>```

Now, If I use annotations from both dependencies in same class like:

```<code>@Entity(tableName = "test")
@Getter
public final class TestEntity {...}
</code>```

It'll produce an error, that is:

```<code>error: Cannot find getter for field.
</code>```

But if I remove any one of them, it'll work fine.

Any ideas/solutions?

答: Are you using val in your model class? If yes, change to var</p>

Body:
I'm using Lombok in android studio 3.0 preview with gradle 3.0.0-alpha1. I have following two annotation processor in my dependency:

annotationProcessor "android.arch.persistence.room:compiler:1.0.0-alpha1"
annotationProcessor "org.projectlombok:lombok:1.16.16"

Now, If I use annotations from both dependencies in same class like:

@Entity(tableName = "test")
@Getter
public final class TestEntity {...}

It'll produce an error, that is:

error: Cannot find getter for field.

But if I remove any one of them, it'll work fine.

Any ideas/solutions?


问:
Add Links block to view's page, below filter, in Drupal 8
I have this view with a Page display that has a filter and a list with content to be filtered.

I would like to add a Links block right below the filters form but I just don't get it how. I tried adding the block to the sidebars (from /structure/block) but the sidebars are outside the main content (Bootstrap theme) and the View edit form (views/view/myview/edit) has no option or place where I could add a Builder block.

How would you do this?

答:
You can setup the view as block display(or duplicate the page display as block display) and go with the option "Exposed form in block" = Yes in the Advanced section.

It will let you to show the main view block (content list) and the exposed form(filters) in different configurable blocks in any basic/blank page.

Then you can easily insert your links block in between them.


问:
iOS: How to get the constraints for button inside horizontal stack-view right?
I am new to iOS development and am following the udacity course for iOS development. I am stuck at the lesson whose link I have given below.

https://classroom.udacity.com/courses/ud585/lessons/6991272849/concepts/72642287220923#

I am unable to reduce the size of stop button in the last stack view. I tried reducing the size of the button by setting the width constraint of the button to 64 and height of stack-view containing that button to 64. But XCode gives error of conflicting constraints.

I am attaching screenshots below for reference.

What I actually want is:

https://d17h27t6h515a5.cloudfront.net/topher/2016/November/582a8006_interface/interface.png

答:
You may be getting the conflicting constraints because when you tried to "change" the height and width you actually added additional height and width constraints. Check them in the measurements editor and if your see constraints with the >= symbol, you should delete those. Click edit on the height and width remaining to make the changes. This should fix the problem. You may need to clean and build as well.

Hope that helps!


问:
Ionic2 - angular2 http post request returns an error
I try to send post request on my ionic2 application , when call to post method then return an error but not have an any message. I think that I do wrong anyone on angular2 post request.

Here is my function for request;

```<code>load(username, password){
    let body = new FormData();
     body.append('email', username);
     body.append('password', password);
    let headers = new Headers({
   'Content-Type': 'application/x-www-form-urlencoded'
  });
    let options = new RequestOptions({ headers: headers,  method: "post" });

  return new Promise((resolve) => {
debugger;
    this.http
        .post('http://asis-services.com/AsisTransitApi/token', body, options)
        .map(res => res.json())
        .subscribe(
            data => {
              console.log(data);
            },
            err => {
              console.log("ERROR!: ", err);
            }
        );
  }
  )};
</code>```

you can look result;

post request gets an error at the result

答: I solved the issue.That is a permission problem for ionic 2 applications.If you are developping ionic 2 app in ionic serve mode and you use angular2 post method with authentication header, http://blog.ionic.io/handling-cors-issues-in-ionic/ help your problem, basically you should add chrome extension then you can easily call your post method on ajax. </p>

Body:
I try to send post request on my ionic2 application , when call to post method then return an error but not have an any message. I think that I do wrong anyone on angular2 post request.

Here is my function for request;

load(username, password){
    let body = new FormData();
     body.append('email', username);
     body.append('password', password);
    let headers = new Headers({
   'Content-Type': 'application/x-www-form-urlencoded'
  });
    let options = new RequestOptions({ headers: headers,  method: "post" });

  return new Promise((resolve) => {
debugger;
    this.http
        .post('http://asis-services.com/AsisTransitApi/token', body, options)
        .map(res => res.json())
        .subscribe(
            data => {
              console.log(data);
            },
            err => {
              console.log("ERROR!: ", err);
            }
        );
  }
  )};

you can look result;

post request gets an error at the result


问:
high performance (yet dumb) web server
I'm trying to write a very simple web server that does the following:

Receive request.

Respond with a tiny file; close the connection.

Handle the request data.

In other words, the response doesn't depend on the request information, but the request information is still important. The data will be persisted and then used for analytics.

I've tried to do this with some event-driven networking frameworks, but they all seem to hold the connection until the handling code returns. This makes sense, because generally a server doesn't have to do any work after responding, but in my case there's no need for this particular way of doing things.

Ideally, the server should keep responding to requests, whilst the request data is added to a stack which is emptied as it is persisted.

We expect to handle thousands of requests per second. Is event-driven programming really the way to go, or should I stick with (traditional) threads? Which language or framework is more appropriate for this kind of work?

Thanks.

答:
I realized that instead of using the callback (or green thread, if you will) to do any sort of real work, I'd be better off just delegating the request data to an independent application. Some research into this pointed me to work queues like beanstalkd and RabbitMQ.

beanstalkd seems lighter and faster than the competition, so I'll probably stick to it.

Title: high performance (yet dumb) web server


问:
Checking the input and output file are not the same in Python
I have a python script that takes in two arguments, the name of the input and output files, i.e. it starts of like

```<code>inputFile=open(sys.argv[1],'r')
outFile=open(sys.argv[2],'w')
</code>```

Then performs whatever operation reading from inputFile and writing to the outFile.

Now a few times through human error I've accidentally given the same argument twice, the result being that my input file is replaced with a blank line. Is there are a straight-forward way to stop this happening?

I thought it might be as simple as adding

```<code>if sys.argv[1]==sys.argv[2]:
        inputFile.close()
        outFile.close()
</code>```

immediately after the first lines above, but this already leaves the file blank.

答:
opening the file for writing immediately truncates the file, so the damage is already done when you compare the strings.

That said:

on windows filesystems, the protection is "built-in" since if the file is open as read mode, it cannot be open as write mode at the same time: good (there's a "grey area" for networked filesystems, though)

on Linux/Unix, the risk is there. But comparing the name isn't enough. What if both different paths point on the same file after all? (consider: foo/bar and /mydrive/foo/bar or foo/../bar and bar)

You could use os.path.realpath() on both files prior to comparing for instance to resolve relative paths that could be different (that wouldn't solve symbolic link problems, but it's better than nothing)

And for the windows "gray area" I was mentionning, comparing the lowercase version of the names would be a good idea.

Body:
I have a python script that takes in two arguments, the name of the input and output files, i.e. it starts of like

inputFile=open(sys.argv[1],'r')
outFile=open(sys.argv[2],'w')

Then performs whatever operation reading from inputFile and writing to the outFile.

Now a few times through human error I've accidentally given the same argument twice, the result being that my input file is replaced with a blank line. Is there are a straight-forward way to stop this happening?

I thought it might be as simple as adding

if sys.argv[1]==sys.argv[2]:
        inputFile.close()
        outFile.close()

immediately after the first lines above, but this already leaves the file blank.


问:
Remove DIV dynamically with JQuery
i have a problem to reference an identifier of a DIV. I allow to add a div with a text field and a button to delete the text field, and i set a id to the DIV like an array with this code:

```<code>$('#aggiungi').on('click',function () {
        $count ++;
        $('#corsi').append(
            '<div class="form-group row" id="corso['+$count+']>' +
                '<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
                '<div class="col-sm-10 form-inline">' +
                    '<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
                    '<a class="btn btn-default" id="eliminacorso['+$count+']" aria-label="Elimina">' +
                        '<i class="fa fa-times" aria-hidden="true"></i>' +
                    '</a>' +
                '</div>' +
            '</div>' +
        '');
    });
</code>```

So.. if i press on the botton at the at the side of the text area, i'll call a function that will remove it.
The skeleton of the function is the follow:

```<code>$('#eliminacorso[]').on('click', function() {
  $count --;
  $('#corso[]').remove();
});
</code>```

So my ask is: How can i insert between the square brackets the right identifier of the div?

答:
Use as below the script that add DIV. Remove '[' from id attribute from div tag and anchor tag as below

```<code>$('#aggiungi').on('click',function () {
    $count ++;
    $('#corsi').append(
        '<div class="form-group row" id="corso'+$count+'>' +
            '<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
            '<div class="col-sm-10 form-inline">' +
                '<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
                '<a class="btn btn-default" id="corso'+$count+'" aria-label="Elimina">' +
                    '<i class="fa fa-times" aria-hidden="true"></i>' +
                '</a>' +
            '</div>' +
        '</div>' +
    '');
});
</code>```

And then script to get the clicked id and remove the matched div on click of button as below

```<code>$('.btn').on('click', function() {
   var selectedId = $(this).attr('id');
   $('#'+selectedId).remove();
});
</code>```

Title: Remove DIV dynamically with JQuery

Body:
i have a problem to reference an identifier of a DIV. I allow to add a div with a text field and a button to delete the text field, and i set a id to the DIV like an array with this code:

$('#aggiungi').on('click',function () {
        $count ++;
        $('#corsi').append(
            '
' +
                'Corso ' + $count +'' +
                '
' +
                    '<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
                    '' +
                        '' +
                    '' +
                '
' +
            '
' +
        '');
    });

So.. if i press on the botton at the at the side of the text area, i'll call a function that will remove it.
The skeleton of the function is the follow:

$('#eliminacorso[]').on('click', function() {
  $count --;
  $('#corso[]').remove();
});

So my ask is: How can i insert between the square brackets the right identifier of the div?

Body:
Use as below the script that add DIV. Remove '[' from id attribute from div tag and anchor tag as below

$('#aggiungi').on('click',function () {
    $count ++;
    $('#corsi').append(
        '<div class="form-group row" id="corso'+$count+'>' +
            '<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
            '<div class="col-sm-10 form-inline">' +
                '<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
                '<a class="btn btn-default" id="corso'+$count+'" aria-label="Elimina">' +
                    '<i class="fa fa-times" aria-hidden="true"></i>' +
                '</a>' +
            '</div>' +
        '</div>' +
    '');
});

And then script to get the clicked id and remove the matched div on click of button as below

$('.btn').on('click', function() {
   var selectedId = $(this).attr('id');
   $('#'+selectedId).remove();
});


问:
Datatable loading icon in modal
Is it possible while loading/searching/sorting jquery datatables to display the loading icon in a bootstrap Modal?
is there any example</p>

答:
Add a Bootstrap modal in your view, for example,

```<code> <div class="modal fade" id="myModal" role="dialog" data-keyboard="false" data-backdrop="static">
 <div class="modal-dialog">
  <!-- Modal content-->
  <div class="modal-content">
    <div class="modal-header">
      <h4 class="modal-title">Loading...</h4>
    </div>
    <div class="modal-body">
      <p>Please wait. It's loading data.</p>
      <img src="my loading gif url here" />
    </div>
  </div>
</div>
</code>```

In your Search datatable,

```<code>$('#myInput').on( 'keyup', function () {  //This is an example
 //here load the Modal
 $('#myModal').modal('show');
 //Here call your Ajax method to call your Action Method or Api blah blah
 //Then in success method of your Ajax, hide the Modal, like,
 success:function(result)
 {
  //Your rest code here
  $('#myModal').modal('hide');
 }
} );
</code>```

Same like you can call the Modal in pagination etc etc.

Note: See I set data-keyboard="false" data-backdrop="static" in Bootstrap Modal, so that user can't able to close that since the data fetching and loading. It will automatically hide.

Updated:
As you have commented bellow, you have no Ajax success method. So there is a properties of Datatable called fnInitComplete where you can hide your Modal. For example,

```<code>"fnInitComplete": function ()
 {
  $('#myModal').modal('hide');
 }
</code>```

That's it.
Hope it helps :)

Title: Datatable loading icon in modal

Body:
Add a Bootstrap modal in your view, for example,

 <div class="modal fade" id="myModal" role="dialog" data-keyboard="false" data-backdrop="static">
 <div class="modal-dialog">
  <!-- Modal content-->
  <div class="modal-content">
    <div class="modal-header">
      <h4 class="modal-title">Loading...</h4>
    </div>
    <div class="modal-body">
      <p>Please wait. It's loading data.</p>
      <img src="my loading gif url here" />
    </div>
  </div>
</div>

In your Search datatable,

$('#myInput').on( 'keyup', function () {  //This is an example
 //here load the Modal
 $('#myModal').modal('show');
 //Here call your Ajax method to call your Action Method or Api blah blah
 //Then in success method of your Ajax, hide the Modal, like,
 success:function(result)
 {
  //Your rest code here
  $('#myModal').modal('hide');
 }
} );

Same like you can call the Modal in pagination etc etc.

Note: See I set data-keyboard="false" data-backdrop="static" in Bootstrap Modal, so that user can't able to close that since the data fetching and loading. It will automatically hide.

Updated:
As you have commented bellow, you have no Ajax success method. So there is a properties of Datatable called fnInitComplete where you can hide your Modal. For example,

"fnInitComplete": function ()
 {
  $('#myModal').modal('hide');
 }

That's it.
Hope it helps :)


问:
How to display numeric value which was state stored in state to TextInput?
I was just learning react native, Now i was just trying arithmetic app.On that i have just stored two numeric values in state when I press submit button the result is want to display in TextInput.I was change TextInput editable:false so I can't edit want to show result only.</p>

答:
You can display the result in TextInput . Get final added value in state and assign this final state to TextInput value.

For ex:

```<code>this.state = {
int1:2,
int2:3,
result:0,
}

let val = this.state.int1 + this.state.int2;
this.setState({
  result:val,
});

<TextInput
     maxLength={160}
     multiline={false}
     underlineColorAndroid="transparent"
     editable={false}
     style={styles.input}
     value={this.state.result}
   />
</code>```

Body:
You can display the result in TextInput . Get final added value in state and assign this final state to TextInput value.

For ex:

this.state = {
int1:2,
int2:3,
result:0,
}

let val = this.state.int1 + this.state.int2;
this.setState({
  result:val,
});

<TextInput
     maxLength={160}
     multiline={false}
     underlineColorAndroid="transparent"
     editable={false}
     style={styles.input}
     value={this.state.result}
   />


答:
You can use something like this

var count = 3;

$('button').click(function(){
  count--;
  $($('.corso')[count]).remove();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="corso">1. <input type="text" /></div><br />
<div class="corso">2. <input type="text" /></div><br />
<div class="corso">3. <input type="text" /></div><br />
<br />
<button>Remove</button></code>```

Title: Remove DIV dynamically with JQuery

Body:
You can use something like this

var count = 3;

$('button').click(function(){
  count--;
  $($('.corso')[count]).remove();

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="corso">1. <input type="text" /></div><br />
<div class="corso">2. <input type="text" /></div><br />
<div class="corso">3. <input type="text" /></div><br />
<br />
<button>Remove</button>