问:
Why would an AdMob mess with EditText flow and keyboard?
I am finishing up an Android calculator app, and I have two versions: free and full. I noticed that in the free version when an ad is displayed in the screen, the flow of the EditText fields doesn't go through all the way down to the last EditText; meaning that when the user hits "NEXT" on the virtual keyboard, the flow breaks when the next field is (I guess) enclosed in another LinearLayout, but it works if the input fields are in the same LinearLayout parent. In the full version, without the ad, it works flawlessly.

In addition, when the user is on the last field, the virtual keyboard shows the "DONE" button; in the free version when this button is clicked, the keyboard goes from a numbers only keyboard (InputType:number) to a full keyboard with all it's letters and etc... and doesn't disappear. However, on the full version without the admob, the keyboard simply disappears, as it is suppose to.

I don't know if the location of the admob matters, but this is basically the markup:

```<code><LinearLayout>

    <LinearLayout>
        <calculator_labels_and_fields>
            Calculator goes here
        </calculator_labels_and_fields>
    </LinearLayout>

    <LinearLayout>
        The ad from AdMob
    </LinearLayout>

</LinearLayout>
</code>```

I hope this is clear. I am new to Android dev and am not sure how to approach this very specific behavior.

答:
Ok, so I figured out a solution, alls I had to do was to explicitly define nextFocusDown for each input field and on the last input field, I defined imeOptions="actionDone". Here is a quick example:

```<code><EditText
    android:id="@+id/et_field_1"
    android:inputType="numberDecimal"
    android:nextFocusDown="@id/et_field_2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<EditText
    android:id="@+id/et_field_2"
    android:inputType="numberDecimal"
    android:nextFocusDown="@id/et_field_3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<EditText
    android:id="@+id/et_field_3"
    android:inputType="numberDecimal"
    android:imeOptions="actionDone"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
</code>```

I still don't know why AdMob messes with the flow of inputs, but fortunately I found a solution. It's usually better to define these values anyway, so it's all good.

Body:
I am finishing up an Android calculator app, and I have two versions: free and full. I noticed that in the free version when an ad is displayed in the screen, the flow of the EditText fields doesn't go through all the way down to the last EditText; meaning that when the user hits "NEXT" on the virtual keyboard, the flow breaks when the next field is (I guess) enclosed in another LinearLayout, but it works if the input fields are in the same LinearLayout parent. In the full version, without the ad, it works flawlessly.

In addition, when the user is on the last field, the virtual keyboard shows the "DONE" button; in the free version when this button is clicked, the keyboard goes from a numbers only keyboard (InputType:number) to a full keyboard with all it's letters and etc... and doesn't disappear. However, on the full version without the admob, the keyboard simply disappears, as it is suppose to.

I don't know if the location of the admob matters, but this is basically the markup:

<LinearLayout>

    <LinearLayout>
        <calculator_labels_and_fields>
            Calculator goes here
        </calculator_labels_and_fields>
    </LinearLayout>

    <LinearLayout>
        The ad from AdMob
    </LinearLayout>

</LinearLayout>

I hope this is clear. I am new to Android dev and am not sure how to approach this very specific behavior.

Body:
Ok, so I figured out a solution, alls I had to do was to explicitly define nextFocusDown for each input field and on the last input field, I defined imeOptions="actionDone". Here is a quick example:

<EditText
    android:id="@+id/et_field_1"
    android:inputType="numberDecimal"
    android:nextFocusDown="@id/et_field_2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<EditText
    android:id="@+id/et_field_2"
    android:inputType="numberDecimal"
    android:nextFocusDown="@id/et_field_3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<EditText
    android:id="@+id/et_field_3"
    android:inputType="numberDecimal"
    android:imeOptions="actionDone"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

I still don't know why AdMob messes with the flow of inputs, but fortunately I found a solution. It's usually better to define these values anyway, so it's all good.


来源: stackexchange

问:
What is the need for C startup routine?
Quoting from one of the unix programming books,

When a C program is executed by the
  kernelby, one of the exec functions
  calls special start-up routine. This
  function is called before the main
  function is called. The executable
  program file specifies this routine as
  the starting address for the program;
  this is set up by the link editor when
  it is invoked by the C compiler. This
  start-up routine takes values from the
  kernel the command-line arguments and
  the environment and sets things up so
  that the main function is called as
  shown earlier.

Why do we a need a middle man start-up routine. The exec function could have straightway called the main function and the kernel could have directly passed the command line arguments and environment to the main function. Why do we need the start-up routine in between?

答:
Important to know also is that an application program is executed in user mode, and any system calls out, set the privileged bit and go into kernel mode.  This helps increase OS security by preventing the user from accessing kernel level system calls and a myriad of other complications.  So a call to printf will trap, set kernel mode bit, execute code, then reset to user mode and return to your application.

The CRT is required to help you and allow you to use the languages you want in Windows and Linux.  it provides some very fundamental bootstrapping into the OS to provide you with feature sets for development.

ContentLicense: CC BY-SA 3.0

Title: What is the need for C startup routine?

ContentLicense: CC BY-SA 2.5


问:
How can I implement the PropertyChange event?
I wish to get the details of what has been changed in a MailItem.

I have been able to get ItemChange to trigger based upon Application.Session.Folders("TargetFolder") to a variable as such:
Private Sub olInvMbxItems_ItemChange(ByVal X As Object).

I would like to know the property changed in X. If I pass X to an global variable for Private Sub X_PropertyChange(ByVal x As Object), it will miss the first iteration as X was not initialized on the first pass of ItemChange.

How can I monitor a folder of MailItems to detect Category changes. Whilst ItemChange does this, it gives duplication of action, if I look for specific categories, as many changes trigger ItemChange as mentioned here:

Handle ItemChange event when outlook appointments are dismissed

and here:

Outlook Macro that will copy an email I flag and put it in a folder

The binary flag for the UserProperties in the second item will not function as it is not a one-off event.

Outlook Events VBA says to use PropertyChange but doesn't provide a technique for implementation.

答: There is no way to do that - even on the MAPI level, the store provider does not keep track on what changed. Your only solution is to compare the old (saved elsewhere by you) and new values to see what changed.</p>


问:
How to listen socket, when app is running in gtk.main()?
I've tried to search, but nothing seems to work. For example:

Separate threads

I am currently writing simple communication app in Python2.7 with PyGTK. I have background process, which is listening socket in while loop like that. I want to display message, when I receive it form server. But when I start gtk.main(), it obviously starts to loop again, so my listening loop doesn't working. I need to display new window for each message or close old window and display new window with all unread messages. Can I somehow display window (or more than one window) and don't block my listening loop?

IOChannel solution

```<code> while True: #listening loop
  print 'Start'
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  sock.bind((socket.gethostname(), 80))
  sock.listen(2)
  conn, address = sock.accept()
  conn.sendall('200 OK')
  fd = conn.fileno() #Make file descriptor from socket
  gio_channel = glib.IOChannel(fd) #Pass it to IOChannel

  if(new_message):
    #display message with gtk.main()
  else
    #Do something else like update file
</code>```

subprocess.Popen solution

```<code>while True: #listening loop
  print 'Start'
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  sock.bind((socket.gethostname(), 80))
  sock.listen(2)
  conn, address = sock.accept()
  conn.sendall('200 OK')
  all_json = conn.recv(2048)

  if(new_message):
    # This script run pygtk app in the background
    subprocess.Popen(['python', 'communication_app.py'])
  else
    #Do something else like update file
</code>```

答:
You may want to give a try using GLib's GIOChannel (GLib.IOChannel in the Python doc) to handle the sockets as en event source (a GSource). Then use g_io_create_watch (GLib.IOChannel.add_watch in Python) to integrate in GTK+ main loop.

https://lazka.github.io/pgi-docs/#GLib-2.0/classes/IOChannel.html#GLib.IOChannel

https://developer.gnome.org/glib/stable/glib-IO-Channels.html

You also have lots of more advanced socket handling stuff in the Gio library:

https://lazka.github.io/pgi-docs/#Gio-2.0

https://developer.gnome.org/gio/stable/ (see "Low-level network support" and "High-level network functionallity" sections)

Body:
I've tried to search, but nothing seems to work. For example:

Separate threads

I am currently writing simple communication app in Python2.7 with PyGTK. I have background process, which is listening socket in while loop like that. I want to display message, when I receive it form server. But when I start gtk.main(), it obviously starts to loop again, so my listening loop doesn't working. I need to display new window for each message or close old window and display new window with all unread messages. Can I somehow display window (or more than one window) and don't block my listening loop?

IOChannel solution

 while True: #listening loop
  print 'Start'
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  sock.bind((socket.gethostname(), 80))
  sock.listen(2)
  conn, address = sock.accept()
  conn.sendall('200 OK')
  fd = conn.fileno() #Make file descriptor from socket
  gio_channel = glib.IOChannel(fd) #Pass it to IOChannel

  if(new_message):
    #display message with gtk.main()
  else
    #Do something else like update file

subprocess.Popen solution

while True: #listening loop
  print 'Start'
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  sock.bind((socket.gethostname(), 80))
  sock.listen(2)
  conn, address = sock.accept()
  conn.sendall('200 OK')
  all_json = conn.recv(2048)

  if(new_message):
    # This script run pygtk app in the background
    subprocess.Popen(['python', 'communication_app.py'])
  else
    #Do something else like update file


问:
Error while using setfile to set icon for dmg created via hdiutil in mac
I have created an app & signed using "Developer ID Application: x" certificate.
then using hdiutil i created the dmg

```<code>hdiutil create -size 1.5m -format UDRW myapp.dmg -srcfolder ./myapp/ -fs HFS+
</code>```

to set the drive icons when i execute the below commandsit throws the error

```<code># custom drive volume icon..
#cp drive_icon.icns /Volumes/myapp/.VolumeIcon.icns
#SetFile -c icnC /Volumes/myapp/.VolumeIcon.icns //(throws error -5000)
dev:Unexpected error. (-5000) on file: /Volumes/myapp/.VolumeIcon.icns
</code>```

I thought it would be related to size and increased the size of dmg from 1.5m to 4.5m but that also not helps, image size is 291kb and the overall app size is 666kb.

I created the .app in build machine (mac 10.10 xcode6.2), and tried creating this hdutil in our codesigning server (mac 10.11).
can anyone tell me where it went wrong.

In the man page I see setfile is deprecated is there any other equivalent command to do

Thanks and Regards,
Saravana

答:
found another way to set icon.
Right click the DMG file and click "GetInfo"
Drag and drop the icon file to the icon location present in the GetInfo dialog box.
it sets.

Thanks and regards,
Saravana

Body:
I have created an app & signed using "Developer ID Application: x" certificate.
then using hdiutil i created the dmg

hdiutil create -size 1.5m -format UDRW myapp.dmg -srcfolder ./myapp/ -fs HFS+

to set the drive icons when i execute the below commandsit throws the error

# custom drive volume icon..
#cp drive_icon.icns /Volumes/myapp/.VolumeIcon.icns
#SetFile -c icnC /Volumes/myapp/.VolumeIcon.icns //(throws error -5000)
dev:Unexpected error. (-5000) on file: /Volumes/myapp/.VolumeIcon.icns

I thought it would be related to size and increased the size of dmg from 1.5m to 4.5m but that also not helps, image size is 291kb and the overall app size is 666kb.

I created the .app in build machine (mac 10.10 xcode6.2), and tried creating this hdutil in our codesigning server (mac 10.11).
can anyone tell me where it went wrong.

In the man page I see setfile is deprecated is there any other equivalent command to do

Thanks and Regards,
Saravana


问:
How to run shell script on multiple EC2 instances using AWS CLI?
I'm trying to do a simple AWS CLI command that can run a shell command to multiple instances.

I know first I need to get the list of instances ids:

```<code>aws ec2 describe-instances --filter "Name=tag:Group,Values=Development" --query 'Reservations[].Instances[].[InstanceId]' --output text
</code>```

I then will have to assign them to an array. Then loop through each instance id and send the command.

Do we have an option for aws to send a shell command to an instance with a specific id?

Something like this:

```<code>aws ssm send-command --instance-ids "i-xxxxxxxxxxxxxxxx" --document-name "shellscript"
</code>```

I keep getting this error:

An error occurred (InvalidInstanceId) when calling the SendCommand operation:

I've made sure that the SSM agent is running on that specific instance and made sure everything is correct according to these docs pages.

答:
I was able to create a script with Python using Boto3.

import boto3
import botocore
import paramiko

tagkey = 'Environment'
tagvalue = 'DEV'

# list_instances functions returns a list of ip addresses containing a set of tags
def list_instances(tagkey, tagvalue):

    ec2client = boto3.client('ec2')

    response = ec2client.describe_instances(
        Filters=[
            {
                'Name': 'tag:'+tagkey,
                'Values': [tagvalue]
            }
       ]
    )
    instancelist = []
    for reservation in (response["Reservations"]):
        for instance in reservation["Instances"]:
            instancelist.append(instance["PublicDnsName"])
    return instancelist

# Results of the function get stored in a list.
list = list_instances(tagkey, tagvalue)

key = paramiko.RSAKey.from_private_key_file("/home/ec2-user/key.pem")
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Looping through all the instannces in the list
for instance_ip in list[:]:
                # Connect/ssh to an instance
    try:
                # Here 'ec2-user' is user name and 'instance_ip' is public IP of EC2
                client.connect(hostname=instance_ip, username="ec2-user", pkey=key)

                # Execute a command after connecting/ssh to an instance
                stdin, stdout, stderr = client.exec_command("touch test")

                # close the client connection once the job is done
                print "Command sent:",instance_ip

    except Exception, e:
        print e```

Body:
I'm trying to do a simple AWS CLI command that can run a shell command to multiple instances.

I know first I need to get the list of instances ids:

aws ec2 describe-instances --filter "Name=tag:Group,Values=Development" --query 'Reservations[].Instances[].[InstanceId]' --output text

I then will have to assign them to an array. Then loop through each instance id and send the command.

Do we have an option for aws to send a shell command to an instance with a specific id?

Something like this:

aws ssm send-command --instance-ids "i-xxxxxxxxxxxxxxxx" --document-name "shellscript"

I keep getting this error:

An error occurred (InvalidInstanceId) when calling the SendCommand operation:

I've made sure that the SSM agent is running on that specific instance and made sure everything is correct according to these docs pages.


问:
Code Signing Error: No profiles for app were found. How to solve?

Check dependencies Code Signing Error: No profiles for 'com.app528054'
  were found:

  Xcode couldn't find any iOS App Development provisioning
  profiles matching 'com.app528054'.
  Automatic signing is disabled and
  unable to generate a profile.

To enable automatic signing, pass
  -allowProvisioningUpdates to xcodebuild.
  Code Signing Error: Code signing is required for product type 'Application' in SDK 'iOS 11.1'

I don't get this error. I can build the app via xCode and I don't get any errors, except for the fact that I can't see my code changes in the app (as it's probably not synchronized because of the error above).

When I try ionic cordova build ios, though, it gives me this stacktrace.

I have signed the app with my Apple Developer account and thus that shouldn't be the problem.

Where can I match the profile of the app? How do I solve this?

答:
I had a similar code-signing problem that I solved in XCode but could not get to build from a command line.  I found the value in the "build.json" file that I needed to manually change to properly reflect the value I had set in XCode:

```<code>"debug": {
        "codeSignIdentity": "iPhone Developer",
        "developmentTeam": "5QAC6D6FT5",
        "packageType": "development",
        "provisioningProfile":"[incorrect provisioning profile]",
        "buildFlag": [
            "EMBEDDED_CONTENT_CONTAINS_SWIFT = YES",
            "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES=NO",
            "LD_RUNPATH_SEARCH_PATHS = \"@executable_path/Frameworks\""
        ]
    }
</code>```

In my case, I had the correct blank (automatic?) setting in XCode but that blank setting was not picked up during a cordova build.  Manually removing it from the build.json allowed the successfully signed build in cordova.

Body:
I had a similar code-signing problem that I solved in XCode but could not get to build from a command line.  I found the value in the "build.json" file that I needed to manually change to properly reflect the value I had set in XCode:

"debug": {
        "codeSignIdentity": "iPhone Developer",
        "developmentTeam": "5QAC6D6FT5",
        "packageType": "development",
        "provisioningProfile":"[incorrect provisioning profile]",
        "buildFlag": [
            "EMBEDDED_CONTENT_CONTAINS_SWIFT = YES",
            "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES=NO",
            "LD_RUNPATH_SEARCH_PATHS = \"@executable_path/Frameworks\""
        ]
    }

In my case, I had the correct blank (automatic?) setting in XCode but that blank setting was not picked up during a cordova build.  Manually removing it from the build.json allowed the successfully signed build in cordova.


问:
track pedestrian with trail using cesium CZML
Does someone have a handy example of a CZML file that uses sample properties to track a pedestrian walking a terrain.

I need a billboard at the head of the trail for the person, who will have some custome properties I want to see in the infoblock (about 18K samples).

And my assumption is that a separate id for a path that grows as trace of the path (with the head being the billboard). And this would be in a separate packet, shown as a polyline with material.

and Both would have a epoch for the start and then sample properties for each time step

I.e. the epoch would be today at noon, and the sample properties would be 1 second intervals for each position of the pedestrian which would be duplicated for both the polyline and the billboard.

But is there a better way, and I assume someone has done a sandcastle with an example, right?

答:
I found an example that shows how one can do this more effectively than what I thought (that is you can do this just by adding the data to the coordinates of the billboard as Sampled Data).

https://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=CZML%20Path.html&label=


问:
Is design now a subset of refactoring?
Looking at the cool new principles of software development:

Agile

You Ain't Gonna Need It

Less As A Competitive Advantage

Behaviour-Driven Development

The Evils Of Premature Optimization

The New Way seems to be to dive in and write what you need to achieve the first iteration of scope objectives, and refactor as necessary to have elegant solutions. Your codebase grows incrementally, and never has a big planning/hierarchical design stage. That, to me, suggests that software design (worthy though it is) has been subsumed into refactoring, because that's where the elegant code comes from, not the incremental additions to functionality.

Am I wrong?

答:
Reminds me of the following quote:

The goal is clean code that works. [...] First we'll solve the "that works" part of the problem. Then we'll solve the "clean code" part. This is the opposite of architecture-driven development, where you solve "clean code" first, then scramble around trying to integrate into the design the things you learn as you solve the "that works" problem. (Kent Beck, "TDD by Example")

OwnerDisplayName: Phil H

Title: Is design now a subset of refactoring?

LastEditorDisplayName: Phil H

OwnerDisplayName: Fabian Steeg


问:
Set permissions for directorys/subdirectorys/files
I want to be able to set the persmissions for subfolders and files inside a targeted folder for a specific user.

Up until now i found out how to set the permissions for a specific folder. But not for subfolders and files inside the original folder.
After extensive internet search i could not find any clue on how to tackle this problem. Also the windows doku just shows how to set permission for only a directory.

```<code>class DirectoryPermissions
{
    public static void DirectoryPermissionsMain(string Directory, string Account, string Rights, int Takeaway, string Domain)
    {
        try
        {
            string DirectoryName = Directory;

            Console.WriteLine("Adding access control entry for " + DirectoryName);
            if(Takeaway == 0 && Rights.Equals("Read")){
                AddDirectorySecurity(DirectoryName, Domain + @"\" + Account, FileSystemRights.ReadData, AccessControlType.Allow);

                Console.WriteLine("Removing access control entry from " + DirectoryName);
            }

            MessageBox.Show("Done");

        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }

        Console.ReadLine();
    }

    // Adds an ACL entry on the specified directory for the specified account.
    public static void AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
    {
        // Create a new DirectoryInfo object.
        DirectoryInfo dInfo = new DirectoryInfo(FileName);

        // Get a DirectorySecurity object that represents the
        // current security settings.
        DirectorySecurity dSecurity = dInfo.GetAccessControl();

        // Add the FileSystemAccessRule to the security settings.
        dSecurity.AddAccessRule(new FileSystemAccessRule(Account,
                                                        Rights,
                                                        ControlType));

        // Set the new access settings.
        dInfo.SetAccessControl(dSecurity);

    }
}
</code>```

I hope one of you can point me in the right direction.

答:
You have to add another AccessRule  with InheritanceFlags set to ContainerInherit AND ObjectInherit.

To get the permissions to propgate to child folders, the PropagationFlag is set to Inherit only.

Here's an example below

```<code>    public void PropogateSecurity(string userid,string directory)
    {

        var myDirectoryInfo = new DirectoryInfo(directory);
        var myDirectorySecurity = myDirectoryInfo.GetAccessControl();
        myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(userid, FileSystemRights.Modify, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
        myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(userid, FileSystemRights.Modify, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
        myDirectoryInfo.SetAccessControl(myDirectorySecurity);

    }
</code>```

You can also do this with recursion, but the above would be my preferred method as cleaning up permissions would be annoying.

Body:
I want to be able to set the persmissions for subfolders and files inside a targeted folder for a specific user.

Up until now i found out how to set the permissions for a specific folder. But not for subfolders and files inside the original folder.
After extensive internet search i could not find any clue on how to tackle this problem. Also the windows doku just shows how to set permission for only a directory.

class DirectoryPermissions
{
    public static void DirectoryPermissionsMain(string Directory, string Account, string Rights, int Takeaway, string Domain)
    {
        try
        {
            string DirectoryName = Directory;

            Console.WriteLine("Adding access control entry for " + DirectoryName);
            if(Takeaway == 0 && Rights.Equals("Read")){
                AddDirectorySecurity(DirectoryName, Domain + @"\" + Account, FileSystemRights.ReadData, AccessControlType.Allow);

                Console.WriteLine("Removing access control entry from " + DirectoryName);
            }

            MessageBox.Show("Done");

        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }

        Console.ReadLine();
    }

    // Adds an ACL entry on the specified directory for the specified account.
    public static void AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
    {
        // Create a new DirectoryInfo object.
        DirectoryInfo dInfo = new DirectoryInfo(FileName);

        // Get a DirectorySecurity object that represents the
        // current security settings.
        DirectorySecurity dSecurity = dInfo.GetAccessControl();

        // Add the FileSystemAccessRule to the security settings.
        dSecurity.AddAccessRule(new FileSystemAccessRule(Account,
                                                        Rights,
                                                        ControlType));

        // Set the new access settings.
        dInfo.SetAccessControl(dSecurity);

    }
}

I hope one of you can point me in the right direction.

Body:
You have to add another AccessRule  with InheritanceFlags set to ContainerInherit AND ObjectInherit.

To get the permissions to propgate to child folders, the PropagationFlag is set to Inherit only.

Here's an example below

    public void PropogateSecurity(string userid,string directory)
    {

        var myDirectoryInfo = new DirectoryInfo(directory);
        var myDirectorySecurity = myDirectoryInfo.GetAccessControl();
        myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(userid, FileSystemRights.Modify, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
        myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(userid, FileSystemRights.Modify, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
        myDirectoryInfo.SetAccessControl(myDirectorySecurity);

    }

You can also do this with recursion, but the above would be my preferred method as cleaning up permissions would be annoying.


问:
sqlalchemy, specify database name with DSN
I am trying to connect to a SQL Server from Linux using sqlalchemy. This page shows DSN-based connection as below.

engine = create_engine("mssql+pyodbc://scott:tiger@some_dsn")

Is there a way to specify a database name using DSN? I am aware that we can specify a database name either in odbc.ini or a SQL query but I would like to know if we can also do something like this.

engine = create_engine("mssql+pyodbc://scott:tiger@some_dsn/databasename")

答:
You can pass arguments directly to the pyodbc.connect method through the connect_args parameter in create_engine:

```<code>def my_create_engine(mydsn, mydatabase, **kwargs):
    connection_string = 'mssql+pyodbc://@%s' % mydsn
    cargs = {'database': mydatabase}
    cargs.update(**kwargs)
    e = sqla.create_engine(connection_string, connect_args=cargs)
    return e
</code>```

This will also enable the database to be persisted through several transactions / sessions.

Body:
You can pass arguments directly to the pyodbc.connect method through the connect_args parameter in create_engine:

def my_create_engine(mydsn, mydatabase, **kwargs):
    connection_string = 'mssql+pyodbc://@%s' % mydsn
    cargs = {'database': mydatabase}
    cargs.update(**kwargs)
    e = sqla.create_engine(connection_string, connect_args=cargs)
    return e

This will also enable the database to be persisted through several transactions / sessions.


问:
How to increase the size of the downloaded image from canvas with fabricjs?
I'm using the following to download my fabricjs canvas and it works great but I wondered how I might be able to make the downloaded image larger so that it's clearer when I print it? Thanks for any help in advance.

```<code>// Download as png
function download(url, name) {
  // make the link. set the href and download. emulate dom click
  $('<a>').attr({
    href: url,
    download: name
  })[0].click();
}

function downloadFabric(canvas, name) {
  //  convert the canvas to a data url and download it.
  download(canvas.toDataURL(), name + '.png');
}
</code>```

```<code><button onclick="downloadFabric(canvas,'save');">Save</button>
</code>```

答:
You can set the canvas width and height as bigger than the showing size.

```<code><canvas width="2400" height="2400" style="width:600px;height:600px;"></canvas>
</code>```

Because render png refers to canvas width and height.

FIDDLE(you can get 2400x2400 image from the fiddle)

Body:
I'm using the following to download my fabricjs canvas and it works great but I wondered how I might be able to make the downloaded image larger so that it's clearer when I print it? Thanks for any help in advance.

// Download as png
function download(url, name) {
  // make the link. set the href and download. emulate dom click
  $('').attr({
    href: url,
    download: name
  })[0].click();
}

function downloadFabric(canvas, name) {
  //  convert the canvas to a data url and download it.
  download(canvas.toDataURL(), name + '.png');
}

<button onclick="downloadFabric(canvas,'save');">Save</button>

Body:
You can set the canvas width and height as bigger than the showing size.

<canvas width="2400" height="2400" style="width:600px;height:600px;"></canvas>

Because render png refers to canvas width and height.

FIDDLE(you can get 2400x2400 image from the fiddle)


问:
Unable to build Go application after Mac update
I just updated to High Sierra and now I can't build any GoLang Applications. I get the following error:

```<code>> # command-line-arguments
/usr/local/Cellar/go/1.8.3/libexec/pkg/tool/darwin_amd64/link: running clang failed: exit status 1
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun
</code>```

I have tried

```<code>xcode-select --install
</code>```

and

```<code>xcode-select --reset
</code>```

But neither have worked, has anyone else encountered this?

答:
I encountered this after upgrade to High Sierra and addressed it with</p>

```<code>sudo xcode-select --reset
</code>```

Body:
I just updated to High Sierra and now I can't build any GoLang Applications. I get the following error:

> # command-line-arguments
/usr/local/Cellar/go/1.8.3/libexec/pkg/tool/darwin_amd64/link: running clang failed: exit status 1
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun

I have tried

xcode-select --install

and

xcode-select --reset

But neither have worked, has anyone else encountered this?

Body:
I encountered this after upgrade to High Sierra and addressed it with

sudo xcode-select --reset


问:
How do I show multiple recaptchas on a single page?
I have 2 forms on a single page.  One of the forms has a Recaptcha displaying all the time.  The other should display a Recaptcha only after a certain event such as maxing out login attempts.  So there are times when I would need 2 Recaptchas to appear on the same page.  Is this possible?  I know I could probably use a single one for both, but the way I have the layout, I would much prefer to have 2.  Thanks.

Update: well I guess it may not be possible.  Can anybody recommend another capture library to use side by side with reCaptcha?  I really want to be able to have 2 captchas on the same page.

Update 2: What if I put each form in an iframe?  Would this be an acceptable solution?

答:
I would use invisible recaptcha.  Then on your button use a tag like " formname='yourformname' " to specify which form is to be submitted and hide a submit form input.

The advantage of this is it allows for you to keep the html5 form validation intact, one recaptcha, but multiple button interfaces.  Just capture the "captcha" input value for the token key generated by recaptcha.

```<code><script src="https://www.google.com/recaptcha/api.js" async defer ></script>

<div class="g-recaptcha" data-sitekey="yours" data-callback="onSubmit" data-size="invisible"></div>
<script>
var formanme = ''
$('button').on('click', function () { formname = '#'+$(this).attr('formname');
    if ( $(formname)[0].checkValidity() == true) { grecaptcha.execute(); }
    else { $(formname).find('input[type="submit"]').click() }
    });

var onSubmit = function(token) {
    $(formname).append("<input type='hidden' name='captcha' value='"+token+"' />");
    $(formname).find('input[type="submit"]').click()
    };
</script>
</code>```

I find this FAR simpler and easier to manage.

ContentLicense: CC BY-SA 4.0

Body:
I would use invisible recaptcha.  Then on your button use a tag like " formname='yourformname' " to specify which form is to be submitted and hide a submit form input.

The advantage of this is it allows for you to keep the html5 form validation intact, one recaptcha, but multiple button interfaces.  Just capture the "captcha" input value for the token key generated by recaptcha.

<script src="https://www.google.com/recaptcha/api.js" async defer ></script>

<div class="g-recaptcha" data-sitekey="yours" data-callback="onSubmit" data-size="invisible"></div>
<script>
var formanme = ''
$('button').on('click', function () { formname = '#'+$(this).attr('formname');
    if ( $(formname)[0].checkValidity() == true) { grecaptcha.execute(); }
    else { $(formname).find('input[type="submit"]').click() }
    });

var onSubmit = function(token) {
    $(formname).append("<input type='hidden' name='captcha' value='"+token+"' />");
    $(formname).find('input[type="submit"]').click()
    };
</script>

I find this FAR simpler and easier to manage.


问:
why the marker is not visible in mapbox?
I'm messing my head around mapbox but the marker is not visible no matter what i do here is my code

```<code>map.on('dblclick', function (e) {
            var el = document.createElement('div');
            el.setAttribute("style","width: 25px,height: 25px,border-radius: 50%,border:1px solid gray,background-color:lightblue");
            var letcoordinates = [e.lngLat.lng, e.lngLat.lat];
            // make a marker for each feature and add to the map
            debugger
            new mapboxgl.Marker(el)
            .setLngLat(letcoordinates)
            .addTo(map);
   });
</code>```

i don't what what i'm doing wrong

thanks in advance

答:
In your setAttribute(), the properties should be separated by a semicolon:

```<code>el.setAttribute("style","width: 25px;height: 25px;border-radius: 50%;border:1px solid gray;background-color:lightblue");
</code>```

Result: https://codepen.io/eddydg/pen/vWZGGB?editors=1010

Body:
I'm messing my head around mapbox but the marker is not visible no matter what i do here is my code

map.on('dblclick', function (e) {
            var el = document.createElement('div');
            el.setAttribute("style","width: 25px,height: 25px,border-radius: 50%,border:1px solid gray,background-color:lightblue");
            var letcoordinates = [e.lngLat.lng, e.lngLat.lat];
            // make a marker for each feature and add to the map
            debugger
            new mapboxgl.Marker(el)
            .setLngLat(letcoordinates)
            .addTo(map);
   });

i don't what what i'm doing wrong

thanks in advance

Body:
In your setAttribute(), the properties should be separated by a semicolon:

el.setAttribute("style","width: 25px;height: 25px;border-radius: 50%;border:1px solid gray;background-color:lightblue");

Result: https://codepen.io/eddydg/pen/vWZGGB?editors=1010


问:
Show "pop up window" when is mouser over listBox item
I bind observable collection on listBox. I have data tempate on listbox item. It consit one image control and som textBlock.

If is mouse over on some listBox item I would like achieve this behavior:

Show PopUp/ToolTip (some "rectangle" with controls) and bind values from listBox current item.

And on textBox in item data template I have style, I would like change color of text in textBlock, for example from black to green.

Style is here:

```<code>        <Style x:Key="FriedNickStyle" TargetType="TextBlock">
            <Setter Property="Margin" Value="2,2,2,2"/>
            <Setter Property="FontSize" Value="13"/>
            <Setter Property="FontWeight" Value="Medium"/>
            <Setter Property="Foreground" Value="Black"/>
        </Style>
</code>```

Sory for my english, I have problem how describe this behavior correct. I try many thing but any of them doesn’t work good.

Here is it my style:

```<code>     <DataTemplate x:Key="FriendListBoxItemTemplate">
                <Grid Name="RootLayout">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="0.3*"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="60"></RowDefinition>
                    </Grid.RowDefinitions>
                    <Image Margin="4,4,4,2" Grid.Column="0">
                        <Image.Source >
                            <MultiBinding Converter="{StaticResource avatarConverter}">
                                <Binding Path="ProfilePhoto"></Binding>
                                <Binding Path="StatusInfo.IsLogged"></Binding>
                            </MultiBinding>
                        </Image.Source>
                    </Image>
                    <Grid  Grid.Column="1">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"></ColumnDefinition>
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"></RowDefinition>
                        </Grid.RowDefinitions>
                    <TextBlock
                                       Text="{Binding Path=Nick}"
                                       Style="{StaticResource FriedNickStyle}"
                                       Grid.Column="0" Grid.Row="0">
                    </TextBlock>
                    </Grid>
                </Grid>
                <DataTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <!--SHOW SOME POP UP WINDOW and bind properties from ITEM (VALUE)-->
<!--Change color of textBlock-->
                    </Trigger>
                </DataTemplate.Triggers>
            </DataTemplate>
</code>```

Thank everybody who help me.

答:
Well, I found this turorial, this article, by the MSDN and another stack overflow's question.
Basically, here's how:

```<code><Popup Margin="10,10,0,13"
    Name="Popup1"
    HorizontalAlignment="Left"
    VerticalAlignment="Top"
    Width="194"
    Height="200"
    IsOpen="True">                      // change this to open it

   <TextBlock Name="McTextBlock" Background="LightBlue" >
        This is popup text
   </TextBlock>
</code>```

Body:
I bind observable collection on listBox. I have data tempate on listbox item. It consit one image control and som textBlock.

If is mouse over on some listBox item I would like achieve this behavior:

Show PopUp/ToolTip (some "rectangle" with controls) and bind values from listBox current item.

And on textBox in item data template I have style, I would like change color of text in textBlock, for example from black to green.

Style is here:

Sory for my english, I have problem how describe this behavior correct. I try many thing but any of them doesn’t work good.

Here is it my style:

     <DataTemplate x:Key="FriendListBoxItemTemplate">
                <Grid Name="RootLayout">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="0.3*"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="60"></RowDefinition>
                    </Grid.RowDefinitions>
                    <Image Margin="4,4,4,2" Grid.Column="0">
                        <Image.Source >
                            <MultiBinding Converter="{StaticResource avatarConverter}">
                                <Binding Path="ProfilePhoto"></Binding>
                                <Binding Path="StatusInfo.IsLogged"></Binding>
                            </MultiBinding>
                        </Image.Source>
                    </Image>
                    <Grid  Grid.Column="1">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"></ColumnDefinition>
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"></RowDefinition>
                        </Grid.RowDefinitions>
                    <TextBlock
                                       Text="{Binding Path=Nick}"
                                       Style="{StaticResource FriedNickStyle}"
                                       Grid.Column="0" Grid.Row="0">
                    </TextBlock>
                    </Grid>
                </Grid>
                <DataTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">

                    </Trigger>
                </DataTemplate.Triggers>
            </DataTemplate>

Thank everybody who help me.

Body:
Well, I found this turorial, this article, by the MSDN and another stack overflow's question.
Basically, here's how:

<Popup Margin="10,10,0,13"
    Name="Popup1"
    HorizontalAlignment="Left"
    VerticalAlignment="Top"
    Width="194"
    Height="200"
    IsOpen="True">                      // change this to open it

   <TextBlock Name="McTextBlock" Background="LightBlue" >
        This is popup text
   </TextBlock>


问:
Python: average of dictionary key values over panda values
I have a rather complex data structure, namely dictionaries in a panda dataframe. Lets say I have this dataframe.

```<code>trials_ = [1,2,1,2]
stimul_ = [1,1,2,2]
data_ = [[{'peak_voltage': [30.5, 65], 'Spikecount': [2]}], [{'peak_voltage': [30.5, 65, 30], 'Spikecount': [3]}], [{'peak_voltage': [20.1], 'Spikecount': [1]}], 'NaN']
featve  = pd.DataFrame({'trial': trials_, 'stimulus': stimul_, 'data': data_})
featve

    data                                                stimulus    trial
0   [{'peak_voltage': [30.5, 65], 'Spikecount': [2]}]   1           1
1   [{'peak_voltage': [30.5, 65, 30], 'Spikecount'...   1           2
2   [{'peak_voltage': [20.1], 'Spikecount': [1]}]       2           1
3   NaN                                                 2           2
</code>```

I now want to calculate the median and 25% / 75% quartiles of each key element of my dictionaries in my 'data' column (here peak_voltage and Spikecount) for each stimulus over all trials.

One example for the median:
I want the median peak_voltage value when stimulus 1 was applied across all trials [30.5, 65, 20.1] -> 30.5. The same for when stimulus two was applied [30.5, 65, 30, NaN] -> 30.5. And of course the same for Spikecount.

To be honest, I've no idea where to start. If I only wanted to calculate the median regardless of the simulus, I would simply use.

```<code>featve.data.median
</code>```

But this is not what I want. Also, if I didn't have dictionaries but only numbers, I would have used something like

```<code>featve.groupby('stimulus').data.apply(np.nanmedian)
</code>```

But what can I do in my case with dictionaries in a panda table?

EDIT 1

I have 10 stimuli with 16 trials each, resulting in 160 rows in total. The dictionaries are the output of a toolbox called EFEL that I use to find certain characteristics of my data traces (e.g. the timing of peaks of neuronal action potentials). I decided to organize the resulting 160 dictionaries in a panda dataframe to keep track of the data, stimuli and trials at the same time. I don't know if this is unfortunate in the first place.

答:
First, I'm not sure why you're putting your dicionaries in lists, but I would recommend having a version of your data without them. Also, if most of your data is in the form of dictionaries, then I recommend putting missing data in the form of dictionaries as well. Once you do that, you can put data_ in a dataframe. So

my_data =  pd.DataFrame([{'peak_voltage': [30.5, 65], 'Spikecount': [2]}, {'peak_voltage': [30.5, 65, 30], 'Spikecount': [3]}, {'peak_voltage': [20.1], 'Spikecount': [1]}, {}]).

You can then have a dataframe of stimulus and trial:

stimulus_trial_df = pd.DataFrame({'trial': trials_, 'stimulus': stimul_}).

Next, you can slice my_data on properties of stiumulus_trial_df:

subset1 = my_data.loc[stimulus_trial_df['stimulus']==1].

Note that you do have to make sure that your two dataframes have consistent indices for this to work.

Once you have subset1, you can flatten columns in it:

spikecount_agg= [spikecount for row in subset1['Spikecount'] for spikecount in row].

Finally, you can perform whatever operation you want on the flattened column:

```<code>import statistics
current_median = statistics.median(spikecount_agg)
</code>```

A final note: you put in your question [30.5, 65, 20.1] -> 30.5, but your data has two copies of 30.5 and 65. In this particular case, this doesn't change what the median is, but you should think about whether you want to take into account multiple copies in your data. My code includes them, so if you don't want them, you'll have to adjust the code.

EDIT:
Regarding subsetting for different stimuli, a for-loop should suffice. If you have an object containing unique stimuli, you can loop over that; if you don't, you can generate it with unique_stimuli = set(stimul_):

```<code>for stimulus in unique_stimuli:
   subset = my_data.loc[stimulus_trial_df['stimulus']==stimulus]
   #do what you want with subset
</code>```

Body:
I have a rather complex data structure, namely dictionaries in a panda dataframe. Lets say I have this dataframe.

trials_ = [1,2,1,2]
stimul_ = [1,1,2,2]
data_ = [[{'peak_voltage': [30.5, 65], 'Spikecount': [2]}], [{'peak_voltage': [30.5, 65, 30], 'Spikecount': [3]}], [{'peak_voltage': [20.1], 'Spikecount': [1]}], 'NaN']
featve  = pd.DataFrame({'trial': trials_, 'stimulus': stimul_, 'data': data_})
featve

    data                                                stimulus    trial
0   [{'peak_voltage': [30.5, 65], 'Spikecount': [2]}]   1           1
1   [{'peak_voltage': [30.5, 65, 30], 'Spikecount'...   1           2
2   [{'peak_voltage': [20.1], 'Spikecount': [1]}]       2           1
3   NaN                                                 2           2

I now want to calculate the median and 25% / 75% quartiles of each key element of my dictionaries in my 'data' column (here peak_voltage and Spikecount) for each stimulus over all trials.

One example for the median:
I want the median peak_voltage value when stimulus 1 was applied across all trials [30.5, 65, 20.1] -> 30.5. The same for when stimulus two was applied [30.5, 65, 30, NaN] -> 30.5. And of course the same for Spikecount.

To be honest, I've no idea where to start. If I only wanted to calculate the median regardless of the simulus, I would simply use.

featve.data.median

But this is not what I want. Also, if I didn't have dictionaries but only numbers, I would have used something like

featve.groupby('stimulus').data.apply(np.nanmedian)

But what can I do in my case with dictionaries in a panda table?

EDIT 1

I have 10 stimuli with 16 trials each, resulting in 160 rows in total. The dictionaries are the output of a toolbox called EFEL that I use to find certain characteristics of my data traces (e.g. the timing of peaks of neuronal action potentials). I decided to organize the resulting 160 dictionaries in a panda dataframe to keep track of the data, stimuli and trials at the same time. I don't know if this is unfortunate in the first place.

Body:
First, I'm not sure why you're putting your dicionaries in lists, but I would recommend having a version of your data without them. Also, if most of your data is in the form of dictionaries, then I recommend putting missing data in the form of dictionaries as well. Once you do that, you can put data_ in a dataframe. So

my_data =  pd.DataFrame([{'peak_voltage': [30.5, 65], 'Spikecount': [2]}, {'peak_voltage': [30.5, 65, 30], 'Spikecount': [3]}, {'peak_voltage': [20.1], 'Spikecount': [1]}, {}]).

You can then have a dataframe of stimulus and trial:

stimulus_trial_df = pd.DataFrame({'trial': trials_, 'stimulus': stimul_}).

Next, you can slice my_data on properties of stiumulus_trial_df:

subset1 = my_data.loc[stimulus_trial_df['stimulus']==1].

Note that you do have to make sure that your two dataframes have consistent indices for this to work.

Once you have subset1, you can flatten columns in it:

spikecount_agg= [spikecount for row in subset1['Spikecount'] for spikecount in row].

Finally, you can perform whatever operation you want on the flattened column:

import statistics
current_median = statistics.median(spikecount_agg)

A final note: you put in your question [30.5, 65, 20.1] -> 30.5, but your data has two copies of 30.5 and 65. In this particular case, this doesn't change what the median is, but you should think about whether you want to take into account multiple copies in your data. My code includes them, so if you don't want them, you'll have to adjust the code.

EDIT:
Regarding subsetting for different stimuli, a for-loop should suffice. If you have an object containing unique stimuli, you can loop over that; if you don't, you can generate it with unique_stimuli = set(stimul_):

for stimulus in unique_stimuli:
   subset = my_data.loc[stimulus_trial_df['stimulus']==stimulus]
   #do what you want with subset


问:
Accessing Eloquent Relationship Automatically when loaded
I am working on  a project which requires me to get all the list of all information from a table --Just like in  a blog, i used the all() method to do this but when i try to get the method i declared in my Model i get an error, saying

the collection instance does not exists

But when i use The
Model::find($id)->relationship()->name;

it works fine. Is there any way to load all relationship with the all() function in laravel.

Thanks for your help..

答:
When you perform Model::find($id)->relationship(); you are actually accesing to the Dynamic relationships Properties

You need to convert it into a collection using Model::find($id)->relationship()->get();

Then you can perform any collection method to get the result you want. After doing this you can access to its attributes like this:

```<code>$model_varible = Model::find($id)->relationship()->get();
$model_variable = $model_variable->find($id)->name;
</code>```

Let me know if this works for you.

Body:
When you perform Model::find($id)->relationship(); you are actually accesing to the Dynamic relationships Properties

You need to convert it into a collection using Model::find($id)->relationship()->get();

Then you can perform any collection method to get the result you want. After doing this you can access to its attributes like this:

$model_varible = Model::find($id)->relationship()->get();
$model_variable = $model_variable->find($id)->name;

Let me know if this works for you.


问:
Toggle the div with a button and hide the div when click outside of that div
I have a menu which I'm trying to toggle with a button (Which I've been able to do quit easily). But I also want menu to hide when clicked outside of it, And after lot of Googling I came across this solution. It works well i.e If you click outside the div, it hides it. But now I can't toggle the div with toggle button.

$('.toggle').click(function() {
  $(this).siblings('div').toggle();
});

$(document).mouseup(function(e) {
  var container = $(".menu");

  // if the target of the click isn't the container nor a descendant of the container
  if (!container.is(e.target) && container.has(e.target).length === 0) {
    container.hide();
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.toggle {
  border: 1px solid gray;
  padding: 3px;
  width: 50px;
  border-radius: 3px;
  cursor: pointer;
}

.menu {
  border: 1px solid gray;
  width: 150px;
  border-radius: 5px;
  margin-top: 8px;
}

.list,
{
  list-style: none;
}</code>```

  Toggle

Friends

Family

College

Colleague

Acquaintances

Unsorted

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

<p>I would really be greatful if alteast any one could explain to me what this line of code is actually doing.</p>

```container.has(e.target).length === 0
```

答:
Here's a working fiddle - https://jsfiddle.net/s29ppsbd/

The red area is the doc, the yellow area is the menu container.

The condition does exactly what it says in the comment that can be seen in the snippet, it checks if the target of the click isn't the container nor a descendant of the container.

You are interested in toggler clicks as well as menu item clicks, instead of expanding the condition, I decided to wrap everything in a div with the class menu-container, if a click event comes from that and children of it (menu items themselves), it will not close the menu, otherwise, it will.

Closing the menu immediately as soon as a menu item was clicked on is a matter of choice, I personally don't like sites that immediately close the menu when I click a link, I get confused for 1 second, til I see the loading icon of the browser.

Body:
I have a menu which I'm trying to toggle with a button (Which I've been able to do quit easily). But I also want menu to hide when clicked outside of it, And after lot of Googling I came across this solution. It works well i.e If you click outside the div, it hides it. But now I can't toggle the div with toggle button.

$('.toggle').click(function() {
  $(this).siblings('div').toggle();
});

$(document).mouseup(function(e) {
  var container = $(".menu");

  // if the target of the click isn't the container nor a descendant of the container
  if (!container.is(e.target) && container.has(e.target).length === 0) {
    container.hide();
  }
});

.toggle {
  border: 1px solid gray;
  padding: 3px;
  width: 50px;
  border-radius: 3px;
  cursor: pointer;
}

.menu {
  border: 1px solid gray;
  width: 150px;
  border-radius: 5px;
  margin-top: 8px;
}

.list,
{
  list-style: none;
}

  Toggle

Friends

Family

College

Colleague

Acquaintances

Unsorted

I would really be greatful if alteast any one could explain to me what this line of code is actually doing.

container.has(e.target).length === 0


问:
Elegant Solution avoiding Global Variable
I am trying to find an elegant and still readable Way of getting rid of that global Var. But cannot find a way to do it. no jQuery please it should work without any imports.

```

答:
No need to do all that coding. You can already hide it from the global by just wrapping the value inside the eventhandler of the load function. Note this will not run, but at least I added a clearInterval after the first error. ;)

This sample also uses the built in fetch method, which works with promises and makes the code a lot more readable.

window.addEventListener('load', function() {
  let results;
  let interval = setInterval(() => {
    fetch('ajax1.php', {
      method: 'POST'
    }).then(response => {
      let count = parseInt(response.text);
      if (results === undefined) {
        results = count;
        return;
      }
      if (results !== count) {
        clearInterval(interval);
        document.location.reload();
      }
    }).catch(() => clearInterval(interval));
  }, 250);
});```
</div>
</div>
</p>

<p>A few more things to note about your original code though. :)</p>

```window.onload = ajax(anfang);
```

<p>This statement is useless, as it executes the function at once, so the assignment is useless, it could be written instead as:</p>

```window.onload = () => ajax(anfang);
```

<p>Your <code>XMLHttpRequest</code> method is also a bit overly verbose, note that the <code>async</code> parameter is optional and defaults to <code>true</code> so there is absolutely no reason to supply it as an argument.</p>

<p>Which would execute it after the window has loaded, or you could use the <code>addEventListener</code> as shown in the code above.</p>

<p>Also reloading it if the counts are different seems very resource heavy, wouldn't it be better to reload the data that now has changed?</p>

<p>Concerning the count function, what happens if in the polling interval, an item got added and deleted?</p>

<p>And a final point, if your polling page would throw an error, many errors would occur, considering to either warn the user that the polling didn't work, or to disable the polling so that the user doesn't keep on sending requests if it failed (maybe giving a manual button to refresh, or showing a message to the user that refreshing was disabled).</p>

<p>You could eventually also rewrite your code in the following way</p>

```function ajax() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      if (ajax.results === undefined) {
        ajax.results = this.responseText;
      } else if (ajax.results !== this.responseText) {
        document.location.reload();
      }
    }
  };
  xhttp.open("POST", "ajax1.php"); // SELECT COUNT(*)
  xhttp.send();
}

window.addEventListener('load', function() {
  setInterval( ajax, 250 );
});
```

This uses the ajax function to store the data, as functions are also objects. So the first time it will load the data, it will set the original values, the next times, it will compare the responseText with the value previously saved as a property on the ajax function.

Body:
No need to do all that coding. You can already hide it from the global by just wrapping the value inside the eventhandler of the load function. Note this will not run, but at least I added a clearInterval after the first error. ;)

This sample also uses the built in fetch method, which works with promises and makes the code a lot more readable.

window.addEventListener('load', function() {
  let results;
  let interval = setInterval(() => {
    fetch('ajax1.php', {
      method: 'POST'
    }).then(response => {
      let count = parseInt(response.text);
      if (results === undefined) {
        results = count;
        return;
      }
      if (results !== count) {
        clearInterval(interval);
        document.location.reload();
      }
    }).catch(() => clearInterval(interval));
  }, 250);
});

A few more things to note about your original code though. :)

window.onload = ajax(anfang);

This statement is useless, as it executes the function at once, so the assignment is useless, it could be written instead as:

window.onload = () => ajax(anfang);

Your XMLHttpRequest method is also a bit overly verbose, note that the async parameter is optional and defaults to true so there is absolutely no reason to supply it as an argument.

Which would execute it after the window has loaded, or you could use the addEventListener as shown in the code above.

Also reloading it if the counts are different seems very resource heavy, wouldn't it be better to reload the data that now has changed?

Concerning the count function, what happens if in the polling interval, an item got added and deleted?

And a final point, if your polling page would throw an error, many errors would occur, considering to either warn the user that the polling didn't work, or to disable the polling so that the user doesn't keep on sending requests if it failed (maybe giving a manual button to refresh, or showing a message to the user that refreshing was disabled).

You could eventually also rewrite your code in the following way

function ajax() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      if (ajax.results === undefined) {
        ajax.results = this.responseText;
      } else if (ajax.results !== this.responseText) {
        document.location.reload();
      }
    }
  };
  xhttp.open("POST", "ajax1.php"); // SELECT COUNT(*)
  xhttp.send();
}

window.addEventListener('load', function() {
  setInterval( ajax, 250 );
});

This uses the ajax function to store the data, as functions are also objects. So the first time it will load the data, it will set the original values, the next times, it will compare the responseText with the value previously saved as a property on the ajax function.


问:
c# invalid win32 application
Okay so I've read about, tried fair few solutions but still haven't managed to resolve this problem.

My application when testing on a 32bit machine (I've only tested on 1) instantly crashes on startup with invalid 32 application and no other error messages or information for guidance.

The application is a c# .NET 4.5.2; built in visual studio 2017. I've set it to X86 in the build configuration and the application runs on my 64bit development machine.

For test purposes I made a 32bit windows 7 virtual machine, built the solution and copied everything in the output bin folder to this virtual 32bit windows 7 machine. It runs fine, as expected. However, if I copy that exact folder to the physical 32bit machine, it crashes saying invalid 32bit application.

I even put a condition in to check the IntPtr.Size is 4, to assure my application is running in 32bit.

That made me think maybe a resource is built in 64bit, but if thats the case why would it run in the 32bit virtual environment. O.o

I'm going to try and find another physical 32 bit machine to test on.

Any guidance on how I can troubleshoot, or retrieve more information on the error would be great.

The physical machine has dot net 4.5.2 installed and 99.99% sure vcredist_x86 is also installed.

答:
Not sure why my question has been negative points... But this has now been resolved. </p>

<p>The problem was that Team-viewer was corrupting the files somehow while transferring them. I tried to transfer the files zipped and noticed that the zip was strangely small and not opening. So I went into the office and did the swap by USB and BAM. Working. Annoying or what. </p>

Title: c# invalid win32 application

Body:
Not sure why my question has been negative points... But this has now been resolved.

The problem was that Team-viewer was corrupting the files somehow while transferring them. I tried to transfer the files zipped and noticed that the zip was strangely small and not opening. So I went into the office and did the swap by USB and BAM. Working. Annoying or what.


问:
Treating 1D array (pointer) as 3D matrix at run time in C
I receive some image data as unsigned char *image = load_image(…);

This data is a 3D matrix: x (char),y (char) and channel (RGB) (char).

How can I access each element as image[x][y][channel]?

e.g. row 999, column 10000, green channel: image[999][10000][1]

Clarifications:

I'd like to use C multi-dimensional array syntax:

array[x][y][z], not array[x * height * channels + y * channels + z]

I can access a 1D array as a 2D array:

unsigned char (*imageMatrix)[height] = (unsigned char (*)[height])image
  imageMatrix[x][y] = 100

答:
If you can use this: unsigned char (*imageMatrix)[height] = (unsigned char (*)[height])image,, then your compiler supports Variable Length Arrays. VLA were introduced in C99 but were made back optional in C11.

But when VLA are supported, you can alias a 1D array to a 3D array exactly the same you alias it to a 2D array:

```<code>unsigned char (*imageMatrix)[width][channel] = (unsigned char (*)[width][channel])image;
imageMatrix[x][y][channel] = 100;
</code>```

Body:
If you can use this: unsigned char (*imageMatrix)[height] = (unsigned char (*)[height])image,, then your compiler supports Variable Length Arrays. VLA were introduced in C99 but were made back optional in C11.

But when VLA are supported, you can alias a 1D array to a 3D array exactly the same you alias it to a 2D array:

unsigned char (*imageMatrix)[width][channel] = (unsigned char (*)[width][channel])image;
imageMatrix[x][y][channel] = 100;