问:
Object.assign - Update Specific Property
Using React & Redux here:

My State looks something similar to this:

```<code>State : {
   First : {
      prop1 : "a",
      prop2 : "b"
   },
   ...
   Last : {
      prop1 : "c",
      prop2 : "d"
   }
}
</code>```

My Reducer function looks like this:

```<code>const tabsState = ( state = initialTabState, action ) => {
    switch( action.type ) {
    case( ENABLE_TAB ):
        return (
            Object.assign( {}, state, action.payload )
        );
    default:
        return state;
    }
};
</code>```

For the action.payload, I only want to send data containing new values for prop1. My understanding of Object.assign is that the sources parameters only update the props, they do not over-write the objects in state, is that correct?

In the above, My action.payload is similar to this:

```<code>   First : {
      prop1 : "z"
   },
   Second : {
      prop2 : "x"
   },
   ...
</code>```

It seems to be overwriting the First & subsequent objects within the State object. That is to say, that the new State returned by the Reducer does not have the 2nd prop of each object. prop2s

答:
Let's say you have a state that looks like this:

```<code>{
  state: {
    meta: {
      data: {
        foo: 'bar',
      },
    },
  },
}
</code>```

And you want it to look like this:

```<code>{
  state: {
    meta: {
      data: {
        foo: 'bar',
        hello: 'world',
      },
    },
  },
}
</code>```

First, create a function to update the nested property you want to get at:

```<code>const update = (data, obj) => {
  return Object.assign(
    {},
    data,
    obj,
  )
}
</code>```

And then, call that update function like this:

```<code>return Object.assign(
  {},
  state,
  {
    meta: {
      data: update(state.meta.data, {hello: 'world'}),
    },
  },
)
</code>```

Body:
Using React & Redux here:

My State looks something similar to this:

State : {
   First : {
      prop1 : "a",
      prop2 : "b"
   },
   ...
   Last : {
      prop1 : "c",
      prop2 : "d"
   }
}

My Reducer function looks like this:

const tabsState = ( state = initialTabState, action ) => {
    switch( action.type ) {
    case( ENABLE_TAB ):
        return (
            Object.assign( {}, state, action.payload )
        );
    default:
        return state;
    }
};

For the action.payload, I only want to send data containing new values for prop1. My understanding of Object.assign is that the sources parameters only update the props, they do not over-write the objects in state, is that correct?

In the above, My action.payload is similar to this:

   First : {
      prop1 : "z"
   },
   Second : {
      prop2 : "x"
   },
   ...

It seems to be overwriting the First & subsequent objects within the State object. That is to say, that the new State returned by the Reducer does not have the 2nd prop of each object. prop2s

Body:
Let's say you have a state that looks like this:

{
  state: {
    meta: {
      data: {
        foo: 'bar',
      },
    },
  },
}

And you want it to look like this:

{
  state: {
    meta: {
      data: {
        foo: 'bar',
        hello: 'world',
      },
    },
  },
}

First, create a function to update the nested property you want to get at:

const update = (data, obj) => {
  return Object.assign(
    {},
    data,
    obj,
  )
}

And then, call that update function like this:

return Object.assign(
  {},
  state,
  {
    meta: {
      data: update(state.meta.data, {hello: 'world'}),
    },
  },
)


来源: stackexchange

问:
Snapping an object to another object vertex in Maya over Python Script
I want to snap / align an object A to vertex of object B. I have tried using below script but its not snapping exactly to the vertex but snapping with an offset. Can any one suggest me a solution. Here are the snapshots.

```<code>import maya.cmds as cmds

vertices = [];
srcObj = "pCone1";

def snapToVertex(vertex,object):

    cmds.select(vertex);
    x,y,z = cmds.pointPosition();
    cmds.select(object);
    cmds.duplicate();
    cmds.move(x,y,z);

def processTask():

    cmds.select( cmds.polyListComponentConversion( tv=True ) );
    vertices = cmds.ls(sl = True);

    print vertices;
    for vrtx in vertices:
        snapToVertex(vrtx,srcObj);

processTask();
</code>```

Snapped with my above Script, Which didn't snap exactly to vertex.

But it should be snapped exactly to the Vervex's as below image.

答:
you could greatly simplify your code and only use a few commands

```<code>import maya.cmds as mc

verts = mc.ls(os=True)
src = 'pCone1'
base_name = 'fancy_cone'

for i, vert in enumerate(verts):
    dup = mc.duplicate(src, n='%s_%s' %(base_name, i))[0]
    mc.xform(dup, ws=True, t=mc.xform(vert, q=True, ws=True, t=True))
</code>```

keep in mind a few caveats:

1) this is assuming that the pivot of your source cone is at the tip with the tip at the origin... so it requires setting up that source cone the way you want it as if the origin point is a vertex you will be snapping it to. This would also be beneficial if the object you're 'pinning' to is rotated (no need to do any kind of vector math to determine the positional offset that way)

2) to use the orderedSelection (os) flag in the ls command, you need to be sure track selection order is turned on in your maya preferences under the selection sub section - this way you can select the verts you want in the order you want them to be created (top-down, bottum-up, whatever) instead of the vert index order

This should also be significantly faster - by tracking any created objects, you don't actually need to select anything and can manipulate the objects directly.  I also put it all into one loop without any function calls which would be faster (although, you probably won't notice it unless you're making a LOOOOOOT of these).

Depending on your needs though, you may actually want to utilize a snapping function multiple places; However, I would suggest keeping the duplication out of it in case there are situations you want to snap without duplicating.

Something like this (subject to same caveats as above):

```<code>import maya.cmds as mc

def snapToVertex(vertex, object):
    pos = mc.xform(vertex, q=True, ws=True, t=True)
    mc.xform(object, ws=True, t=pos)  # combine to single line if prefered

def processTask():
    verts = mc.ls(os=True)
    src = 'pCone1'
    base_name = 'fancy_cone'

    for i, vert in enumerate(verts):
        dup = mc.duplicate(src, n='%s_%s' %(base_name, i))[0]
        snapToVertex(vert, dup)

processTask()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to snap / align an object A to vertex of object B. I have tried using below script but its not snapping exactly to the vertex but snapping with an offset. Can any one suggest me a solution. Here are the snapshots.

import maya.cmds as cmds

vertices = [];
srcObj = "pCone1";

def snapToVertex(vertex,object):

    cmds.select(vertex);
    x,y,z = cmds.pointPosition();
    cmds.select(object);
    cmds.duplicate();
    cmds.move(x,y,z);

def processTask():

    cmds.select( cmds.polyListComponentConversion( tv=True ) );
    vertices = cmds.ls(sl = True);

    print vertices;
    for vrtx in vertices:
        snapToVertex(vrtx,srcObj);

processTask();

Snapped with my above Script, Which didn't snap exactly to vertex.

But it should be snapped exactly to the Vervex's as below image.

Body:
you could greatly simplify your code and only use a few commands

import maya.cmds as mc

verts = mc.ls(os=True)
src = 'pCone1'
base_name = 'fancy_cone'

for i, vert in enumerate(verts):
    dup = mc.duplicate(src, n='%s_%s' %(base_name, i))[0]
    mc.xform(dup, ws=True, t=mc.xform(vert, q=True, ws=True, t=True))

keep in mind a few caveats:

1) this is assuming that the pivot of your source cone is at the tip with the tip at the origin... so it requires setting up that source cone the way you want it as if the origin point is a vertex you will be snapping it to. This would also be beneficial if the object you're 'pinning' to is rotated (no need to do any kind of vector math to determine the positional offset that way)

2) to use the orderedSelection (os) flag in the ls command, you need to be sure track selection order is turned on in your maya preferences under the selection sub section - this way you can select the verts you want in the order you want them to be created (top-down, bottum-up, whatever) instead of the vert index order

This should also be significantly faster - by tracking any created objects, you don't actually need to select anything and can manipulate the objects directly.  I also put it all into one loop without any function calls which would be faster (although, you probably won't notice it unless you're making a LOOOOOOT of these).

Depending on your needs though, you may actually want to utilize a snapping function multiple places; However, I would suggest keeping the duplication out of it in case there are situations you want to snap without duplicating.

Something like this (subject to same caveats as above):

import maya.cmds as mc

def snapToVertex(vertex, object):
    pos = mc.xform(vertex, q=True, ws=True, t=True)
    mc.xform(object, ws=True, t=pos)  # combine to single line if prefered

def processTask():
    verts = mc.ls(os=True)
    src = 'pCone1'
    base_name = 'fancy_cone'

    for i, vert in enumerate(verts):
        dup = mc.duplicate(src, n='%s_%s' %(base_name, i))[0]
        snapToVertex(vert, dup)

processTask()


问:
pynput Keyboard Listener returns shift when shift is pressed, but does not modify shift_pressed
I've got a simple program to familiarize myself with Keyboard Listeners using pynput. What it does is not important. What is important is that the shift_pressed attribute never seems to change to True. My program currently looks like this:

```<code>from pynput.keyboard import Controller, Listener

boo = True
keyboard = Controller()

fib_lst = [0, 1]

def on_press(key):
    print(key)
    print(keyboard.shift_pressed)

Listener(on_press=on_press).start()

while boo:
    nxt = fib_lst[-1] + fib_lst[-2]
    input(nxt)
    fib_lst.append(nxt)
</code>```

I'm trying to do something like this in on_press (or on_release):

```<code>def on_press(key):
    if key == Key.delete:
        if keyboard.shift_pressed:
            func1()

        else:
            func2()
</code>```

This code should perform func1 when shift is pressed or func2 if it is not. But it is currently only doing func2 since shift_pressed is perpetually false. What can I do differently to get shift_pressed to work as it should?

Edit 1: Specified the desired end result more clearly.

Edit 2: Changed the appending string to two different functions to add more clarity.

Edit 3: Changed the parameters of the final question to match the more recent example

答:
I'm not hundred percent sure but when I have worked with pynput I noticed that I can handle action on key release, not key press so you can try something like below:

```<code>from pynput import keyboard

def on_press(key):
    if key == keyboard.Key.shift: # handles if key press is shift
        print('foo', end='')

def on_release(key):
    if key == keyboard.Key.shift:
        print()
    elif key == keyboard.Key.delete:
        print('bar')
    elif key == keyboard.Key.esc:
        return False

def get_current_key_input():
    with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()

get_current_key_input()
</code>```

if you need any other help let me know with your specific motive.

Body:
I've got a simple program to familiarize myself with Keyboard Listeners using pynput. What it does is not important. What is important is that the shift_pressed attribute never seems to change to True. My program currently looks like this:

from pynput.keyboard import Controller, Listener

boo = True
keyboard = Controller()

fib_lst = [0, 1]

def on_press(key):
    print(key)
    print(keyboard.shift_pressed)

Listener(on_press=on_press).start()

while boo:
    nxt = fib_lst[-1] + fib_lst[-2]
    input(nxt)
    fib_lst.append(nxt)

I'm trying to do something like this in on_press (or on_release):

def on_press(key):
    if key == Key.delete:
        if keyboard.shift_pressed:
            func1()

        else:
            func2()

This code should perform func1 when shift is pressed or func2 if it is not. But it is currently only doing func2 since shift_pressed is perpetually false. What can I do differently to get shift_pressed to work as it should?

Edit 1: Specified the desired end result more clearly.

Edit 2: Changed the appending string to two different functions to add more clarity.

Edit 3: Changed the parameters of the final question to match the more recent example

Body:
I'm not hundred percent sure but when I have worked with pynput I noticed that I can handle action on key release, not key press so you can try something like below:

from pynput import keyboard

def on_press(key):
    if key == keyboard.Key.shift: # handles if key press is shift
        print('foo', end='')

def on_release(key):
    if key == keyboard.Key.shift:
        print()
    elif key == keyboard.Key.delete:
        print('bar')
    elif key == keyboard.Key.esc:
        return False

def get_current_key_input():
    with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()

get_current_key_input()

if you need any other help let me know with your specific motive.


问:
Powershell or cmd - How to search for a file on client and replace with a different file on network share?
We are looking to replace the defaultlayouts.xml for all profiles when upgrading to Windows 10 Pro v. 1607.  This will be accomplished with SCCM site-wide.  We have the new layoutmodification.xml configured and ready for deployment however, we are struggling to push this to all profiles due to the variation of users on a client machine.  No issues deploying to the 'default' profile.

The defaultlayouts.xml lives here: C:\Users\johndoe\AppData\Local\Microsoft\Windows\Shell

The variable will be johndoe.

Multiple users' profiles may exist on the client, so we need to search the 'c:\users' folder for the defaultlayouts.xml in each user's profile.

If the file exists in any of the profiles we want to delete it then copy the layoutmodification.xml from a network share.

I have experience in scripting, powershell and SCCM. Any ideas, thoughts, comments, and recommendations would be greatly appreciated.

Thank you!

答:
Find all defaultlayouts.xml files in C:\Users. Then delete each item and copy layoutmodification.xml file from networkshare.

```<code>Get-ChildItem C:\Users\*\AppData\Local\Microsoft\Windows\shell\defaultlayouts.xml  | ForEach-Object {
    Remove-Item $_.FullName
    Copy-Item \\server\layoutmodification.xml  $(Split-Path $_.FullName)
}
</code>```

EDIT: Changed to wildcard path -> C:\Users*\AppData\Local\Microsoft\Windows\shell\defaultlayouts.xml from just C:\Users\ -recurse

Thank you Noah Sparks

Body:
Find all defaultlayouts.xml files in C:\Users. Then delete each item and copy layoutmodification.xml file from networkshare.

Get-ChildItem C:\Users\*\AppData\Local\Microsoft\Windows\shell\defaultlayouts.xml  | ForEach-Object {
    Remove-Item $_.FullName
    Copy-Item \\server\layoutmodification.xml  $(Split-Path $_.FullName)
}

EDIT: Changed to wildcard path -> C:\Users*\AppData\Local\Microsoft\Windows\shell\defaultlayouts.xml from just C:\Users\ -recurse

Thank you Noah Sparks


问:
Laravel 5.2 Storage::makeDirectory($dir) is not creating directory
I am getting confused with this logic. I am using Laravel 5.2 Storage::makeDirectory to create two paths, first (video/) is created correctly and the other (thumbnails/) don't.

```<code>$user = 1;

if(!File::exists(public_path() . "/video/$user"))
{
    Storage::makeDirectory(public_path() . "/video/$user", 0777);
}

$file = rand(1111111111111, 9999999999999);
$imgpath = public_path() . "/thumbnails/$file";

if(!File::exists($imgpath))
{
    Storage::makeDirectory($imgpath, 0777);
}
</code>```

Here is the permission configuration:

```<code>drwxrwxrwx 2 ubuntu ubuntu 4096 Jun 28 19:33 thumbnails/
drwxrwxrwx 3 ubuntu ubuntu 4096 Jun 29 15:21 video/
</code>```

I also could create a directory from cli with the given string from $imgpath:

```<code>mkdir /home/ubuntu/workspace/site/public/thumbnails/6300643852187
</code>```

Any suggestions?

答:
You need to force it to do it like this

```<code>$dr = $_SERVER['DOCUMENT_ROOT'];
$is_dir = File::makeDirectory($dr.'/uploads/images/'.$user.'/thumbs/', 0755, true, true);
</code>```

0755 is folder permissions

1st true  is recursive creation of folders

2nd true is to force it to do it

Body:
I am getting confused with this logic. I am using Laravel 5.2 Storage::makeDirectory to create two paths, first (video/) is created correctly and the other (thumbnails/) don't.

$user = 1;

if(!File::exists(public_path() . "/video/$user"))
{
    Storage::makeDirectory(public_path() . "/video/$user", 0777);
}

$file = rand(1111111111111, 9999999999999);
$imgpath = public_path() . "/thumbnails/$file";

if(!File::exists($imgpath))
{
    Storage::makeDirectory($imgpath, 0777);
}

Here is the permission configuration:

drwxrwxrwx 2 ubuntu ubuntu 4096 Jun 28 19:33 thumbnails/
drwxrwxrwx 3 ubuntu ubuntu 4096 Jun 29 15:21 video/

I also could create a directory from cli with the given string from $imgpath:

mkdir /home/ubuntu/workspace/site/public/thumbnails/6300643852187

Any suggestions?

Body:
You need to force it to do it like this

$dr = $_SERVER['DOCUMENT_ROOT'];
$is_dir = File::makeDirectory($dr.'/uploads/images/'.$user.'/thumbs/', 0755, true, true);

0755 is folder permissions

1st true  is recursive creation of folders

2nd true is to force it to do it


问:
Jquery toggle not working when toggling back
I am using jquery toggle, to show one image and then when the user clicks on an element, change to another image and if they click again show the original image. Like an open close kind of thing. It works when I first click, but nothing after that. Here is my jquery

```<code> $(".filterInventory").on("click", function () {

    $(".inventory-search").toggle();
    $(".filer-arrow.down").hide();
    $(".filer-arrow.up").show();

    return false;

});
</code>```

and here is the HTML

```<code><div class="container container-padding-top inventory-search-button">
        <div class="row">
            <div class="col-md-12">
                <a href="#" class="filterInventory">Filter <img src="~/Images/icons/down-arrow-white.png" class="filer-arrow down" alt="Filter Arrow" /><img src="~/Images/icons/up-arrow-white.png" class="filer-arrow up" alt="Filter Arrow" /></a>
            </div>
        </div>
    </div>
</code>```

CSS:

```<code>#communities a.filterInventory img.up {
    display: none;
}

#communities .filterInventory .filer-arrow {
    height: 10px;
}
</code>```

答:
Hide one image initially and then on click toggle images.

How about this approach ?

HTML:

```<code><div id="infoToggler"><img src="https://lorempixel.com/400/200/sports/Dummy-Text"/>
<img src="https://lorempixel.com/400/200/abstract/Dummy-Text" style="display:none"/>
</div>
</code>```

JS:

```<code>$("#infoToggler").click(function() {
  $(this).find('img').toggle();
});
</code>```

http://jsfiddle.net/M9QBb/522/

Body:
I am using jquery toggle, to show one image and then when the user clicks on an element, change to another image and if they click again show the original image. Like an open close kind of thing. It works when I first click, but nothing after that. Here is my jquery

 $(".filterInventory").on("click", function () {

    $(".inventory-search").toggle();
    $(".filer-arrow.down").hide();
    $(".filer-arrow.up").show();

    return false;

});

and here is the HTML

                Filter

CSS:

#communities a.filterInventory img.up {
    display: none;
}

#communities .filterInventory .filer-arrow {
    height: 10px;
}

Body:
Hide one image initially and then on click toggle images.

How about this approach ?

HTML:

<div id="infoToggler"><img src="https://lorempixel.com/400/200/sports/Dummy-Text"/>
<img src="https://lorempixel.com/400/200/abstract/Dummy-Text" style="display:none"/>
</div>

JS:

$("#infoToggler").click(function() {
  $(this).find('img').toggle();
});

http://jsfiddle.net/M9QBb/522/


问:
Converting LPSTR to LPCTSTR
I have a program I am modifying to take command line argument as a variable of the type LPSTR. Currently the value is hardcoded in the program and passes to the desired function in the form _T("program.exe"). The function expects the type LPCTSTR. I have tried to cast my command line argument from a LPSTR to a LPCTSTR to no avail. Similar attempts using a char* as an intermediary have also failed. I know I am probably missing something stupidly simple, but at this point I would appreciate the help.

答:
Normally LPSTR should convert to LPCTSTR.

However, it’s obviously not in your case, so stating that doesn’t help anyone.

If you’re using Visual Studio, got to Project ⟩ [Project Name] Properties ⟩ Configuration Properties ⟩ General ⟩ Project Defaults and change the value of Character Set to ‘Use Multi-Byte Character Set’

If you’re using a custom .vcxproj file, inside of each

```<code><PropertyGroup Condition= "'$(Configuration)|$(Platform)'=='[Configuration]|[Platform]'" Label="Configuration"></PropertyGroup>
</code>```

you will need to add a line that says:

```<code><CharacterSet>MultiByte</CharacterSet>
</code>```

If you already have a <CharacterSet> in there, then simply change its value to 'MultiByte'.

Title: Converting LPSTR to LPCTSTR

Body:
Normally LPSTR should convert to LPCTSTR.

However, it’s obviously not in your case, so stating that doesn’t help anyone.

If you’re using Visual Studio, got to Project ⟩ [Project Name] Properties ⟩ Configuration Properties ⟩ General ⟩ Project Defaults and change the value of Character Set to ‘Use Multi-Byte Character Set’

If you’re using a custom .vcxproj file, inside of each

<PropertyGroup Condition= "'$(Configuration)|$(Platform)'=='[Configuration]|[Platform]'" Label="Configuration"></PropertyGroup>

you will need to add a line that says:

<CharacterSet>MultiByte</CharacterSet>

If you already have a <CharacterSet> in there, then simply change its value to 'MultiByte'.


问:
Batch file closes after a goto command
Here's the code</p>

```<code>@echo off
color 0a
:user_login
set /p username=What is your username?
if %username% == admin (
cls
 goto admin_request_password
)

echo Incorrect username please try again.
cls
goto user_login

:admin_request_password

set /p Password=What is your Encryption Key?:
if %Password% == ecca1924889236 (
pause
cls
goto admin_menu
pause
 )

echo Incorrect password
pause
cls
goto user_login

:admin_menu

echo Type acct_info for account info.
echo Type site_key for website file manager.
echo type ip_info for your ip info.
echo Type close to close the Net-Sec portal
goto admin_menu_process

:admin_menu_process
set /a choice=Waiting for Request:
if %choice% == acct_info (
cls
goto acct_info ) echo Incorrect term cls goto admin_menu

if %choice%  == site_key (
goto site_key  )echo Incorrect term
cls
goto admin_menu

if %choice% == ip_info (
goto ip_info ) echo Incorrect term
cls
goto admin_menu

if %choice% == close (
goto close ) echo Incorrect term
cls
goto admin_menu
:ip_info
ipconfig
pause
cls
goto admin_menu

:acct_info
echo Your username is: admin
echo your password is: ecca1924889236
pause
cls
goto admin_menu

:site_info
The username is: net-sec
The password is: netsec127
pause
cls
goto admin_menu

:close
cls
</code>```

答:
Suggestions:

Do not set a variable to %username% as that is already an existing system variable.

Enclose both strings with double quotes in a string comparison.

Use the choice command when you have a known set of choices.

Try not to include unnecessary labels.

Here is a rewrite of your code to hopefully help you in your scripting exploits:

@Echo Off
Color 0A

:getName
ClS
Set/P "uname=What is your username? "
If /I Not "%uname%"=="admin" (Echo Incorrect username please try again.
    >Nul Timeout 3
    GoTo getName)

:getPass
ClS
Set/P "password=What is your encryption key? "
If Not "%password%"=="ecca1924889236" (Echo Incorrect password please try again.
    >Nul Timeout 3
    GoTo getPass)

:menu
ClS
Echo [1] Account information.
Echo [2] Website File Manager.
Echo [3] IP information.
Echo [4] Close the Net-Sec portal.

Choice /C 1234 /M "Enter your request"

If ErrorLevel 4 GoTo close
If ErrorLevel 3 GoTo ip_info
If ErrorLevel 2 GoTo site_info
If ErrorLevel 1 GoTo acct_info

GoTo :EOF

:acct_info
Echo Your username is: admin
Echo your password is: ecca1924889236
Timeout 3
GoTo menu

:site_info
Echo The username is: net-sec
Echo The password is: netsec127
Timeout 3
GoTo menu

:ip_info
IPConfig
Timeout -1
GoTo menu

:close
ClS
Echo Closing...
Timeout 3
```

Title: Batch file closes after a goto command

Body:
Here's the code

@echo off
color 0a
:user_login
set /p username=What is your username?
if %username% == admin (
cls
 goto admin_request_password
)

echo Incorrect username please try again.
cls
goto user_login

:admin_request_password

set /p Password=What is your Encryption Key?:
if %Password% == ecca1924889236 (
pause
cls
goto admin_menu
pause
 )

echo Incorrect password
pause
cls
goto user_login

:admin_menu

echo Type acct_info for account info.
echo Type site_key for website file manager.
echo type ip_info for your ip info.
echo Type close to close the Net-Sec portal
goto admin_menu_process

:admin_menu_process
set /a choice=Waiting for Request:
if %choice% == acct_info (
cls
goto acct_info ) echo Incorrect term cls goto admin_menu

if %choice%  == site_key (
goto site_key  )echo Incorrect term
cls
goto admin_menu

if %choice% == ip_info (
goto ip_info ) echo Incorrect term
cls
goto admin_menu

if %choice% == close (
goto close ) echo Incorrect term
cls
goto admin_menu
:ip_info
ipconfig
pause
cls
goto admin_menu

:acct_info
echo Your username is: admin
echo your password is: ecca1924889236
pause
cls
goto admin_menu

:site_info
The username is: net-sec
The password is: netsec127
pause
cls
goto admin_menu

:close
cls


问:
Using locals() and format() method for strings: are there any caveats?
Are there any disadvantages, caveats or bad practice warnings about using the following pattern?

```<code>def buildString(user, name = 'john', age=22):
    userId = user.getUserId()
    return "Name: {name}, age: {age}, userid:{userId}".format(**locals())
</code>```

I had a very repetitive string generation code to write and was tempted to use this, but something about using locals() makes me uncomfortable. Is there any danger of unexpected behavior in this?

Edit: context

I found myself constantly writing stuff like:

```<code>"{name} {age} {userId} {etc}...".format(name=name, age=age, userId=userId, etc=etc)
</code>```

答:
There is now an official way to do this, as of Python 3.6.0: formatted string literals.

It works like this:

```<code>f'normal string text {local_variable_name}'
</code>```

E.g. instead of these:

```<code>"hello %(name) you are %(age) years old" % locals()
"hello {name} you are {age} years old".format(**locals())
"hello {name} you are {age} years old".format(name=name, age=age)
</code>```

just do this:

```<code>f"hello {name} you are {age} years old"
</code>```

Here's the official example:

```<code>>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}"  # nested fields
'result:      12.35'
</code>```

Reference:

Python 3.6 What's New

PEP 498

Lexical analysis description

Body:
Are there any disadvantages, caveats or bad practice warnings about using the following pattern?

def buildString(user, name = 'john', age=22):
    userId = user.getUserId()
    return "Name: {name}, age: {age}, userid:{userId}".format(**locals())

I had a very repetitive string generation code to write and was tempted to use this, but something about using locals() makes me uncomfortable. Is there any danger of unexpected behavior in this?

Edit: context

I found myself constantly writing stuff like:

"{name} {age} {userId} {etc}...".format(name=name, age=age, userId=userId, etc=etc)

Body:
There is now an official way to do this, as of Python 3.6.0: formatted string literals.

It works like this:

f'normal string text {local_variable_name}'

E.g. instead of these:

"hello %(name) you are %(age) years old" % locals()
"hello {name} you are {age} years old".format(**locals())
"hello {name} you are {age} years old".format(name=name, age=age)

just do this:

f"hello {name} you are {age} years old"

Here's the official example:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}"  # nested fields
'result:      12.35'

Reference:

Python 3.6 What's New

PEP 498

Lexical analysis description

ContentLicense: CC BY-SA 4.0


问:
Generate tiles from large photos (iOs PhotoScroller)
I'm studdying the WWDC session #104 for mastering UIScrollViews. I need to create a script or find a tool or write a script to generate the tiles needed for the CATiledLayer from some large jpg photo.

1000 500 and 250 scale factors are needed and the generated tiles need to respect a naming pattern like this:

```<code>name_scale_col_row.jpg
</code>```

Any suggestion for a tool or script that I could use for this or do I need to write one?

EDIT: I'm working on my own little bash script. This is what I did until now:

```<code>#!/bin/sh

file_list=`ls | grep png`

for i in 25 50 100; do
    for file in $file_list; do
        convert $file -scale ${i}%x${i}% -crop 256x256  \
        -set filename:tile "%[fx:page.x/256]_%[fx:page.y/256]" \
        +repage +adjoin "${file%.*}_${i}0_%[filename:tile].${file#*.}"
    done
done
</code>```

Of cours it's far from being a real tool but it works and respect the Apple photoscroller example naming convention for tiles. Any suggestion, improvement appreciated.

答:
This script will automatically generate all the tiles you need at all the different resolutions:

http://www.mikelin.ca/blog/2010/06/iphone-splitting-image-into-tiles-for-faster-loading-with-imagemagick/

A small heads up: that script will name everything with 100, 50, etc. scale factors rather than 1000, 500, etc. you can adjust for this by changing 1000 to 100 in the tileForScale: method in TilingView.m in the PhotoScroller example.

ContentLicense: CC BY-SA 2.5

Body:
I'm studdying the WWDC session #104 for mastering UIScrollViews. I need to create a script or find a tool or write a script to generate the tiles needed for the CATiledLayer from some large jpg photo.

1000 500 and 250 scale factors are needed and the generated tiles need to respect a naming pattern like this:

name_scale_col_row.jpg

Any suggestion for a tool or script that I could use for this or do I need to write one?

EDIT: I'm working on my own little bash script. This is what I did until now:

#!/bin/sh

file_list=`ls | grep png`

for i in 25 50 100; do
    for file in $file_list; do
        convert $file -scale ${i}%x${i}% -crop 256x256  \
        -set filename:tile "%[fx:page.x/256]_%[fx:page.y/256]" \
        +repage +adjoin "${file%.*}_${i}0_%[filename:tile].${file#*.}"
    done
done

Of cours it's far from being a real tool but it works and respect the Apple photoscroller example naming convention for tiles. Any suggestion, improvement appreciated.


问:
How to serialize data to a given file using ujson library in python
I am using below code to generate json file.

```<code>f = open("test.txt", 'r')
buffer = f.readlines()
rec_cnt = 1
with open("test.json", "w") as ujson_file:
for line in buffer:
    data_dict[rec_cnt] = {line}
    if rec_cnt == 100:
        ujson.dump(data_dict.values(), ujson_file)
        data_dict.clear()
rec_cnt +=1
f.close()
ujson_file
</code>```

The issue is whenever I do it by batch, each batch of records are enclosed with [], which is forming an invalid json file.

for example
Input file will be

```<code> fruits      Orange       Apple        Kiwi        Banana     Veggies     Tomato       Potatoe      Carrot      Peas       Bigfruits   WaterMelon   cantaloupes  Papaya      melon
</code>```

output file should be:

```<code>[{Key:fruits, Values: [Orange, Apple, Kiwi, Banana]}][{Key:Veggies, Values: [Tomato, Potatoe, Carrot, Peas]}][{Key:Bigfruits, Values: [WaterMelon, cantaloupes, Papaya, melon]}]
</code>```

Any suggestions of serializing the data with only one '[]' or without '[]'

答:
I don't normally write entire scripts for people but I've been finding myself sitting around waiting for batch processes to finish all week.

Try this instead. It accounts for the failure case I mentioned earlier, is much easier to read and should accomplish what you're looking for.

```<code>import ujson

# Define what our keys are
keys = ('fruits', 'veggies', 'bigfruits')

# Define how big we want each batch
batch_size = 100

# Define a method to write a list out to a json file
# (I think the way you did this is the original source of your problem)
def flush(objs):
    with open("test.json", "wb") as ujson_file:
        ujson.dump(objs, ujson_file, indent=4)

# Use a context manager to handle file I/O
with open('test.txt', 'rb') as input_source:

    # Create somewhere to put stuff to write to file
    output = []

    # Don't read the entire file into memory, you may run
    # out of memory with larger files...
    # buffer = f.readlines()

    # ...instead, load it line by line.
    for line in input_source:
        data = {}

        # Parse the line, make it a list we can iterate through
        line = line.split(' ')

        # Look through the list, store any value that isn't a known key
        current_key = None
        for term in line:
            # Erase spaces
            term = term.strip()
            # If it's a blank "word", skip it
            if not term:
                continue

            # If it's a key, let's start a new list
            elif term.lower() in keys: # Lowercase the term just in case capitalization is inconsistent
                data[term] = []
                current_key = term

            # We know the current key we're working with; add this to that list
            else:
                data[current_key].append(term)

        # Add the dict to our output buffer
        output.append(data)

        # If we've written enough to flush, flush it
        if len(output) >= batch_size:
            flush(output)

     # We've reached the end of the file. If we have anything left to flush,
     # do it now.
     flush(output)
</code>```

Body:
I am using below code to generate json file.

f = open("test.txt", 'r')
buffer = f.readlines()
rec_cnt = 1
with open("test.json", "w") as ujson_file:
for line in buffer:
    data_dict[rec_cnt] = {line}
    if rec_cnt == 100:
        ujson.dump(data_dict.values(), ujson_file)
        data_dict.clear()
rec_cnt +=1
f.close()
ujson_file

The issue is whenever I do it by batch, each batch of records are enclosed with [], which is forming an invalid json file.

for example
Input file will be

 fruits      Orange       Apple        Kiwi        Banana     Veggies     Tomato       Potatoe      Carrot      Peas       Bigfruits   WaterMelon   cantaloupes  Papaya      melon

output file should be:

[{Key:fruits, Values: [Orange, Apple, Kiwi, Banana]}][{Key:Veggies, Values: [Tomato, Potatoe, Carrot, Peas]}][{Key:Bigfruits, Values: [WaterMelon, cantaloupes, Papaya, melon]}]

Any suggestions of serializing the data with only one '[]' or without '[]'

Body:
I don't normally write entire scripts for people but I've been finding myself sitting around waiting for batch processes to finish all week.

Try this instead. It accounts for the failure case I mentioned earlier, is much easier to read and should accomplish what you're looking for.

import ujson

# Define what our keys are
keys = ('fruits', 'veggies', 'bigfruits')

# Define how big we want each batch
batch_size = 100

# Define a method to write a list out to a json file
# (I think the way you did this is the original source of your problem)
def flush(objs):
    with open("test.json", "wb") as ujson_file:
        ujson.dump(objs, ujson_file, indent=4)

# Use a context manager to handle file I/O
with open('test.txt', 'rb') as input_source:

    # Create somewhere to put stuff to write to file
    output = []

    # Don't read the entire file into memory, you may run
    # out of memory with larger files...
    # buffer = f.readlines()

    # ...instead, load it line by line.
    for line in input_source:
        data = {}

        # Parse the line, make it a list we can iterate through
        line = line.split(' ')

        # Look through the list, store any value that isn't a known key
        current_key = None
        for term in line:
            # Erase spaces
            term = term.strip()
            # If it's a blank "word", skip it
            if not term:
                continue

            # If it's a key, let's start a new list
            elif term.lower() in keys: # Lowercase the term just in case capitalization is inconsistent
                data[term] = []
                current_key = term

            # We know the current key we're working with; add this to that list
            else:
                data[current_key].append(term)

        # Add the dict to our output buffer
        output.append(data)

        # If we've written enough to flush, flush it
        if len(output) >= batch_size:
            flush(output)

     # We've reached the end of the file. If we have anything left to flush,
     # do it now.
     flush(output)


问:
Cargo run ignores the features specified to cargo build
I've compiled the Rust GTK examples this way:

$ cargo build --features gtk_3_10
```

<p>When I try to run the example, an error occurs:</p>

<pre class="lang-none prettyprint-override"><code>   $ cargo run --bin gtktest
    Compiling gtk-rs-examples v0.0.1 (file:///home/me123/rust/gtk_examples)
    Finished dev [unoptimized + debuginfo] target(s) in 0.39 secs
     Running `target/debug/gtktest`
This example only work with GTK 3.10 and later
Did you forget to build with `--features gtk_3_10`?
</code>```

How to fix that?

答:
You need to pass the features when calling cargo run:

cargo run --bin gtktest --features gtk_3_10
```

<p>You could also run the executable directly after building it:</p>

<pre class="lang-none prettyprint-override"><code>$ cargo build --bin gtktest --features gtk_3_10
$ ./target/debug/gtktest
</code>```

You can tell that your command isn't doing what you expect because the output says that your code is being recompiled:

Compiling gtk-rs-examples v0.0.1 (file:///home/me123/rust/gtk_examples)
```

Body:
I've compiled the Rust GTK examples this way:

$ cargo build --features gtk_3_10

When I try to run the example, an error occurs:

   $ cargo run --bin gtktest
    Compiling gtk-rs-examples v0.0.1 (file:///home/me123/rust/gtk_examples)
    Finished dev [unoptimized + debuginfo] target(s) in 0.39 secs
     Running `target/debug/gtktest`
This example only work with GTK 3.10 and later
Did you forget to build with `--features gtk_3_10`?

How to fix that?

Body:
You need to pass the features when calling cargo run:

cargo run --bin gtktest --features gtk_3_10

You could also run the executable directly after building it:

$ cargo build --bin gtktest --features gtk_3_10
$ ./target/debug/gtktest

You can tell that your command isn't doing what you expect because the output says that your code is being recompiled:

Compiling gtk-rs-examples v0.0.1 (file:///home/me123/rust/gtk_examples)


问:
Does XMLUnit have an assert to ignore whitespace
I want to compare two xml strings in a test, but the test keeps failing due to whitespace.</p>

```<code>@Test
public void testForEquality() throws Exception {
 String myControlXML = "<msg><uuid>0x00435A8C</uuid></msg>";
 String myTestXML = "<msg><uuid>0x00435A8C</uuid>      </msg>";
 assertXMLEqual(myControlXML, myTestXML);
 Diff diff = new Diff(myControlXML, myTestXML);
 assertTrue(diff.similar());
}
</code>```

答:
The API has changed with XMLUnit 2.x.

Now, for unit tests, you can ignore whitespace with a hamcrest matcher like so:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo;
...
assertThat(actual, isIdenticalTo(expected).ignoreWhitespace());
```

<p>Or alternatively, with the builder API directly:</p>

<pre class="lang-java prettyprint-override"><code>import org.xmlunit.builder.DiffBuilder;
...
boolean areDifferent = DiffBuilder.compare(left).withTest(right)
                                  .ignoreWhitespace().build().hasDifferences();
</code>```

Body:
I want to compare two xml strings in a test, but the test keeps failing due to whitespace.

@Test
public void testForEquality() throws Exception {
 String myControlXML = "<msg><uuid>0x00435A8C</uuid></msg>";
 String myTestXML = "<msg><uuid>0x00435A8C</uuid>      </msg>";
 assertXMLEqual(myControlXML, myTestXML);
 Diff diff = new Diff(myControlXML, myTestXML);
 assertTrue(diff.similar());
}

Body:
The API has changed with XMLUnit 2.x.

Now, for unit tests, you can ignore whitespace with a hamcrest matcher like so:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo;
...
assertThat(actual, isIdenticalTo(expected).ignoreWhitespace());

Or alternatively, with the builder API directly:

import org.xmlunit.builder.DiffBuilder;
...
boolean areDifferent = DiffBuilder.compare(left).withTest(right)
                                  .ignoreWhitespace().build().hasDifferences();


问:
C# numerical recipes
im begginer in C# and programming in general and i want to ask. I'm trying to make a project with datagridview in it and some calculations. Basicly what i want to do is from table of empirical data aproximate the data with chebyshev aproximation. Using code from numerical recipes i want to use this fuction, chebft and it looks like this:

```<code>void chebft(NRREAL a, NRREAL b, NRREAL c[], int n, NRREAL (*func)(NRREAL))
{
    int k,j;
    NRREAL fac,bpa,bma,*f;

    f=vector(0,n-1);
    bma=NR_1_2*(b-a);
    bpa=NR_1_2*(b+a);
    for (k=0;k<n;k++) {
    NRREAL y=cos(NR_PI*(k+NR_1_2)/n);
    f[k]=(*func)(y*bma+bpa);
    }
    fac=NR_2/n;
    for (j=0;j<n;j++) {
    NRZEAL sum=NR_0;
    for (k=0;k<n;k++)
        sum += f[k]*cos(NZ_PI*j*(k+NZ_1_2)/n);
    c[j]=fac*(NRREAL)sum;
    }
    free_vector(f,0,n-1);
}
</code>```

and i want it to use in C# so what i have so far:

```<code>public void chebft(double a, double b, double[] c, int n, double func)
    {
        int k,j;
        double fac, bpa, bma;

        double PI = 3.14159265358979323846;
        Vector f = new Vector(0, n - 1);
        bma = 0.5 * (b - a);
        bpa = 0.5 * (b - a);

        for (k = 0; k < n; k++)
        {
            double y = Math.Cos(PI*(k+0.5)/n);
            f[k] = (func)(y*bma+bpa);
        }

        fac = 2.0 / n;
        for (j = 0; j < n; j++)
        {
            double sum = 0.0;

            for (k = 0; k < n; k++)
            {
                sum += f[k] * Math.Cos(PI * j * (k + 0.5) / n);
                c[j] = fac * (double)sum;
            }
        }

    }
</code>```

I know there are mistakes in that func part and f[k] part, but i dont know how to fix them.

Thanks for help

答:
The translation appears to be relatively solid with one exception (leaving aside possible numeric issues that require some more advanced knowledge of the problem to diagnose):

The function pointer func accepts a double-valued parameter and returns a double. To pass such a lambda function in C#, which is essentially equivalent to a function pointer in C++, use the following form:

```<code>Func<double, double> func
</code>```

You can then call the function as follows:

```<code>f[k] = func(y*bma+bpa);
</code>```

More information can be found here.

Also note that you do not need to cast sum to a double in the final loop, as it already is a double, and that the Math class already defines the constant Math.PI.

Title: C# numerical recipes

Body:
im begginer in C# and programming in general and i want to ask. I'm trying to make a project with datagridview in it and some calculations. Basicly what i want to do is from table of empirical data aproximate the data with chebyshev aproximation. Using code from numerical recipes i want to use this fuction, chebft and it looks like this:

void chebft(NRREAL a, NRREAL b, NRREAL c[], int n, NRREAL (*func)(NRREAL))
{
    int k,j;
    NRREAL fac,bpa,bma,*f;

    f=vector(0,n-1);
    bma=NR_1_2*(b-a);
    bpa=NR_1_2*(b+a);
    for (k=0;k<n;k++) {
    NRREAL y=cos(NR_PI*(k+NR_1_2)/n);
    f[k]=(*func)(y*bma+bpa);
    }
    fac=NR_2/n;
    for (j=0;j<n;j++) {
    NRZEAL sum=NR_0;
    for (k=0;k<n;k++)
        sum += f[k]*cos(NZ_PI*j*(k+NZ_1_2)/n);
    c[j]=fac*(NRREAL)sum;
    }
    free_vector(f,0,n-1);
}

and i want it to use in C# so what i have so far:

public void chebft(double a, double b, double[] c, int n, double func)
    {
        int k,j;
        double fac, bpa, bma;

        double PI = 3.14159265358979323846;
        Vector f = new Vector(0, n - 1);
        bma = 0.5 * (b - a);
        bpa = 0.5 * (b - a);

        for (k = 0; k < n; k++)
        {
            double y = Math.Cos(PI*(k+0.5)/n);
            f[k] = (func)(y*bma+bpa);
        }

        fac = 2.0 / n;
        for (j = 0; j < n; j++)
        {
            double sum = 0.0;

            for (k = 0; k < n; k++)
            {
                sum += f[k] * Math.Cos(PI * j * (k + 0.5) / n);
                c[j] = fac * (double)sum;
            }
        }

    }

I know there are mistakes in that func part and f[k] part, but i dont know how to fix them.

Thanks for help

Body:
The translation appears to be relatively solid with one exception (leaving aside possible numeric issues that require some more advanced knowledge of the problem to diagnose):

The function pointer func accepts a double-valued parameter and returns a double. To pass such a lambda function in C#, which is essentially equivalent to a function pointer in C++, use the following form:

Func<double, double> func

You can then call the function as follows:

f[k] = func(y*bma+bpa);

More information can be found here.

Also note that you do not need to cast sum to a double in the final loop, as it already is a double, and that the Math class already defines the constant Math.PI.


问:
Show in a ListView a TextView and an Image from Firebase
I have in my Database this:

I want to display all the data into a ListView, I have no errors but is not showing me the text and the image. I have a ModelClass:

```<code>public class ModelClass {
String title,image;

public ModelClass(String title,String image) {
    this.image = image;
    this.title = title;
}

public ModelClass() {
}

public String getTitle() {return title;   }
public void setTitle(String title) {
    this.title = title;
}
public String getImage() {
    return image;
}
public void setImage(String image) {
    this.image = image;
}}
</code>```

An Adaptor:

```<code>public class MyAdapter extends ArrayAdapter<ModelClass> {
private Activity context;
private int resource;
private List<ModelClass> listImage;

public MyAdapter(@NonNull Activity context, @LayoutRes int resource, @NonNull List<ModelClass> objects) {
    super(context, resource, objects);
    this.context = context;
    this.resource = resource;
    listImage = objects;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();

    View v = inflater.inflate(resource, null);
    TextView tvName = (TextView) v.findViewById(R.id.txt_desert);
    ImageView img = (ImageView) v.findViewById(R.id.iv_desert);

    tvName.setText(listImage.get(position).getTitle());
    Glide.with(context).load(listImage.get(position).getImage()).into(img);

    return v;

}}
</code>```

And the class where is the ListView:

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

private DatabaseReference mDatabaseRef;
private List<ModelClass> imgList;
private ListView lv;
private MyAdapter myAdapter;
private ProgressDialog progressDialog;

@Override
protected void onCreate( Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_deserturi);

   imgList = new ArrayList<>();
   lv = (ListView) findViewById(R.id.blog_list);

   progressDialog = new ProgressDialog(this);
   progressDialog.setMessage("Please wait loading list image...");
   progressDialog.show();

   mDatabaseRef = FirebaseDatabase.getInstance().getReference("Data");

   mDatabaseRef.addValueEventListener(new ValueEventListener() {
       @Override
       public void onDataChange(DataSnapshot dataSnapshot) {
           progressDialog.dismiss();

           for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

               ModelClass img = snapshot.getValue(ModelClass.class);
               imgList.add(img);
           }

           myAdapter = new MyAdapter(Deserturi.this, R.layout.design_row, imgList);

           lv.setAdapter(myAdapter);
       }

       @Override
       public void onCancelled(DatabaseError databaseError) {

           progressDialog.dismiss();
       }
   });
</code>```

Can you please tell me what I did wrong?! Thanks

答:
Try this in your activity:

```<code>...
myAdapter = new MyAdapter(Deserturi.this, R.layout.design_row, imgList);
lv.setAdapter(myAdapter);

mDatabaseRef.addValueEventListener(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
       progressDialog.dismiss();

       for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

           ModelClass img = snapshot.getValue(ModelClass.class);
           myAdapter.addElement(img);
       }

       myAdapter.notifyDataSetChanged();
   }
</code>```

In your adapter:

```<code>public void addElement(ModelClass element) {

    listImage.add(element);
}
</code>```

And in your model:

```<code>public class ModelClass {
String Nume,imagine;
...
</code>```

Body:
I have in my Database this:

I want to display all the data into a ListView, I have no errors but is not showing me the text and the image. I have a ModelClass:

public class ModelClass {
String title,image;

public ModelClass(String title,String image) {
    this.image = image;
    this.title = title;
}

public ModelClass() {
}

public String getTitle() {return title;   }
public void setTitle(String title) {
    this.title = title;
}
public String getImage() {
    return image;
}
public void setImage(String image) {
    this.image = image;
}}

An Adaptor:

public class MyAdapter extends ArrayAdapter<ModelClass> {
private Activity context;
private int resource;
private List<ModelClass> listImage;

public MyAdapter(@NonNull Activity context, @LayoutRes int resource, @NonNull List<ModelClass> objects) {
    super(context, resource, objects);
    this.context = context;
    this.resource = resource;
    listImage = objects;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();

    View v = inflater.inflate(resource, null);
    TextView tvName = (TextView) v.findViewById(R.id.txt_desert);
    ImageView img = (ImageView) v.findViewById(R.id.iv_desert);

    tvName.setText(listImage.get(position).getTitle());
    Glide.with(context).load(listImage.get(position).getImage()).into(img);

    return v;

}}

And the class where is the ListView:

public class Deserturi extends AppCompatActivity {

private DatabaseReference mDatabaseRef;
private List<ModelClass> imgList;
private ListView lv;
private MyAdapter myAdapter;
private ProgressDialog progressDialog;

@Override
protected void onCreate( Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_deserturi);

   imgList = new ArrayList<>();
   lv = (ListView) findViewById(R.id.blog_list);

   progressDialog = new ProgressDialog(this);
   progressDialog.setMessage("Please wait loading list image...");
   progressDialog.show();

   mDatabaseRef = FirebaseDatabase.getInstance().getReference("Data");

   mDatabaseRef.addValueEventListener(new ValueEventListener() {
       @Override
       public void onDataChange(DataSnapshot dataSnapshot) {
           progressDialog.dismiss();

           for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

               ModelClass img = snapshot.getValue(ModelClass.class);
               imgList.add(img);
           }

           myAdapter = new MyAdapter(Deserturi.this, R.layout.design_row, imgList);

           lv.setAdapter(myAdapter);
       }

       @Override
       public void onCancelled(DatabaseError databaseError) {

           progressDialog.dismiss();
       }
   });

Can you please tell me what I did wrong?! Thanks

Body:
Try this in your activity:

...
myAdapter = new MyAdapter(Deserturi.this, R.layout.design_row, imgList);
lv.setAdapter(myAdapter);

mDatabaseRef.addValueEventListener(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
       progressDialog.dismiss();

       for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

           ModelClass img = snapshot.getValue(ModelClass.class);
           myAdapter.addElement(img);
       }

       myAdapter.notifyDataSetChanged();
   }

In your adapter:

public void addElement(ModelClass element) {

    listImage.add(element);
}

And in your model:

public class ModelClass {
String Nume,imagine;
...


问:
Perform swipe on screen using AccessibilityService
I want to perform swipe on screen using accessibility service.
i tried this but this only perform a single touch.
i know it is possible because when enable my service on device it says this service can perform swipe,touch,pinch etc.</p>

```<code>Point position=new Point(100,10);
GestureDescription.Builder builder = new GestureDescription.Builder();
Path p = new Path();
p.moveTo(position.x, position.y);
builder.addStroke(new GestureDescription.StrokeDescription(p, 100L, 50L));
GestureDescription gesture = builder.build();
boolean isDispatched =    dispatchGesture(gesture,gestureResultCallback,null);
</code>```

答:
Make sure you configured your service to perform gestures:

```<code>android:canPerformGestures="true"
</code>```

Setup your path correctly:

```<code>p.moveTo(position.x, position.y);
p.lineTo(position.x + 300, position.y);
</code>```

It only works on android 24 and above.

Body:
I want to perform swipe on screen using accessibility service.
i tried this but this only perform a single touch.
i know it is possible because when enable my service on device it says this service can perform swipe,touch,pinch etc.

Point position=new Point(100,10);
GestureDescription.Builder builder = new GestureDescription.Builder();
Path p = new Path();
p.moveTo(position.x, position.y);
builder.addStroke(new GestureDescription.StrokeDescription(p, 100L, 50L));
GestureDescription gesture = builder.build();
boolean isDispatched =    dispatchGesture(gesture,gestureResultCallback,null);

Body:
Make sure you configured your service to perform gestures:

android:canPerformGestures="true"

Setup your path correctly:

p.moveTo(position.x, position.y);
p.lineTo(position.x + 300, position.y);

It only works on android 24 and above.


问:
A web app with logins in a kiosk situation
We are looking at setting up an internal web application (ASP.NET MVC) as a kiosk for the employees that don't have a dedicated computer. We currently do not have this kiosk setup. Each employee will have their own login to look at some basic payroll information and request leaves of absence. This same web application will be used by the office workers with a dedicated PC at their desk.

I am going to go out on a limb and say that no matter how many times we tell the employees, the employees will not click log off when they walk away from the kiosk. What would you do to help prevent this from happening?

答:
The simple way is to use a little javascript.

Just have it set to something like 30 seconds of inactivity.  If the user hasn't clicked on anything have the javascript send it back to a login page.

Here's a link to get you started.


问:
How to filter on most recent value for specific column
Running a query that has multiple rows showing db table statistics, in both a before and after status after a scheduled job that runs on either Sat/Sun.

```<code>Select [batchNum] ,[RunDate] ,[tableName] ,[numberofRows] ,[dataSize]
FROM TableNames
ORDER BY RunDate ASC
</code>```

The before/after is differentiated by the batch number. So for example, this table has batch numbers 2-159. Where '158' is the 'before' job/batch from the scheduled job that ran this past weekend, and batch 159 would be the 'after.

```<code>    batchNum    RunDate             tableName   numberofRows    dataSize
    158         06/04/2017 04:30:51 TableData1  1700            104
    158         06/04/2017 04:30:51 TableData2  1276             99
    158         06/04/2017 04:30:51 TableData3  1700            157
    158         06/04/2017 04:30:51 TableData4   200             47

    159         06/04/2017 05:30:51 TableData1  1500             85
    159         06/04/2017 05:30:55 TableData2  1134             94
    159         06/04/2017 05:30:57 TableData3  1500            101
    159         06/04/2017 05:30:59 TableData4   167             40
</code>```

Since the batch will always be revolving, I'd like to filter this query to only return rows of most recent batchNum for the most recent weekend, any time i run it through out the year.

答:
Make a subquery with this in the select and all the other data you need:

```<code>ROW_NUMBER() OVER(PARTITION BY tableName ORDER BY batchNum DESC) [rownum]
</code>```

Then take WHERE rownum = 1 in the outer query

Body:
Running a query that has multiple rows showing db table statistics, in both a before and after status after a scheduled job that runs on either Sat/Sun.

Select [batchNum] ,[RunDate] ,[tableName] ,[numberofRows] ,[dataSize]
FROM TableNames
ORDER BY RunDate ASC

The before/after is differentiated by the batch number. So for example, this table has batch numbers 2-159. Where '158' is the 'before' job/batch from the scheduled job that ran this past weekend, and batch 159 would be the 'after.

    batchNum    RunDate             tableName   numberofRows    dataSize
    158         06/04/2017 04:30:51 TableData1  1700            104
    158         06/04/2017 04:30:51 TableData2  1276             99
    158         06/04/2017 04:30:51 TableData3  1700            157
    158         06/04/2017 04:30:51 TableData4   200             47

    159         06/04/2017 05:30:51 TableData1  1500             85
    159         06/04/2017 05:30:55 TableData2  1134             94
    159         06/04/2017 05:30:57 TableData3  1500            101
    159         06/04/2017 05:30:59 TableData4   167             40

Since the batch will always be revolving, I'd like to filter this query to only return rows of most recent batchNum for the most recent weekend, any time i run it through out the year.

Body:
Make a subquery with this in the select and all the other data you need:

ROW_NUMBER() OVER(PARTITION BY tableName ORDER BY batchNum DESC) [rownum]

Then take WHERE rownum = 1 in the outer query


问:
Can std::function be move-constructed from rvalue reference to a temporary functor object?
I have an untemplated functor object that I'm trying to store as a std::function inside another object. This object is really heavyweight, so it's marked as uncopyable, but it does have a move constructor. However, trying to construct a std::function, or assign it, from a temporary constructor fails.

Here is a minimal example to provoke the error.

```<code>// pretend this is a really heavyweight functor that can't be copied.
struct ExampleTest
{
    int x;
    int operator()(void) const {return x*2;}
    ExampleTest(  ) :x(0){}
    ExampleTest( int a ) :x(a){}

    // allow move
    ExampleTest( ExampleTest &&other ) :x(other.x) {};

private: // disallow copy, assignment
    ExampleTest( const ExampleTest &other );
    void operator=( const ExampleTest &other );
};

// this sometimes stores really big functors and other times stores tiny lambdas.
struct ExampleContainer
{
    ExampleContainer( int );
    std::function<int(void)> funct;
};

/******** ERROR:
 Compiler error: 'ExampleTest::ExampleTest' : cannot access private member
 declared in class 'ExampleTest'
******************/
ExampleContainer::ExampleContainer( int x )
    : funct( ExampleTest( x ) )
{}

/******** ERROR:
 Compiler error: 'ExampleTest::ExampleTest' : cannot access private member
 declared in class 'ExampleTest'
******************/
int SetExample( ExampleContainer *container )
{
    container->funct = ExampleTest();
    return container->funct();
}
</code>```

In an even simpler construction, where I'm just making a local function, I also get the error:

```<code>int ContrivedExample(  )
{
    // extra parens to sidestep most vexing parse
    std::function<int()> zug( (ExampleTest()) );
    /*** ERROR: 'ExampleTest::ExampleTest' : cannot access private member
         declared in class 'ExampleTest' */
    int troz = zug(  ) ;
    return troz;
}
</code>```

So far as I can tell, in all of these cases, a temporary ExampleTest ought to be passed to the function constructor as an rvalue. Yet the compiler wants to copy them.

What gives? Is it possible to pass uncopyable (but move-copyable) functor objects to a std::function constructor? There are workarounds with pointers and so on, but I want to understand what is going on here.

The specific errors above are from Visual Studio 2012 with the CTP C++11 patch. GCC 4.8 and Clang 3 also fall down, with their own error messages.

答:
std::function can be move-constructed from rvalue of a functor object. And most implementations do that.

The "my target must be copy-constructable" requirement of std::function is due to its own requirement of being copy-constructable. std::function's type is defined only by its target's signature(eg: void(int)) and std::function itself is defined by the standard to be copy-constructable. So when you copy-construct a std::function, it needs to call the copy-ctor of the its target(the underlying functor). So it requires its target having one. It has no other choices.

Having the requirement that the target being copy-constructable, the standard does not say that the implementations should copy, instead of move, when you construct a std::function from a rvalue callable object. The implemention will probably only call the move-ctor of your callable object.

More detailed additional information with examples and tests:

For example in gcc(MSVC is similar) implementation for the ctor of std::function from any callable object:

```<code>template<typename _Res, typename... _ArgTypes>
  template<typename _Functor, typename>
    function<_Res(_ArgTypes...)>::
    function(_Functor __f)
    : _Function_base()
    {
        typedef _Function_handler<_Signature_type, _Functor> _My_handler;

        // don't need to care about details below, but when it uses __f, it
        // either uses std::move, or passes it by references
        if (_My_handler::_M_not_empty_function(__f))
        {
           _My_handler::_M_init_functor(_M_functor, std::move(__f));
           _M_invoker = &_My_handler::_M_invoke;
           _M_manager = &_My_handler::_M_manager;
        }
    }
</code>```

passing by value of the argument of "_Functor __f" will use its move constructor if it has one, and it will use its copy constructor if it does not have a move ctor. As the following test program can demonstrate:

```<code>int main(){
    using namespace std;
    struct TFunctor
    {
        TFunctor() = default;
        TFunctor(const TFunctor&) { cout << "cp ctor called" << endl; }
        TFunctor(TFunctor&&) { cout << "mv ctor called" << endl; };
        void operator()(){}
    };

    {   //!!!!COPY CTOR of TFunctor is NEVER called in this scope
        TFunctor myFunctor;

        //TFunctor move ctor called here
        function<void()> myStdFuncTemp{ std::move(myFunctor) };

        function<void()> myStdFunc{ move(myStdFuncTemp) };
    }

    {   //TFunctor copy ctor is called twice in this scope
        TFunctor myFunctor;

        //TFunctor copy ctor called once here
        function<void()> myStdFuncTemp{ myFunctor };

        //TFunctor copy ctor called once here
        function<void()> myStdFunc{ myStdFuncTemp };
    }
}
</code>```

Finally, you could make a unstd::function_only_movable which has almost everything the same with std::function but deletes its own copy ctor so it does not need to require the target callable object to have one copy ctor. You also need to only construct it from rvalue of callable objects.

Body:
I have an untemplated functor object that I'm trying to store as a std::function inside another object. This object is really heavyweight, so it's marked as uncopyable, but it does have a move constructor. However, trying to construct a std::function, or assign it, from a temporary constructor fails.

Here is a minimal example to provoke the error.

// pretend this is a really heavyweight functor that can't be copied.
struct ExampleTest
{
    int x;
    int operator()(void) const {return x*2;}
    ExampleTest(  ) :x(0){}
    ExampleTest( int a ) :x(a){}

    // allow move
    ExampleTest( ExampleTest &&other ) :x(other.x) {};

private: // disallow copy, assignment
    ExampleTest( const ExampleTest &other );
    void operator=( const ExampleTest &other );
};

// this sometimes stores really big functors and other times stores tiny lambdas.
struct ExampleContainer
{
    ExampleContainer( int );
    std::function<int(void)> funct;
};

/******** ERROR:
 Compiler error: 'ExampleTest::ExampleTest' : cannot access private member
 declared in class 'ExampleTest'
******************/
ExampleContainer::ExampleContainer( int x )
    : funct( ExampleTest( x ) )
{}

/******** ERROR:
 Compiler error: 'ExampleTest::ExampleTest' : cannot access private member
 declared in class 'ExampleTest'
******************/
int SetExample( ExampleContainer *container )
{
    container->funct = ExampleTest();
    return container->funct();
}

In an even simpler construction, where I'm just making a local function, I also get the error:

int ContrivedExample(  )
{
    // extra parens to sidestep most vexing parse
    std::function<int()> zug( (ExampleTest()) );
    /*** ERROR: 'ExampleTest::ExampleTest' : cannot access private member
         declared in class 'ExampleTest' */
    int troz = zug(  ) ;
    return troz;
}

So far as I can tell, in all of these cases, a temporary ExampleTest ought to be passed to the function constructor as an rvalue. Yet the compiler wants to copy them.

What gives? Is it possible to pass uncopyable (but move-copyable) functor objects to a std::function constructor? There are workarounds with pointers and so on, but I want to understand what is going on here.

The specific errors above are from Visual Studio 2012 with the CTP C++11 patch. GCC 4.8 and Clang 3 also fall down, with their own error messages.

Body:
std::function can be move-constructed from rvalue of a functor object. And most implementations do that.

The "my target must be copy-constructable" requirement of std::function is due to its own requirement of being copy-constructable. std::function's type is defined only by its target's signature(eg: void(int)) and std::function itself is defined by the standard to be copy-constructable. So when you copy-construct a std::function, it needs to call the copy-ctor of the its target(the underlying functor). So it requires its target having one. It has no other choices.

Having the requirement that the target being copy-constructable, the standard does not say that the implementations should copy, instead of move, when you construct a std::function from a rvalue callable object. The implemention will probably only call the move-ctor of your callable object.

More detailed additional information with examples and tests:

For example in gcc(MSVC is similar) implementation for the ctor of std::function from any callable object:

template<typename _Res, typename... _ArgTypes>
  template<typename _Functor, typename>
    function<_Res(_ArgTypes...)>::
    function(_Functor __f)
    : _Function_base()
    {
        typedef _Function_handler<_Signature_type, _Functor> _My_handler;

        // don't need to care about details below, but when it uses __f, it
        // either uses std::move, or passes it by references
        if (_My_handler::_M_not_empty_function(__f))
        {
           _My_handler::_M_init_functor(_M_functor, std::move(__f));
           _M_invoker = &_My_handler::_M_invoke;
           _M_manager = &_My_handler::_M_manager;
        }
    }

passing by value of the argument of "_Functor __f" will use its move constructor if it has one, and it will use its copy constructor if it does not have a move ctor. As the following test program can demonstrate:

int main(){
    using namespace std;
    struct TFunctor
    {
        TFunctor() = default;
        TFunctor(const TFunctor&) { cout << "cp ctor called" << endl; }
        TFunctor(TFunctor&&) { cout << "mv ctor called" << endl; };
        void operator()(){}
    };

    {   //!!!!COPY CTOR of TFunctor is NEVER called in this scope
        TFunctor myFunctor;

        //TFunctor move ctor called here
        function<void()> myStdFuncTemp{ std::move(myFunctor) };

        function<void()> myStdFunc{ move(myStdFuncTemp) };
    }

    {   //TFunctor copy ctor is called twice in this scope
        TFunctor myFunctor;

        //TFunctor copy ctor called once here
        function<void()> myStdFuncTemp{ myFunctor };

        //TFunctor copy ctor called once here
        function<void()> myStdFunc{ myStdFuncTemp };
    }
}

Finally, you could make a unstd::function_only_movable which has almost everything the same with std::function but deletes its own copy ctor so it does not need to require the target callable object to have one copy ctor. You also need to only construct it from rvalue of callable objects.


问:
How would I be able to make it so a youtube embed cannot be paused [HTML5]
I am making a chrome NewTab Extension - Here is a download link if you want to be able to see the exact code

I want to be able to change make it so that end users cannot pause the youtube embed on my main index.html

```<code> <div class="vidbg"style="position: fixed; z-index: -99; width: 100%; height: 100%">
</code>```

答:
Remove the controls from the embedded player.

Put a transparent cover div over the player to stop direct clicking or interaction.

If you still wish to interact with the player, have js links for the api for the desired actions.


问:
Magento Product Import - Beyond CSV/XLS
I want to move an entire catalog from one magento store to another store on another server.  I realize I can import via csv, but I also want to maintain product relationships, grouped product relationship, config product relationships and images.  The only way I can think to do this is to write my own script using the Magento API.   Is there another more straight forward way of doing this? </p>

答:
Export the DB directly and you would retain all this information. This would also be significantly faster for large sets of objects.

If that feels too dirty, your API solution will contain all the data, but will take longer to import/export.

Title: Magento Product Import - Beyond CSV/XLS


答:
You could check to see if one of them is visible and then do actions on them through that.</p>

```<code>$(".filterInventory").on("click", function () {
    if($(".filer-arrow.down").is(":visible")) {
      $(".filer-arrow.down").hide();
      $(".filer-arrow.up").show();
    } else {
      $(".filer-arrow.up").hide();
      $(".filer-arrow.down").show();
    }
});
</code>```

Title: Jquery toggle not working when toggling back

Body:
I am using jquery toggle, to show one image and then when the user clicks on an element, change to another image and if they click again show the original image. Like an open close kind of thing. It works when I first click, but nothing after that. Here is my jquery

 $(".filterInventory").on("click", function () {

    $(".inventory-search").toggle();
    $(".filer-arrow.down").hide();
    $(".filer-arrow.up").show();

    return false;

});

and here is the HTML

                Filter

CSS:

#communities a.filterInventory img.up {
    display: none;
}

#communities .filterInventory .filer-arrow {
    height: 10px;
}

Body:
You could check to see if one of them is visible and then do actions on them through that.

$(".filterInventory").on("click", function () {
    if($(".filer-arrow.down").is(":visible")) {
      $(".filer-arrow.down").hide();
      $(".filer-arrow.up").show();
    } else {
      $(".filer-arrow.up").hide();
      $(".filer-arrow.down").show();
    }
});


问:
Css positioning button at center of Overlay with image in background

.msg-ex {
  display: flex;
  align-items: center;
  justify-content: center;
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
}

.msg-ex .msg-ex-overlay {
  position: relative;
  background-color: rgba(0, 0, 0, 0.4);
  width: 100%;
  height: 100%;
  opacity: 0;
  z-index: 2;
}

.msg-ex .msg-ex-overlay .msg-ex-cta {
  position: absolute;
  color: red;
  background-color: #DCE0E3;
  font-size: 1.1em;
  font-weight: 700;
  border-radius: 18px;
  height: 38px;
  width: 100px;
  cursor: pointer;
  top: 50%;
  left: 50%;
  transform: translateX(-48%) translateY(-47%);
}

.msg-ex .msg-ex-overlay:hover {
  opacity: 1;
}

.msg-ex-box {
  position: relative;
  background-color: $voiceColor;
}

.msg-ex-box::after {
  content: '';
  bottom: 0;
  right: 0;
  width: 32px;
  height: 32px;
  background-image: url(../pics/data/img1.png);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: absolute;
  z-index: 1;
}

}
.msg-ex-voice:hover {
  background-color: rgba(0, 0, 0, 0.4);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="msg-ex msg-ex-box">
  <div class="msg-ex-overlay">
    <button class="msg-ex-cta">Show</button>
  </div>
</div></code>```

I am positioning my "Show" button at the center using transform: translateX(-48%) translateY(-47%); but ideally it should be transform: translateX(50%) translateY(50%); which centers it - cannot figure out what I am doing wrong. Please help.

答:
If you want to center anything, put this inside the parent:

```<code>display: flex;
justify-content: center;
</code>```

And add this to the child you are trying to center:

```<code>align-self: center;
</code>```

Hope this helps!

Body:
.msg-ex {
  display: flex;
  align-items: center;
  justify-content: center;
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
}

.msg-ex .msg-ex-overlay {
  position: relative;
  background-color: rgba(0, 0, 0, 0.4);
  width: 100%;
  height: 100%;
  opacity: 0;
  z-index: 2;
}

.msg-ex .msg-ex-overlay .msg-ex-cta {
  position: absolute;
  color: red;
  background-color: #DCE0E3;
  font-size: 1.1em;
  font-weight: 700;
  border-radius: 18px;
  height: 38px;
  width: 100px;
  cursor: pointer;
  top: 50%;
  left: 50%;
  transform: translateX(-48%) translateY(-47%);
}

.msg-ex .msg-ex-overlay:hover {
  opacity: 1;
}

.msg-ex-box {
  position: relative;
  background-color: $voiceColor;
}

.msg-ex-box::after {
  content: '';
  bottom: 0;
  right: 0;
  width: 32px;
  height: 32px;
  background-image: url(../pics/data/img1.png);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: absolute;
  z-index: 1;
}

}
.msg-ex-voice:hover {
  background-color: rgba(0, 0, 0, 0.4);
}

    <button class="msg-ex-cta">Show</button>

I am positioning my "Show" button at the center using transform: translateX(-48%) translateY(-47%); but ideally it should be transform: translateX(50%) translateY(50%); which centers it - cannot figure out what I am doing wrong. Please help.

Body:
If you want to center anything, put this inside the parent:

display: flex;
justify-content: center;

And add this to the child you are trying to center:

align-self: center;

Hope this helps!


问:
Re-order bootstrap columns
I want to re-order bootstrap columns for the desktop version of my web page.

Please see image below.

The columns don't have a fixed height.

Column B is higher than A and C on the desktop version because of larger content.

Basically, I want to "merge" column A and C on the desktop version.

I want to avoid using duplicate HTML (show/hide) or jQuery to "cut and paste" the element depending on browser size.

Any ideas how to achieve this with CSS?

Thanks!

Mobile version:

```<code><div class="column-A col-xs-12">
     ...
</div>

<div class="column-B col-xs-12">
    ...
</div>

<div class="column-C col-xs-12">
     ...
</div>
</code>```

Desktop version:

答:
Good question. This is possible by using Pull and Push classes in bootstrap. Bootstrap calls is Column Ordering. (http://getbootstrap.com/css/#grid-column-ordering )

So, basic fundamental is that first you order the HTML to the way you want it to appear on your mobile and then for the desktop, you push the first element to the right and at the same time pull the second element to the left. This will give you the desired output.

Following is how you would code it:

```<code><div class="row">
  <div class="col-xs-12 col-md-9 col-md-push-3">.col-md-9 .col-md-push-3</div>
  <div class="col-xs-12 col-md-3 col-md-pull-9">.col-md-3 .col-md-pull-9</div>
</div>
</code>```

Try it out, if you face any issues, post it in comments and I'll have a look at it.

Title: Re-order bootstrap columns

Body:
I want to re-order bootstrap columns for the desktop version of my web page.

Please see image below.

The columns don't have a fixed height.

Column B is higher than A and C on the desktop version because of larger content.

Basically, I want to "merge" column A and C on the desktop version.

I want to avoid using duplicate HTML (show/hide) or jQuery to "cut and paste" the element depending on browser size.

Any ideas how to achieve this with CSS?

Thanks!

Mobile version:

     ...

    ...

     ...

Desktop version:

Body:
Good question. This is possible by using Pull and Push classes in bootstrap. Bootstrap calls is Column Ordering. (http://getbootstrap.com/css/#grid-column-ordering )

So, basic fundamental is that first you order the HTML to the way you want it to appear on your mobile and then for the desktop, you push the first element to the right and at the same time pull the second element to the left. This will give you the desired output.

Following is how you would code it:

<div class="row">
  <div class="col-xs-12 col-md-9 col-md-push-3">.col-md-9 .col-md-push-3</div>
  <div class="col-xs-12 col-md-3 col-md-pull-9">.col-md-3 .col-md-pull-9</div>
</div>

Try it out, if you face any issues, post it in comments and I'll have a look at it.


问:
Parse multiple xml files in Python
I am stuck with a problem here. So I want to parse multiple xml files with the same structure within it. I was already able to get all the locations for each file and save them into three different lists, since there are three different types of xml structures. Now I want to create three  functions (for each list), which is looping through the lists and parse the information I need. Somehow I am not able to do it. Anybody here who could give me a hint how to do it?

```<code>import os
import glob
import xml.etree.ElementTree as ET
import fnmatch
import re
import sys

#### Get the location of each XML file and save them into a list ####

all_xml_list =[]

def locate(pattern,root=os.curdir):
    for path, dirs, files in os.walk(os.path.abspath(root)):
        for filename in fnmatch.filter(files,pattern):
            yield os.path.join(path,filename)

for files in locate('*.xml',r'C:\Users\Lars\Documents\XML-Files'):
    all_xml_list.append(files)

#### Create lists by GameDay Events ####

xml_GameDay_Player   = [x for x in all_xml_list if 'Player' in x]
xml_GameDay_Team     = [x for x in all_xml_list if 'Team' in x]
xml_GameDay_Match    = [x for x in all_xml_list if 'Match' in x]
</code>```

The XML file looks like this:

<sports-content xmlns:imp="url">
  <sports-metadata date-time="20160912T000000+0200" doc-id="sports_event_" publisher="somepublisher" language="en_EN" document-class="player-statistics">
    <sports-title>player-statistics-165483</sports-title>
  </sports-metadata>
  <sports-event>
    <event-metadata id="E_165483" event-key="165483" event-status="post-event" start-date-time="20160827T183000+0200" start-weekday="saturday" heat-number="1" site-attendance="52183" />
    <team>
      <team-metadata id="O_17" team-key="17">
        <name full="TeamName" nickname="NicknameoftheTeam" imp:dfl-3-letter-code="NOT" official-3-letter-code="" />
      </team-metadata>
      <player>
        <player-metadata player-key="33201" uniform-number="1">
          <name first="Max" last="Mustermann" full="Max Mustermann" nickname="Mäxchen" imp:extensive="Name" />
        </player-metadata>
        <player-stats stats-coverage="standard" date-coverage-type="event" minutes-played="90" score="0">
          <rating rating-type="standard" imp:rating-value-goalie="7.6" imp:rating-value-defenseman="5.6" imp:rating-value-mid-fielder="5.8" imp:rating-value-forward="5.0" />
          <rating rating-type="grade" rating-value="2.2" />
          <rating rating-type="index" imp:rating-value-goalie="7.6" imp:rating-value-defenseman="3.7" imp:rating-value-mid-fielder="2.5" imp:rating-value-forward="1.2" />
          <rating rating-type="bemeister" rating-value="16.04086" />
          <player-stats-soccer imp:duels-won="1" imp:duels-won-ground="0" imp:duels-won-header="1" imp:duels-lost-ground="0" imp:duels-lost-header="0" imp:duels-lost="0" imp:duels-won-percentage="100" imp:passes-completed="28" imp:passes-failed="4" imp:passes-completions-percentage="87.5" imp:passes-failed-percentage="12.5" imp:passes="32" imp:passes-short-total="22" imp:balls-touched="50" imp:tracking-distance="5579.80" imp:tracking-average-speed="3.41" imp:tracking-max-speed="23.49" imp:tracking-sprints="0" imp:tracking-sprints-distance="0.00" imp:tracking-fast-runs="3" imp:tracking-fast-runs-distance="37.08" imp:tracking-offensive-runs="0" imp:tracking-offensive-runs-distance="0.00" dfl-distance="5579.80" dfl-average-speed="3.41" dfl-max-speed="23.49">
            <stats-soccer-defensive saves="5" imp:catches-punches-crosses="3" imp:catches-punches-corners="0" goals-against-total="1" imp:penalty-saves="0" imp:clear-cut-chance="0" />
            <stats-soccer-offensive shots-total="0" shots-on-goal-total="0" imp:shots-off-post="0" offsides="0" corner-kicks="0" imp:crosses="0" assists-total="0" imp:shot-assists="0" imp:freekicks="3" imp:miss-chance="0" imp:throw-in="0" imp:punt="2" shots-penalty-shot-scored="0" shots-penalty-shot-missed="0" dfl-assists-total="0" imp:shots-total-outside-box="0" imp:shots-total-inside-box="0" imp:shots-foot-inside-box="0" imp:shots-foot-outside-box="0" imp:shots-total-header="0" />
            <stats-soccer-foul fouls-commited="0" fouls-suffered="0" imp:yellow-red-cards="0" imp:red-cards="0" imp:yellow-cards="0" penalty-caused="0" />
          </player-stats-soccer>
        </player-stats>
      </player>
    </team>
  </sports-event>
</sports-content>
```

I want to extract everything which is within the "player meta tag" and "player-stats coverage" and "player stats soccer" tag.

答:
Improving on @Gnudiff's answer, here is a more resilient approach:

```<code>import os
from glob import glob
from lxml import etree

xml_GameDay = {
    'Player': [],
    'Team': [],
    'Match': [],
}

# sort all files into the right buckets
for filename in glob(r'C:\Users\Lars\Documents\XML-Files\*.xml'):
    for key in xml_GameDay.keys():
        if key in os.path.basename(filename):
            xml_GameDay[key].append(filename)
            break

def select_first(context, path):
    result = context.xpath(path)
    if len(result):
        return result[0]
    return None

# extract data from Player files
for filename in xml_GameDay['Player']:
    tree = etree.parse(filename)

    for player in tree.xpath('.//player'):
        player_data = {
            'key': select_first(player, './player-metadata/@player-key'),
            'lastname': select_first(player, './player-metadata/name/@last'),
            'firstname': select_first(player, './player-metadata/name/@first'),
            'nickname': select_first(player, './player-metadata/name/@nickname'),
        }
        print(player_data)
        # ...
</code>```

XML files can come in a variety of byte encodings and are prefixed by the XML declaration, which declares the encoding of the rest of the file.

```<code><?xml version="1.0" encoding="UTF-8"?>
</code>```

UTF-8 is a common encoding for XML files (it also is the default), but in reality it can be anything. It's impossible to predict and it's very bad practice to hard-code your program to expect a certain encoding.

XML parsers are designed to deal with this peculiarity in a transparent way, so you don't really have to worry about it, unless you do it wrong.

This is a good example of doing it wrong:

```<code># BAD CODE, DO NOT USE
def file_get_contents(filename):
    with open(filename) as f:
        return f.read()

tree = etree.XML(file_get_contents('some_filename.xml'))
</code>```

What happens here is this:

Python opens filename as a text file f

f.read() returns a string

etree.XML() parses that string and creates a DOM object tree

Doesn't sound so wrong, does it? But if the XML is like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Player nickname="Mäxchen">...</Player>
</code>```

then the DOM you will end up with will be:

```<code>Player
    @nickname="MÃ¤xchen"
</code>```

You have just destroyed the data. And unless the XML contained an "extended" character like ä, you would not even have noticed that this approach is borked. This can easily slip into production unnoticed.

There is exactly one correct way of opening an XML file (and it's also simpler than the code above): Give the file name to the parser.

```<code>tree = etree.parse('some_filename.xml')
</code>```

This way the parser can figure out the file encoding before it reads the data and you don't have to care about those details.

Title: Parse multiple xml files in Python

Body:
I am stuck with a problem here. So I want to parse multiple xml files with the same structure within it. I was already able to get all the locations for each file and save them into three different lists, since there are three different types of xml structures. Now I want to create three  functions (for each list), which is looping through the lists and parse the information I need. Somehow I am not able to do it. Anybody here who could give me a hint how to do it?

import os
import glob
import xml.etree.ElementTree as ET
import fnmatch
import re
import sys

#### Get the location of each XML file and save them into a list ####

all_xml_list =[]

def locate(pattern,root=os.curdir):
    for path, dirs, files in os.walk(os.path.abspath(root)):
        for filename in fnmatch.filter(files,pattern):
            yield os.path.join(path,filename)

for files in locate('*.xml',r'C:\Users\Lars\Documents\XML-Files'):
    all_xml_list.append(files)

#### Create lists by GameDay Events ####

xml_GameDay_Player   = [x for x in all_xml_list if 'Player' in x]
xml_GameDay_Team     = [x for x in all_xml_list if 'Team' in x]
xml_GameDay_Match    = [x for x in all_xml_list if 'Match' in x]

The XML file looks like this:

<sports-content xmlns:imp="url">
  <sports-metadata date-time="20160912T000000+0200" doc-id="sports_event_" publisher="somepublisher" language="en_EN" document-class="player-statistics">
    <sports-title>player-statistics-165483</sports-title>
  </sports-metadata>
  <sports-event>
    <event-metadata id="E_165483" event-key="165483" event-status="post-event" start-date-time="20160827T183000+0200" start-weekday="saturday" heat-number="1" site-attendance="52183" />
    <team>
      <team-metadata id="O_17" team-key="17">
        <name full="TeamName" nickname="NicknameoftheTeam" imp:dfl-3-letter-code="NOT" official-3-letter-code="" />
      </team-metadata>
      <player>
        <player-metadata player-key="33201" uniform-number="1">
          <name first="Max" last="Mustermann" full="Max Mustermann" nickname="Mäxchen" imp:extensive="Name" />
        </player-metadata>
        <player-stats stats-coverage="standard" date-coverage-type="event" minutes-played="90" score="0">
          <rating rating-type="standard" imp:rating-value-goalie="7.6" imp:rating-value-defenseman="5.6" imp:rating-value-mid-fielder="5.8" imp:rating-value-forward="5.0" />
          <rating rating-type="grade" rating-value="2.2" />
          <rating rating-type="index" imp:rating-value-goalie="7.6" imp:rating-value-defenseman="3.7" imp:rating-value-mid-fielder="2.5" imp:rating-value-forward="1.2" />
          <rating rating-type="bemeister" rating-value="16.04086" />
          <player-stats-soccer imp:duels-won="1" imp:duels-won-ground="0" imp:duels-won-header="1" imp:duels-lost-ground="0" imp:duels-lost-header="0" imp:duels-lost="0" imp:duels-won-percentage="100" imp:passes-completed="28" imp:passes-failed="4" imp:passes-completions-percentage="87.5" imp:passes-failed-percentage="12.5" imp:passes="32" imp:passes-short-total="22" imp:balls-touched="50" imp:tracking-distance="5579.80" imp:tracking-average-speed="3.41" imp:tracking-max-speed="23.49" imp:tracking-sprints="0" imp:tracking-sprints-distance="0.00" imp:tracking-fast-runs="3" imp:tracking-fast-runs-distance="37.08" imp:tracking-offensive-runs="0" imp:tracking-offensive-runs-distance="0.00" dfl-distance="5579.80" dfl-average-speed="3.41" dfl-max-speed="23.49">
            <stats-soccer-defensive saves="5" imp:catches-punches-crosses="3" imp:catches-punches-corners="0" goals-against-total="1" imp:penalty-saves="0" imp:clear-cut-chance="0" />
            <stats-soccer-offensive shots-total="0" shots-on-goal-total="0" imp:shots-off-post="0" offsides="0" corner-kicks="0" imp:crosses="0" assists-total="0" imp:shot-assists="0" imp:freekicks="3" imp:miss-chance="0" imp:throw-in="0" imp:punt="2" shots-penalty-shot-scored="0" shots-penalty-shot-missed="0" dfl-assists-total="0" imp:shots-total-outside-box="0" imp:shots-total-inside-box="0" imp:shots-foot-inside-box="0" imp:shots-foot-outside-box="0" imp:shots-total-header="0" />
            <stats-soccer-foul fouls-commited="0" fouls-suffered="0" imp:yellow-red-cards="0" imp:red-cards="0" imp:yellow-cards="0" penalty-caused="0" />
          </player-stats-soccer>
        </player-stats>
      </player>
    </team>
  </sports-event>
</sports-content>

I want to extract everything which is within the "player meta tag" and "player-stats coverage" and "player stats soccer" tag.

Body:
Improving on @Gnudiff's answer, here is a more resilient approach:

import os
from glob import glob
from lxml import etree

xml_GameDay = {
    'Player': [],
    'Team': [],
    'Match': [],
}

# sort all files into the right buckets
for filename in glob(r'C:\Users\Lars\Documents\XML-Files\*.xml'):
    for key in xml_GameDay.keys():
        if key in os.path.basename(filename):
            xml_GameDay[key].append(filename)
            break

def select_first(context, path):
    result = context.xpath(path)
    if len(result):
        return result[0]
    return None

# extract data from Player files
for filename in xml_GameDay['Player']:
    tree = etree.parse(filename)

    for player in tree.xpath('.//player'):
        player_data = {
            'key': select_first(player, './player-metadata/@player-key'),
            'lastname': select_first(player, './player-metadata/name/@last'),
            'firstname': select_first(player, './player-metadata/name/@first'),
            'nickname': select_first(player, './player-metadata/name/@nickname'),
        }
        print(player_data)
        # ...

XML files can come in a variety of byte encodings and are prefixed by the XML declaration, which declares the encoding of the rest of the file.

<?xml version="1.0" encoding="UTF-8"?>

UTF-8 is a common encoding for XML files (it also is the default), but in reality it can be anything. It's impossible to predict and it's very bad practice to hard-code your program to expect a certain encoding.

XML parsers are designed to deal with this peculiarity in a transparent way, so you don't really have to worry about it, unless you do it wrong.

This is a good example of doing it wrong:

# BAD CODE, DO NOT USE
def file_get_contents(filename):
    with open(filename) as f:
        return f.read()

tree = etree.XML(file_get_contents('some_filename.xml'))

What happens here is this:

Python opens filename as a text file f

f.read() returns a string

etree.XML() parses that string and creates a DOM object tree

Doesn't sound so wrong, does it? But if the XML is like this:

<?xml version="1.0" encoding="UTF-8"?>
<Player nickname="Mäxchen">...</Player>

then the DOM you will end up with will be:

Player
    @nickname="MÃ¤xchen"

You have just destroyed the data. And unless the XML contained an "extended" character like ä, you would not even have noticed that this approach is borked. This can easily slip into production unnoticed.

There is exactly one correct way of opening an XML file (and it's also simpler than the code above): Give the file name to the parser.

tree = etree.parse('some_filename.xml')

This way the parser can figure out the file encoding before it reads the data and you don't have to care about those details.


问:
Compare two floats
```<code>#include <stdbool.h>

bool Equality(double a, double b, double epsilon)
{
  if (fabs(a-b) < epsilon) return true;
  return false;
}
</code>```

I tried this method to compare two doubles, but I always get problems since I don't know how to chose the epsilon, actually I want to compare small numbers (6 6 digits after the decimal point) like 0.000001. I tried with some numbers, sometimes I get 0.000001 != 0.000001 and sometimes 0.000001 == 0.000002
Is there another method else than comparing with the epsilon?

My purpose is to compare two doubles (which represent the time in my case). The variable t which represents the time in milliseconds is a double. It is incremented by another function 0.000001 then 0.000002 etc. each time t changes, I want to check if it is equal to another variable of type double tt, in case tt == t, I have some instructions to execute..

Thanks for your help

答:
Alternatively, you could compare two integers instead. Just multiply your two floats by the desired precision and cast them to integers.
Be sure to round up/down correctly. Here is what it looks like:</p>

```<code>BOOL floatcmp(float float1, float float2, unsigned int precision){
   int int1, int2;

   if (float1 > 0)
      int1 = (int)(float1 * precision + .5);
   else
      int1 = (int)(float1 * precision - .5);

   if (float2 > 0)
      int2 = (int)(float2 * precision + .5);
   else
      int2 = (int)(float2 * precision - .5);

   return (int1 == int2);
}
</code>```

Title: Compare two floats

Body:
#include <stdbool.h>

bool Equality(double a, double b, double epsilon)
{
  if (fabs(a-b) < epsilon) return true;
  return false;
}

I tried this method to compare two doubles, but I always get problems since I don't know how to chose the epsilon, actually I want to compare small numbers (6 6 digits after the decimal point) like 0.000001. I tried with some numbers, sometimes I get 0.000001 != 0.000001 and sometimes 0.000001 == 0.000002
Is there another method else than comparing with the epsilon?

My purpose is to compare two doubles (which represent the time in my case). The variable t which represents the time in milliseconds is a double. It is incremented by another function 0.000001 then 0.000002 etc. each time t changes, I want to check if it is equal to another variable of type double tt, in case tt == t, I have some instructions to execute..

Thanks for your help

Body:
Alternatively, you could compare two integers instead. Just multiply your two floats by the desired precision and cast them to integers.
Be sure to round up/down correctly. Here is what it looks like:

BOOL floatcmp(float float1, float float2, unsigned int precision){
   int int1, int2;

   if (float1 > 0)
      int1 = (int)(float1 * precision + .5);
   else
      int1 = (int)(float1 * precision - .5);

   if (float2 > 0)
      int2 = (int)(float2 * precision + .5);
   else
      int2 = (int)(float2 * precision - .5);

   return (int1 == int2);
}


问:
How to test GUI for color blind person?
Is there a way to test if a GUI is usable for color blind person?

I know that it has many degrees and I guess that's why simply doing a screenshot in black & white is not the best way to test the usability of a GUI for a color blind person. What is the best way or best tool to do it?

答:
Color Oracle

It's for Win/Mac/*nix. It takes the image that is currently shown on your screen and applies a colorblindness filter, so that you easily can see how it looks, without having to capture screenshots and use photoshop to do the filtering. You can even assign a hotkey so that you instantly can see it. Best of all it's free.

Colorblind Vision

iPhone app for realtime simulation of colorblindness. I wrote it as my first iOS program.

Title: How to test GUI for color blind person?


问:
One liner for extend loop python
I have the following code lines:

```<code>records = []

for future in futures:
  records.extends(future.result())
</code>```

each future returns a list.

How can I write the above code but in one liner?

```<code>records = [future.result() for future in futures]
</code>```

would result in a list inside list.

I have millions of records, i would rather not flat it after creating lists inside list

答:
There are many ways to do this:

Use itertools.chain:

records = list(itertools.chain.from_iterable(future.result() for future in futures))

Use the itertools consume recipe:

records = collections.deque((records.extend(future.result()) for future in futures), maxlen=0)

Use a throw-away list:

[records.extend(future.result()) for future in futures]. records will now have all the required content, and you will have temporarily made a list of Nones

You could also do functools.reduce(operator.add, (future.result() for future in futures)), but that wouldn't scale very well

Title: One liner for extend loop python

Body:
I have the following code lines:

records = []

for future in futures:
  records.extends(future.result())

each future returns a list.

How can I write the above code but in one liner?

records = [future.result() for future in futures]

would result in a list inside list.

I have millions of records, i would rather not flat it after creating lists inside list